Пример #1
0
HRESULT UIAbstractText::DrawBackGround(DK_IMAGE drawingImg)
{
    if (!m_eraseBackground)
    {
        return S_OK;
    }
    HRESULT hr(S_OK);
    CTpGraphics grf(drawingImg);
    //TODO, should get background color from m_TextDrawer
    const DK_ARGBCOLOR& bgcolor = m_TextDrawer.GetBackgroundColor();
    INT color = ~((bgcolor.rgbRed<<16 & 0xFF0000) | (bgcolor.rgbGreen<<8 & 0xFF00) | (bgcolor.rgbBlue & 0xFF));
    RTN_HR_IF_FAILED(grf.FillRect(0, 0, m_iWidth, m_iHeight, color));
    return hr;
}
int SoundSourceMediaFoundation::open()
{
    if (sDebug) {
        qDebug() << "open()" << m_qFilename;
    }

    QString qurlStr(m_qFilename);
    int wcFilenameLength(m_qFilename.toWCharArray(m_wcFilename));
    // toWCharArray does not append a null terminator to the string!
    m_wcFilename[wcFilenameLength] = '\0';

    HRESULT hr(S_OK);
    // Initialize the COM library.
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (FAILED(hr)) {
        qWarning() << "SSMF: failed to initialize COM";
        return ERR;
    }

    // Initialize the Media Foundation platform.
    hr = MFStartup(MF_VERSION);
    if (FAILED(hr)) {
        qWarning() << "SSMF: failed to initialize Media Foundation";
        return ERR;
    }

    // Create the source reader to read the input file.
    hr = MFCreateSourceReaderFromURL(m_wcFilename, NULL, &m_pReader);
    if (FAILED(hr)) {
        qWarning() << "SSMF: Error opening input file:" << m_qFilename;
        return ERR;
    }

    if (!configureAudioStream()) {
        qWarning() << "SSMF: Error configuring audio stream.";
        return ERR;
    }

    if (!readProperties()) {
        qWarning() << "SSMF::readProperties failed";
        return ERR;
    }

    //Seek to position 0, which forces us to skip over all the header frames.
    //This makes sure we're ready to just let the Analyser rip and it'll
    //get the number of samples it expects (ie. no header frames).
    seek(0);

    return OK;
}
Пример #3
0
STDMETHODIMP FileIStream::CopyTo(IStream *pstm, // A pointer to the destination stream. The stream pointed to by pstm can be a new stream or a clone of the source stream.
	ULARGE_INTEGER cb, // The number of bytes to copy from the source stream.
	ULARGE_INTEGER* pcbRead, // A pointer to the location where this method writes the actual number of bytes read from the source. You can set this pointer to NULL. In this case, this method does not provide the actual number of bytes read.
	ULARGE_INTEGER* pcbWritten) { // A pointer to the location where this method writes the actual number of bytes written to the destination. You can set this pointer to NULL. In this case, this method does not provide the actual number of bytes written.
	/*
	This method is equivalent to reading cb bytes into memory using ISequentialStream::Read and then immediately 
	writing them to the destination stream using ISequentialStream::Write, although IStream::CopyTo will be more efficient.
	The destination stream can be a clone of the source stream created by calling the IStream::Clone method.
	*/
	HRESULT hr(S_OK);
	unsigned char buf[0x1000];
	unsigned __int64 to_read = cb.QuadPart;
	unsigned long read = min((unsigned long)to_read, sizeof(buf));
	unsigned long readed, written;
	unsigned __int64 total_read(0), total_written(0);
	while ((readed = stream_impl->Read(buf, read)) > 0) {
		total_read += readed;
		
		if ((hr = pstm->Write(buf, readed, &written)) != S_OK)
			break;
		total_written += written;
		
		if ((to_read -= readed) == 0)
			break;
		read = min((unsigned long)to_read, sizeof(buf));
	}
	if (pcbWritten)
		pcbWritten->QuadPart = total_written;
	if (pcbRead)
		pcbRead->QuadPart = total_read;
	
	return hr;
	/*ULONG written;
    ULONG read = min(cb.LowPart, (ULONG)(m_buffer->size()-m_pos));
    HRESULT hr = pstm->Write(m_buffer->data()+m_pos, read, &written);
    if (pcbWritten) {
        pcbWritten->HighPart = 0;
        pcbWritten->LowPart = written;
    }
    if (pcbRead) {
        pcbRead->HighPart = 0;
        pcbRead->LowPart = read;
    }

    return hr;
	*/
}
Пример #4
0
// Used to set the next time event, if any.
void eventUpdate(ModelInstance* comp, fmi2EventInfo* eventInfo, int isTimeEvent) {
    long currentTime = comp->time;
    if (_isTime(comp)) {
        _removeLast(comp);
        eventInfo->nextEventTimeDefined  = fmi2False;
    }
    if (!_isEmpty(comp)) {
        Event nextEvent = _getLast(comp);
        comp->eventInfo.nextEventTime = nextEvent.time;
        eventInfo->nextEventTimeDefined  = fmi2True;
    }
    if (hr(input_) == present_) {
        _addEvent(comp, r(input_), currentTime + i(delay_));
        eventInfo->nextEventTimeDefined  = fmi2True;
        comp->eventInfo.nextEventTime = _getTime(comp);
    }
}
long SoundSourceMediaFoundation::seek(long filepos)
{
    if (sDebug) { qDebug() << "seek()" << filepos; }
    PROPVARIANT prop;
    HRESULT hr(S_OK);
    qint64 seekTarget(filepos / kNumChannels);
    qint64 mfSeekTarget(mfFromFrame(seekTarget) - 1);
    // minus 1 here seems to make our seeking work properly, otherwise we will
    // (more often than not, maybe always) seek a bit too far (although not
    // enough for our calculatedFrameFromMF <= nextFrame assertion in ::read).
    // Has something to do with 100ns MF units being much smaller than most
    // frame offsets (in seconds) -bkgood
    long result = m_iCurrentPosition;
    if (m_dead) {
        return result;
    }

    // this doesn't fail, see MS's implementation
    hr = InitPropVariantFromInt64(mfSeekTarget < 0 ? 0 : mfSeekTarget, &prop);


    hr = m_pReader->Flush(MF_SOURCE_READER_FIRST_AUDIO_STREAM);
    if (FAILED(hr)) {
        qWarning() << "SSMF: failed to flush before seek";
    }

    // http://msdn.microsoft.com/en-us/library/dd374668(v=VS.85).aspx
    hr = m_pReader->SetCurrentPosition(GUID_NULL, prop);
    if (FAILED(hr)) {
        // nothing we can do here as we can't fail (no facility to other than
        // crashing mixxx)
        qWarning() << "SSMF: failed to seek" << (
            hr == MF_E_INVALIDREQUEST ? "Sample requests still pending" : "");
    } else {
        result = filepos;
    }
    PropVariantClear(&prop);

    // record the next frame so that we can make sure we're there the next
    // time we get a buffer from MFSourceReader
    m_nextFrame = seekTarget;
    m_seeking = true;
    m_iCurrentPosition = result;
    return result;
}
Пример #6
0
int PPInstance::DownloadFile( const std::string& from, const std::string& to )
{
    int error( 0 );
	HRESULT hr( S_OK ); 

    nout << "Downloading " << from << " into " << to << "\n";
	{
		PPDownloadRequest p3dFileDownloadRequest( *this, to ); 
		PPDownloadCallback dcForFile( p3dFileDownloadRequest );
		hr = ::URLOpenStream( m_parentCtrl.GetControllingUnknown(), from.c_str(), 0, &dcForFile );
	}
    if ( FAILED( hr ) )
    {   
        error = 1;
        nout << "Error downloading " << from << " :" << hr << "\n";
    }
    return error;
}
Пример #7
0
void arrayRing_array::start(arrayMessage *msg)
{
  const int maxRings = 10;

  if(!msg->check()) {
    CkAbort("Message corrupted!\n");
  }
  if(thisIndex==0)
    msg->iter++;
  if (msg->iter < maxRings) {
    CProxy_arrayRing_array hr(thisArrayID);
    hr[(thisIndex+1) % ckGetArraySize()].start(msg);
  } else {
    delete msg;
    megatest_finish();
  }
  return;
}
Пример #8
0
  void CalcSchurComplement (const FlatMatrix<double> a, 
			    FlatMatrix<double> s,
			    const BitArray & used,
			    LocalHeap & lh)
  {
    if (s.Height() == 0) return;
    if (s.Height() == a.Height())
      {
        s = a;
        return;
      }

    HeapReset hr(lh);

    int n = a.Height();
    Array<int> used_dofs(n, lh);
    Array<int> unused_dofs(n, lh);
    used_dofs.SetSize(0);
    unused_dofs.SetSize(0);
    for (int i = 0; i < n; i++)
      if (used[i])
        used_dofs.Append(i);
      else
        unused_dofs.Append(i);

    s = a.Rows(used_dofs).Cols(used_dofs);
    FlatMatrix<> b1 = a.Rows(unused_dofs).Cols(used_dofs) | lh;
    FlatMatrix<> b2 = a.Rows(used_dofs).Cols(unused_dofs) | lh;
    FlatMatrix<> c = a.Rows(unused_dofs).Cols(unused_dofs) | lh;
    FlatMatrix<> hb1 (b1.Height(), b1.Width(), lh);

    if (n > 10)
      {
        LapackInverse (c);
        hb1 = c * b1 | Lapack;
        s -= b2 * hb1 | Lapack;
      }
    else
      {
        CalcInverse (c);
        hb1 = c * b1;
        s -= b2 * hb1;
      }
  }
