Ejemplo n.º 1
0
Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QApplication> app(createApplication(argc, argv));



    cv::Mat img, img2, out, out2;
    img = cvLoadImage("Imagenes/city_night.jpeg");
    img2 = cvLoadImage("Imagenes/city_night.jpeg");
    out.create(img.size(), img.type());
    out2.create(img2.size(), img2.type());

    QElapsedTimer timer;
    qint64 nanoSec, nanoSec2;
    timer.start();

    //Lo hace todo en un solo hilo
    cv::threshold(img2,out2,66,255,1);
    nanoSec = timer.nsecsElapsed();
    qDebug() << nanoSec;

    timer.restart();

    // create 8 threads and use TBB
    cv::parallel_for_(cv::Range(0, 8), Parallel_process(img, out, 5, 8));

    nanoSec2 = timer.nsecsElapsed();
    qDebug() << nanoSec - nanoSec2;

    cv::imshow("image", out2);
    cv::imshow("blur", out);

    return app->exec();
}
Ejemplo n.º 2
0
void QSGWindowsRenderLoop::show(QQuickWindow *window)
{
    RLDEBUG("show");
    if (windowData(window) != 0)
        return;

    // This happens before the platform window is shown, but after
    // it is created. Creating the GL context takes a lot of time
    // (hundreds of milliseconds) and will prevent us from rendering
    // the first frame in time for the initial show on screen.
    // By preparing the GL context here, it is feasible (if the app
    // is quick enough) to have a perfect first frame.
    if (!m_gl) {
        QSG_RENDER_TIMING_SAMPLE(time_start);

        RLDEBUG(" - creating GL context");
        m_gl = new QOpenGLContext();
        m_gl->setFormat(window->requestedFormat());
        if (QSGContext::sharedOpenGLContext())
            m_gl->setShareContext(QSGContext::sharedOpenGLContext());
        bool created = m_gl->create();
        if (!created) {
            qWarning("QtQuick: failed to create OpenGL context");
            delete m_gl;
            m_gl = 0;
            return;
        }
        QSG_RENDER_TIMING_SAMPLE(time_created);
        RLDEBUG(" - making current");
        bool current = m_gl->makeCurrent(window);
        RLDEBUG(" - initializing SG");
        QSG_RENDER_TIMING_SAMPLE(time_current);
        if (current)
            m_rc->initialize(m_gl);

#ifndef QSG_NO_RENDER_TIMING
        if (qsg_render_timing) {
            qDebug("WindowsRenderLoop: GL=%d ms, makeCurrent=%d ms, SG=%d ms",
                   int((time_created - time_start)/1000000),
                   int((time_current - time_created)/1000000),
                   int((qsg_render_timer.nsecsElapsed() - time_current)/1000000));
        }
        if (QQmlProfilerService::enabled) {
            QQmlProfilerService::sceneGraphFrame(
                        QQmlProfilerService::SceneGraphWindowsRenderShow,
                        time_created - time_start,
                        time_current - time_created,
                        qsg_render_timer.nsecsElapsed() - time_current);
        }
#endif

    }

    WindowData data;
    data.window = window;
    data.pendingUpdate = false;
    m_windows << data;

    RLDEBUG(" - done with show");
}
Ejemplo n.º 3
0
void QSGRenderer::preprocess()
{
    Q_ASSERT(m_root_node);

    // We need to take a copy here, in case any of the preprocess calls deletes a node that
    // is in the preprocess list and thus, changes the m_nodes_to_preprocess behind our backs
    // For the default case, when this does not happen, the cost is neglishible.
    QSet<QSGNode *> items = m_nodes_to_preprocess;

    for (QSet<QSGNode *>::const_iterator it = items.constBegin();
         it != items.constEnd(); ++it) {
        QSGNode *n = *it;
        if (!nodeUpdater()->isNodeBlocked(n, m_root_node)) {
            n->preprocess();
        }
    }

#ifndef QSG_NO_RENDER_TIMING
    bool profileFrames = qsg_render_timing || QQmlProfilerService::enabled;
    if (profileFrames)
        preprocessTime = frameTimer.nsecsElapsed();
#endif

    nodeUpdater()->setToplevelOpacity(context()->renderAlpha());
    nodeUpdater()->updateStates(m_root_node);

#ifndef QSG_NO_RENDER_TIMING
    if (profileFrames)
        updatePassTime = frameTimer.nsecsElapsed();
#endif

}
Ejemplo n.º 4
0
void test_qelapsedtimer_nsec()
{
  QElapsedTimer elapsedTimer;
  elapsedTimer.start();

  quint64 beg = elapsedTimer.nsecsElapsed();
  quint64 end;
  quint64 diff;
  for (int i = 0; i < LOOP_CNT; i++)
  {
    end = elapsedTimer.nsecsElapsed();
    diff = end - beg;
  }
  std::cout << diff /1000000 << "\t" << __func__ << std::endl;
}
Ejemplo n.º 5
0
void Evnav::checkCachePerformance()
{
    QVector<int> hist(50);
    int bin = 10;

    QElapsedTimer timer;
    timer.start();
    computeDistanceHistogram(hist, bin);
    auto e1 = timer.nsecsElapsed();
    timer.restart();
    computeDistanceHistogram(hist, bin);
    auto e2 = timer.nsecsElapsed();
    qDebug() << "e1:" << e1 << "ms" << " e2:" << e2 << "ms";
    qDebug() << "hist:" << hist;
}
Ejemplo n.º 6
0
bool QMutexPrivate::wait(int timeout)
{
    struct timespec ts, *pts = 0;
    QElapsedTimer timer;
    if (timeout >= 0) {
        ts.tv_nsec = ((timeout % 1000) * 1000) * 1000;
        ts.tv_sec = (timeout / 1000);
        pts = &ts;
        timer.start();
    }
    while (contenders.fetchAndStoreAcquire(2) > 0) {
        int r = _q_futex(&contenders._q_value, FUTEX_WAIT, 2, pts, 0, 0);
        if (r != 0 && errno == ETIMEDOUT)
            return false;

        if (pts) {
            // recalculate the timeout
            qint64 xtimeout = timeout * 1000 * 1000;
            xtimeout -= timer.nsecsElapsed();
            if (xtimeout < 0) {
                // timer expired after we returned
                return false;
            }

            ts.tv_sec = xtimeout / Q_INT64_C(1000) / 1000 / 1000;
            ts.tv_nsec = xtimeout % (Q_INT64_C(1000) * 1000 * 1000);
        }
    }
    return true;
}
Ejemplo n.º 7
0
QSGMaterialShader *QSGContext::prepareMaterial(QSGMaterial *material)
{
    Q_D(QSGContext);
    QSGMaterialType *type = material->type();
    QSGMaterialShader *shader = d->materials.value(type);
    if (shader)
        return shader;

#ifndef QSG_NO_RENDER_TIMING
    if (qsg_render_timing  || QQmlProfilerService::enabled)
        qsg_renderer_timer.start();
#endif

    shader = material->createShader();
    shader->compile();
    shader->initialize();
    d->materials[type] = shader;

#ifndef QSG_NO_RENDER_TIMING
    if (qsg_render_timing)
        printf("   - compiling material: %dms\n", (int) qsg_renderer_timer.elapsed());

    if (QQmlProfilerService::enabled) {
        QQmlProfilerService::sceneGraphFrame(
                    QQmlProfilerService::SceneGraphContextFrame,
                    qsg_renderer_timer.nsecsElapsed());
    }
#endif

    return shader;
}
Ejemplo n.º 8
0
double elapsed(std::function<void ()> func)
{
    QElapsedTimer timer;
    timer.start();
    func();
    return timer.nsecsElapsed() / 1000000000.0f;
}
	virtual QPair<qint64, double> callFunction(std::function<void()> functionToCall) const
	{
		QElapsedTimer timer;
		qint64 array[20];
		qint64 time = 0;
		qint64 expectedValue = 0;
		qint64 variance = 0;

		for (int i = 0; i < 20; ++i) {
			timer.start();
			for (int i = 0; i < 20; ++i) {
				functionToCall();
			}

			array[i] = timer.nsecsElapsed();
			time += array[i];
		}

		expectedValue = time / 20;

		for (int t = 0; t < 20; ++t) {
			variance += qPow((array[t] - expectedValue), 2);
		}

		variance = variance / 20;
		double sqrtVariance = sqrt(variance);

		QPair<qint64, double> result = qMakePair(expectedValue, sqrtVariance);
		return result;
	}
