bool NzMD5AnimParser::Parse(NzAnimation* animation) { while (Advance(false)) { switch (m_currentLine[0]) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING case 'M': // MD5Version if (m_currentLine.GetWord(0) != "MD5Version") UnrecognizedLine(); break; #endif case 'b': // baseframe/bounds if (m_currentLine.StartsWith("baseframe {")) { if (!ParseBaseframe()) { Error("Failed to parse baseframe"); return false; } } else if (m_currentLine.StartsWith("bounds {")) { if (!ParseBounds()) { Error("Failed to parse bounds"); return false; } } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif break; #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING case 'c': // commandline if (m_currentLine.GetWord(0) != "commandline") UnrecognizedLine(); break; #endif case 'f': { unsigned int index; if (std::sscanf(&m_currentLine[0], "frame %u {", &index) == 1) { if (m_frameIndex != index) { Error("Unexpected frame index (expected " + NzString::Number(m_frameIndex) + ", got " + NzString::Number(index) + ')'); return false; } if (!ParseFrame()) { Error("Failed to parse frame"); return false; } m_frameIndex++; } else if (std::sscanf(&m_currentLine[0], "frameRate %u", &m_frameRate) != 1) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING UnrecognizedLine(); #endif } break; } case 'h': // hierarchy if (m_currentLine.StartsWith("hierarchy {")) { if (!ParseHierarchy()) { Error("Failed to parse hierarchy"); return false; } } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif break; case 'n': // num[Frames/Joints] { unsigned int count; if (std::sscanf(&m_currentLine[0], "numAnimatedComponents %u", &count) == 1) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!m_animatedComponents.empty()) Warning("Animated components count is already defined"); #endif m_animatedComponents.resize(count); } else if (std::sscanf(&m_currentLine[0], "numFrames %u", &count) == 1) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!m_frames.empty()) Warning("Frame count is already defined"); #endif m_frames.resize(count); } else if (std::sscanf(&m_currentLine[0], "numJoints %u", &count) == 1) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!m_joints.empty()) Warning("Joint count is already defined"); #endif m_joints.resize(count); } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif break; } default: #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING UnrecognizedLine(); #endif break; } } unsigned int frameCount = m_frames.size(); if (frameCount == 0) { NazaraError("Frame count is invalid or missing"); return false; } unsigned int jointCount = m_joints.size(); if (jointCount == 0) { NazaraError("Joint count is invalid or missing"); return false; } if (m_frameIndex != frameCount) { NazaraError("Missing frame infos: [" + NzString::Number(m_frameIndex) + ',' + NzString::Number(frameCount) + ']'); return false; } if (m_frameRate == 0) { NazaraWarning("Framerate is either invalid or missing, assuming a default value of 24"); m_frameRate = 24; } // À ce stade, nous sommes censés avoir assez d'informations pour créer l'animation if (!animation->CreateSkeletal(frameCount, jointCount)) { NazaraError("Failed to create animation"); return false; } NzSequence sequence; sequence.firstFrame = 0; sequence.frameCount = m_frames.size(); sequence.frameRate = m_frameRate; sequence.name = m_stream.GetPath().SubStringFrom(NAZARA_DIRECTORY_SEPARATOR, -1, true); if (!animation->AddSequence(sequence)) NazaraWarning("Failed to add sequence"); NzSequenceJoint* sequenceJoints = animation->GetSequenceJoints(); // Pour que le squelette soit correctement aligné, il faut appliquer un quaternion "de correction" aux joints à la base du squelette NzQuaternionf rotationQuat = NzEulerAnglesf(-90.f, 90.f, 0.f); for (unsigned int i = 0; i < jointCount; ++i) { int parent = m_joints[i].parent; for (unsigned int j = 0; j < frameCount; ++j) { NzSequenceJoint& sequenceJoint = sequenceJoints[j*jointCount + i]; if (parent >= 0) { sequenceJoint.position = m_frames[j].joints[i].pos; sequenceJoint.rotation = m_frames[j].joints[i].orient; } else { sequenceJoint.position = rotationQuat * m_frames[j].joints[i].pos; sequenceJoint.rotation = rotationQuat * m_frames[j].joints[i].orient; } sequenceJoint.scale = NzVector3f(1.f, 1.f, 1.f); } } return true; }
BOOL ClipboardCopy(void) { HGLOBAL hMem; char huge *pMem; LONG lSize; BOOL WideCharConvert = FALSE; UINT Codepage = 0; /*prepare resources...*/ if (!SelectCount) { Error(209); return (FALSE); } if (!OpenClipboard(hwndMain)) { ErrorBox(MB_ICONEXCLAMATION, 302); return (FALSE); } lSize = SelectCount + sizeof(BinaryPart); if (!(GetVersion() & 0x80000000U)) if (UtfEncoding || CharSet == CS_OEM || AnsiCodePage != CP_ACP) { /*copy as wide chars...*/ Codepage = CharSet == CS_OEM ? OemCodePage : AnsiCodePage; if (UtfEncoding != 16) lSize <<= 1; WideCharConvert = TRUE; } hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, lSize); if (!hMem) { CloseClipboard(); ErrorBox(MB_ICONEXCLAMATION, 304); return (FALSE); } pMem = GlobalLock(hMem); if (pMem == NULL) { CloseClipboard(); GlobalFree(hMem); ErrorBox(MB_ICONEXCLAMATION, 305); return (FALSE); } /*copy into memory...*/ { POSITION Pos; ULONG Bytes = SelectCount; UINT i; BOOL NullbyteFound = FALSE; Pos = SelectStart; if (UtfEncoding && WideCharConvert) { POSITION EndPos = Pos; WCHAR *pw = (WCHAR *)pMem; Advance(&EndPos, Bytes); //if (CountBytes(&Pos) != 0 || (i = CharAndAdvance(&Pos)) == C_BOM) i = CharAndAdvance(&Pos); for (;;) { if (ComparePos(&Pos, &EndPos) > 0) break; if (i == C_EOF) break; if (i == C_CRLF) { if ((char *)pw + 6 > pMem + lSize) break; *pw++ = '\r'; i = '\n'; } if ((char *)pw + 4 > pMem + lSize) break; *pw++ = i; i = CharAndAdvance(&Pos); } *pw = '\0'; } else while (Bytes) { LPSTR p, pNull; CharAt(&Pos); /*normalize position and enforce page load*/ i = Pos.p->Fill - Pos.i; if (i > Bytes) i = (UINT)Bytes; p = Pos.p->PageBuf + Pos.i; if (!NullbyteFound && (pNull = _fmemchr(p, '\0', i)) != NULL) { if (ErrorBox(MB_ICONINFORMATION|MB_OKCANCEL, 328) == IDCANCEL) { CloseClipboard(); GlobalUnlock(hMem); GlobalFree(hMem); return (FALSE); } NullbyteFound = TRUE; i = pNull - p + 1; if (CharSet == CS_EBCDIC) EbcdicConvert(pMem, p, i); else if (WideCharConvert) { MultiByteToWideChar(Codepage, 0, p, i, (WCHAR*)pMem, i); pMem += i; } else hmemcpy(pMem, p, i); pMem += i; Bytes -= --i; Pos.i += i; i = wsprintf(BinaryPart, BinaryFormat, Bytes); if (WideCharConvert) { MultiByteToWideChar(Codepage, 0, BinaryPart, i, (WCHAR*)pMem, i); pMem += i; } else hmemcpy(pMem, BinaryPart, i); pMem += i; continue; } if (CharSet == CS_EBCDIC) EbcdicConvert(pMem, Pos.p->PageBuf + Pos.i, i); else if (WideCharConvert) { MultiByteToWideChar(Codepage, 0, Pos.p->PageBuf + Pos.i, i, (WCHAR*)pMem, i); if (CharSet == CS_OEM) { extern WCHAR const MapLowOemToUtf16[33]; PWSTR pw = (WCHAR*)pMem; INT j; for (j=i; j>0; --j) { if (*pw < ' ') { switch (*pw) { case '\0': case '\t': case '\n': case '\r': break; default: *pw = MapLowOemToUtf16[*pw]; } } ++pw; } } pMem += i; } else hmemcpy(pMem, Pos.p->PageBuf + Pos.i, i); pMem += i; Bytes -= i; Pos.i += i; } } /*unlock...*/ GlobalUnlock(hMem); /*clear previous clipboard contents...*/ if (!EmptyClipboard()) { CloseClipboard(); GlobalFree(hMem); ErrorBox(MB_ICONEXCLAMATION, 303); return (FALSE); } /*finally, publish...*/ SetClipboardData(WideCharConvert ? CF_UNICODETEXT : CharSet == CS_OEM ? CF_OEMTEXT : CF_TEXT, hMem); CloseClipboard(); CheckClipboard(); return (TRUE); }
inline char AdvanceGetChar() { Advance(); return c0_; }
AST* ParseProgram(ParserState* parser) { parser->nextToken = GetNextToken(parser->lex); Advance(parser); return ParseBlock(parser); }
inline void AdvanceSkipWhitespace() { do { Advance(); } while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r'); }
/** This methods executes one round of gameplay. The game progresses through phases Ph_START, Ph_NORMAL, and Ph_KO. If a KO happened, it will invoke InstantReplay. At the end of the round m_aiRoundsWonByPlayer[x] will be incremented depending on the outcome. m_iNumberOfRounds will also increase by 1. */ void CGame::DoOneRound() { m_enGamePhase = Ph_START; m_poBackground->DeleteExtraLayers(); int iTeamSize = (SState::Team_ONE_VS_ONE==g_oState.m_enTeamMode) ? 1 : g_oPlayerSelect.GetPlayerInfo(0).m_aenTeam.size(); int aiTeamNumber[MAXPLAYERS]; for ( int i=0; i<g_oState.m_iNumPlayers; ++i ) { aiTeamNumber[i] = 0; } if ( IsTeamMode() ) { for ( int i=0; i<g_oState.m_iNumPlayers; ++i ) { g_oPlayerSelect.SetPlayer( i, g_oPlayerSelect.GetPlayerInfo(i).m_aenTeam[aiTeamNumber[i]] ); } } g_oBackend.PerlEvalF( "GameStart(%d,%d,%d,%d,%d);", IsMaster() ? g_oState.m_iHitPoints : g_poNetwork->GetGameParams().iHitPoints, g_oState.m_iNumPlayers, iTeamSize, m_bWide, m_bDebug ); g_oBackend.ReadFromPerl(); if ( IsNetworkGame() ) { g_poNetwork->SynchStartRound(); g_poNetwork->SendGameTick( g_oBackend.m_iGameTick-1 ); } int iKoFrame = -1; double dGameTime = 2 * 1000; // Only for the "greeting phase", the real gametime will be set after. int iThisTick, iLastTick, iGameSpeed; bool bHurryUp = false; bool bReplayAfter = true; iGameSpeed = IsMaster() ? g_oState.m_iGameSpeed : g_poNetwork->GetGameParams().iGameSpeed; iThisTick = SDL_GetTicks() / iGameSpeed; iLastTick = iThisTick - 1; m_oKeyQueue.Reset(); oFpsCounter.Reset(); // 1. DO THE NORMAL GAME ROUND (START, NORMAL, KO, TIMEUP) while ( dGameTime >= 0 ) { if ( m_enInitialGameMode != g_oState.m_enGameMode ) { return; } // 1. Wait for the next tick (on extremely fast machines..) while (iThisTick == iLastTick) { iThisTick = SDL_GetTicks() / iGameSpeed; if ( iThisTick==iLastTick ) SDL_Delay(1); } // 2. Advance as many ticks as necessary.. int iNumTicks = iThisTick - iLastTick; if ( iNumTicks > MAXFRAMESKIP ) iNumTicks = MAXFRAMESKIP; Advance( iNumTicks ); dGameTime -= iNumTicks * iGameSpeed; // 3. Check for state transitions and game time. // START -> NORMAL // NORMAL -> KO // NORMAL -> TIMEUP // bHurryUp flag can be set during NORMAL phase if ( Ph_START == m_enGamePhase ) // Check for the end of the START phase { if ( dGameTime <= 0 ) { m_enGamePhase = Ph_NORMAL; dGameTime = (IsMaster() ? g_oState.m_iRoundLength : g_poNetwork->GetGameParams().iRoundLength) * 1000; } } else if ( Ph_NORMAL == m_enGamePhase ) // Check for the end of the NORMAL phase { if ( dGameTime < 10 * 1000 && !bHurryUp ) { bHurryUp = true; g_poNetwork->SendHurryup( 1 ); HurryUp(); iGameSpeed = iGameSpeed * 3 / 4; } if ( g_oBackend.m_bKO ) { m_enGamePhase = Ph_KO; dGameTime = 10 * 1000; iKoFrame = m_aReplayOffsets.size(); } else if ( dGameTime <= 0 ) { m_enGamePhase = Ph_TIMEUP; g_poNetwork->SendHurryup( 2 ); TimeUp(); break; } } m_iGameTime = (int) ((dGameTime + 500.0) / 1000.0); iLastTick = iThisTick; // ProcessEvents will read keyboard/gamepad input // It will also transmit them to the remote side in a network game. if ( ProcessEvents() || g_oState.m_bQuitFlag ) { bReplayAfter = false; break; } oFpsCounter.Tick(); // 3. Draw the next game screen.. Draw(); // 4. Check 'end of round' condition. for ( int i=0; i<g_oState.m_iNumPlayers; ++i ) { if ( g_oBackend.m_aoPlayers[i].m_iRealHitPoints <= -10000 ) { // We have a dead player here. if ( aiTeamNumber[i] < iTeamSize-1 ) { ++aiTeamNumber[i]; AddBodyToBackground( i ); FighterEnum enFighter = g_oPlayerSelect.GetPlayerInfo(i).m_aenTeam[ aiTeamNumber[i] ]; g_oPlayerSelect.SetPlayer( i, enFighter ); g_oBackend.PerlEvalF( "NextTeamMember(%d,%d);", i, enFighter ); } } } if ( g_oBackend.m_iGameOver ) { break; } if ( !IsMaster() ) { if ( g_poNetwork->IsRoundOver() ) { break; } } } int p1h = g_oBackend.m_aoPlayers[0].m_iRealHitPoints; int p2h = g_oBackend.m_aoPlayers[1].m_iRealHitPoints; // 3. DO THE REPLAY (IF THERE WAS A KO) if ( iKoFrame>0 && bReplayAfter && !IsNetworkGame() ) { InstantReplay( iKoFrame ); } // 4. END OF ROUND debug( "Game over; p1h = %d; p2h = %d\n", p1h, p2h ); if ( IsMaster() ) { int iWhoWon = -1; if ( p1h > p2h ) { ++m_aiRoundsWonByPlayer[0]; iWhoWon = 0; } if ( p2h > p1h ) { ++m_aiRoundsWonByPlayer[1]; iWhoWon = 1; } if ( IsNetworkGame() ) { g_poNetwork->SendGameTick( g_oBackend.m_iGameTick + m_iEnqueueDelay * 100 ); g_poNetwork->SendRoundOver( iWhoWon, m_iNumberOfRounds > 0 ); } } else { int iWhoWon = g_poNetwork->GetWhoWon(); if ( iWhoWon>=0 ) { ++m_aiRoundsWonByPlayer[iWhoWon]; } } ++m_iNumberOfRounds; }
/*-------------- main starts here --------------------------*/ extern Int2 Main (void) { RecT r1, r2; #ifdef WIN_MAC m = AppleMenu (NULL); DeskAccGroup(m); m = PulldownMenu(NULL, "File"); s = SubMenu(m, "Open"); i = CommandItem(m, "Quit/Q", QuitProc); #endif InitProc(GetArgc(), GetArgv()); w = RoundWindow(-50, -33, -10, -10, "PDBeast: Taxonomy Assignment", NULL); #ifndef WIN_MAC SetUpDrawingTools(); /* Red(); SetColor(5); */ InvertColors(); wpdb = RoundWindow(-53, -33, -10, -10, "PDB File Display", NULL); p = StaticPrompt(wpdb, "Pdb File", 0, dialogTextHeight, systemFont, '1'); Advance(wpdb); PdbOpen = DefaultButton(wpdb, "Open", PdbOpenProc); Break(wpdb); p = StaticPrompt(wpdb, "Blast Search", 0, dialogTextHeight, systemFont, '1'); Advance(wpdb); lBlastChain = SingleList(wpdb, 10, 3, ListBlastChainProc); Advance(wpdb); BlastSearchAccept = DefaultButton(wpdb, "Send Query", BlastSearchAcceptProc); Break(wpdb); p = StaticPrompt(wpdb, "String Search", 0, dialogTextHeight, systemFont, '1'); Advance(wpdb); Pdbfile_string = DialogText(wpdb, "", 15, NULL); Advance(wpdb); Pdbfile_string_accept = DefaultButton(wpdb, "Find", PdbfileStringAcceptProc); Break(wpdb); pdbfile_panel = DocumentPanel(wpdb, 650, 20*stdLineHeight); Break(wpdb); p = StaticPrompt(wpdb," ", 0, dialogTextHeight, systemFont, '1'); Advance(wpdb); PdbClose = PushButton(wpdb,"Close", PdbCloseProc); Break(wpdb); m = PulldownMenu(w, "File"); s1 = SubMenu(m, "Open"); i = CommandItem(s1, "Entry", EntryProc); s2 = SubMenu(s1, "List"); c = ChoiceGroup(s2, ListOpenProc); ChoiceItem(c, myargs[6].strvalue); /* s3 = SubMenu(m, "Update"); c = ChoiceGroup(s3, ListUpdateProc); ChoiceItem(c, myargs[6].strvalue); */ i = CommandItem(m, "Quit/Q", QuitProc); /* edit = PulldownMenu(w, "Edit"); i = CommandItem(edit, "cut", StdCutTextProc); i = CommandItem(edit, "copy", StdCopyTextProc); i = CommandItem(edit, "paste", StdPasteTextProc); */ #endif infilemode = NormalGroup(w, 3, 0, "Data Mode of Input Entry",systemFont, InFileTypeProc); RadioButton(infilemode, "Text"); RadioButton(infilemode, "Binary"); /* SafeSetValue(infilemode, 2); */ GetPosition(infilemode, &r1); outfilemode = NormalGroup(w, 3, 0, "Data Mode of Output Entry",systemFont, OutFileTypeProc); RadioButton(outfilemode, "Text"); RadioButton(outfilemode, "Binary"); /* SafeSetValue(outfilemode, 2); */ r2.top = r1.top; r2.bottom = r1.bottom; r2.left = r1.right + 80; r2. right = r2.left + r1.right - r1.left; SetPosition(outfilemode, &r2); Break(w); p = StaticPrompt(w, "Seq-entry", 0, dialogTextHeight, systemFont, '1'); Advance (w); l = SingleList(w, 20, 3, ListProc); Disable(l); Advance(w); ListEntry_start = DefaultButton(w, "Start", ListEntryStartProc); Disable(ListEntry_start); Advance(w); ListEntry_next = DefaultButton(w, "Next", ListEntryNextProc); Disable(ListEntry_next); Advance(w); ListEntry_specific = DefaultButton(w, "Specific", ListEntrySpecificProc); Disable(ListEntry_specific); Break(w); p = StaticPrompt(w, "Enter Entry Code", 0, dialogTextHeight, systemFont, '1'); Advance (w); Entry_code = DialogText(w, "", 15, (TxtActnProc) EnableProc); Select(Entry_code); Advance (w); Entry_accept = DefaultButton(w, "Open", EntryOpenProc); Disable(Entry_accept); Break(w); p = StaticPrompt(w, "Chain", 0, dialogTextHeight, systemFont, '1'); chain_panel = DocumentPanel(w, 200, stdLineHeight); Break(w); p = StaticPrompt(w, "Pdb Source:", 0, dialogTextHeight, systemFont, '1'); pdb_source = ScrollText(w, 38, 3, systemFont, TRUE, NULL); Advance(w); Break(w); p = StaticPrompt(w, "Taxonomy Data:", 0, dialogTextHeight, systemFont, '1'); org = DocumentPanel(w,400,6*stdLineHeight); Break(w); p = StaticPrompt(w, "Taxonomy Accept?", 0, dialogTextHeight, systemFont, '1'); Break(w); Tax_accept = DefaultButton(w, "Yes", TaxAcceptProc); Advance(w); p = StaticPrompt(w, "to ", 0, dialogTextHeight, systemFont, '1'); Advance(w); Tax_all_accept = DefaultButton(w, "All", TaxAllAcceptProc); Disable(Tax_all_accept); Advance(w); p = StaticPrompt(w, " or ", 0, dialogTextHeight, systemFont, '1'); Advance(w); Tax_part_accept = DefaultButton(w, "Chain", TaxPartAcceptProc); Disable(Tax_part_accept); Advance(w); lchain = SingleList(w, 2, 4, TaxPartAssignProc); Advance(w); Tax_finish = DefaultButton(w, "All Done", TaxFinishProc); Disable(Tax_finish); Break(w); Tax_reject = DefaultButton(w, "No", ReLookupProc); Disable(Tax_accept); Disable(Tax_reject); Break(w); p = StaticPrompt(w, "Look up Taxonomy Database with another String?", 0, dialogTextHeight, systemFont, '1'); Advance(w); ReLookup_accept = DefaultButton(w, "Yes", AddStringProc); Advance(w); ReLookup_reject = DefaultButton(w, "No", ReLookupRejectProc); Disable(ReLookup_accept); Disable(ReLookup_reject); Break(w); p = StaticPrompt(w,"Search Taxonomy Database with", 0, dialogTextHeight, systemFont, '1'); Advance(w); Source_string = DialogText(w, "", 15, NULL); Advance(w); Source_string_accept = DefaultButton(w, "Start", SourceStringAcceptProc); Disable(Source_string_accept); Break(w); Show(w); Show(wpdb); ProcessEvents(); return 0; }
bool MD5AnimParser::ParseHierarchy() { unsigned int jointCount = m_joints.size(); if (jointCount == 0) { Error("Joint count is invalid or missing"); return false; } for (unsigned int i = 0; i < jointCount; ++i) { if (!Advance()) return false; unsigned int pos = m_currentLine.Find(' '); if (pos == String::npos) { UnrecognizedLine(true); return false; } if (pos >= 64) { NazaraError("Joint name is too long (>= 64 characters)"); return false; } char name[64]; if (std::sscanf(&m_currentLine[0], "%63s %d %u %u", &name[0], &m_joints[i].parent, &m_joints[i].flags, &m_joints[i].index) != 4) { UnrecognizedLine(true); return false; } m_joints[i].name = name; m_joints[i].name.Trim('"'); int parent = m_joints[i].parent; if (parent >= 0) { if (static_cast<unsigned int>(parent) >= jointCount) { Error("Joint's parent is out of bounds (" + String::Number(parent) + " >= " + String::Number(jointCount) + ')'); return false; } } } if (!Advance()) return false; if (m_currentLine != '}') { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING Warning("Hierarchy braces closing not found"); #endif // On tente de survivre à l'erreur m_keepLastLine = true; } return true; }
bool MD5AnimParser::Parse() { while (Advance(false)) { switch (m_currentLine[0]) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING case 'M': // MD5Version if (m_currentLine.GetWord(0) != "MD5Version") UnrecognizedLine(); break; #endif case 'b': // baseframe/bounds if (m_currentLine.StartsWith("baseframe {")) { if (!ParseBaseframe()) { Error("Failed to parse baseframe"); return false; } } else if (m_currentLine.StartsWith("bounds {")) { if (!ParseBounds()) { Error("Failed to parse bounds"); return false; } } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif break; #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING case 'c': // commandline if (m_currentLine.GetWord(0) != "commandline") UnrecognizedLine(); break; #endif case 'f': { unsigned int index; if (std::sscanf(&m_currentLine[0], "frame %u {", &index) == 1) { if (m_frameIndex != index) { Error("Unexpected frame index (expected " + String::Number(m_frameIndex) + ", got " + String::Number(index) + ')'); return false; } if (!ParseFrame()) { Error("Failed to parse frame"); return false; } m_frameIndex++; } else if (std::sscanf(&m_currentLine[0], "frameRate %u", &m_frameRate) != 1) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING UnrecognizedLine(); #endif } break; } case 'h': // hierarchy if (m_currentLine.StartsWith("hierarchy {")) { if (!ParseHierarchy()) { Error("Failed to parse hierarchy"); return false; } } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif break; case 'n': // num[Frames/Joints] { unsigned int count; if (std::sscanf(&m_currentLine[0], "numAnimatedComponents %u", &count) == 1) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!m_animatedComponents.empty()) Warning("Animated components count is already defined"); #endif m_animatedComponents.resize(count); } else if (std::sscanf(&m_currentLine[0], "numFrames %u", &count) == 1) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!m_frames.empty()) Warning("Frame count is already defined"); #endif m_frames.resize(count); } else if (std::sscanf(&m_currentLine[0], "numJoints %u", &count) == 1) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!m_joints.empty()) Warning("Joint count is already defined"); #endif m_joints.resize(count); } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif break; } default: #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING UnrecognizedLine(); #endif break; } } unsigned int frameCount = m_frames.size(); if (frameCount == 0) { NazaraError("Frame count is invalid or missing"); return false; } unsigned int jointCount = m_joints.size(); if (jointCount == 0) { NazaraError("Joint count is invalid or missing"); return false; } if (m_frameIndex != frameCount) { NazaraError("Missing frame infos: [" + String::Number(m_frameIndex) + ',' + String::Number(frameCount) + ']'); return false; } if (m_frameRate == 0) { NazaraWarning("Framerate is either invalid or missing, assuming a default value of 24"); m_frameRate = 24; } return true; }
ExprAST * FAO::ParseNumberExpr() { ExprAST * result = new IntegerExpr(cur_token_.GetValue()); Advance(); return result; }
bool MD5AnimParser::ParseFrame() { unsigned int animatedComponentsCount = m_animatedComponents.size(); if (animatedComponentsCount == 0) { Error("Animated components count is missing or invalid"); return false; } unsigned int jointCount = m_joints.size(); if (jointCount == 0) { Error("Joint count is invalid or missing"); return false; } String line; unsigned int count = 0; do { if (!Advance()) return false; unsigned int index = 0; unsigned int size = m_currentLine.GetSize(); do { float f; int read; if (std::sscanf(&m_currentLine[index], "%f%n", &f, &read) != 1) { UnrecognizedLine(true); return false; } index += read; m_animatedComponents[count] = f; count++; } while (index < size); } while (count < animatedComponentsCount); m_frames[m_frameIndex].joints.resize(jointCount); for (unsigned int i = 0; i < jointCount; ++i) { Quaternionf jointOrient = m_joints[i].bindOrient; Vector3f jointPos = m_joints[i].bindPos; unsigned int j = 0; if (m_joints[i].flags & 1) // Px jointPos.x = m_animatedComponents[m_joints[i].index + j++]; if (m_joints[i].flags & 2) // Py jointPos.y = m_animatedComponents[m_joints[i].index + j++]; if (m_joints[i].flags & 4) // Pz jointPos.z = m_animatedComponents[m_joints[i].index + j++]; if (m_joints[i].flags & 8) // Qx jointOrient.x = m_animatedComponents[m_joints[i].index + j++]; if (m_joints[i].flags & 16) // Qy jointOrient.y = m_animatedComponents[m_joints[i].index + j++]; if (m_joints[i].flags & 32) // Qz jointOrient.z = m_animatedComponents[m_joints[i].index + j++]; jointOrient.ComputeW(); m_frames[m_frameIndex].joints[i].orient = jointOrient; m_frames[m_frameIndex].joints[i].pos = jointPos; } if (!Advance(false)) return true; if (m_currentLine != '}') { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING Warning("Hierarchy braces closing not found"); #endif // On tente de survivre à l'erreur m_keepLastLine = true; } return true; }
/// <summary>Read the section handler section.</summary> /// <remarks>All 'Small' sections are to be converted to 'Fat' sections.</remarks> void Method::ReadSections() { if ((m_header.Flags & CorILMethod_MoreSects) == CorILMethod_MoreSects) { BYTE flags = 0; do { Align<DWORD>(); // must be DWORD aligned flags = Read<BYTE>(); _ASSERTE((flags & CorILMethod_Sect_EHTable) == CorILMethod_Sect_EHTable); if ((flags & CorILMethod_Sect_FatFormat) == CorILMethod_Sect_FatFormat) { Advance(-1); int count = ((Read<ULONG>() >> 8) / 24); for (int i = 0; i < count; i++) { CorExceptionFlag type = (CorExceptionFlag)Read<ULONG>(); long tryStart = Read<long>(); long tryEnd = Read<long>(); long handlerStart = Read<long>(); long handlerEnd = Read<long>(); long filterStart = 0; ULONG token = 0; switch (type) { case COR_ILEXCEPTION_CLAUSE_FILTER: filterStart = Read<long>(); break; default: token = Read<ULONG>(); break; } ExceptionHandler * pSection = new ExceptionHandler(); pSection->m_handlerType = type; pSection->m_tryStart = GetInstructionAtOffset(tryStart); pSection->m_tryEnd = GetInstructionAtOffset(tryStart + tryEnd); pSection->m_handlerStart = GetInstructionAtOffset(handlerStart); pSection->m_handlerEnd = GetInstructionAtOffset(handlerStart + handlerEnd, (type & COR_ILEXCEPTION_CLAUSE_FINALLY) == COR_ILEXCEPTION_CLAUSE_FINALLY); if (filterStart!=0) { pSection->m_filterStart = GetInstructionAtOffset(filterStart); } pSection->m_token = token; m_exceptions.push_back(pSection); } } else { int count = (int)(Read<BYTE>() / 12); Advance(2); for (int i = 0; i < count; i++) { CorExceptionFlag type = (CorExceptionFlag)Read<USHORT>(); long tryStart = Read<USHORT>(); long tryEnd = Read<BYTE>(); long handlerStart = Read<USHORT>(); long handlerEnd = Read<BYTE>(); long filterStart = 0; ULONG token = 0; switch (type) { case COR_ILEXCEPTION_CLAUSE_FILTER: filterStart = Read<long>(); break; default: token = Read<ULONG>(); break; } ExceptionHandler * pSection = new ExceptionHandler(); pSection->m_handlerType = type; pSection->m_tryStart = GetInstructionAtOffset(tryStart); pSection->m_tryEnd = GetInstructionAtOffset(tryStart + tryEnd); pSection->m_handlerStart = GetInstructionAtOffset(handlerStart); pSection->m_handlerEnd = GetInstructionAtOffset(handlerStart + handlerEnd, (type & COR_ILEXCEPTION_CLAUSE_FINALLY) == COR_ILEXCEPTION_CLAUSE_FINALLY); if (filterStart!=0) { pSection->m_filterStart = GetInstructionAtOffset(filterStart); } pSection->m_token = token; m_exceptions.push_back(pSection); } } } while((flags & CorILMethod_Sect_MoreSects) == CorILMethod_Sect_MoreSects);
void begin (int argc, const char * argv[]) { size_t infile; size_t n_fields; size_t field; size_t n_params; size_t param; const char * comment; infile = Infile ("-"); File_fix (infile, 1, 0); puts ("#: taql-0.1/text"); n_fields = N_fields (infile); for (field = 0; field < n_fields; ++field) { fputs ("# field ", stdout); Fprint (stdout, Field_name (infile, field)); fputs (" ", stdout); Fprint (stdout, Field_type (infile, field)); fputc ('\n', stdout); } n_params = N_params (infile); for (param = 0; param < n_params; ++param) { fputs ("# param ", stdout); Fprint (stdout, Param_name (infile, param)); fputs (" ", stdout); Fprint (stdout, Param_value (infile, param)); fputc ('\n', stdout); } comment = Comment (infile); if (!comment || !comment[0]) { fputs ("#.\n", stdout); } else { const char * c; fputs ("#-\n# ", stdout); for (c = comment; *c; ++c) { if (*c == '\n') fputs ("\n# ", stdout); else fputc (*c, stdout); } fputs ("\n#.\n", stdout); } while (N_ahead (infile)) { for (field = 0; field < n_fields; ++field) { if (field) fputc (' ', stdout); Fprint (stdout, Peek (infile, 0, field)); } fputc ('\n', stdout); Advance (infile, 1); } }
int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); /** Application variable */ std::vector<float> myFloats = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<int> myInts = {0, -1, -2, -3, -4, -5, -6, -7, -8, -9}; const std::size_t Nx = myFloats.size(); try { /** ADIOS class factory of IO class objects, DebugON is recommended */ adios2::ADIOS adios(MPI_COMM_WORLD, adios2::DebugON); /*** IO class object: settings and factory of Settings: Variables, * Parameters, Transports, and Execution: Engines */ adios2::IO &bpIO = adios.DeclareIO("BPFile_N2N"); /// Setting flush policy // the user can set the memory explicitly for ADIOS (more advance users) bpIO.SetSingleParameter("MaxBufferSize", "100Mb"); // or by number of steps (naively trying to allocate "N=3" steps before // flushing // bpIO.SetSingleParameter("StepsToBuffer", "3"); /** global array : name, { shape (total) }, { start (local) }, { * count * (local) }, all are constant dimensions */ adios2::Variable<float> &bpFloats = bpIO.DefineVariable<float>( "bpFloats", {size * Nx}, {rank * Nx}, {Nx}, adios2::ConstantDims); adios2::Variable<int> &bpInts = bpIO.DefineVariable<int>( "bpInts", {size * Nx}, {rank * Nx}, {Nx}, adios2::ConstantDims); /** Engine derived class, spawned to start IO operations */ /** Deferred Mode: Write buffering will be done at Put(), the user makes * the commitment that pointers passed at Write won't be reused */ auto bpWriter = bpIO.Open("myVector.bp", adios2::Mode::Write | adios2::Mode::Deferred); // default = 0, in bp1 format this is translated to 1, but user should // be able to start at any step bpWriter.SetStep(1); /** Write variable for buffering */ for (unsigned int t = 0; t < 100; ++t) { bpWriter.Write<float>(bpFloats, myFloats.data()); bpWriter.Write<int>(bpInts, myInts.data()); bpWriter.Advance(); // advances step if (t % 10 == 0) // checkpoint/restart every 10 steps, force flush { bpWriter.Flush(); } } /** Engine becomes unreachable after Close */ bpWriter.Close(); } catch (std::invalid_argument &e) { std::cout << "Invalid argument exception, STOPPING PROGRAM from rank " << rank << "\n"; std::cout << e.what() << "\n"; } catch (std::ios_base::failure &e) { std::cout << "IO System base failure exception, STOPPING PROGRAM " "from rank " << rank << "\n"; std::cout << e.what() << "\n"; } catch (std::exception &e) { std::cout << "Exception, STOPPING PROGRAM from rank " << rank << "\n"; std::cout << e.what() << "\n"; } MPI_Finalize(); return 0; }
/** * @brief Creates logical tiles from the two input logical tiles after applying * join predicate. * @return true on success, false otherwise. */ bool MergeJoinExecutor::DExecute() { LOG_INFO( "********** Merge Join executor :: 2 children " "left:: start: %lu, end: %lu, done: %d " "right:: start: %lu, end: %lu, done: %d", left_start_row, left_end_row, left_child_done_, right_start_row, right_end_row, right_child_done_); // Build outer join output when done if (right_child_done_ && left_child_done_) { return BuildOuterJoinOutput(); } //===--------------------------------------------------------------------===// // Pick right and left tiles //===--------------------------------------------------------------------===// // Try to get next tile from RIGHT child if (((right_child_done_ == false) && (right_start_row == right_end_row)) || (left_child_done_ == true)) { if (children_[1]->Execute() == false) { LOG_TRACE("Did not get right tile "); right_child_done_ = true; // Try again return DExecute(); } LOG_TRACE("Got right tile "); auto right_tile = children_[1]->GetOutput(); BufferRightTile(right_tile); right_start_row = 0; right_end_row = Advance(right_tile, right_start_row, false); LOG_TRACE("size of right tiles: %lu", right_result_tiles_.size()); } // Try to get next tile from LEFT child if (((left_child_done_ == false) && (left_start_row == left_end_row)) || (right_child_done_ == true)) { if (children_[0]->Execute() == false) { LOG_TRACE("Did not get left tile "); left_child_done_ = true; // Try again return DExecute(); } LOG_TRACE("Got left tile "); auto left_tile = children_[0]->GetOutput(); BufferLeftTile(left_tile); left_start_row = 0; left_end_row = Advance(left_tile, left_start_row, true); LOG_TRACE("size of left tiles: %lu", left_result_tiles_.size()); } // Check if we have logical tiles to process if(left_result_tiles_.empty() || right_result_tiles_.empty()) { return false; } LogicalTile *left_tile = left_result_tiles_.back().get(); LogicalTile *right_tile = right_result_tiles_.back().get(); //===--------------------------------------------------------------------===// // Build Join Tile //===--------------------------------------------------------------------===// // Build output logical tile auto output_tile = BuildOutputLogicalTile(left_tile, right_tile); // Build position lists LogicalTile::PositionListsBuilder pos_lists_builder(left_tile, right_tile); while ((left_end_row > left_start_row) && (right_end_row > right_start_row)) { expression::ContainerTuple<executor::LogicalTile> left_tuple( left_tile, left_start_row); expression::ContainerTuple<executor::LogicalTile> right_tuple( right_tile, right_start_row); bool not_matching_tuple_pair = false; // Evaluate and compare the join clauses for (auto &clause : *join_clauses_) { auto left_value = clause.left_->Evaluate(&left_tuple, &right_tuple, nullptr); auto right_value = clause.right_->Evaluate(&left_tuple, &right_tuple, nullptr); // Compare the values int comparison = left_value.Compare(right_value); // Left key < Right key, advance left if (comparison < 0) { LOG_TRACE("left < right, advance left "); left_start_row = left_end_row; left_end_row = Advance(left_tile, left_start_row, true); not_matching_tuple_pair = true; break; } // Left key > Right key, advance right else if (comparison > 0) { LOG_TRACE("left > right, advance right "); right_start_row = right_end_row; right_end_row = Advance(right_tile, right_start_row, false); not_matching_tuple_pair = true; break; } // Left key == Right key, go and check next join clause } // Atleast one of the join clauses don't match // One of the tile has been advanced if (not_matching_tuple_pair) { continue; } // Join clauses matched, try to match predicate LOG_TRACE("one pair of tuples matches join clause "); // Join predicate exists if (predicate_ != nullptr) { if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_) .IsFalse()) { // Join predicate is false. Advance both. left_start_row = left_end_row; left_end_row = Advance(left_tile, left_start_row, true); right_start_row = right_end_row; right_end_row = Advance(right_tile, right_start_row, false); } } // Sub tile matched, do a Cartesian product // Go over every pair of tuples in left and right logical tiles for (size_t left_tile_row_itr = left_start_row; left_tile_row_itr < left_end_row; left_tile_row_itr++) { for (size_t right_tile_row_itr = right_start_row; right_tile_row_itr < right_end_row; right_tile_row_itr++) { // Insert a tuple into the output logical tile pos_lists_builder.AddRow(left_tile_row_itr, right_tile_row_itr); RecordMatchedLeftRow(left_result_tiles_.size() - 1, left_tile_row_itr); RecordMatchedRightRow(right_result_tiles_.size() - 1, right_tile_row_itr); } } // Then, advance both left_start_row = left_end_row; left_end_row = Advance(left_tile, left_start_row, true); right_start_row = right_end_row; right_end_row = Advance(right_tile, right_start_row, false); } // Check if we have any join tuples. if (pos_lists_builder.Size() > 0) { output_tile->SetPositionListsAndVisibility(pos_lists_builder.Release()); SetOutput(output_tile.release()); return true; } // Try again else { // If we are out of any more pairs of child tiles to examine, // then we will return false earlier in this function // So, no need to return false here DExecute(); } return true; }
char *CanonPathname (char *pathname) { char *temp; char *canon = NULL; char *src; int error = 0; if ((temp = KMalloc (MAX_PATHNAME_SZ)) != NULL) { if (CopyInStr (current_process->user_as, temp, pathname, MAX_PATHNAME_SZ) == 0) { if ((canon = KMalloc (MAX_PATHNAME_SZ)) != NULL) { *canon = '\0'; if (*temp != '/') { StrLCpy (canon, current_process->current_dir, MAX_PATHNAME_SZ); src = temp; } else { src = Advance (temp); } while (*src != '\0') { if (CompareComponent("..", src) == 0) { if (DeleteLastComponent(canon) != 0) { SetError(ENOENT); error = -1; break; } } else if (CompareComponent(".", src) != 0) { if (AppendComponent (canon, src) != 0) { SetError(ENAMETOOLONG); error = -1; break; } } src = Advance (src); } if (error == 0) { if (*canon == '\0') StrLCpy (canon, "/", MAX_PATHNAME_SZ); } else { KFree (canon); } } else error = -1; } else error = -1; KFree (temp); } if (error == -1) return NULL; else return canon; }
/* ************************* Header and message ************************* */ void DebugApi::Header (const char *pDataChar, int pType) { if (!mOk) return; switch (pType) { // Ok case (1): { // Line LOG_PRINT(" "); LOG_PRINT(" [ OK ] "); Advance (); LOG_PRINT("%c\n", pDataChar); break; } // Error case (2): { // Line LOG_PRINT(" "); LOG_PRINT(" [ ERROR ] "); Advance (); LOG_PRINT("%c\n", pDataChar); // If we are inside a BEGIN / END, we go out if (mDepth > 0) { // Going back mDepth -= ESP; // Close bracket //LOG_PRINT(""); "; Advance (); LOG_PRINT("}\n"); // Line WriteTime (); LOG_PRINT(" [ END ] "); Advance (); LOG_PRINT("Error occurred"); // Measure the time between BEGIN and END unsigned long mElapsedTime = timeGetTime() - mTableTime [(mDepth + ESP) / ESP]; if (mElapsedTime < 0) mElapsedTime = 0; // Medida de seguridad LOG_PRINT(" [Elaped time = %d seg]\n", mElapsedTime * 0.001f); // Line jump after BEGIN/END if (!mDepth) { LOG_PRINT("---------------------------------------------------------------------\n"); } } break; } // Info // Info dosen't make a line jump in order DataChar and DataInt could write just after that line case (3): { // Line LOG_PRINT(" "); LOG_PRINT(" [ INFO ] "); Advance (); LOG_PRINT("%c", pDataChar); break; } // Warning case (4): { // Line LOG_PRINT(" "); LOG_PRINT(" [WARNING] "); Advance (); LOG_PRINT("%c\n", pDataChar); break; } // Begin case (5): { // Line WriteTime (); LOG_PRINT(" [ BEGIN ] "); Advance (); LOG_PRINT("-- %c --\n", pDataChar); // Open brackets LOG_PRINT(" "); Advance (); LOG_PRINT("{\n"); // Advance mDepth += ESP; // Store the current time in the time table mTableTime [mDepth / ESP] = timeGetTime(); break; } // End case (6): { // Going back mDepth -= ESP; // Close bracket LOG_PRINT(" "); Advance (); LOG_PRINT("}\n"); // Line WriteTime (); LOG_PRINT(" [ END ] "); Advance (); LOG_PRINT("%c", pDataChar); // Measure the time between BEGIN and END unsigned long mElapsedTime = timeGetTime() - mTableTime [(mDepth + ESP) / ESP]; if (mElapsedTime < 0) mElapsedTime = 0; // Security Measure LOG_PRINT(" [Elapsed time = %d seg]\n", mElapsedTime * 0.001f); // Line jump after BEGIN/END if (!mDepth) { LOG_PRINT("---------------------------------------------------------------------\n"); } break; } } }
bool MTLParser::Parse(Stream& stream) { m_currentStream = &stream; // Force stream in text mode, reset it at the end Nz::CallOnExit resetTextMode; if ((stream.GetStreamOptions() & StreamOption_Text) == 0) { stream.EnableTextMode(true); resetTextMode.Reset([&stream] () { stream.EnableTextMode(false); }); } m_keepLastLine = false; m_lineCount = 0; m_materials.clear(); Material* currentMaterial = nullptr; while (Advance(false)) { String keyword = m_currentLine.GetWord(0).ToLower(); if (keyword == "ka") { float r, g, b; if (std::sscanf(&m_currentLine[3], "%f %f %f", &r, &g, &b) == 3) { if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->ambient = Color(static_cast<UInt8>(r*255.f), static_cast<UInt8>(g*255.f), static_cast<UInt8>(b*255.f)); } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } else if (keyword == "kd") { float r, g, b; if (std::sscanf(&m_currentLine[3], "%f %f %f", &r, &g, &b) == 3) { if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->diffuse = Color(static_cast<UInt8>(r*255.f), static_cast<UInt8>(g*255.f), static_cast<UInt8>(b*255.f)); } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } else if (keyword == "ks") { float r, g, b; if (std::sscanf(&m_currentLine[3], "%f %f %f", &r, &g, &b) == 3) { if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->specular = Color(static_cast<UInt8>(r*255.f), static_cast<UInt8>(g*255.f), static_cast<UInt8>(b*255.f)); } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } else if (keyword == "ni") { float density; if (std::sscanf(&m_currentLine[3], "%f", &density) == 1) { if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->refractionIndex = density; } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } else if (keyword == "ns") { float coef; if (std::sscanf(&m_currentLine[3], "%f", &coef) == 1) { if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->shininess = coef; } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } else if (keyword == 'd') { float alpha; if (std::sscanf(&m_currentLine[(keyword[0] == 'd') ? 2 : 3], "%f", &alpha) == 1) { if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->alpha = alpha; } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } else if (keyword == "tr") { float alpha; if (std::sscanf(&m_currentLine[(keyword[0] == 'd') ? 2 : 3], "%f", &alpha) == 1) { if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->alpha = 1.f - alpha; // tr vaut pour la "valeur de transparence", 0 = opaque } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } else if (keyword == "illum") { unsigned int model; if (std::sscanf(&m_currentLine[6], "%u", &model) == 1) { if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->illumModel = model; } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } else if (keyword == "map_ka") { std::size_t mapPos = m_currentLine.GetWordPosition(1); if (mapPos != String::npos) { String map = m_currentLine.SubString(mapPos); if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->ambientMap = map; } } else if (keyword == "map_kd") { std::size_t mapPos = m_currentLine.GetWordPosition(1); if (mapPos != String::npos) { String map = m_currentLine.SubString(mapPos); if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->diffuseMap = map; } } else if (keyword == "map_ks") { std::size_t mapPos = m_currentLine.GetWordPosition(1); if (mapPos != String::npos) { String map = m_currentLine.SubString(mapPos); if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->specularMap = map; } } else if (keyword == "map_bump" || keyword == "bump") { std::size_t mapPos = m_currentLine.GetWordPosition(1); if (mapPos != String::npos) { String map = m_currentLine.SubString(mapPos); if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->bumpMap = map; } } else if (keyword == "map_d") { std::size_t mapPos = m_currentLine.GetWordPosition(1); if (mapPos != String::npos) { String map = m_currentLine.SubString(mapPos); if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->alphaMap = map; } } else if (keyword == "map_decal" || keyword == "decal") { std::size_t mapPos = m_currentLine.GetWordPosition(1); if (mapPos != String::npos) { String map = m_currentLine.SubString(mapPos); if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->decalMap = map; } } else if (keyword == "map_disp" || keyword == "disp") { std::size_t mapPos = m_currentLine.GetWordPosition(1); if (mapPos != String::npos) { String map = m_currentLine.SubString(mapPos); if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->displacementMap = map; } } else if (keyword == "map_refl" || keyword == "refl") { std::size_t mapPos = m_currentLine.GetWordPosition(1); if (mapPos != String::npos) { String map = m_currentLine.SubString(mapPos); if (!currentMaterial) currentMaterial = AddMaterial("default"); currentMaterial->reflectionMap = map; } } else if (keyword == "newmtl") { String materialName = m_currentLine.SubString(m_currentLine.GetWordPosition(1)); if (!materialName.IsEmpty()) currentMaterial = AddMaterial(materialName); #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING else UnrecognizedLine(); #endif } return true; }
void EatSpace() { while (index < length && IsSpace(Current())) Advance(); }
/** Advances to the next vertex */ void operator++() { Advance(); }
BOOL CALLBACK SearchCallback(HWND hDlg, UINT uMsg, WPARAM wPar, LPARAM lPar) { extern BOOL SearchBoxPosition, HexEditTextSide; extern INT SearchBoxX, SearchBoxY; static RECT DlgRect; static BOOL Enabled; static CHAR CloseString[10]; PARAM_NOT_USED(lPar); switch (uMsg) { RECT r; case WM_INITDIALOG: GetWindowRect(hDlg, &DlgRect); GetWindowRect(GetDlgItem(hDlg, IDC_REPLACE), &r); SetWindowPos(hDlg, 0, SearchBoxX, SearchBoxY, DlgRect.right - DlgRect.left, r.top - DlgRect.top, SearchBoxPosition ? SWP_NOZORDER : SWP_NOZORDER | SWP_NOMOVE); SendMessage(hDlg, DM_REPOSITION, 0, 0); EnableWindow(GetDlgItem(hDlg, IDC_SHOWREPLACE), FALSE); if (HexInput != (HexEditMode && !HexEditTextSide)) { HexInput ^= TRUE; *SearchBuf = '\0'; } if (SelectCount && (HexInput ? 3 : 1) * SelectCount < WSIZE(SearchBuf)) { POSITION SelPos; INT i, c; PWSTR p = SearchBuf; SelPos = SelectStart; for (i=(INT)SelectCount; i; --i) { if (HexInput) { c = ByteAt(&SelPos); if (Advance(&SelPos, 1) != 1) break; if (UtfEncoding == 16 && i > 1) { if (UtfLsbFirst) c |= ByteAt(&SelPos) << 8; else c = (c << 8) | ByteAt(&SelPos); if (Advance(&SelPos, 1) != 1) break; --i; } p += _snwprintf(p, WSIZE(SearchBuf) - (p-SearchBuf), UtfEncoding == 16 ? L"%04x " : L"%02x ", c); } else { if ((c = CharAt(&SelPos)) == C_CRLF) c = '\r'; else if (!UtfEncoding) c = CharSetToUnicode(c); if (UtfEncoding == 16) { if (i > 1) --i; if (Advance(&SelPos, 2) != 2) break; } else if (Advance(&SelPos, 1) != 1) break; *p++ = c; } } if (HexInput) --p; *p = '\0'; if (*SearchBuf && !ViewOnlyFlag) EnableWindow(GetDlgItem(hDlg, IDC_SHOWREPLACE), TRUE); } else { PWSTR p; if ((p = ExtractIdentifier(NULL)) != NULL) wcsncpy(SearchBuf, p, WSIZE(SearchBuf)); } Enabled = *SearchBuf!='\0'; if (Enabled) { EnableWindow(GetDlgItem(hDlg, IDOK), TRUE); SetDlgItemTextW(hDlg, IDC_SEARCHSTRING, SearchBuf); SendMessage(hDlg, DM_SETDEFID, IDOK, 0L); } else { SendMessage(hDlg, DM_SETDEFID, IDCANCEL, 0L); EnableWindow(GetDlgItem(hDlg, IDOK), FALSE); } EnableWindow(GetDlgItem(hDlg, IDC_REPLACESTRING), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_REPLACE), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_REPLACEALL), FALSE); CheckDlgButton(hDlg, *SrchDispBuf=='?' ? IDC_BACKWARD : IDC_FORWARD, TRUE); CheckDlgButton(hDlg, IDC_MATCHCASE, !IgnoreCaseFlag); CheckDlgButton(hDlg, IDC_MAGIC, Magic); CheckDlgButton(hDlg, IDC_HEXSEARCH, HexInput); CheckDlgButton(hDlg, IDC_WHOLEWORD, WholeWord); CheckDlgButton(hDlg, IDC_WRAPSCAN, WrapScanFlag); LOADSTRING(hInst, 909, CloseString, sizeof(CloseString)); ReplaceOpen = FALSE; PostMessage(hDlg, WM_COMMAND, 4569, 0); /*for Wine*/ return (TRUE); case WM_COMMAND: switch (COMMAND) { case 4569: /*Disable/enable again for Wine...*/ EnableWindow(GetDlgItem(hDlg, IDOK), Enabled); break; case IDOK: SearchOk(hDlg); break; case IDCANCEL: if (ReplacingAll) Interrupted = TRUE; PostMessage(hDlg, WM_CLOSE, 0, 0); break; case IDC_SEARCHSTRING: GetDlgItemTextW(hDlg, IDC_SEARCHSTRING, CommandBuf, 4); if (Enabled != (*CommandBuf != '\0')) { if (Enabled ^= TRUE) { EnableWindow(GetDlgItem(hDlg, IDOK), TRUE); SendMessage(hDlg, DM_SETDEFID, IDOK, 0L); } else { SendMessage(hDlg, DM_SETDEFID, IDCANCEL, 0L); EnableWindow(GetDlgItem(hDlg, IDOK), FALSE); } if (ReplaceOpen) { EnableWindow(GetDlgItem(hDlg,IDC_REPLACE), Enabled); EnableWindow(GetDlgItem(hDlg,IDC_REPLACEALL),Enabled); } } break; case IDC_SHOWREPLACE: EnableWindow(GetDlgItem(hDlg, IDC_REPLACESTRING), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_REPLACE), SelectCount!=0); EnableWindow(GetDlgItem(hDlg, IDC_REPLACEALL), TRUE); SetWindowPos(hDlg, 0,0,0, DlgRect.right-DlgRect.left, DlgRect.bottom-DlgRect.top, SWP_NOZORDER | SWP_NOMOVE); SendMessage(hDlg, DM_REPOSITION, 0, 0); SetFocus(GetDlgItem(hDlg, IDC_REPLACESTRING)); SendMessage(hDlg, DM_SETDEFID, IDC_REPLACE, 0L); EnableWindow(GetDlgItem(hDlg, IDC_SHOWREPLACE), FALSE); ReplaceOpen = TRUE; break; case IDC_REPLACE: ReplaceSearched(hDlg); SetDlgItemText(hDlg, IDCANCEL, CloseString); break; case IDC_REPLACEALL: SetupSearchString(hDlg, NULL); GlobalSubst(hDlg); SetDlgItemText(hDlg, IDCANCEL, CloseString); } return (TRUE); case WM_MOVE: case WM_CLOSE: SearchBoxPosition = TRUE; GetWindowRect(hDlg, &r); SearchBoxX = r.left; SearchBoxY = r.top; if (uMsg == WM_CLOSE) { DestroyWindow(hDlg); hwndSearch = NULL; } return (TRUE); } return (FALSE); }
/** * Scan a unicode-range token. These match the regular expression * * u\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})? * * However, some such tokens are "invalid". There are three valid forms: * * u+[0-9a-f]{x} 1 <= x <= 6 * u+[0-9a-f]{x}\?{y} 1 <= x+y <= 6 * u+[0-9a-f]{x}-[0-9a-f]{y} 1 <= x <= 6, 1 <= y <= 6 * * All unicode-range tokens have their text recorded in mIdent; valid ones * are also decoded into mInteger and mInteger2, and mIntegerValid is set. * Note that this does not validate the numeric range, only the syntactic * form. */ bool nsCSSScanner::ScanURange(nsCSSToken& aResult) { int32_t intro1 = Peek(); int32_t intro2 = Peek(1); int32_t ch = Peek(2); MOZ_ASSERT((intro1 == 'u' || intro1 == 'U') && intro2 == '+' && (IsHexDigit(ch) || ch == '?'), "should not have been called"); aResult.mIdent.Append(intro1); aResult.mIdent.Append(intro2); Advance(2); bool valid = true; bool haveQues = false; uint32_t low = 0; uint32_t high = 0; int i = 0; do { aResult.mIdent.Append(ch); if (IsHexDigit(ch)) { if (haveQues) { valid = false; // All question marks should be at the end. } low = low*16 + HexDigitValue(ch); high = high*16 + HexDigitValue(ch); } else { haveQues = true; low = low*16 + 0x0; high = high*16 + 0xF; } i++; Advance(); ch = Peek(); } while (i < 6 && (IsHexDigit(ch) || ch == '?')); if (ch == '-' && IsHexDigit(Peek(1))) { if (haveQues) { valid = false; } aResult.mIdent.Append(ch); Advance(); ch = Peek(); high = 0; i = 0; do { aResult.mIdent.Append(ch); high = high*16 + HexDigitValue(ch); i++; Advance(); ch = Peek(); } while (i < 6 && IsHexDigit(ch)); } aResult.mInteger = low; aResult.mInteger2 = high; aResult.mIntegerValid = valid; aResult.mType = eCSSToken_URange; return true; }
result_t ParseJsonString(v8::Local<v8::Value> &retVal) { wstring str; Advance(); while (c0_ != '"') { if (c0_ >= 0 && c0_ < 0x20) return ReportUnexpectedCharacter(); if (c0_ != '\\') { int32_t beg_pos = position_; while (c0_ != '"' && c0_ != '\\') { Advance(); if (c0_ >= 0 && c0_ < 0x20) return ReportUnexpectedCharacter(); } str.append(utf8to16String(source_ + beg_pos, position_ - beg_pos)); } else { Advance(); switch (c0_) { case '"': case '\\': case '/': str.append(1, c0_); break; case 'b': str.append(1, '\x08'); break; case 'f': str.append(1, '\x0c'); break; case 'n': str.append(1, '\x0a'); break; case 'r': str.append(1, '\x0d'); break; case 't': str.append(1, '\x09'); break; case 'u': { uint16_t value = 0; for (int32_t i = 0; i < 4; i++) { Advance(); if (!qisxdigit(c0_)) return ReportUnexpectedCharacter(); value = value * 16 + qhex(c0_); } str.append(1, value); break; } default: return ReportUnexpectedCharacter(); } Advance(); } } AdvanceSkipWhitespace(); retVal = v8::String::NewFromTwoByte(isolate->m_isolate, (const uint16_t*)str.c_str(), v8::String::kNormalString, (int32_t) str.length()); return 0; }
/** * If there is a valid escape sequence starting at the current read * position, consume it, decode it, append the result to |aOutput|, * and return true. Otherwise, consume nothing, leave |aOutput| * unmodified, and return false. If |aInString| is true, accept the * additional form of escape sequence allowed within string-like tokens. */ bool nsCSSScanner::GatherEscape(nsString& aOutput, bool aInString) { MOZ_ASSERT(Peek() == '\\', "should not have been called"); int32_t ch = Peek(1); if (ch < 0) { // If we are in a string (or a url() containing a string), we want to drop // the backslash on the floor. Otherwise, we want to treat it as a U+FFFD // character. Advance(); if (aInString) { SetEOFCharacters(eEOFCharacters_DropBackslash); } else { aOutput.Append(UCS2_REPLACEMENT_CHAR); SetEOFCharacters(eEOFCharacters_ReplacementChar); } return true; } if (IsVertSpace(ch)) { if (aInString) { // In strings (and in url() containing a string), escaped // newlines are completely removed, to allow splitting over // multiple lines. Advance(); AdvanceLine(); return true; } // Outside of strings, backslash followed by a newline is not an escape. return false; } if (!IsHexDigit(ch)) { // "Any character (except a hexadecimal digit, linefeed, carriage // return, or form feed) can be escaped with a backslash to remove // its special meaning." -- CSS2.1 section 4.1.3 Advance(2); if (ch == 0) { aOutput.Append(UCS2_REPLACEMENT_CHAR); } else { aOutput.Append(ch); } return true; } // "[at most six hexadecimal digits following a backslash] stand // for the ISO 10646 character with that number, which must not be // zero. (It is undefined in CSS 2.1 what happens if a style sheet // does contain a character with Unicode codepoint zero.)" // -- CSS2.1 section 4.1.3 // At this point we know we have \ followed by at least one // hexadecimal digit, therefore the escape sequence is valid and we // can go ahead and consume the backslash. Advance(); uint32_t val = 0; int i = 0; do { val = val * 16 + HexDigitValue(ch); i++; Advance(); ch = Peek(); } while (i < 6 && IsHexDigit(ch)); // "Interpret the hex digits as a hexadecimal number. If this number is zero, // or is greater than the maximum allowed codepoint, return U+FFFD // REPLACEMENT CHARACTER" -- CSS Syntax Level 3 if (MOZ_UNLIKELY(val == 0)) { aOutput.Append(UCS2_REPLACEMENT_CHAR); } else { AppendUCS4ToUTF16(ENSURE_VALID_CHAR(val), aOutput); } // Consume exactly one whitespace character after a // hexadecimal escape sequence. if (IsVertSpace(ch)) { AdvanceLine(); } else if (IsHorzSpace(ch)) { Advance(); } return true; }
inline void SkipWhitespace() { while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r') { Advance(); } }
/** * Scan a Number, Percentage, or Dimension token (all of which begin * like a Number). Can produce a Symbol when a '.' is not followed by * digits, or when '+' or '-' are not followed by either a digit or a * '.' and then a digit. Can also produce a HTMLComment when it * encounters '-->'. */ bool nsCSSScanner::ScanNumber(nsCSSToken& aToken) { int32_t c = Peek(); #ifdef DEBUG { int32_t c2 = Peek(1); int32_t c3 = Peek(2); MOZ_ASSERT(IsDigit(c) || (IsDigit(c2) && (c == '.' || c == '+' || c == '-')) || (IsDigit(c3) && (c == '+' || c == '-') && c2 == '.'), "should not have been called"); } #endif // Sign of the mantissa (-1 or 1). int32_t sign = c == '-' ? -1 : 1; // Absolute value of the integer part of the mantissa. This is a double so // we don't run into overflow issues for consumers that only care about our // floating-point value while still being able to express the full int32_t // range for consumers who want integers. double intPart = 0; // Fractional part of the mantissa. This is a double so that when we convert // to float at the end we'll end up rounding to nearest float instead of // truncating down (as we would if fracPart were a float and we just // effectively lost the last several digits). double fracPart = 0; // Absolute value of the power of 10 that we should multiply by (only // relevant for numbers in scientific notation). Has to be a signed integer, // because multiplication of signed by unsigned converts the unsigned to // signed, so if we plan to actually multiply by expSign... int32_t exponent = 0; // Sign of the exponent. int32_t expSign = 1; aToken.mHasSign = (c == '+' || c == '-'); if (aToken.mHasSign) { Advance(); c = Peek(); } bool gotDot = (c == '.'); if (!gotDot) { // Scan the integer part of the mantissa. MOZ_ASSERT(IsDigit(c), "should have been excluded by logic above"); do { intPart = 10*intPart + DecimalDigitValue(c); Advance(); c = Peek(); } while (IsDigit(c)); gotDot = (c == '.') && IsDigit(Peek(1)); } if (gotDot) { // Scan the fractional part of the mantissa. Advance(); c = Peek(); MOZ_ASSERT(IsDigit(c), "should have been excluded by logic above"); // Power of ten by which we need to divide our next digit double divisor = 10; do { fracPart += DecimalDigitValue(c) / divisor; divisor *= 10; Advance(); c = Peek(); } while (IsDigit(c)); } bool gotE = false; if (c == 'e' || c == 'E') { int32_t expSignChar = Peek(1); int32_t nextChar = Peek(2); if (IsDigit(expSignChar) || ((expSignChar == '-' || expSignChar == '+') && IsDigit(nextChar))) { gotE = true; if (expSignChar == '-') { expSign = -1; } Advance(); // consumes the E if (expSignChar == '-' || expSignChar == '+') { Advance(); c = nextChar; } else { c = expSignChar; } MOZ_ASSERT(IsDigit(c), "should have been excluded by logic above"); do { exponent = 10*exponent + DecimalDigitValue(c); Advance(); c = Peek(); } while (IsDigit(c)); } } nsCSSTokenType type = eCSSToken_Number; // Set mIntegerValid for all cases (except %, below) because we need // it for the "2n" in :nth-child(2n). aToken.mIntegerValid = false; // Time to reassemble our number. // Do all the math in double precision so it's truncated only once. double value = sign * (intPart + fracPart); if (gotE) { // Explicitly cast expSign*exponent to double to avoid issues with // overloaded pow() on Windows. value *= pow(10.0, double(expSign * exponent)); } else if (!gotDot) { // Clamp values outside of integer range. if (sign > 0) { aToken.mInteger = int32_t(std::min(intPart, double(INT32_MAX))); } else { aToken.mInteger = int32_t(std::max(-intPart, double(INT32_MIN))); } aToken.mIntegerValid = true; } nsString& ident = aToken.mIdent; // Check for Dimension and Percentage tokens. if (c >= 0) { if (StartsIdent(c, Peek(1))) { if (GatherText(IS_IDCHAR, ident)) { type = eCSSToken_Dimension; } } else if (c == '%') { Advance(); type = eCSSToken_Percentage; value = value / 100.0f; aToken.mIntegerValid = false; } } aToken.mNumber = value; aToken.mType = type; return true; }
void vsscanf( char* buf /* in */, char* format /* in */, va_list argp /* out */) { char* fmtp; char* bufp; char* sval_ptr; int* ival_ptr; double* dval_ptr; float* fval_ptr; #ifdef CDEBUG printf("In vsscanf\n"); #endif bufp = buf; #ifdef CDEBUG printf("At start bufp = %s, format = %s\n", bufp, format); #endif for (fmtp = format; *fmtp; fmtp++) { if (*fmtp == '%') switch (*++fmtp) { case 'd': #ifdef CDEBUG printf("fmtp = %s, bufp = %s\n", fmtp, bufp); #endif ival_ptr = va_arg(argp, int *); /* advance argp */ sscanf(bufp, "%d", ival_ptr); bufp = Advance(bufp); break; case 'f': #ifdef CDEBUG printf("fmtp = %s, bufp = %s\n", fmtp, bufp); #endif fval_ptr = va_arg(argp, float *); /* advance argp */ sscanf(bufp, "%f", fval_ptr); bufp = Advance(bufp); break; case 'l': #ifdef CDEBUG printf("fmtp = %s, bufp = %s\n", fmtp, bufp); #endif dval_ptr = va_arg(argp, double *); /* advance argp */ sscanf(bufp, "%lf", dval_ptr); bufp = Advance(bufp); break; case 's': #ifdef CDEBUG printf("fmtp = %s, bufp = %s\n", fmtp, bufp); #endif sval_ptr = va_arg(argp, char *); /* advance argp */ sscanf(bufp, "%s", sval_ptr); bufp = Advance(bufp); break; default: #ifdef CDEBUG printf("fmtp = %s, bufp = %s\n", fmtp, bufp); #endif break; } /* switch */ } /* for */ } /* vsscanf */
void FluidSystem::Run () { bool bTiming = true; mint::Time start, stop; float ss = m_Param [ SPH_PDIST ] / m_Param[ SPH_SIMSCALE ]; // simulation scale (not Schutzstaffel) if ( m_Vec[EMIT_RATE].x > 0 && (++m_Frame) % (int) m_Vec[EMIT_RATE].x == 0 ) { //m_Frame = 0; Emit ( ss ); } #ifdef NOGRID // Slow method - O(n^2) SPH_ComputePressureSlow (); SPH_ComputeForceSlow (); #else if ( m_Toggle[USE_CUDA] ) { #ifdef BUILD_CUDA // -- GPU -- start.SetSystemTime ( ACC_NSEC ); TransferToCUDA ( mBuf[0].data, (int*) &m_Grid[0], NumPoints() ); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "TO: %s\n", stop.GetReadableTime().c_str() ); } start.SetSystemTime ( ACC_NSEC ); Grid_InsertParticlesCUDA (); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "INSERT (CUDA): %s\n", stop.GetReadableTime().c_str() ); } start.SetSystemTime ( ACC_NSEC ); SPH_ComputePressureCUDA (); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "PRESS (CUDA): %s\n", stop.GetReadableTime().c_str() ); } start.SetSystemTime ( ACC_NSEC ); SPH_ComputeForceCUDA (); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "FORCE (CUDA): %s\n", stop.GetReadableTime().c_str() ); } //** CUDA integrator is incomplete.. // Once integrator is done, we can remove TransferTo/From steps /*start.SetSystemTime ( ACC_NSEC ); SPH_AdvanceCUDA( m_DT, m_DT/m_Param[SPH_SIMSCALE] ); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "ADV (CUDA): %s\n", stop.GetReadableTime().c_str() ); }*/ start.SetSystemTime ( ACC_NSEC ); TransferFromCUDA ( mBuf[0].data, (int*) &m_Grid[0], NumPoints() ); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "FROM: %s\n", stop.GetReadableTime().c_str() ); } // .. Do advance on CPU Advance(); #endif } else { // -- CPU only -- start.SetSystemTime ( ACC_NSEC ); Grid_InsertParticles (); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "INSERT: %s\n", stop.GetReadableTime().c_str() ); } start.SetSystemTime ( ACC_NSEC ); SPH_ComputePressureGrid (); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "PRESS: %s\n", stop.GetReadableTime().c_str() ); } start.SetSystemTime ( ACC_NSEC ); SPH_ComputeForceGridNC (); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "FORCE: %s\n", stop.GetReadableTime().c_str() ); } start.SetSystemTime ( ACC_NSEC ); Advance(); if ( bTiming) { stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; printf ( "ADV: %s\n", stop.GetReadableTime().c_str() ); } } #endif }
result_t ParseJsonNumber(v8::Local<v8::Value> &retVal) { bool negative = false; int32_t beg_pos = position_; if (c0_ == '-') { Advance(); negative = true; } if (c0_ == '0') { Advance(); if (IsDecimalDigit(c0_)) return ReportUnexpectedCharacter(); } else { int32_t i = 0; int32_t digits = 0; if (c0_ < '1' || c0_ > '9') return ReportUnexpectedCharacter(); do { i = i * 10 + c0_ - '0'; digits++; Advance(); } while (IsDecimalDigit(c0_)); if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) { SkipWhitespace(); retVal = v8::Int32::New(isolate->m_isolate, negative ? -i : i); return 0; } } if (c0_ == '.') { Advance(); if (!IsDecimalDigit(c0_)) return ReportUnexpectedCharacter(); do { Advance(); } while (IsDecimalDigit(c0_)); } if (AsciiAlphaToLower(c0_) == 'e') { Advance(); if (c0_ == '-' || c0_ == '+') Advance(); if (!IsDecimalDigit(c0_)) return ReportUnexpectedCharacter(); do { Advance(); } while (IsDecimalDigit(c0_)); } int32_t length = position_ - beg_pos; double number; std::string chars(source_ + beg_pos, length); number = atof(chars.c_str()); SkipWhitespace(); retVal = v8::Number::New(isolate->m_isolate, number); return 0; }
void ComputeIntersection(Vec *P, Vec *Q) { Vec Pdir, Qdir; /* "Current" directed edges on P and Q */ Vec other; /* Temporary "edge-like" variable */ int ip, iq; /* Indices of ends of Pdir, Qdir */ int ip_begin, iq_begin; /* Indices of beginning of Pdir, Qdir */ int PToQDir; /* Qdir direction relative to Pdir */ /* (e.g. CLOCKWISE) */ int qEndpointFromPdir; /* End P vertex as viewed from beginning */ /* of Qdir relative to Qdir */ int pEndpointFromQdir; /* End Q vertex as viewed from beginning */ /* of Pdir relative to Pdir */ Vec firstIntersection; /* Point of intersection of Pdir, Qdir */ Vec secondIntersection; /* Second point of intersection */ /* (if there is one) */ int interiorFlag; /* Which polygon is inside the other */ int contained; /* Used for "completely contained" check */ int p_advances, q_advances; /* Number of times we've advanced */ /* P and Q indices */ int isFirstPoint; /* Is this the first point? */ int intersectionCode; /* SegSegIntersect() return code. */ /* Check for Q contained in P */ contained = TRUE; for(ip=0; ip<np; ++ip) { ip_begin = (ip + np - 1) % np; Cross(&P[ip_begin], &P[ip], &Pdir); Normalize(&Pdir); for(iq=0; iq<nq; ++iq) { if(debug >= 4) { printf("Q in P: Dot%d%d = %12.5e\n", ip, iq, Dot(&Pdir, &Q[iq])); fflush(stdout); } if(Dot(&Pdir, &Q[iq]) < -tolerance) { contained = FALSE; break; } } if(!contained) break; } if(contained) { if(debug >= 4) { printf("Q is entirely contained in P (output pixel is in input pixel)\n"); fflush(stdout); } for(iq=0; iq<nq; ++iq) SaveVertex(&Q[iq]); return; } /* Check for P contained in Q */ contained = TRUE; for(iq=0; iq<nq; ++iq) { iq_begin = (iq + nq - 1) % nq; Cross(&Q[iq_begin], &Q[iq], &Qdir); Normalize(&Qdir); for(ip=0; ip<np; ++ip) { if(debug >= 4) { printf("P in Q: Dot%d%d = %12.5e\n", iq, ip, Dot(&Qdir, &P[ip])); fflush(stdout); } if(Dot(&Qdir, &P[ip]) < -tolerance) { contained = FALSE; break; } } if(!contained) break; } if(contained) { if(debug >= 4) { printf("P is entirely contained in Q (input pixel is in output pixel)\n"); fflush(stdout); } nv = 0; for(ip=0; ip<np; ++ip) SaveVertex(&P[ip]); return; } /* Then check for polygon overlap */ ip = 0; iq = 0; p_advances = 0; q_advances = 0; interiorFlag = UNKNOWN; isFirstPoint = TRUE; while(FOREVER) { if(p_advances >= 2*np) break; if(q_advances >= 2*nq) break; if(p_advances >= np && q_advances >= nq) break; if(debug >= 4) { printf("-----\n"); if(interiorFlag == UNKNOWN) { printf("Before advances (UNKNOWN interiorFlag): ip=%d, iq=%d ", ip, iq); printf("(p_advances=%d, q_advances=%d)\n", p_advances, q_advances); } else if(interiorFlag == P_IN_Q) { printf("Before advances (P_IN_Q): ip=%d, iq=%d ", ip, iq); printf("(p_advances=%d, q_advances=%d)\n", p_advances, q_advances); } else if(interiorFlag == Q_IN_P) { printf("Before advances (Q_IN_P): ip=%d, iq=%d ", ip, iq); printf("(p_advances=%d, q_advances=%d)\n", p_advances, q_advances); } else printf("\nBAD INTERIOR FLAG. Shouldn't get here\n"); fflush(stdout); } /* Previous point in the polygon */ ip_begin = (ip + np - 1) % np; iq_begin = (iq + nq - 1) % nq; /* The current polygon edges are given by */ /* the cross product of the vertex vectors */ Cross(&P[ip_begin], &P[ip], &Pdir); Cross(&Q[iq_begin], &Q[iq], &Qdir); PToQDir = DirectionCalculator(&P[ip], &Pdir, &Qdir); Cross(&Q[iq_begin], &P[ip], &other); pEndpointFromQdir = DirectionCalculator(&Q[iq_begin], &Qdir, &other); Cross(&P[ip_begin], &Q[iq], &other); qEndpointFromPdir = DirectionCalculator(&P[ip_begin], &Pdir, &other); if(debug >= 4) { printf(" "); printDir("P", "Q", PToQDir); printDir("pEndpoint", "Q", pEndpointFromQdir); printDir("qEndpoint", "P", qEndpointFromPdir); printf("\n"); fflush(stdout); } /* Find point(s) of intersection between edges */ intersectionCode = SegSegIntersect(&Pdir, &Qdir, &P[ip_begin], &P[ip], &Q[iq_begin], &Q[iq], &firstIntersection, &secondIntersection); if(intersectionCode == NORMAL_INTERSECT || intersectionCode == ENDPOINT_ONLY) { if(interiorFlag == UNKNOWN && isFirstPoint) { p_advances = 0; q_advances = 0; isFirstPoint = FALSE; } interiorFlag = UpdateInteriorFlag(&firstIntersection, interiorFlag, pEndpointFromQdir, qEndpointFromPdir); if(debug >= 4) { if(interiorFlag == UNKNOWN) printf(" interiorFlag -> UNKNOWN\n"); else if(interiorFlag == P_IN_Q) printf(" interiorFlag -> P_IN_Q\n"); else if(interiorFlag == Q_IN_P) printf(" interiorFlag -> Q_IN_P\n"); else printf(" BAD interiorFlag. Shouldn't get here\n"); fflush(stdout); } } /*-----Advance rules-----*/ /* Special case: Pdir & Qdir overlap and oppositely oriented. */ if((intersectionCode == COLINEAR_SEGMENTS) && (Dot(&Pdir, &Qdir) < 0)) { if(debug >= 4) { printf(" ADVANCE: Pdir and Qdir are colinear.\n"); fflush(stdout); } SaveSharedSeg(&firstIntersection, &secondIntersection); RemoveDups(); return; } /* Special case: Pdir & Qdir parallel and separated. */ if((PToQDir == PARALLEL) && (pEndpointFromQdir == CLOCKWISE) && (qEndpointFromPdir == CLOCKWISE)) { if(debug >= 4) { printf(" ADVANCE: Pdir and Qdir are disjoint.\n"); fflush(stdout); } RemoveDups(); return; } /* Special case: Pdir & Qdir colinear. */ else if((PToQDir == PARALLEL) && (pEndpointFromQdir == PARALLEL) && (qEndpointFromPdir == PARALLEL)) { if(debug >= 4) { printf(" ADVANCE: Pdir and Qdir are colinear.\n"); fflush(stdout); } /* Advance but do not output point. */ if(interiorFlag == P_IN_Q) iq = Advance(iq, &q_advances, nq, interiorFlag == Q_IN_P, &Q[iq]); else ip = Advance(ip, &p_advances, np, interiorFlag == P_IN_Q, &P[ip]); } /* Generic cases. */ else if(PToQDir == COUNTERCLOCKWISE || PToQDir == PARALLEL) { if(qEndpointFromPdir == COUNTERCLOCKWISE) { if(debug >= 4) { printf(" ADVANCE: Generic: PToQDir is COUNTERCLOCKWISE "); printf("|| PToQDir is PARALLEL, "); printf("qEndpointFromPdir is COUNTERCLOCKWISE\n"); fflush(stdout); } ip = Advance(ip, &p_advances, np, interiorFlag == P_IN_Q, &P[ip]); } else { if(debug >= 4) { printf(" ADVANCE: Generic: PToQDir is COUNTERCLOCKWISE "); printf("|| PToQDir is PARALLEL, qEndpointFromPdir is CLOCKWISE\n"); fflush(stdout); } iq = Advance(iq, &q_advances, nq, interiorFlag == Q_IN_P, &Q[iq]); } } else { if(pEndpointFromQdir == COUNTERCLOCKWISE) { if(debug >= 4) { printf(" ADVANCE: Generic: PToQDir is CLOCKWISE, "); printf("pEndpointFromQdir is COUNTERCLOCKWISE\n"); fflush(stdout); } iq = Advance(iq, &q_advances, nq, interiorFlag == Q_IN_P, &Q[iq]); } else { if(debug >= 4) { printf(" ADVANCE: Generic: PToQDir is CLOCKWISE, "); printf("pEndpointFromQdir is CLOCKWISE\n"); fflush(stdout); } ip = Advance(ip, &p_advances, np, interiorFlag == P_IN_Q, &P[ip]); } } if(debug >= 4) { if(interiorFlag == UNKNOWN) { printf("After advances: ip=%d, iq=%d ", ip, iq); printf("(p_advances=%d, q_advances=%d) interiorFlag=UNKNOWN\n", p_advances, q_advances); } else if(interiorFlag == P_IN_Q) { printf("After advances: ip=%d, iq=%d ", ip, iq); printf("(p_advances=%d, q_advances=%d) interiorFlag=P_IN_Q\n", p_advances, q_advances); } else if(interiorFlag == Q_IN_P) { printf("After advances: ip=%d, iq=%d ", ip, iq); printf("(p_advances=%d, q_advances=%d) interiorFlag=Q_IN_P\n", p_advances, q_advances); } else printf("BAD INTERIOR FLAG. Shouldn't get here\n"); printf("-----\n\n"); fflush(stdout); } } RemoveDups(); return; }