Пример #9
0
std::string stringifyCustomType(HREFTYPE refType, ITypeInfo* pti) 
{
	CComPtr<ITypeInfo> pTypeInfo(pti);
	CComPtr<ITypeInfo> pCustTypeInfo;
	HRESULT hr(pTypeInfo->GetRefTypeInfo(refType, &pCustTypeInfo));

	if(hr) 
		return "UnknownCustomType";

	CComBSTR bstrType;
	hr = pCustTypeInfo->GetDocumentation(-1, &bstrType, 0, 0, 0);
	if(hr) 
		return "UnknownCustomType";

	char ansiType[MAX_PATH];
	WideCharToMultiByte(CP_ACP, 0, bstrType, bstrType.Length() + 1, ansiType, MAX_PATH, 0, 0);

	return ansiType;
}
Пример #10
0
Файл: look.C Проект: elaird/nuqe
void compare1() {
  Init();

  //mine
  TFile f1("../../events_1.root");
  TFile f4("../../events_4.root");
  gROOT->cd();
  TTree *tree1=(TTree*)f1.Get("tree");
  TGraph *gr1=(TGraph*)f1.Get("ccqe_rate");

  TTree *tree4=(TTree*)f4.Get("tree");
  TGraph *gr4=(TGraph*)f4.Get("ccqe_rate");

  
  Int_t N_bins=10;
  Double_t lower=0.0;
  Double_t upper=1.2;

  TString var="q[1]**2+q[2]**2+q[3]**2-q[0]**2";
  TString title=";Q^{2} (GeV^{2});d#sigma/dQ^{2} (cm^{2}/GeV^{2})";

  TH1D h1("h1",title,N_bins,lower,upper);
  h1.Sumw2();
  TH1D h4("h4",title,N_bins,lower,upper);
  h4.Sumw2();
  TH1D hr("hr",title,N_bins,lower,upper);
  hr.Sumw2();
  hr.GetYaxis()->SetTitle("ratio");
  
  Double_t dummy,xs1,xs4;

  gr1->GetPoint(1,dummy,xs1);
  gr4->GetPoint(4,dummy,xs4);

  tree1->Draw(var+">>h1","","goff");
  h1.Scale(xs1/h1.Integral("width"));
  tree4->Draw(var+">>h4","","goff");
  h4.Scale(xs4/h4.Integral("width"));

  hr.Divide(&h1,&h4);
  hr.DrawClone("");
}
Пример #11
0
HRESULT WINAPI NVUTFindDXSDKMediaFileCchT( LPTSTR strDestPath, int cchDest, LPCTSTR strFilename )
{
    HRESULT hr(S_OK);
    USES_CONVERSION;

    CT2W wstrFileName(strFilename);
    LPWSTR wstrDestPath = new WCHAR[cchDest];
    
    hr = NVUTFindDXSDKMediaFileCch(wstrDestPath, cchDest, wstrFileName);
    
    if(!FAILED(hr))
    {
        LPTSTR tstrDestPath = W2T(wstrDestPath);
        _tcsncpy_s(strDestPath, cchDest, tstrDestPath, cchDest);
    }

    delete[] wstrDestPath;

    return hr;
}
Пример #12
0
void PPInstance::HandleRequestGetUrl( void* data )
{
	HRESULT hr( S_OK );
    P3D_request *request = static_cast<P3D_request*>( data );
    if ( !request )
    {
        return;
    }
    int unique_id = request->_request._get_url._unique_id;
    const std::string &url = request->_request._get_url._url;
    CP3DActiveXCtrl* parent = static_cast<CP3DActiveXCtrl*> ( request->_instance->_user_data );

    if ( !parent )
    {
        return;
    }

    nout << "Handling P3D_RT_get_url request from " << url << "\n";
	{
		PPDownloadRequest p3dObjectDownloadRequest( parent->m_instance, request ); 
		PPDownloadCallback bsc( p3dObjectDownloadRequest );
		hr = ::URLOpenStream( parent->GetControllingUnknown(), url.c_str(), 0, &bsc );
	}
    P3D_result_code result_code = P3D_RC_done;
    if ( FAILED( hr ) )
    {
        nout << "Error handling P3D_RT_get_url request" << " :" << hr << "\n"; 
        result_code = P3D_RC_generic_error;
    }

    P3D_instance_feed_url_stream_ptr( 
        request->_instance, 
        request->_request._get_url._unique_id, 
        result_code, 
        0, 
        0, 
        (const void*)NULL, 
        0 
        );
    P3D_request_finish_ptr( request, true );
}
Пример #13
0
HRESULT UIPdfTrimColumnedDlg::DrawBackGround(DK_IMAGE drawingImg) 
{
	DebugPrintf(DLC_ZHY,"enter %s:%s,%s(%d)",GetClassName(),__FUNCTION__,__FILE__,__LINE__);
	HRESULT hr(S_OK);
	DK_IMAGE imgSelf;
	DK_RECT rcSelf={m_iLeft, m_iTop, m_iWidth, m_iHeight};

	//drawing original image
	DK_IMAGE* backGroundImage = m_pBookReader->GetPageBMP();
	rcSelf.top     = m_iHeight > backGroundImage->iHeight? (m_iHeight - backGroundImage->iHeight) >> 1: m_iTop;
	rcSelf.bottom  = rcSelf.top + backGroundImage->iHeight;
	rcSelf.left    = m_iWidth > backGroundImage->iWidth? (m_iWidth - backGroundImage->iWidth) >> 1: m_iLeft;
	rcSelf.right   = rcSelf.left + backGroundImage->iWidth;
	CTpGraphics grf(drawingImg);
	grf.EraserBackGround(ColorManager::knWhite);
	RTN_HR_IF_FAILED(CropImage(drawingImg, rcSelf, &imgSelf));
	CopyImage(imgSelf, *backGroundImage);

	DebugPrintf(DLC_ZHY,"leave %s:%s,%s(%d)",GetClassName(),__FUNCTION__,__FILE__,__LINE__);
	return hr;
}
Пример #14
0
void CTDCTaskListCtrl::RemoveDeletedItems()
{
	CTLSHoldResync hr(*this, m_lcColumns);

	int nItem = m_lcTasks.GetItemCount();
	
	while (nItem--)
	{
		if (GetTask(nItem) == NULL)
		{
			m_lcTasks.DeleteItem(nItem);
			m_lcColumns.DeleteItem(nItem);
		}
	}

	// fix up item data of columns
	nItem = m_lcColumns.GetItemCount();
	
	while (nItem--)
		m_lcColumns.SetItemData(nItem, nItem);
}
Пример #15
0
bool loadBulletFile(std::string name, btBvhTriangleMeshShape*& trimeshShape)
{
    hr_helper   hr(name);
    
    btBulletWorldImporter import(0);//don't store info into the world
    // import.setVerboseMode(0xFF);

    if (import.loadFile(name.c_str()))
    {


        int numBvh = import.getNumBvhs();
        int numBRB = import.getNumRigidBodies();
        //if (numBvh)
        //{
        //    btOptimizedBvh* bvh = import.getBvhByIndex(0);
        //    btVector3 aabbMin(-1000,-1000,-1000),aabbMax(1000,1000,1000);

        //    trimeshShape  = new btBvhTriangleMeshShape(m_indexVertexArrays,useQuantizedAabbCompression,aabbMin,aabbMax,false);
        //    trimeshShape->setOptimizedBvh(bvh);

        //}
        //btCompoundShape* cs;
        int numShape = import.getNumCollisionShapes();
        if (numShape)
        {
            //trimeshShape = (btBvhTriangleMeshShape*)import.getCollisionShapeByIndex(0);

            ////if you know the name, you can also try to get the shape by name:
            //const char* meshName = import.getNameForPointer(trimeshShape);
            //if (meshName)
            trimeshShape = (btBvhTriangleMeshShape*)import.getCollisionShapeByName("lod3");
        }

        return true;
    }

    return false;
}
Пример #16
0
bool tdnMesh::CreateVertex( unsigned int numVertexes, unsigned int vertexSize, void *vertexArray )
{
	HRESULT hr( S_OK );

	// 頂点配列のサイズ計算
	unsigned int vertexesSize = vertexSize * numVertexes;
	this->numVertexes = numVertexes;

	// バッファnew
	hr = tdnSystem::GetDevice()->CreateVertexBuffer(
		vertexesSize,    // 頂点配列のバイト数
		D3DUSAGE_DYNAMIC,               // 使用方法 D3DUSAGE
		D3DFVF_MESHVERTEX2,      // ?
		D3DPOOL_SYSTEMMEM, // 保存したデータの使用方法(読み込み専用, 最適化する ...)
		&vertexBuffer,   // 頂点バッファ <out>
		0 );             // ?
	if ( FAILED( hr ) )
		return false;

	// バッファにコピー
	void* workVertex( nullptr );
	hr = vertexBuffer->Lock( 0, 0, ( void** ) &workVertex, 0 );      // バッファロック (バファのポインター取得)
	if ( FAILED( hr ) )
		return false;
	memcpy_s( workVertex, vertexesSize, vertexArray, vertexesSize ); // バッファに頂点情報をコピー
	hr = vertexBuffer->Unlock();                                     // バッファロックを解除
	if ( FAILED( hr ) )
		return false;

	if ( vertexArray != this->vertexArray )
	{
		delete[] this->vertexArray;
		this->vertexArray = new MESHVERTEX2[numVertexes];
		memcpy_s( this->vertexArray, vertexesSize, vertexArray, vertexesSize ); // 配列に頂点情報をコピー
	}

	return true;
}
Пример #17
0
void Bridge::printConnections() const
{
	string dhr("=======================================================\n");
	string hr("--------------------------------------------------------\n");
	cout << dhr << "CONNECTION LIST\n" << dhr;
	cout << setw(7) << left << "FD" <<  setw(4) << left << "PORT" << endl;
	cout << hr;
	for (auto it = connected_ifaces.begin(); it != connected_ifaces.end(); ++it)
	{
		cout << setw(7) << left << it->second << setw(20) << it->first << endl;
	}
	cout << dhr << "MAC CACHE\n" << dhr;
	cout << setw(INET_MACSTRLEN) << left << "MAC ADDRESS" << setw(7) << left << "FD" << setw(5) << "TTL" << endl;
	cout << hr;

	for (auto it = connections.begin(); it != connections.end(); ++it)
	{
		cout << setw(INET_MACSTRLEN) << left << it->first;
		cout << setw(7) << left << it->second.port;
		cout << setw(5) << left << it->second.TTL << endl;
	}
	cout << dhr;
}
Пример #18
0
BOOL CTDCTaskListCtrl::EnsureSelectionVisible()
{
	if (GetSelectedCount())
	{
		OSVERSION nOSVer = COSVersion();
		
		if ((nOSVer == OSV_LINUX) || (nOSVer < OSV_VISTA))
		{
			m_lcTasks.PostMessage(LVM_ENSUREVISIBLE, GetSelectedItem());
		}
		else
		{
			CHoldRedraw hr(*this);
			
			m_lcTasks.EnsureVisible(GetSelectedItem(), FALSE);
		}

		return TRUE;
	}
	
	// else
	return FALSE;
}
Пример #19
0
// Used to set the next time event, if any.
void eventUpdate(ModelInstance* comp, fmi2EventInfo* eventInfo, int isTimeEvent) {
    long currentTime = comp->time;
    // printf("DELAY: eventUpdate, time = %ld, _isTime(comp) = %d\n", comp->time, _isTime(comp));
    if (_isTime(comp)) {
        _removeLast();
        eventInfo->nextEventTimeDefined  = fmi2False;
    }
    if (!_isEmpty()) {
        Event nextEvent = _getLast();
        comp->eventInfo.nextEventTime = nextEvent.time;
        eventInfo->nextEventTimeDefined  = fmi2True;
        // printf("- not empty\n");
        // printf("- eventInfo->nextEventTimeDefined = fmi2True\n");
        // printf("- addedEvent at time %ld, %ld\n", _getTime(), _getIndex());
    }
    if (hr(input_) == present_) {
        _addEvent(comp, r(input_), currentTime + i(delay_));
        eventInfo->nextEventTimeDefined  = fmi2True;
        comp->eventInfo.nextEventTime = _getTime();
        // printf("- present\n");
        // printf("- eventInfo->nextEventTimeDefined = fmi2True\n");
        // printf("- addedEvent at time %ld, %ld\n", _getTime(), _getIndex());
    }
}
Пример #20
0
int confOption::setValueFromFile(QString line)
{
  // Used to set values in confOptions from a file line
  
  QString rval = line.section("=",1).trimmed();

  qDebug() << "setting " << realName << " to " << rval << " (from file)";
    
  if (type == BOOL)
  {
    if (rval == "true" || rval == "on" || rval == "yes")
    {
      value = true;
      return 0;
    }
    else if (rval == "false" || rval == "off" || rval == "no")
    {
      value = false;
      return 0;
    }
    qDebug() << rval << "is not a valid value for setting" << realName << ". Ignoring...";
    return -1;
  }

  else if (type == INTEGER)
  {
    bool ok;
    qlonglong rvalToNmbr = rval.toLongLong(&ok);
    if (ok && rvalToNmbr >= minVal && rvalToNmbr <= maxVal)
    {
      value = rvalToNmbr;
      return 0;
    }
    qDebug() << rval << "is not a valid value for setting" << realName << ". Ignoring...";
    return -1;
  }

  else if (type == STRING)
  {
    value = rval;
    return 0;
  }  
  
  else if (type == LIST)
  {
    if (realName == "ShowStatus") // ShowStatus needs special treatment
    {
      if (rval.toLower() == "true" || rval.toLower() == "on")
        rval = "yes";
      else if (rval.toLower() == "false" || rval.toLower() == "off")
        rval = "no";
    }
    if (possibleVals.contains(rval))
    {
      value = rval.toLower();
      return 0;
    }
    qDebug() << rval << "is not a valid value for setting" << realName << ". Ignoring...";
    value = defVal;
    return -1;
  }

  else if (type == MULTILIST)
  {
    QVariantMap map;

    QStringList readList = rval.split(" ", QString::SkipEmptyParts);
    for (int i = 0; i < readList.size(); ++i)
    {
      if (!possibleVals.contains(readList.at(i)))
      {
        qDebug() << rval << "is not a valid value for setting" << realName << ". Ignoring...";
        return -1;
      }
    }
    
    for (int i = 0; i < possibleVals.size(); ++i)
    {
      if (readList.contains(possibleVals.at(i)))
        map[possibleVals.at(i)] = true;
      else
        map[possibleVals.at(i)] = false;
    }

    value = map;
    return 0;

  }  
  
  else if (type == TIME)
  {
    int pos = 0;
    QRegExp rxValid;

    // These regex check whether rval is a valid time interval
    if (hasNsec)
      rxValid = QRegExp("^(?:\\d*\\.?\\d *(ns|nsec|us|usec|ms|msec|s|sec|second|seconds|m|min|minute|minutes|h|hr|hour|hours|d|day|days|w|week|weeks|month|months|y|year|years)? *)+$");
    else
      rxValid = QRegExp("^(?:\\d*\\.?\\d *(us|usec|ms|msec|s|sec|second|seconds|m|min|minute|minutes|h|hr|hour|hours|d|day|days|w|week|weeks|month|months|y|year|years)? *)+$");

    pos = rxValid.indexIn(rval);

    if (pos > -1)
    {
      pos = 0;
      seconds secs(0);

      // This regex parses individual elements of the time interval
      QRegExp rxTimeParse = QRegExp("(\\d*\\.?\\d+) *([a-z]*)");

      while ((pos = rxTimeParse.indexIn(rval, pos)) != -1)
      {
        if (rxTimeParse.cap(2) == "ns" ||
            rxTimeParse.cap(2) == "nsec" )
        {
          nanoseconds ns(rxTimeParse.cap(1).trimmed().toDouble());
          secs += ns;
        }
        else if (rxTimeParse.cap(2) == "us" ||
            rxTimeParse.cap(2) == "usec" )
        {
          microseconds us(rxTimeParse.cap(1).trimmed().toDouble());
          secs += us;
        }
        else if (rxTimeParse.cap(2) == "ms" ||
            rxTimeParse.cap(2) == "msec" )
        {
          milliseconds ms(rxTimeParse.cap(1).trimmed().toDouble());
          secs += ms;
        }
        else if (rxTimeParse.cap(2) == "s" ||
                 rxTimeParse.cap(2) == "sec" ||
                 rxTimeParse.cap(2) == "second" ||
                 rxTimeParse.cap(2) == "seconds" )
        {
          seconds s(rxTimeParse.cap(1).trimmed().toDouble());
          secs += s;
        }
        else if (rxTimeParse.cap(2) == "m" ||
                 rxTimeParse.cap(2) == "min" ||
                 rxTimeParse.cap(2) == "minute" ||
                 rxTimeParse.cap(2) == "minutes" )
        {
          minutes min(rxTimeParse.cap(1).trimmed().toDouble());
          secs += min;
        }
        else if (rxTimeParse.cap(2) == "h" ||
                 rxTimeParse.cap(2) == "hr" ||
                 rxTimeParse.cap(2) == "hour" ||
                 rxTimeParse.cap(2) == "hours" )
        {
          hours hr(rxTimeParse.cap(1).trimmed().toDouble());
          secs += hr;
        }
        else if (rxTimeParse.cap(2) == "d" ||
                 rxTimeParse.cap(2) == "day" ||
                 rxTimeParse.cap(2) == "days")
        {
          days dy(rxTimeParse.cap(1).trimmed().toDouble());
          secs += dy;
        }
        else if (rxTimeParse.cap(2) == "w" ||
                 rxTimeParse.cap(2) == "week" ||
                 rxTimeParse.cap(2) == "weeks")
        {
          weeks w(rxTimeParse.cap(1).trimmed().toDouble());
          secs += w;
        }
        else if (rxTimeParse.cap(2) == "month" ||
                 rxTimeParse.cap(2) == "months")
        {
          months m(rxTimeParse.cap(1).trimmed().toDouble());
          secs += m;
        }
        else if (rxTimeParse.cap(2) == "y" ||
                 rxTimeParse.cap(2) == "year" ||
                 rxTimeParse.cap(2) == "years")
        {
          years y(rxTimeParse.cap(1).trimmed().toDouble());
          secs += y;
        }

        else if (rxTimeParse.cap(2).isEmpty())
        {
          // unitless number, convert it from defReadUnit to seconds
          seconds tmpSeconds(convertTimeUnit(rxTimeParse.cap(1).trimmed().toDouble(), defReadUnit, timeUnit::s).toDouble());
          secs += tmpSeconds;
        }

        pos += rxTimeParse.matchedLength();
      }

      // Convert the read value in seconds to defUnit
      if (defUnit == ns)
        value = nanoseconds(secs).count();
      else if (defUnit == us)
        value = microseconds(secs).count();
      else if (defUnit == ms)
        value = milliseconds(secs).count();
      else if (defUnit == s)
        value = secs.count();
      else if (defUnit == min)
        value = minutes(secs).count();
      else if (defUnit == h)
        value = hours(secs).count();
      else if (defUnit == d)
        value = days(secs).count();
      else if (defUnit == w)
        value = weeks(secs).count();
      else if (defUnit == month)
        value = months(secs).count();
      else if (defUnit == year)
        value = years(secs).count();

      value = value.toULongLong(); // Convert to ulonglong (we don't support float in ui)
      return 0;

    }
    else
    {
      qDebug() << rval << "is not a valid value for setting" << realName << ". Ignoring...";
      return -1;
    }
  }
  
  else if (type == RESLIMIT)
  {
    bool ok;
    int nmbr = rval.toUInt(&ok);
    if (ok)
    {
      value = nmbr;
      return 0;
    }
    else if (rval.toLower().trimmed() == "infinity" || rval.trimmed().isEmpty())
    {
      value = -1;
      return 0;
    }
    qDebug() << rval << "is not a valid value for setting" << realName << ". Ignoring...";
    return -1;
    
  }
  
  else if (type == SIZE)
  {
    // RegExp to match a number (possibly with decimals) followed by a size unit (or no unit for byte)
    QRegExp rxSize = QRegExp("(\\b\\d+\\.?\\d*(K|M|G|T|P|E)?\\b)");
    
    int pos = 0;
    pos = rxSize.indexIn(rval);
    if (pos > -1 && rxSize.cap(0) == rval.trimmed())
    {
      // convert the specified size unit to megabytes
      if (rxSize.cap(0).contains("K"))
        value = rxSize.cap(0).remove("K").toDouble() / 1024;
      else if (rxSize.cap(0).contains("M"))
        value = rxSize.cap(0).remove("M").toDouble();
      else if (rxSize.cap(0).contains("G"))
        value = rxSize.cap(0).remove("G").toDouble() * 1024;
      else if (rxSize.cap(0).contains("T"))
        value = rxSize.cap(0).remove("T").toDouble() * 1024 * 1024;
      else if (rxSize.cap(0).contains("P"))
        value = rxSize.cap(0).remove("P").toDouble() * 1024 * 1024 * 1024;
      else if (rxSize.cap(0).contains("E"))
        value = rxSize.cap(0).remove("E").toDouble() * 1024 * 1024 * 1024 * 1024;
      else
        value = rxSize.cap(0).toDouble() / 1024 / 1024;
      
      // Convert from double to ulonglong (we don't support float in ui)
      value = value.toULongLong();
      return 0;
    }
    else
    {
      qDebug() << rval << "is not a valid value for setting" << realName << ". Ignoring...";
      return -1;
    }
   
  }
  return -1;
}
Пример #21
0
float BoundingTree<BoxType>::compute_signed_distance(const CGLA::Vec3f& p,
																										 float minmax) const
{
	int N=100;
	vector<HE<Node> > Q(N);
	Q[0] = HE<Node>(p,root);
	
	HE<Node> *Q_beg = &Q[0];
	int Q_end = 1;
	int pushes = 1;
	while(const IntNode* n = dynamic_cast<const IntNode*>(Q[0].get_node()))
		{
			float q0_max= Q[0].get_sq_dist_max();
			//float q0_min= Q[0].get_sq_dist_min();
			pop_heap(Q_beg, Q_beg + Q_end);
			--Q_end;
			

			HE<Node> hl(p,n->get_left());
			if(hl.get_sq_dist_min() < (minmax + DIST_THRESH))
				{
					if(hl.get_sq_dist_max() < minmax)
							minmax = hl.get_sq_dist_max();
					
					Q[Q_end++] = hl;
					push_heap(Q_beg, Q_beg + Q_end);
					if(Q_end == N) 
						{
							Q.resize(N=2*N);
							Q_beg = &Q[0];
						}
					++pushes;
				}

			HE<Node> hr(p,n->get_right());
			if(hr.get_sq_dist_min() < (minmax + DIST_THRESH))
				{
					if(hr.get_sq_dist_max() < minmax)
							minmax = hr.get_sq_dist_max();

					Q[Q_end++] = hr;
					push_heap(Q_beg, Q_beg + Q_end);
					if(Q_end == N)
						{
							Q.resize(N=2*N);
							Q_beg = &Q[0];
						}
					++pushes;
				}

//  			if((hr.get_sq_dist_min() > (q0_max + DIST_THRESH)) &&
// 				 (hl.get_sq_dist_min() > (q0_max + DIST_THRESH)) )
// 				{
// 					cout.precision(4);
// 					cout << q0_min << " " << q0_max << endl;
// 					cout << hl.get_sq_dist_min() << endl;
// 					cout << hr.get_sq_dist_min() << endl;
// 					cout << typeid(*n).name() << endl;
// 					if(const LeafNode* ll =dynamic_cast<const LeafNode*>(hl.get_node()))
// 						{
// 							ll->get_tri().print();
// 							cout << sqr_length(p-ll->get_tri().get_v0()) << endl;
// 							cout << sqr_length(p-ll->get_tri().get_v1()) << endl;
// 							cout << sqr_length(p-ll->get_tri().get_v2()) << endl;
// 							float d=FLT_MAX, s;
// 							ll->get_tri().signed_distance(p,d,s);
// 							cout << "Dist " << d << endl;
// 						}
// 					if(const LeafNode* lr =dynamic_cast<const LeafNode*>(hr.get_node()))
// 						{
// 							lr->get_tri().print();
// 							cout << sqr_length(p-lr->get_tri().get_v0()) << endl;
// 							cout << sqr_length(p-lr->get_tri().get_v1()) << endl;
// 							cout << sqr_length(p-lr->get_tri().get_v2()) << endl;
// 							float d=FLT_MAX, s;
// 							lr->get_tri().signed_distance(p,d,s);
// 							cout << "Dist " << d << endl;
// 						}
// 					cout << "P=" << p<< endl;
// 				}

 			assert((hr.get_sq_dist_min() < (q0_max + DIST_THRESH)) ||
 						 (hl.get_sq_dist_min() < (q0_max + DIST_THRESH)) );
			assert(Q_end > 0);
			assert(Q_end <=N);
		}
	return Q[0].get_dist();
}
Пример #22
0
		/*!-----------------------------------------------------------
		//	@brief		作成
		//  @param[in]  _pd3dDevice		デバイスポインタ
		//	@param[in]	_numInstance	インスタンス数
		//	@return		S_OK:作成成功 それ以外:作成失敗
		//	@author		Tatsunori Aoyama
		//	@date		2014/09/17
		------------------------------------------------------------*/
		HRESULT	Create(
			ID3D11Device* _pd3dDevice,
			u32 _numInstance)
		{
			this->numInstance = _numInstance;
			this->dataSize = sizeof(T) * this->numInstance;

			HRESULT hr(E_FAIL);
			hr = ao::CreateVertexBuffer(
				_pd3dDevice,
				this->cMatrixBuffer.ToCreator(),
				sizeof(XMFLOAT4X4)*this->numInstance,
				nullptr,
				D3D11_USAGE_DYNAMIC,
				D3D11_CPU_ACCESS_WRITE);
#ifdef __AO_DEBUG__
			if (FAILED(hr))
			{
				ao::debug::PrintfColor(ConsoleColor::H_RED, _T("[InstanceBuffer::Create]Failed create camera matrix data.\n"));
				return E_FAIL;
			}
#endif

			hr = ao::CreateVertexBuffer(
				_pd3dDevice,
				this->lMatrixBuffer.ToCreator(),
				sizeof(XMFLOAT4X4)*this->numInstance,
				nullptr,
				D3D11_USAGE_DYNAMIC,
				D3D11_CPU_ACCESS_WRITE);
#ifdef __AO_DEBUG__
			if (FAILED(hr))
			{
				ao::debug::PrintfColor(ConsoleColor::H_RED, _T("[InstanceBuffer::Create]Failed create light matrix data.\n"));
				return E_FAIL;
			}
#endif

			hr = ao::CreateVertexBuffer(
				_pd3dDevice,
				this->pGpuInstanceBuffer.ToCreator(),
				this->dataSize,
				nullptr,
				D3D11_USAGE_DYNAMIC,
				D3D11_CPU_ACCESS_WRITE);
#ifdef __AO_DEBUG__
			if (FAILED(hr))
			{
				ao::debug::PrintfColor(ConsoleColor::H_RED, _T("[InstanceBuffer::Create]Failed create instance data.\n"));
				return E_FAIL;
			}
#endif

			if (this->cMatrix)
				delete[] this->cMatrix;
			this->cMatrix = new XMFLOAT4X4[this->numInstance];
			if (this->lMatrix)
				delete[] this->lMatrix;
			this->lMatrix = new XMFLOAT4X4[this->numInstance];
			if (this->pInstance)
				delete[] this->pInstance;
			this->pInstance = new T[this->numInstance];

			return S_OK;
		}