double monotonicallyIncreasingTime()
{
    ASSERT(QElapsedTimer::isMonotonic());
    static QElapsedTimer timer;
    if (!timer.isValid())
        timer.start();
    return timer.nsecsElapsed() / 1.0e9;
}
Ejemplo n.º 11
0
void VideoExtractor::run(void)
{
    QElapsedTimer timer;
    //qint64 endOfCapture;
    //qint64 endOfHandle;
    qint64 begin;
    timer.start();
    while( ! m_stopped )
    {
        m_mutex.lock();
        while( ! m_autoPlay )
            m_cond.wait(&m_mutex);

        begin = timer.nsecsElapsed();

        m_videoStream[0]->grab(); // a for for that ... I'm too lazy
        m_videoStream[1]->grab();

        if( m_timeMax && m_timeMax > begin)
            m_autoPlay = false;

        processFrame();

        if( m_nbMaxImage && m_nbImageHandled == m_nbMaxImage )
            m_autoPlay = false;

        m_mutex.unlock();

        qint64 waitTime = ( m_paramPeriod.toInt() - timer.nsecsElapsed() + begin )/1000;
        if(waitTime < 0)
        {
            /*   std::cerr << "Warning : la boucle a du retard : " <<  waitTime
                         << "\nDuree de la boucle : " << m_paramPeriod.toInt()
                         << "\nDuree reelle : " << timer.nsecsElapsed() << std::endl; */
        }
        else
            QThread::usleep( waitTime );
    }

    emit finished();
    deleteLater();
}
Ejemplo n.º 12
0
void Generator::computeStarPositions(InputVertices& destination, unsigned limit, unsigned seed) {
    InputVertices* vertices = & destination;
    //_limit = limit;
    
    QElapsedTimer startTime;
    startTime.start();
    
    srand(seed);
    
    vertices->clear();
    vertices->reserve(limit);
    
    const unsigned MILKY_WAY_WIDTH = 12.0; // width in degrees of one half of the Milky Way
    const float MILKY_WAY_INCLINATION = 0.0f; // angle of Milky Way from horizontal in degrees
    const float MILKY_WAY_RATIO = 0.4f;
    const unsigned NUM_DEGREES = 360;
    
    for(int star = 0; star < floor(limit * (1 - MILKY_WAY_RATIO)); ++star) {
        float azimuth, altitude;
        azimuth = (((float)rand() / (float) RAND_MAX) * NUM_DEGREES) - (NUM_DEGREES / 2);
        altitude = (acos((2.0f * ((float)rand() / (float)RAND_MAX)) - 1.0f) / PI_OVER_180) + 90;
        vertices->push_back(InputVertex(azimuth, altitude, computeStarColor(STAR_COLORIZATION)));
    }
    
    for(int star = 0; star < ceil(limit * MILKY_WAY_RATIO); ++star) {
        float azimuth = ((float)rand() / (float) RAND_MAX) * NUM_DEGREES;
        float altitude = powf(randFloat()*0.5f, 2.0f)/0.25f * MILKY_WAY_WIDTH;
        if (randFloat() > 0.5f) {
            altitude *= -1.0f;
        }
        
        // we need to rotate the Milky Way band to the correct orientation in the sky
        // convert from spherical coordinates to cartesian, rotate the point and then convert back.
        // An improvement would be to convert all stars to cartesian at this point and not have to convert back.
        
        float tempX = sin(azimuth * PI_OVER_180) * cos(altitude * PI_OVER_180);
        float tempY = sin(altitude * PI_OVER_180);
        float tempZ = -cos(azimuth * PI_OVER_180) * cos(altitude * PI_OVER_180);
        
        float xangle = MILKY_WAY_INCLINATION * PI_OVER_180;
        float newX = (tempX * cos(xangle)) - (tempY * sin(xangle));
        float newY = (tempX * sin(xangle)) + (tempY * cos(xangle));
        float newZ = tempZ;
        
        azimuth = (atan2(newX,-newZ) + Radians::pi()) / PI_OVER_180;
        altitude = atan2(-newY, hypotf(newX, newZ)) / PI_OVER_180;
        
        vertices->push_back(InputVertex(azimuth, altitude, computeStarColor(STAR_COLORIZATION)));
    }
    
    double timeDiff = (double)startTime.nsecsElapsed() / 1000000.0; // ns to ms
    qDebug() << "Total time to generate stars: " << timeDiff << " msec";
}
Ejemplo n.º 13
0
double time_it(std::function<void ()> fn)
{
    QElapsedTimer timer;

    // warm-up
    fn();

    timer.start();
    fn();
    ulong elapsed = timer.nsecsElapsed();
    return (double) elapsed / 1000000000.0;
}
Ejemplo n.º 14
0
/*
 * Go through all windows we control and render them in turn.
 * Then tick animations if active.
 */