Пример #23
0
	bool DirectX10Renderer::ResizeScreen()
	{
		DEBUG_OUT("DirectX10Renderer::ResizeScreen");

		//If there is a valid render target
		if(pRenderTargetView)
		{
			pRenderTargetView->Release();
		}
    
		//Resize the swap chain's buffer to the given dimensions
		pSwapChain->ResizeBuffers(
			2, 
			m_ScreenWidth, m_ScreenHeight, 
			DXGI_FORMAT_R8G8B8A8_UNORM, 
			DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH
		);
        
		ID3D10Texture2D *pBufferTexture(NULL);

		//Get the swap chain's primary backbuffer (index 0)
		HRESULT hr(pSwapChain->GetBuffer(
			0,
			__uuidof(ID3D10Texture2D),
			(LPVOID*) &pBufferTexture
		));

		//If no buffer was retrieved
		if(FAILED(hr))
		{
			return FatalError("Failed to retrieve buffer");
		}

		//Create a new render target view using this backbuffer
		hr = pD3DDevice->CreateRenderTargetView(
			pBufferTexture, 
			NULL,
			&pRenderTargetView
		);

		//Release the reference to the backbuffer
		pBufferTexture->Release();

		//If you failed to create a render target view
		if(FAILED(hr))
		{
			return FatalError("Failed to create Render Target View!");
		}
  
		//Create a definition of the viewport
		D3D10_VIEWPORT viewPort;
		viewPort.Width = m_ScreenWidth;
		viewPort.Height = m_ScreenHeight;
		viewPort.MinDepth = 0.0f;
		viewPort.MaxDepth = 1.0f;
		viewPort.TopLeftX = 0;
		viewPort.TopLeftY = 0;

		//Set the device's viewport
		pD3DDevice->RSSetViewports(1, &viewPort);
  
		//create a depth stencil texture
		D3D10_TEXTURE2D_DESC descDepth;
		descDepth.Width = m_ScreenWidth;
		descDepth.Height = m_ScreenHeight;
		descDepth.MipLevels = 1;
		descDepth.ArraySize = 1;
		descDepth.Format = DXGI_FORMAT_D32_FLOAT;
		descDepth.SampleDesc.Count = 1;
		descDepth.SampleDesc.Quality = 0;
		descDepth.Usage = D3D10_USAGE_DEFAULT;
		descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL;
		descDepth.CPUAccessFlags = 0;
		descDepth.MiscFlags = 0;

		if(FAILED(pD3DDevice->CreateTexture2D(&descDepth, NULL, &pDepthStencil)))
		{
			return FatalError("Could not create depth stencil texture");
		}

		//create the depth stencil view
		D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
		descDSV.Format = descDepth.Format;
		descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
		descDSV.Texture2D.MipSlice = 0;

		if(FAILED(pD3DDevice->CreateDepthStencilView(pDepthStencil, &descDSV, &pDepthStencilView)))
		{
			return FatalError("Could not create depth stencil view");
		}

		//Set the device's render target to the one just created
		pD3DDevice->OMSetRenderTargets(1, &pRenderTargetView, NULL);

		return true;
	}