void QSGWindowsRenderLoop::render()
{
    RLDEBUG("render");
    foreach (const WindowData &wd, m_windows) {
        if (wd.pendingUpdate) {
            const_cast<WindowData &>(wd).pendingUpdate = false;
            renderWindow(wd.window);
        }
    }

    if (m_animationDriver->isRunning()) {
        RLDEBUG("advancing animations");
        QSG_RENDER_TIMING_SAMPLE(time_start);
        m_animationDriver->advance();
        RLDEBUG("animations advanced");

#ifndef QSG_NO_RENDER_TIMING
        if (qsg_render_timing) {
            qDebug("WindowsRenderLoop: animations=%d ms",
                   int((qsg_render_timer.nsecsElapsed() - time_start)/1000000));
        }
        if (QQmlProfilerService::Enabled) {
            QQmlProfilerService::sceneGraphFrame(
                        QQmlProfilerService::SceneGraphWindowsAnimations,
                        qsg_render_timer.nsecsElapsed() - time_start);
        }
#endif

        // It is not given that animations triggered another maybeUpdate()
        // and thus another render pass, so to keep things running,
        // make sure there is another frame pending.
        maybePostUpdateTimer();

        emit timeToIncubate();
    }
}
Ejemplo n.º 15
0
void Mesh3D::calcMassProps(const float density, const XMFLOAT3& scale, XMFLOAT3X3& inertiaTensor, XMFLOAT3& centerOfMass, float* mass) const
{
	std::vector<float> inertia;
	std::vector<float> com; // center of mass
	std::vector<float> scaling{ scale.x, scale.y, scale.z };

	QElapsedTimer timer;
	timer.start();
	VolInt::calcMassProps(m_indexData, m_vertexData, scaling, density, inertia, com, mass, nullptr);
	OutputDebugStringA(("Elapsed Volume Integration: " + std::to_string(timer.nsecsElapsed() * 0.000001) + "msec\n").c_str());

	inertiaTensor = XMFLOAT3X3(inertia.data());
	centerOfMass = { com[0], com[1], com[2] };

}
Ejemplo n.º 16
0
quint64 Widget::computeFitness(const QImage& target)
{
#ifdef TIME_FITNESS
    QElapsedTimer timer;
    timer.start();
#endif

    const uchar* origData = pic.bits(), *targetData = target.bits();
    const unsigned BPL = pic.bytesPerLine();

    auto computeSlice = [&](const unsigned start, const unsigned end)
    {
        quint64 partFitness=0;
        __m64 mmFitness = _mm_setzero_si64();
        __m64 tmp;
        for (unsigned i=start; i<end; i++)
        {
            const unsigned curLine = BPL*i;
            // Sum of the differences of each pixel's color
            for (unsigned j=0; j+8<BPL; j+=8)
            {
                __m64 mmOrig = _m_from_int64(*(quint64*)(origData+curLine+j));
                __m64 mmTarget = _m_from_int64(*(quint64*)(targetData+curLine+j));
                tmp = _m_psadbw(mmOrig, mmTarget);
                mmFitness = _mm_add_si64(mmFitness, tmp);
            }
        }
        *(__m64*)(&partFitness) += mmFitness;
        return partFitness;
    };
    QFuture<quint64> slices[N_CORES];
    for (int i=0; i < N_CORES; i++){
        slices[i] = QtConcurrent::run(computeSlice, height/N_CORES*i, height/N_CORES*(i+1));
    }
    quint64 fitness=0;
    for (int i=0; i < N_CORES; i++)
        fitness+=slices[i].result();

#ifdef TIME_FITNESS
    static quint64 elapsed=0, runs=0;
    elapsed += timer.nsecsElapsed();
    runs++;
    qDebug() << "Fitness:" << elapsed/runs/1000;
#endif

    return fitness;
}
Ejemplo n.º 17
0
void OTF2ExportFunctor::exportTrace(Trace * trace, const QString& path,
                                    const QString& filename)
{
    std::cout << "Exporting " << filename.toStdString().c_str() << std::endl;
    QElapsedTimer traceTimer;
    qint64 traceElapsed;

    traceTimer.start();

    OTF2Exporter * exporter = new OTF2Exporter(trace);
    exporter->exportTrace(path, filename);

    traceElapsed = traceTimer.nsecsElapsed();
    RavelUtils::gu_printTime(traceElapsed, "Total export time: ");

    emit(done());
}
Ejemplo n.º 18
0
int main(int argc, char *argv[]){
    static qint64 vTime = 0;

    QElapsedTimer et;
    et.start();

    QApplication a(argc, argv);

    game = new Game();

    game->show();

    vTime += et.nsecsElapsed();
    qDebug() << "time elapsed for app launch:" << vTime << "ns";


    return a.exec();
}
void MainWindow::convert()
{
    emit this->started();

    QtConcurrent::run([&]{
        QElapsedTimer t;
        t.start();
        Book currentBook;
        for(int i = 0; i < ui->listWidget->count(); ++i)
        {
            currentBook.setSource(ui->listWidget->item(i)->text());
            currentBook.convert();
            emit completed((i*100)/ui->listWidget->count());
        }
        qDebug()<<t.nsecsElapsed();
        emit this->finished();
    });

}
Ejemplo n.º 20
0
// the entry point for painting
qint64 SceneXrender::paint(QRegion damage, ToplevelList toplevels)
{
    QElapsedTimer renderTimer;
    renderTimer.start();

    createStackingOrder(toplevels);

    int mask = 0;
    QRegion updateRegion, validRegion;
    paintScreen(&mask, damage, QRegion(), &updateRegion, &validRegion);

    m_backend->showOverlay();

    m_backend->present(mask, updateRegion);
    // do cleanup
    clearStackingOrder();

    return renderTimer.nsecsElapsed();
}
Ejemplo n.º 21
0
void EasySelectorWidget::speedTest(void)
{
  Q_D(EasySelectorWidget);
  static const int BufSize = 512 / 8;
  QByteArray data(BufSize, static_cast<char>(0));
  QCryptographicHash hash(QCryptographicHash::Sha1);
  QElapsedTimer t;
  t.start();
  qint64 n = 0;
  while (!d->doAbortSpeedTest && t.elapsed() < 5000) {
    for (QByteArray::iterator d = data.begin(); d != data.end(); ++d)
      *d = qrand() & 0xff;
    hash.addData(data);
    hash.result();
    hash.reset();
    ++n;
  }
  int coreCount = QThread::idealThreadCount() > 0 ? QThread::idealThreadCount() : 1;
  qreal hashesPerSec = n * coreCount * 1e9 / t.nsecsElapsed();
  emit speedTestFinished(hashesPerSec);
}
Ejemplo n.º 22
0
// Added a second argument to cut-out extremes recalculation if not required
// Currently called from:
// bool TRoom::setArea( int, bool )  -- the second arg there can be used for this
// bool TRoomDB::__removeRoom( int ) -- automatically skipped for area deletion
//                                      (when this would not be needed)
void TArea::removeRoom(int room, bool isToDeferAreaRelatedRecalculations)
{
    static double cumulativeMean = 0.0;
    static quint64 runCount = 0;
    QElapsedTimer timer;
    timer.start();

    // Will use to flag whether some things have to be recalcuated.
    bool isOnExtreme = false;
    if (rooms.contains(room) && !isToDeferAreaRelatedRecalculations) {
        // just a check, if the area DOESN'T have the room then it is not wise
        // to behave as if it did
        TRoom* pR = mpRoomDB->getRoom(room);
        if (pR) {
            // Now see if the room is on an extreme - if it the only room on a
            // particular z-coordinate it will be on all four
            if (xminEbene.contains(pR->z) && xminEbene.value(pR->z) >= pR->x) {
                isOnExtreme = true;
            } else if (xmaxEbene.contains(pR->z) && xmaxEbene.value(pR->z) <= pR->x) {
                isOnExtreme = true;
            } else if (yminEbene.contains(pR->z) && yminEbene.value(pR->z) >= (-1 * pR->y)) {
                isOnExtreme = true;
            } else if (ymaxEbene.contains(pR->z) && ymaxEbene.value(pR->z) <= (-1 * pR->y)) {
                isOnExtreme = true;
            } else if (min_x >= pR->x || min_y >= (-1 * pR->y) || max_x <= pR->x || max_y <= (-1 * pR->y)) {
                isOnExtreme = true;
            }
        }
    }
    rooms.remove(room);
    exits.remove(room);
    if (isOnExtreme) {
        calcSpan();
    }
    quint64 thisTime = timer.nsecsElapsed();
    cumulativeMean += (((thisTime * 1.0e-9) - cumulativeMean) / ++runCount);
    if (runCount % 1000 == 0) {
        qDebug() << "TArea::removeRoom(" << room << ") from Area took" << thisTime * 1.0e-9 << "sec. this time and after" << runCount << "times the average is" << cumulativeMean << "sec.";
    }
}
Ejemplo n.º 23
0
/**
 * Added by Oscar Caravaca 14/05/2015.
 * This method is for ESPO3 initializtion. It takes the EPOS3 to the Operation Mode state
 * @param NUll
 * @return void
 */