Пример #24
0
// Ccalled by fmi2Instantiate.
// Set values for all variables that define a start value.
// Settings used unless changed by fmi2SetX before fmi2EnterInitializationMode.
void setStartValues(ModelInstance *comp) {
    r(output_) = r(start_value_);
    r(der_) = 0.0;
    hr(output_) = present_;
    hr(der_) = absent_;
}
Пример #25
0
// used to check if there is any state event
fmi2Real getEventIndicator(ModelInstance* comp) {
    return (hr(input_) == present_) ? -1 : 1;
}
Пример #26
0
std::string stringifyParameterAttributes(PARAMDESC* paramDesc) 
{
	USHORT paramFlags = paramDesc->wParamFlags;
	int numFlags(0);

	for(DWORD bit(1); bit <= PARAMFLAG_FHASDEFAULT; bit<<=1) 
		numFlags += (paramFlags & bit) ? 1 : 0;

	if(!numFlags) 
		return "";

	std::ostringstream oss;
	oss<< '[';

	if(paramFlags & PARAMFLAG_FIN) 
	{ 
		oss<< "in"; 
		if(--numFlags) 
			oss<< ", "; 
	}
	if(paramFlags & PARAMFLAG_FOUT) 
	{ 
		oss<< "out"; 
		if(--numFlags) 
			oss<< ", "; 
	}
	if(paramFlags & PARAMFLAG_FLCID) 
	{ 
		oss<< "lcid"; 
		if(--numFlags) 
			oss<< ", "; 
	}
	if(paramFlags & PARAMFLAG_FRETVAL) 
	{ 
		oss<< "retval"; 
		if(--numFlags) 
			oss<< ", "; 
	}
	if(paramFlags & PARAMFLAG_FOPT) 
	{ 
		oss<< "optional"; 
		if(--numFlags) 
			oss<< ", "; 
	}

	if(paramFlags & PARAMFLAG_FHASDEFAULT) 
	{
		oss<< "defaultvalue";
		if(paramDesc->pparamdescex) 
		{
			oss<< '(';

			PARAMDESCEX& paramDescEx = *(paramDesc->pparamdescex);
			VARIANT defVal();
			CComBSTR bstrDefValue;
			CComVariant variant;
			HRESULT hr(VariantChangeType(&variant, &paramDescEx.varDefaultValue, 0, VT_BSTR));

			if(hr) 
				oss<< "???)";
			else 
			{
				char ansiDefValue[MAX_PATH];
				WideCharToMultiByte(CP_ACP, 0, variant.bstrVal, SysStringLen(variant.bstrVal) + 1, ansiDefValue, MAX_PATH, 0, 0);

				if(paramDescEx.varDefaultValue.vt == VT_BSTR)
					oss<< '\"'<< ansiDefValue<< '\"'<< ')';
				else 
					oss<< ansiDefValue<< ')';
			}
		}
	}
	oss<< ']';

	return oss.str();
}
Пример #27
0
	explicit CComLibAttr(ITypeLib* tlb) throw(EVeryBadThing) : _pTypeLib(tlb) 
	{
		HRESULT hr(_pTypeLib->GetLibAttr(&_libAttr));
		if(hr) throw EVeryBadThing();
	}
Пример #28
0
// 创建TF
IDWriteTextFormat*	TextFormatCache::CreateTextFormat(const TextFormatParameter* pParameter){
	IDWriteTextFormat* pTextFormat(nullptr);
#ifdef _DEBUG
	if (!s_ppDWriteFactory){
		_cwprintf(L"s_ppDWriteFactory未初始化.\n");
		return NULL;
	}
	if (!(*s_ppDWriteFactory)){
		_cwprintf(L"DWriteFactory未初始化.\n");
		return NULL;
	}
#endif
	(*s_ppDWriteFactory)->CreateTextFormat(
		pParameter->font_name,
		s_pCollection,
		pParameter->font_weight,
		pParameter->font_style,
		pParameter->font_stretch,
		pParameter->font_size * (96.0f / 72.f),
		L"", //locale
		&pTextFormat
		);
	if (pTextFormat){
#ifdef _DEBUG
		HRESULT hr(S_OK);
		// 设置行对齐
		if (SUCCEEDED(hr))
			hr = pTextFormat->SetTextAlignment(pParameter->text_alignmen);
		// 设置列对齐
		if (SUCCEEDED(hr))
			hr = pTextFormat->SetParagraphAlignment(pParameter->paragraph_alignment);
		// 设置自动换行
		if (SUCCEEDED(hr))
			hr = pTextFormat->SetWordWrapping(pParameter->word_wrapping);
		// 设置制表符宽度
		if (SUCCEEDED(hr))
			hr = pTextFormat->SetIncrementalTabStop(pParameter->incremental_tabstop);
		// 段落排列方向
		//if (SUCCEEDED(hr))
			//hr = pTextFormat->SetFlowDirection(DWRITE_FLOW_DIRECTION_BOTTOM_TO_TOP);
		// 设置行距
		if (SUCCEEDED(hr))
			hr = pTextFormat->SetLineSpacing(pParameter->line_spacing_method, pParameter->line_spacing,
			pParameter->baseline);
		if (FAILED(hr)){
			MessageBoxW(nullptr, L"<TextFormatCache::CreateTextFormat>: OK to created but failed to set\n"
				L"创建成功但是设置失败", L"Error", MB_OK);
			SafeRelease(pTextFormat);
			return nullptr;
		}
#else
		// 设置行对齐
		pTextFormat->SetTextAlignment(pParameter->text_alignmen);
		// 设置列对齐
		pTextFormat->SetParagraphAlignment(pParameter->paragraph_alignment);
		// 设置自动换行
		pTextFormat->SetWordWrapping(pParameter->word_wrapping);
		// 设置制表符宽度
		pTextFormat->SetIncrementalTabStop(pParameter->incremental_tabstop);
		// 段落排列方向
		//pTextFormat->SetFlowDirection(pParameter->flow_direction);
		// 设置行距
		pTextFormat->SetLineSpacing(pParameter->line_spacing_method, pParameter->line_spacing,
			pParameter->baseline);
#endif
		return pTextFormat;
	}
	return nullptr;
	//s_aryTextFormat[idx]->SetTrimming();
}
void Packet_handler::operator()() {

    std::cout << "Packet handler has started\n";
    try {
        while(*running_) {
            while(!inQueue_->empty()) {
                Packet *top = &inQueue_->front();
                std::cout << "Handling packet with tag " << top->get_tag() << std::endl;

                switch(top->get_tag()) {
                case Packet::REGISTER_REQUEST: {            // Handshake
                    HandshakeRaw* hr(static_cast<HandshakeRaw*>((top->get_content()).get()));
                    TcpServer::getInstance().connectedClients.register_client(top->get_address(), top->get_address()->connection, hr->nick_);
                        } /*break;*/

                case Packet::SYNCHRONISE_REQUEST: {        // prosba o wyslanie wszystkich zasobow...
                     ClientID s = TcpServer::getInstance().registeredAddresses.get_address_owner(*(top->get_address())); //pobiera id klienta o adresie zapisanym w pakiecie
                     Observer* obs((TcpServer::getInstance().connectedClients.look_up_with_id(s).get())); //rzutowanie z ClientPtr na Observer*
                     TcpServer::getInstance().connectedClients.synchronise(obs);   //kolejno wywoływane metody synchronise u każdego z obserwatorów
                     TcpServer::getInstance().registeredChat.synchronise(obs);
                     TcpServer::getInstance().registeredRooms.synchronise(obs);
                    } break;

                case Packet::CHAT_ENTRY_MESSAGE_REQUEST: {   // prosba o nadanie wiadomosci czatu
                    ChatEntryRaw* cer(static_cast<ChatEntryRaw*>((top->get_content()).get()));
                    TcpServer::getInstance().registeredChat.register_message(*cer);
                } break;

                case Packet::GAMEROOM_CREATE_REQUEST: {    // prosba o stworzenie nowego pokoju
                    GameRoomRaw* gr(static_cast<GameRoomRaw*>((top->get_content()).get()));
                    GameRoomPtr gpt =  TcpServer::getInstance().registeredRooms.add_game_room(gr->host, gr->gameRoomName);
                    // w metodzie add_gameroom() host jest automatycznie dodany do listy graczy
                } break;

                case Packet::GAMEROOM_JOIN_REQUEST: {      // prosba o dolaczenie do pokoju
                    GameRoomRaw* gr(static_cast<GameRoomRaw*>((top->get_content()).get()));
                    GameRoomPtr gpt =  TcpServer::getInstance().registeredRooms.look_up_with_id(gr->id);
                    gpt->add_player(TcpServer::getInstance().registeredAddresses.get_address_owner(*(top->get_address())));
                } break;

                case Packet::GAMEROOM_LEAVE_REQUEST: {     // prosba o opuszczenie pokoju
                    ClientID l = TcpServer::getInstance().registeredAddresses.get_address_owner(*(top->get_address()));
                    GameRoomID gr = TcpServer::getInstance().connectedClients.get_state(l).locationIdentifier;
                    GameRoomPtr gpt = TcpServer::getInstance().registeredRooms.look_up_with_id(gr);
                    gpt->remove_player(l);
                } break;

                case Packet::LOG_OUT_REQUEST: {
                    ClientID rm = TcpServer::getInstance().registeredAddresses.get_address_owner(*(top->get_address()));
                    TcpServer::getInstance().connectedClients.remove_client(rm);
                    // GameRoom, w którym był ten gracz, powinien być obserwatorem ClientsRegister, jeśli ma się dowiedzieć o jego wyjściu lub w ClientsRegister i metodzie remove_client powinno być zrobione zawiadomienie odpowiedniego gameroomu
                }
                //case Packet::GAMEROOM_UPDATE_REQUEST:    // prosba o zmiane ustawien pokoju
                //case Packet::GAMEROOM_START_REQUEST:     // prosba o rozpoczecie rozgrywki
                //case Packet::GAME_START_FAILURE_INFO:    // informacja dla klienta o niespelnionym rzadaniu
                //case Packet::CLOCK_SYNCHRONISE:          // prosba o okreslenie czasu wzgledem serwera
                //case Packet::GAME_STATE:                 // pakiet zawierajacy stan rozgrywki
                //case Packet::GAME_ACTION:                // byc moze sie przyda?
                case Packet::KEEP_ALIVE: {                 // ping! do ustalenia czy ktos stracil polaczenie.
                    std::cout << "Keeping alive client ";
                    ClientID x=TcpServer::getInstance().registeredAddresses.get_address_owner(*(top->get_address()));
                    std::cout << x << std::endl;
                } break;
                case Packet::UPDATED_RESOURCE: {           // dane aktualizacyjne przeznaczone dla klienta
//                     pokazuje na cout zawartość odebranego pakietu (tylko dla testów)
                    std::cout << top->get_tag() << " " << top->show_resource_content() << std::endl;
                } break;
                default:
                    std::cout << "Unexpected packet received. Tag: " << top->get_tag() << std::endl ;
                    std::cout << top->get_data_streambuf() << std::endl;
                    break;
                }

                inQueue_->pop();
            }

            std::this_thread::yield();
        }
    } catch(std::exception &e) {
        std::cout << "Exception at Packet_handler." << e.what() << "\n Packet Queue status:" <<
        inQueue_->size() << " " << std::endl;
    }

    std::cout << "Packet handler has finished\n";
}
Пример #30
0
SINT SoundSourceMediaFoundation::readSampleFrames(
        SINT numberOfFrames, CSAMPLE* sampleBuffer) {
    if (sDebug) {
        qDebug() << "read()" << numberOfFrames;
    }
    SINT framesNeeded(numberOfFrames);

    // first, copy frames from leftover buffer IF the leftover buffer is at
    // the correct frame
    if (m_leftoverBufferLength > 0 && m_leftoverBufferPosition == m_nextFrame) {
        copyFrames(sampleBuffer, &framesNeeded, m_leftoverBuffer,
                m_leftoverBufferLength);
        if (m_leftoverBufferLength > 0) {
            if (framesNeeded != 0) {
                qWarning() << __FILE__ << __LINE__
                        << "WARNING: Expected frames needed to be 0. Abandoning this file.";
                m_dead = true;
            }
            m_leftoverBufferPosition += numberOfFrames;
        }
    } else {
        // leftoverBuffer already empty or in the wrong position, clear it
        m_leftoverBufferLength = 0;
    }

    while (!m_dead && framesNeeded > 0) {
        HRESULT hr(S_OK);
        DWORD dwFlags(0);
        qint64 timestamp(0);
        IMFSample *pSample(nullptr);
        bool error(false); // set to true to break after releasing

        hr = m_pReader->ReadSample(MF_SOURCE_READER_FIRST_AUDIO_STREAM, // [in] DWORD dwStreamIndex,
                0,                                 // [in] DWORD dwControlFlags,
                nullptr,                      // [out] DWORD *pdwActualStreamIndex,
                &dwFlags,                        // [out] DWORD *pdwStreamFlags,
                &timestamp,                     // [out] LONGLONG *pllTimestamp,
                &pSample);                         // [out] IMFSample **ppSample
        if (FAILED(hr)) {
            qWarning() << "ReadSample failed!";
            break; // abort
        }

        if (sDebug) {
            qDebug() << "ReadSample timestamp:" << timestamp << "frame:"
                    << frameFromMF(timestamp, getSamplingRate()) << "dwflags:" << dwFlags;
        }

        if (dwFlags & MF_SOURCE_READERF_ERROR) {
            // our source reader is now dead, according to the docs
            qWarning()
                    << "SSMF: ReadSample set ERROR, SourceReader is now dead";
            m_dead = true;
            break;
        } else if (dwFlags & MF_SOURCE_READERF_ENDOFSTREAM) {
            qDebug() << "SSMF: End of input file.";
            break;
        } else if (dwFlags & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED) {
            qWarning() << "SSMF: Type change";
            break;
        } else if (pSample == nullptr) {
            // generally this will happen when dwFlags contains ENDOFSTREAM,
            // so it'll be caught before now -bkgood
            qWarning() << "SSMF: No sample";
            continue;
        } // we now own a ref to the instance at pSample

        IMFMediaBuffer *pMBuffer(nullptr);
        // I know this does at least a memcopy and maybe a malloc, if we have
        // xrun issues with this we might want to look into using
        // IMFSample::GetBufferByIndex (although MS doesn't recommend this)
        if (FAILED(hr = pSample->ConvertToContiguousBuffer(&pMBuffer))) {
            error = true;
            goto releaseSample;
        }
        CSAMPLE *buffer(nullptr);
        DWORD bufferLengthInBytes(0);
        hr = pMBuffer->Lock(reinterpret_cast<quint8**>(&buffer), nullptr, &bufferLengthInBytes);
        if (FAILED(hr)) {
            error = true;
            goto releaseMBuffer;
        }
        SINT bufferLength = samples2frames(bufferLengthInBytes / sizeof(buffer[0]));

        if (m_seeking) {
            qint64 bufferPosition(frameFromMF(timestamp, getSamplingRate()));
            if (sDebug) {
                qDebug() << "While seeking to " << m_nextFrame
                        << "WMF put us at" << bufferPosition;

            }
            if (m_nextFrame < bufferPosition) {
                // Uh oh. We are farther forward than our seek target. Emit
                // silence? We can't seek backwards here.
                CSAMPLE* pBufferCurpos = sampleBuffer
                        + frames2samples(numberOfFrames - framesNeeded);
                qint64 offshootFrames = bufferPosition - m_nextFrame;

                // If we can correct this immediately, write zeros and adjust
                // m_nextFrame to pretend it never happened.

                if (offshootFrames <= framesNeeded) {
                    qWarning() << __FILE__ << __LINE__
                            << "Working around inaccurate seeking. Writing silence for"
                            << offshootFrames << "frames";
                    // Set offshootFrames samples to zero.
                    memset(pBufferCurpos, 0,
                            sizeof(*pBufferCurpos) * frames2samples(offshootFrames));
                    // Now m_nextFrame == bufferPosition
                    m_nextFrame += offshootFrames;
                    framesNeeded -= offshootFrames;
                } else {
                    // It's more complicated. The buffer we have just decoded is
                    // more than framesNeeded frames away from us. It's too hard
                    // for us to handle this correctly currently, so let's just
                    // try to get on with our lives.
                    m_seeking = false;
                    m_nextFrame = bufferPosition;
                    qWarning() << __FILE__ << __LINE__
                            << "Seek offshoot is too drastic. Cutting losses and pretending the current decoded audio buffer is the right seek point.";
                }
            }

            if (m_nextFrame >= bufferPosition
                    && m_nextFrame < bufferPosition + bufferLength) {
                // m_nextFrame is in this buffer.
                buffer += frames2samples(m_nextFrame - bufferPosition);
                bufferLength -= m_nextFrame - bufferPosition;
                m_seeking = false;
            } else {
                // we need to keep going forward
                goto releaseRawBuffer;
            }
        }

        // If the bufferLength is larger than the leftover buffer, re-allocate
        // it with 2x the space.
        if (frames2samples(bufferLength) > m_leftoverBufferSize) {
            SINT newSize = m_leftoverBufferSize;

            while (newSize < frames2samples(bufferLength)) {
                newSize *= 2;
            }
            CSAMPLE* newBuffer = new CSAMPLE[newSize];
            memcpy(newBuffer, m_leftoverBuffer,
                    sizeof(m_leftoverBuffer[0]) * m_leftoverBufferSize);
            delete[] m_leftoverBuffer;
            m_leftoverBuffer = newBuffer;
            m_leftoverBufferSize = newSize;
        }
        copyFrames(
                sampleBuffer + frames2samples(numberOfFrames - framesNeeded),
                &framesNeeded,
                buffer, bufferLength);

        releaseRawBuffer: hr = pMBuffer->Unlock();
        // I'm ignoring this, MSDN for IMFMediaBuffer::Unlock stipulates
        // nothing about the state of the instance if this fails so might as
        // well just let it be released.
        //if (FAILED(hr)) break;
        releaseMBuffer: safeRelease(&pMBuffer);
        releaseSample: safeRelease(&pSample);
        if (error)
            break;
    }

    SINT framesRead = numberOfFrames - framesNeeded;
    m_iCurrentPosition += framesRead;
    m_nextFrame += framesRead;
    if (m_leftoverBufferLength > 0) {
        if (framesNeeded != 0) {
            qWarning() << __FILE__ << __LINE__
                    << "WARNING: Expected frames needed to be 0. Abandoning this file.";
            m_dead = true;
        }
        m_leftoverBufferPosition = m_nextFrame;
    }
    if (sDebug) {
        qDebug() << "read()" << numberOfFrames << "returning" << framesRead;
    }
    return framesRead;
}