void Epos3ReadWriteLib::initEPOS3()
{
	int val=0;
	cout<<"Initializing ESPO3"<<endl;	
	
    int timeInt[8];

    double avrTime = 0.0;

    QElapsedTimer timer;

    timer.start();
	sendDownloadCommand("0", "0x6040", "0", "uint16","0x00ff");    
    //timeInt[0]=timer.restart();
    sendUploadCommand("0", "0x6041", "0", "uint16");
    //timeInt[1]=timer.restart();
    sendDownloadCommand("0", "0x6040", "0", "uint16","0x0006");
   // timeInt[2]=timer.restart();
    sendUploadCommand("0", "0x6041", "0", "uint16");
   // timeInt[3]=timer.restart();
    sendDownloadCommand("0", "0x6040", "0", "uint16","0x0007");
   // timeInt[4]=timer.restart();
    sendUploadCommand("0", "0x6041", "0", "uint16");
   // timeInt[5]=timer.restart();
    sendDownloadCommand("0", "0x6040", "0", "uint16","0x000f");
   // timeInt[6]=timer.restart();
   // val = sendUploadCommand("0", "0x6041", "0", "uint16");
   // timeInt[7]=timer.restart();

  /*  for(int i=0;i<8;i++)
    {
        avrTime = avrTime+timeInt[i];
        cout<<"Sample "<<i<<" :"<<timeInt[i]<<endl;
    }
    avrTime = avrTime/8;
    */
    cout<<"time: "<<timer.nsecsElapsed()<<endl;

   // cout<<"Val:"<<val<<endl;
}
Ejemplo n.º 24
0
void View::paintEvent(QPaintEvent* event)
{
#if PRINT_REDRAW_SPEED
    static quint64 total=0;
    static quint64 divisor=1;
    QElapsedTimer timer;
    timer.start();
#endif

    QGraphicsView::paintEvent(event);

#if PRINT_REDRAW_SPEED
    qint64 duration = timer.nsecsElapsed();
    total+=duration;
    if(divisor%100==0){
        qDebug() << (total/divisor) * 0.000001 << "ms";
        total=0;
        divisor=0;
    }
    divisor++;
#endif
}
Ejemplo n.º 25
0
/*
 * Go through all windows we control and render them in turn.
 * Then tick animations if active.
 */
void QSGWindowsRenderLoop::render()
{
    RLDEBUG("render");
    bool rendered = false;
    foreach (const WindowData &wd, m_windows) {
        if (wd.pendingUpdate) {
            const_cast<WindowData &>(wd).pendingUpdate = false;
            renderWindow(wd.window);
            rendered = true;
        }
    }

    if (!rendered) {
        RLDEBUG("no changes, sleep");
        QThread::msleep(m_vsyncDelta);
    }

    if (m_animationDriver->isRunning()) {
        RLDEBUG("advancing animations");
        QSG_LOG_TIME_SAMPLE(time_start);
        Q_QUICK_SG_PROFILE_START(QQuickProfiler::SceneGraphWindowsAnimations);
        m_animationDriver->advance();
        RLDEBUG("animations advanced");

        qCDebug(QSG_LOG_TIME_RENDERLOOP,
                "animations ticked in %dms",
                int((qsg_render_timer.nsecsElapsed() - time_start)/1000000));

        Q_QUICK_SG_PROFILE_END(QQuickProfiler::SceneGraphWindowsAnimations);

        // It is not given that animations triggered another maybeUpdate()
        // and thus another render pass, so to keep things running,
        // make sure there is another frame pending.
        maybePostUpdateTimer();

        emit timeToIncubate();
    }
}
Ejemplo n.º 26
0
void AudioInjector::injectAudio() {
    
    QByteArray soundByteArray = _sound->getByteArray();
    
    // make sure we actually have samples downloaded to inject
    if (soundByteArray.size()) {
        // give our sample byte array to the local audio interface, if we have it, so it can be handled locally
        if (_options.getLoopbackAudioInterface()) {
            // assume that localAudioInterface could be on a separate thread, use Qt::AutoConnection to handle properly
            QMetaObject::invokeMethod(_options.getLoopbackAudioInterface(), "handleAudioByteArray",
                                      Qt::AutoConnection,
                                      Q_ARG(QByteArray, soundByteArray));
            
        }
        
        NodeList* nodeList = NodeList::getInstance();
        
        // setup the packet for injected audio
        QByteArray injectAudioPacket = byteArrayWithPopulatedHeader(PacketTypeInjectAudio);
        QDataStream packetStream(&injectAudioPacket, QIODevice::Append);
        
        packetStream << QUuid::createUuid();
        
        // pack the flag for loopback
        uchar loopbackFlag = (uchar) (!_options.getLoopbackAudioInterface());
        packetStream << loopbackFlag;
        
        // pack the position for injected audio
        packetStream.writeRawData(reinterpret_cast<const char*>(&_options.getPosition()), sizeof(_options.getPosition()));
        
        // pack our orientation for injected audio
        packetStream.writeRawData(reinterpret_cast<const char*>(&_options.getOrientation()), sizeof(_options.getOrientation()));
        
        // pack zero for radius
        float radius = 0;
        packetStream << radius;
        
        // pack 255 for attenuation byte
        quint8 volume = MAX_INJECTOR_VOLUME * _options.getVolume();
        packetStream << volume;
        
        QElapsedTimer timer;
        timer.start();
        int nextFrame = 0;
        
        int currentSendPosition = 0;
        
        int numPreAudioDataBytes = injectAudioPacket.size();
        
        // loop to send off our audio in NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL byte chunks
        while (currentSendPosition < soundByteArray.size() && !_shouldStop) {
            
            int bytesToCopy = std::min(NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL,
                                       soundByteArray.size() - currentSendPosition);
            
            // resize the QByteArray to the right size
            injectAudioPacket.resize(numPreAudioDataBytes + bytesToCopy);
            
            // copy the next NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL bytes to the packet
            memcpy(injectAudioPacket.data() + numPreAudioDataBytes, soundByteArray.data() + currentSendPosition, bytesToCopy);
            
            // grab our audio mixer from the NodeList, if it exists
            SharedNodePointer audioMixer = nodeList->soloNodeOfType(NodeType::AudioMixer);
            
            // send off this audio packet
            nodeList->writeDatagram(injectAudioPacket, audioMixer);
            
            currentSendPosition += bytesToCopy;
            
            // send two packets before the first sleep so the mixer can start playback right away
            
            if (currentSendPosition != bytesToCopy && currentSendPosition < soundByteArray.size()) {
                // not the first packet and not done
                // sleep for the appropriate time
                int usecToSleep = (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - timer.nsecsElapsed() / 1000;
                
                if (usecToSleep > 0) {
                    usleep(usecToSleep);
                }
            }
        }
    }
    
    emit finished();
}
Ejemplo n.º 27
0
//  Do some basic timing tests and report the results
void runTimingTests() {
    //  How long does it take to make a call to get the time?
    const int numTests = 1000000;
    int* iResults = (int*)malloc(sizeof(int) * numTests);
    float fTest = 1.0;
    float* fResults = (float*)malloc(sizeof(float) * numTests);
    QElapsedTimer startTime;
    startTime.start();
    float elapsedUsecs;
    
    float NSEC_TO_USEC = 1.0f / 1000.0f;
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("QElapsedTimer::nsecElapsed() usecs: %f", elapsedUsecs);
    
    // Test sleep functions for accuracy
    startTime.start();
    QThread::msleep(1);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("QThread::msleep(1) ms: %f", elapsedUsecs / 1000.0f);

    startTime.start();
    QThread::sleep(1);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("QThread::sleep(1) ms: %f", elapsedUsecs / 1000.0f);

    startTime.start();
    usleep(1);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("usleep(1) ms: %f", elapsedUsecs / 1000.0f);

    startTime.start();
    usleep(10);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("usleep(10) ms: %f", elapsedUsecs / 1000.0f);

    startTime.start();
    usleep(100);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("usleep(100) ms: %f", elapsedUsecs / 1000.0f);

    startTime.start();
    usleep(1000);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("usleep(1000) ms: %f", elapsedUsecs / 1000.0f);

    startTime.start();
    usleep(15000);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("usleep(15000) ms: %f", elapsedUsecs / 1000.0f);

    // Random number generation
    startTime.start();
    for (int i = 0; i < numTests; i++) {
        iResults[i] = rand();
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("rand() stored in array usecs: %f, first result:%d", elapsedUsecs / (float) numTests, iResults[0]);

    // Random number generation using randFloat()
    startTime.start();
    for (int i = 0; i < numTests; i++) {
        fResults[i] = randFloat();
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("randFloat() stored in array usecs: %f, first result: %f", elapsedUsecs / (float) numTests, fResults[0]);

    free(iResults);
    free(fResults);

    //  PowF function
    fTest = 1145323.2342f;
    startTime.start();
    for (int i = 0; i < numTests; i++) {
        fTest = powf(fTest, 0.5f);
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("powf(f, 0.5) usecs: %f", elapsedUsecs / (float) numTests);

    //  Vector Math
    float distance;
    glm::vec3 pointA(randVector()), pointB(randVector());
    startTime.start();
    for (int i = 0; i < numTests; i++) {
        //glm::vec3 temp = pointA - pointB;
        //float distanceSquared = glm::dot(temp, temp);
        distance = glm::distance(pointA, pointB);
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("vector math usecs: %f [%f usecs total for %d tests], last result:%f",
           elapsedUsecs / (float) numTests, elapsedUsecs, numTests, distance);

    //  Vec3 test
    glm::vec3 vecA(randVector()), vecB(randVector());
    float result;
    
    startTime.start();
    for (int i = 0; i < numTests; i++) {
        glm::vec3 temp = vecA-vecB;
        result = glm::dot(temp,temp);
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qDebug("vec3 assign and dot() usecs: %f, last result:%f", elapsedUsecs / (float) numTests, result);
}
Ejemplo n.º 28
0
void ScriptEngine::run() {
    // TODO: can we add a short circuit for _stoppingAllScripts here? What does it mean to not start running if
    // we're in the process of stopping?

    if (!_isInitialized) {
        init();
    }
    _isRunning = true;
    _isFinished = false;
    emit runningStateChanged();

    QScriptValue result = evaluate(_scriptContents);

    QElapsedTimer startTime;
    startTime.start();

    int thisFrame = 0;

    auto nodeList = DependencyManager::get<NodeList>();
    auto entityScriptingInterface = DependencyManager::get<EntityScriptingInterface>();

    qint64 lastUpdate = usecTimestampNow();

    while (!_isFinished) {
        int usecToSleep = (thisFrame++ * SCRIPT_DATA_CALLBACK_USECS) - startTime.nsecsElapsed() / 1000; // nsec to usec
        if (usecToSleep > 0) {
            usleep(usecToSleep);
        }

        if (_isFinished) {
            break;
        }

        QCoreApplication::processEvents();

        if (_isFinished) {
            break;
        }

        if (!_isFinished && entityScriptingInterface->getEntityPacketSender()->serversExist()) {
            // release the queue of edit entity messages.
            entityScriptingInterface->getEntityPacketSender()->releaseQueuedMessages();

            // since we're in non-threaded mode, call process so that the packets are sent
            if (!entityScriptingInterface->getEntityPacketSender()->isThreaded()) {
                entityScriptingInterface->getEntityPacketSender()->process();
            }
        }

        if (!_isFinished && _isAvatar && _avatarData) {

            const int SCRIPT_AUDIO_BUFFER_SAMPLES = floor(((SCRIPT_DATA_CALLBACK_USECS * AudioConstants::SAMPLE_RATE)
                                                           / (1000 * 1000)) + 0.5);
            const int SCRIPT_AUDIO_BUFFER_BYTES = SCRIPT_AUDIO_BUFFER_SAMPLES * sizeof(int16_t);

            QByteArray avatarByteArray = _avatarData->toByteArray();
            auto avatarPacket = NLPacket::create(PacketType::AvatarData, avatarByteArray.size());

            avatarPacket->write(avatarByteArray);

            nodeList->broadcastToNodes(std::move(avatarPacket), NodeSet() << NodeType::AvatarMixer);

            if (_isListeningToAudioStream || _avatarSound) {
                // if we have an avatar audio stream then send it out to our audio-mixer
                bool silentFrame = true;

                int16_t numAvailableSamples = SCRIPT_AUDIO_BUFFER_SAMPLES;
                const int16_t* nextSoundOutput = NULL;

                if (_avatarSound) {

                    const QByteArray& soundByteArray = _avatarSound->getByteArray();
                    nextSoundOutput = reinterpret_cast<const int16_t*>(soundByteArray.data()
                                                                       + _numAvatarSoundSentBytes);

                    int numAvailableBytes = (soundByteArray.size() - _numAvatarSoundSentBytes) > SCRIPT_AUDIO_BUFFER_BYTES
                        ? SCRIPT_AUDIO_BUFFER_BYTES
                        : soundByteArray.size() - _numAvatarSoundSentBytes;
                    numAvailableSamples = numAvailableBytes / sizeof(int16_t);


                    // check if the all of the _numAvatarAudioBufferSamples to be sent are silence
                    for (int i = 0; i < numAvailableSamples; ++i) {
                        if (nextSoundOutput[i] != 0) {
                            silentFrame = false;
                            break;
                        }
                    }

                    _numAvatarSoundSentBytes += numAvailableBytes;
                    if (_numAvatarSoundSentBytes == soundByteArray.size()) {
                        // we're done with this sound object - so set our pointer back to NULL
                        // and our sent bytes back to zero
                        _avatarSound = NULL;
                        _numAvatarSoundSentBytes = 0;
                    }
                }

                auto audioPacket = NLPacket::create(silentFrame
                                                    ? PacketType::SilentAudioFrame
                                                    : PacketType::MicrophoneAudioNoEcho);

                // seek past the sequence number, will be packed when destination node is known
                audioPacket->seek(sizeof(quint16));

                if (silentFrame) {
                    if (!_isListeningToAudioStream) {
                        // if we have a silent frame and we're not listening then just send nothing and break out of here
                        break;
                    }

                    // write the number of silent samples so the audio-mixer can uphold timing
                    audioPacket->writePrimitive(SCRIPT_AUDIO_BUFFER_SAMPLES);

                    // use the orientation and position of this avatar for the source of this audio
                    audioPacket->writePrimitive(_avatarData->getPosition());
                    glm::quat headOrientation = _avatarData->getHeadOrientation();
                    audioPacket->writePrimitive(headOrientation);

                } else if (nextSoundOutput) {
                    // assume scripted avatar audio is mono and set channel flag to zero
                    audioPacket->writePrimitive((quint8) 0);

                    // use the orientation and position of this avatar for the source of this audio
                    audioPacket->writePrimitive(_avatarData->getPosition());
                    glm::quat headOrientation = _avatarData->getHeadOrientation();
                    audioPacket->writePrimitive(headOrientation);

                    // write the raw audio data
                    audioPacket->write(reinterpret_cast<const char*>(nextSoundOutput), numAvailableSamples * sizeof(int16_t));
                }

                // write audio packet to AudioMixer nodes
                auto nodeList = DependencyManager::get<NodeList>();
                nodeList->eachNode([this, &nodeList, &audioPacket](const SharedNodePointer& node){
                    // only send to nodes of type AudioMixer
                    if (node->getType() == NodeType::AudioMixer) {
                        // pack sequence number
                        quint16 sequence = _outgoingScriptAudioSequenceNumbers[node->getUUID()]++;
                        audioPacket->seek(0);
                        audioPacket->writePrimitive(sequence);

                        // send audio packet
                        nodeList->sendUnreliablePacket(*audioPacket, *node);
                    }
                });
            }
        }

        qint64 now = usecTimestampNow();
        float deltaTime = (float) (now - lastUpdate) / (float) USECS_PER_SECOND;

        if (hasUncaughtException()) {
            int line = uncaughtExceptionLineNumber();
            qCDebug(scriptengine) << "Uncaught exception at (" << _fileNameString << ") line" << line << ":" << uncaughtException().toString();
            emit errorMessage("Uncaught exception at (" + _fileNameString + ") line" + QString::number(line) + ":" + uncaughtException().toString());
            clearExceptions();
        }

        if (!_isFinished) {
            emit update(deltaTime);
        }
        lastUpdate = now;

    }

    stopAllTimers(); // make sure all our timers are stopped if the script is ending
    emit scriptEnding();

    // kill the avatar identity timer
    delete _avatarIdentityTimer;

    if (entityScriptingInterface->getEntityPacketSender()->serversExist()) {
        // release the queue of edit entity messages.
        entityScriptingInterface->getEntityPacketSender()->releaseQueuedMessages();

        // since we're in non-threaded mode, call process so that the packets are sent
        if (!entityScriptingInterface->getEntityPacketSender()->isThreaded()) {
            // wait here till the edit packet sender is completely done sending
            while (entityScriptingInterface->getEntityPacketSender()->hasPacketsToSend()) {
                entityScriptingInterface->getEntityPacketSender()->process();
                QCoreApplication::processEvents();
            }
        } else {
            // FIXME - do we need to have a similar "wait here" loop for non-threaded packet senders?
        }
    }

    emit finished(_fileNameString);

    _isRunning = false;
    emit runningStateChanged();

    emit doneRunning();

    _doneRunningThisScript = true;
}
Ejemplo n.º 29
0
Literature::MergeResult Literature::getMergeList(QString &list1, QString &list2){
    int L1size = 0, L2size = 0, L1innerRepetition = 0, L2innerRepetition = 0, LresultSize = 0, titleProblem = 0, repetition = 0;
    //процент сопоставления двух названий при котором считается, что названия схожи
    //при разной длине названий в основной список помещается более длинное
    double comparisonPrecision = Biblio::COMPARISON_PRECISION;
    deleteExcessControlSymbols(list1);
    deleteExcessControlSymbols(list2);

    QStringList *L1 = main_string_normalization(list1);
    QStringList *L2 = main_string_normalization(list2);
    //QSharedPointer<QStringList> List1()

    for(int i = 0; i < L1->size(); ){
        if(L1->at(i).isEmpty()){
            L1->removeAt(i); continue;
        }
        ++i;
    }
    for(int i = 0; i < L2->size(); ){
        if(L2->at(i).isEmpty()){
            L2->removeAt(i); continue;
        }
        ++i;
    }
    L1size = L1->size();
    L2size = L2->size();

    QStringList L1_Titles;
    QStringList L2_Titles;


    for(int i = 0; i < L1->size(); ++i){
        L1_Titles.append(getArticleTitle((*L1)[i]));
        //deleteExcessSeparators(L1_Titles.last());
        if (!L1->at(i).contains(Biblio::titleControlPoint)){
            ++titleProblem;
           //qDebug() >> L1->at(i);
        }
        //        qDebug() >> L1_Titles.last();
    }

    for(int i = 0; i < L2->size(); ++i){
        L2_Titles.append(getArticleTitle((*L2)[i]));
        //deleteExcessSeparators(L2_Titles.last());
        if (!L2->at(i).contains(Biblio::titleControlPoint)){
            ++titleProblem;
           // qDebug() >> L2->at(i);
        }
        //        qDebug() >> L2_Titles.last();
    }

    if ( L1_Titles.size() != L1->size() || L2_Titles.size() != L2->size()){
        QString err("Something WRONG: Critical ERROR!\nКритическая ошибка, программа будет закрыта\nТакого не должно было случиться! Вселенная просит прощения");
        QMessageBox *mess = new QMessageBox;
        mess->setText(err);
        mess->setWindowIcon(QIcon("images:/windowIcon.png"));
        mess->setStandardButtons(QMessageBox::Ok);
        if(mess->exec() == QMessageBox::Ok)
            QApplication::quit();
        exit(1);
    }
    for(int i = 0; i < L1->size(); ++i){
        for(int n = i+1; n < L1->size();){
            double comparisonPercent = compareTitles(L1_Titles[i], L1_Titles[n]);
            if(comparisonPercent >= comparisonPrecision){
                ++L1innerRepetition;
                if(L1_Titles.at(i).size() < L1_Titles.at(n).size())
                    (*L1)[i] = (*L1)[n];

                L1_Titles.removeAt(n);
                L1->removeAt(n); continue;
            }
            ++n;
        }
        emit progress(i*100/L1->size(), Stage::ListCheck_1);
    }
    for(int i = 0; i < L2->size(); ++i){
        for(int n = i+1; n < L2->size();){
            double comparisonPercent = compareTitles(L2_Titles[i], L2_Titles[n]);
            if(comparisonPercent >= comparisonPrecision){
                ++L2innerRepetition;
                if(L2_Titles.at(i).size() < L2_Titles.at(n).size())
                    (*L2)[i] = (*L2)[n];

                L2_Titles.removeAt(n);
                L2->removeAt(n); continue;
            }
            ++n;
        }
        emit progress(i*100/L2->size(), Stage::ListCheck_2);
    }
#ifdef TEST
    QElapsedTimer *timer = new QElapsedTimer;
    timer->start();
    int TEST = 20;
    for(int i = TEST; i >= 0; --i)
#endif
        for(int i = 0; i < L1->size(); ++i){
            for(int n = 0; n < L2->size();){
                //qDebug() >> int(L1_Titles[i] == L2_Titles[n]);
                // if( L1_Titles[i] == L2_Titles[n]){
                double comparisonPercent = compareTitles(L1_Titles[i], L2_Titles[n]);
//                            qDebug() >> L1_Titles[i] >> "\n" >> L2_Titles[n];
//                            qDebug() >> comparisonPercent;
//                            qDebug() >> "_________________________________________________________";
                if( comparisonPercent >= comparisonPrecision){
                    ++repetition;
                    if(L2_Titles.at(n).size() > L1_Titles.at(i).size())
                        (*L1)[i] = (*L2)[n];

                    L2_Titles.removeAt(n);
                    L2->removeAt(n); continue;
                }
                ++n;
            }
             emit progress(i*100/L1->size(), Stage::MergeLists);
        }
#ifdef TEST
    qDebug() >> timer->nsecsElapsed()/TEST;
#endif
    for(int i = 0; i < L2->size(); ++i){
        L1->append(L2->at(i));
    }
    LresultSize = L1->size();

    //QString result = L1->join("\n");
    QString report = QString("Элементов в Списке 1 : ") + QString::number(L1size) + QString("\n") +
            QString ("Элементов в Списке 2 : ") + QString::number(L2size) + QString("\n") +
            QString ("Повторяющихся внутри Списка 1 : ") + QString::number(L1innerRepetition) + QString("\n") +
            QString ("Повторяющихся внутри Списка 2 : ") + QString::number(L2innerRepetition) + QString("\n") +
            QString ("Не удалось распознать название элемента : ") + QString::number(titleProblem) + QString("\n") +
            QString ("Совпадающих элементов : ") + QString::number(repetition) + QString("\n") +
            QString ("Элементов в конечном списке : ") + QString::number(LresultSize);


    Literature::MergeResult result;
    result.resultList = QSharedPointer<QStringList>(L1);
    result.newElements = QSharedPointer<QStringList>(L2);
    result.report = report;

    //    QTextDocument resultDoc;
    //    QString s = L1->join("\n");
    //    resultDoc.setPlainText(s);
    //    s = resultDoc.toHtml();
    //qDebug() >> s;
    return result;


}
Ejemplo n.º 30
0
void CaptureContext::LoadCapture(const rdcstr &captureFile, const rdcstr &origFilename,
                                 bool temporary, bool local)
{
  m_LoadInProgress = true;

  if(local)
    m_Config.CrashReport_LastOpenedCapture = origFilename;

  bool newCapture = (!temporary && !Config().RecentCaptureFiles.contains(origFilename));

  LambdaThread *thread = new LambdaThread([this, captureFile, origFilename, temporary, local]() {
    LoadCaptureThreaded(captureFile, origFilename, temporary, local);
  });
  thread->selfDelete(true);
  thread->start();

  QElapsedTimer loadTimer;
  loadTimer.start();

  ShowProgressDialog(m_MainWindow, tr("Loading Capture: %1").arg(origFilename),
                     [this]() { return !m_LoadInProgress; },
                     [this]() { return UpdateLoadProgress(); });

  ANALYTIC_ADDAVG(Performance.LoadTime, double(loadTimer.nsecsElapsed() * 1.0e-9));

  ANALYTIC_SET(CaptureFeatures.ShaderLinkage, m_APIProps.ShaderLinkage);
  ANALYTIC_SET(CaptureFeatures.YUVTextures, m_APIProps.YUVTextures);
  ANALYTIC_SET(CaptureFeatures.SparseResources, m_APIProps.SparseResources);
  ANALYTIC_SET(CaptureFeatures.MultiGPU, m_APIProps.MultiGPU);
  ANALYTIC_SET(CaptureFeatures.D3D12Bundle, m_APIProps.D3D12Bundle);

  m_MainWindow->setProgress(-1.0f);

  if(m_CaptureLoaded)
  {
    m_CaptureTemporary = temporary;

    m_CaptureMods = CaptureModifications::NoModifications;

    rdcarray<ICaptureViewer *> viewers(m_CaptureViewers);

    // make sure we're on a consistent event before invoking viewer forms
    if(m_LastDrawcall)
      SetEventID(viewers, m_LastDrawcall->eventId, true);
    else if(!m_Drawcalls.empty())
      SetEventID(viewers, m_Drawcalls.back().eventId, true);

    GUIInvoke::blockcall([&viewers]() {
      // notify all the registers viewers that a capture has been loaded
      for(ICaptureViewer *viewer : viewers)
      {
        if(viewer)
          viewer->OnCaptureLoaded();
      }
    });

    if(newCapture && m_Notes.contains(lit("comments")))
    {
      if(!HasCommentView())
        ShowCommentView();
      RaiseDockWindow(GetCommentView()->Widget());
    }
  }
}