Beispiel #1
0
QVector<qreal> PolarChartLogValueAxisRadial::calculateLayout() const
{
    QLogValueAxis *logValueAxis = qobject_cast<QLogValueAxis *>(axis());

    QVector<qreal> points;
    points.resize(logValueAxis->tickCount());

    const qreal logMax = std::log10(logValueAxis->max()) / std::log10(logValueAxis->base());
    const qreal logMin = std::log10(logValueAxis->min()) / std::log10(logValueAxis->base());
    const qreal innerEdge = logMin < logMax ? logMin : logMax;
    const qreal delta = (axisGeometry().width() / 2.0) / qAbs(logMax - logMin);
    const qreal initialSpan = (qCeil(innerEdge) - innerEdge) * delta;

    for (int i = 0; i < logValueAxis->tickCount(); ++i)
        points[i] = initialSpan + (delta * qreal(i));

    return points;
}
Beispiel #2
0
void TestQgsSvgCache::threadSafePicture()
{
  // QPicture playback is NOT thread safe with implicitly shared copies - this
  // unit test checks that concurrent drawing of svg as QPicture from QgsSvgCache
  // returns a detached copy which is safe to use across threads

  // refs:
  // https://issues.qgis.org/issues/17077
  // https://issues.qgis.org/issues/17089

  QgsSvgCache cache;
  QString svgPath = TEST_DATA_DIR + QStringLiteral( "/sample_svg.svg" );

  // smash picture rendering over multiple threads
  QVector< int > list;
  list.resize( 100 );
  QtConcurrent::blockingMap( list, RenderPictureWrapper( cache, svgPath ) );
}
Beispiel #3
0
bool ImageIO::writeImage(QVector<int> &pixels, const QString &filePath, const LayerDesc &desc, int width, int height)
{
    assert(desc.numChannels() == 3);

    QVector<float> image;
    image.resize(pixels.size()*3);
    float* data = image.data();
    for(int i=0; i<pixels.size(); i++){
        int value = pixels.at(i);
        double fvalue = (double)value / 255.0;
        data[3*i]   = fvalue - floor(fvalue);
        fvalue = (double)value / (255.0*255.0);
        data[3*i+1] = fvalue - floor(fvalue);
        fvalue = (double)value / (255.0*255.0*255.0);
        data[3*i+2] = fvalue - floor(fvalue);
    }
   return writeImage(image,filePath,desc,width,height);
}
Beispiel #4
0
int getSoundInputFromUID(int inputid, const QString& uid)
{
    if(uid.isEmpty())
        return inputid;

    QVector<SoundDevice> inputdev;
    int count = 0;
    TT_GetSoundDevices(NULL, &count);
    inputdev.resize(count);
    if(count)
        TT_GetSoundDevices(&inputdev[0], &count);

    SoundDevice dev;
    if(getSoundDevice(uid, inputdev, dev))
        inputid = dev.nDeviceID;

    return inputid;
}
Beispiel #5
0
void NeuroMlWorker::synchronizeSimulator(Simulator *simulator) {
    NeuronSimulator* neuronSimulator = qobject_cast<NeuronSimulator*>(simulator);
    QVector<CylinderVBOData> renderableData;
    renderableData.resize(m_cylinders.size());

    double scale = neuronSimulator->scale();
    for(int i = 0; i < m_cylinders.size(); i++) {
        const CylinderFrustum& cylinder = m_cylinders.at(i);
        CylinderVBOData &renderableCylinder = renderableData[i];
        renderableCylinder.radius1 = scale * cylinder.startRadius.value();
        renderableCylinder.radius2 = scale * cylinder.endRadius.value();
        renderableCylinder.vertex1 = scale * QVector3D(cylinder.start.x.value(), cylinder.start.y.value(), cylinder.start.z.value());
        renderableCylinder.vertex2 = scale * QVector3D(cylinder.end.x.value(), cylinder.end.y.value(), cylinder.end.z.value());
    }
    neuronSimulator->cylinderData()->setData(renderableData);
    neuronSimulator->m_cylinders = m_cylinders;
    neuronSimulator->m_boundingBox = m_boundingBox;
}
QgsRasterRenderer* QgsPalettedRendererWidget::renderer()
{
  int nColors = mTreeWidget->topLevelItemCount();
  QColor* colorArray = new QColor[nColors];
  QVector<QString> labels;
  for ( int i = 0; i < nColors; ++i )
  {
    colorArray[i] = mTreeWidget->topLevelItem( i )->background( 1 ).color();
    QString label = mTreeWidget->topLevelItem( i )->text( 2 );
    if ( !label.isEmpty() )
    {
      if ( i >= labels.size() ) labels.resize( i + 1 );
      labels[i] = label;
    }
  }
  int bandNumber = mBandComboBox->itemData( mBandComboBox->currentIndex() ).toInt();
  return new QgsPalettedRasterRenderer( mRasterLayer->dataProvider(), bandNumber, colorArray, nColors, labels );
}
bool JsonDbReduceDefinition::compileFunctions(QJSEngine *scriptEngine, QJsonObject definition, JsonDbJoinProxy *proxy,
                                              QVector<QJSValue> &functions, QString &message)
{
    bool status = true;
    QStringList functionNames = (QStringList()
                                 << QLatin1String("add")
                                 << QLatin1String("subtract")
                                 << QLatin1String("sourceKeyFunction"));
    int i = 0;
    functions.resize(3);
    foreach (const QString &functionName, functionNames) {
        int functionNumber = i++;
        if (!definition.contains(functionName))
            continue;
        QString script = definition.value(functionName).toString();
        QString jsonDbBinding = proxy
            ? QStringLiteral("{createUuidFromString: proxy.createUuidFromString}")
            : QStringLiteral("{}"); // strict mode causes the above to fail if proxy is undefined

        // first, package it as a function that takes a jsondb proxy and returns the add/subtract function
        QJSValue moduleFunction = scriptEngine->evaluate(QString::fromLatin1("(function (proxy) { %3 var jsondb = %2; return (%1); })")
                                                         .arg(script)
                                                         .arg(jsonDbBinding)
                                                         .arg(jsondbSettings->useStrictMode() ? QLatin1Literal("\"use strict\"; ") : QLatin1Literal("/* use nonstrict mode */")));

        if (moduleFunction.isError() || !moduleFunction.isCallable()) {
            message = QString::fromLatin1("Unable to parse %1 function: %2").arg(functionName).arg(moduleFunction.toString());
            status = false;
            continue;
        }

        // now pass it the jsondb proxy to get the add/subtract function
        QJSValueList args;
        if (proxy)
            args << scriptEngine->newQObject(proxy);
        else
            args << QJSValue(QJSValue::UndefinedValue);
        QJSValue function = moduleFunction.call(args);
        if (function.isError() || !function.isCallable()) {
            message = QString::fromLatin1("Unable to evaluate %1 function: %2").arg(functionName).arg(function.toString());
            status = false;
        }
        functions[functionNumber] = function;
    }
Beispiel #8
0
TraceObject* CachegrindLoader::compressedObject(const QString& name)
{
    if ((name[0] != '(') || !name[1].isDigit()) return _data->object(checkUnknown(name));

    // compressed format using _objectVector
    int p = name.indexOf(')');
    if (p<2) {
        error(QStringLiteral("Invalid compressed ELF object ('%1')").arg(name));
        return 0;
    }
    int index = name.midRef(1, p-1).toInt();
    TraceObject* o = 0;
    p++;
    while((name.length()>p) && name.at(p).isSpace()) p++;
    if (name.length()>p) {
        if (_objectVector.size() <= index) {
            int newSize = index * 2;
#if TRACE_LOADER
            qDebug() << " CachegrindLoader: objectVector enlarged to "
                     << newSize;
#endif
            _objectVector.resize(newSize);
        }

        QString realName = checkUnknown(name.mid(p));
        o = (TraceObject*) _objectVector.at(index);
        if (o && (o->name() != realName)) {
            error(QStringLiteral("Redefinition of compressed ELF object index %1 (was '%2') to %3")
                  .arg(index).arg(o->name()).arg(realName));
        }

        o = _data->object(realName);
        _objectVector.replace(index, o);
    }
    else {
        if ((_objectVector.size() <= index) ||
            ( (o=(TraceObject*)_objectVector.at(index)) == 0)) {
            error(QStringLiteral("Undefined compressed ELF object index %1").arg(index));
            return 0;
        }
    }

    return o;
}
Beispiel #9
0
bool ALSACapturer::processorStarted()
{
	m_max = 0.f;
	m_error = 0.f;

	snd_pcm_hw_params_t *hwparams;
	snd_pcm_hw_params_alloca(&hwparams);
	thePcmHandle = 0;
	if (snd_pcm_open(&thePcmHandle, theDevice.toLatin1(), SND_PCM_STREAM_CAPTURE, thePeriodSize * thePeriods) < 0)
		fprintf(stderr, "Error opening PCM device %s\n", qPrintable(theDevice));
	else if (snd_pcm_hw_params_any(thePcmHandle, hwparams) < 0)
		fprintf(stderr, "Can not configure this PCM device.\n");
	else if (snd_pcm_hw_params_set_access(thePcmHandle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
		fprintf(stderr, "Error setting access.\n");
	else if (snd_pcm_hw_params_set_format(thePcmHandle, hwparams, SND_PCM_FORMAT_S16_LE) < 0)
		fprintf(stderr, "Error setting format.\n");
	else if (snd_pcm_hw_params_set_rate_resample(thePcmHandle, hwparams, theFrequency))
		fprintf(stderr, "The rate %d Hz is not supported by your hardware.\n", theFrequency);
	else if (snd_pcm_hw_params_set_channels(thePcmHandle, hwparams, theChannels) < 0)
		fprintf(stderr, "Error setting channels.\n");
	else if (snd_pcm_hw_params_set_periods(thePcmHandle, hwparams, thePeriods, 0) < 0)
		fprintf(stderr, "Error setting periods.\n");
	else if (snd_pcm_hw_params_set_buffer_size(thePcmHandle, hwparams, (thePeriodSize * thePeriods)) < 0)
		fprintf(stderr, "Error setting buffersize.\n");
	else if (snd_pcm_hw_params(thePcmHandle, hwparams) < 0)
		fprintf(stderr, "Error setting HW params.\n");
	else
	{
		uint f;
		snd_pcm_hw_params_get_rate_resample(thePcmHandle, hwparams, &f);
		qDebug() << "*** ACTUAL FREQUENCY" << f;
		m_inData.resize(thePeriodSize * theChannels);
		assert(!snd_pcm_nonblock(thePcmHandle, 1));
		snd_pcm_prepare(thePcmHandle);
		m_normalisation.clear();
		for (uint c = 0; c < numOutputs(); c++)
			m_inAvg[c] = 0.f;
		return true;
	}
	if (thePcmHandle)
		snd_pcm_close(thePcmHandle);
	thePcmHandle = 0;
	return false;
}
Beispiel #10
0
// Note: Callgrind sometimes gives different IDs for same file
// (when references to same source file come from different ELF objects)
TraceFile* CachegrindLoader::compressedFile(const QString& name)
{
    if ((name[0] != '(') || !name[1].isDigit()) return _data->file(checkUnknown(name));

    // compressed format using _fileVector
    int p = name.indexOf(')');
    if (p<2) {
        error(QStringLiteral("Invalid compressed file ('%1')").arg(name));
        return 0;
    }
    int index = name.midRef(1, p-1).toUInt();
    TraceFile* f = 0;
    p++;
    while((name.length()>p) && name.at(p).isSpace()) p++;
    if (name.length()>p) {
        if (_fileVector.size() <= index) {
            int newSize = index * 2;
#if TRACE_LOADER
            qDebug() << " CachegrindLoader::fileVector enlarged to "
                     << newSize;
#endif
            _fileVector.resize(newSize);
        }

        QString realName = checkUnknown(name.mid(p));
        f = (TraceFile*) _fileVector.at(index);
        if (f && (f->name() != realName)) {
            error(QStringLiteral("Redefinition of compressed file index %1 (was '%2') to %3")
                  .arg(index).arg(f->name()).arg(realName));
        }

        f = _data->file(realName);
        _fileVector.replace(index, f);
    }
    else {
        if ((_fileVector.size() <= index) ||
            ( (f=(TraceFile*)_fileVector.at(index)) == 0)) {
            error(QStringLiteral("Undefined compressed file index %1").arg(index));
            return 0;
        }
    }

    return f;
}
void Generator::generateData(const QAudioFormat& format, unsigned char* ptr, qint64 length)
{
	const int channelBytes = format.sampleSize() / 8;
	if (length <= 0)
		return;
    QMutexLocker lock(m_mutex);

	QVector<qreal> channels;
    channels.resize(2);
	
//	LOG_INFO() << "generating Sounds" << QDateTime::currentDateTime() << length;
	initializeSounds();
	
    while (length) {
        generateTone(channels[0], channels[1], m_sampleIndex);
        //const qreal x = soundFunc(2 * M_PI * frequency * qreal(sampleIndex  ) / format.sampleRate());
        for (int i=0; i<format.channelCount(); ++i) {
            if (format.sampleSize() == 8 && format.sampleType() == QAudioFormat::UnSignedInt) {
                const quint8 value = static_cast<quint8>((1.0 + channels[i]) / 2 * 255);
                *reinterpret_cast<quint8*>(ptr) = value;
            } else if (format.sampleSize() == 8 && format.sampleType() == QAudioFormat::SignedInt) {
                const qint8 value = static_cast<qint8>(channels[i] * 127);
                *reinterpret_cast<quint8*>(ptr) = value;
            } else if (format.sampleSize() == 16 && format.sampleType() == QAudioFormat::UnSignedInt) {
                quint16 value = static_cast<quint16>((1.0 + channels[i]) / 2 * 65535);
                if (format.byteOrder() == QAudioFormat::LittleEndian)
                    qToLittleEndian<quint16>(value, ptr);
                else
                    qToBigEndian<quint16>(value, ptr);
            } else if (format.sampleSize() == 16 && format.sampleType() == QAudioFormat::SignedInt) {
                qint16 value = static_cast<qint16>(channels[i] * 32767);
                if (format.byteOrder() == QAudioFormat::LittleEndian)
                    qToLittleEndian<qint16>(value, ptr);
                else
                    qToBigEndian<qint16>(value, ptr);
            }

            ptr += channelBytes;
            length -= channelBytes;
        }
        ++m_sampleIndex;
    }
	
}
Beispiel #12
0
void FourierDCT::rearrangeDct(QVector<Complex> &elements, bool inverse)
{
	QVector<Complex> result;
	if (!inverse) {
		for (int k = 0; k < elements.size(); k += 2) {
			result << elements.at(k);
		}
		for (int k = elements.size() - 1; k >= 0; k -= 2) {
			result << elements.at(k);
		}
	} else {
		result.resize(elements.size());
		for (int i = 0; i < elements.size() / 2; i++) {
			result[2 * i] = elements.at(i);
			result[2 * i + 1] = elements.at(elements.size() - 1 - i);
		}
	}
	elements = result;
}
Beispiel #13
0
QVector<cl_platform_id> getPlatformList()
{
    QVector<cl_platform_id> list;
    cl_int rv = CL_SUCCESS;
    cl_uint count = 0;

    rv = clGetPlatformIDs(0, NULL, &count);
    if (rv!=CL_SUCCESS || !count)
    {
        return list;
    }
    list.resize(count);
    rv = clGetPlatformIDs(list.size(), list.data(), NULL);
    if (rv!=CL_SUCCESS)
    {
        list.clear();
    }
    return list;
}
QVector<ShaderUniform> QGraphicsHelperES2::programUniformsAndLocations(GLuint programId)
{
    QVector<ShaderUniform> uniforms;

    GLint nbrActiveUniforms = 0;
    m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms);
    uniforms.resize(nbrActiveUniforms);
    for (GLint i = 0; i < nbrActiveUniforms; i++) {
        ShaderUniform uniform;
        QByteArray uniformName(256, '\0');
        // Size is 1 for scalar and more for struct or arrays
        // Type is the GL Type
        m_funcs->glGetActiveUniform(programId, i, 256, NULL, &uniform.m_size, &uniform.m_type , uniformName.data());
        uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName.constData());
        uniform.m_name = QString::fromUtf8(uniformName);
        uniforms.append(uniform);
    }
    return uniforms;
}
Beispiel #15
0
	void ParseAsksData(const QJsonObject& json, QVector<AsksData>& vecAsksData)
	{
		QJsonArray jaSubPrice = json[szAttributeName[AN_PRICE]].toArray();
		QJsonArray jaSubLevel = json[szAttributeName[AN_LEVEL]].toArray();
		QJsonArray jaSubAmount = json[szAttributeName[AN_AMOUNT]].toArray();
		QJsonArray jaSubAccuAmount = json[szAttributeName[AN_ACCUAMOUNT]].toArray();

		vecAsksData.resize(jaSubPrice.size());

		for (int ix = 0; ix != vecAsksData.size(); ++ix)
		{
			AsksData& ad = vecAsksData[ix];

			ad.dPrice = jaSubPrice[ix].toDouble();
			ad.dLevel = jaSubLevel[ix].toDouble();
			ad.dAmount = jaSubAmount[ix].toDouble();
			ad.dAccuAmount = jaSubAccuAmount[ix].toDouble();
		}
	}
void Vehicle::load(QString fileName)
{
    QVector<double> dna;
    QFile *file = new QFile(fileName);
    if (! file -> open(QIODevice::ReadOnly | QIODevice::Text))
    {
        // Error while trying to read file
    }
    else
    {
        // Everything is OK
        QTextStream in(file);
        in >> x;
        in >> y;

        in >> pointsNum;

        int dna_size;
        in >> dna_size;
        dna.resize(dna_size);
        in >> maxWheelsNum;
        in >> wheelsNum;
        in >> springSegmentsNum;
        in >> springWidth;
        in >> springLength;

        in >> wheelRemoveChance;
        in >> wheelAddChance;

        in >> vectorLength;
        in >> wheelRadius;

        for(int i = 0; i < dna.size(); ++i)
        {
            in >> dna[i];
        }
    }

    setDNA(dna);

    file -> close();
    lastUpdateTime = QTime::currentTime();
}
Beispiel #17
0
QVector<double> TimeSeriesMotion::calcTimeSeries(QVector<std::complex<double> > fa, const QVector<std::complex<double> > & tf) const
{
    // Apply the transfer fucntion
    if (!tf.isEmpty()) {

        // If needed, zero pad the Fourier amplitudes such that is has the same length as the incoming transfer function.
        if (fa.size() << tf.size())
            fa.resize(tf.size());

        for (int i = 0; i < fa.size(); ++i)
            fa[i] *= tf.at(i);
    }

    // Compute the time series
    QVector<double> ts;
    ifft(fa, ts);

    return ts;
}
Beispiel #18
0
void Grid::generateVertexData( QVector<float>& vertices,
                               QVector<unsigned int>& indices )
{
    Q_UNUSED( indices );
    vertices.resize( vertexCount() * 3);
    //indices.resize( 6 * m_xDivisions * m_yDivisions );

    float x2 = m_width / 2.0f;
    float y2 = m_height / 2.0f;
    float iFactor = static_cast<float>( m_height ) / static_cast<float>( m_yDivisions );
    float jFactor = static_cast<float>( m_width ) / static_cast<float>( m_xDivisions );
    int vertexIndex = 0;


    for ( int i = 0; i <= m_yDivisions; ++i )
    {
        float y = iFactor * i - y2;
        vertices[vertexIndex] = -x2;
        vertices[vertexIndex+1] = 0.0f;
        vertices[vertexIndex+2] = y;
        
        vertices[vertexIndex+3] = x2;
        vertices[vertexIndex+4] = 0.0f;
        vertices[vertexIndex+5] = y;
        
        vertexIndex += 6;
    }
    
    for ( int j = 0; j <= m_xDivisions; ++j )
    {
        float x = jFactor * j - x2;
        vertices[vertexIndex] = x;
        vertices[vertexIndex+1] = 0.0f;
        vertices[vertexIndex+2] = -y2;
        
        vertices[vertexIndex+3] = x;
        vertices[vertexIndex+4] = 0.0f;
        vertices[vertexIndex+5] = y2;
        
        vertexIndex += 6;
    }
}
Beispiel #19
0
BrushMask BrushMaskGenerator::make(float pressure) const
{
	float r;
	int lut_len;
	const uchar *lut;
	int p;
	if(_usepressure) {
		p = pressure2int(pressure);
		lut = _lut.data() + _index.at(p);
		lut_len = _index.at(p+1) - _index.at(p);
		r = _radius.at(p);
	} else {
		p = 255;
		lut = _lut.data();
		lut_len = _index.at(0);
		r = _radius.at(0);
	}

	// check cache first
	BrushMask *cached = _cache[p];
	if(cached)
		return *cached;

	const int diameter = int(r*2) + 1;

	QVector<uchar> data;
	data.resize(square(diameter));
	uchar *ptr = data.data();

	for(int y=0;y<diameter;++y) {
		const qreal yy = square(y-r+0.5);
		for(int x=0;x<diameter;++x) {
			const int dist = int(square(x-r+0.5) + yy);
			*(ptr++) = dist<lut_len ? lut[dist] : 0;
		}
	}

	BrushMask *bm = new BrushMask(diameter, data);
	_cache.insert(p, bm);

	return *bm;
}
Beispiel #20
0
void Stream::createData()
{
    //read input
    QString runNumber = QString::number(uiStream->spinBox_number->value());
    QString year      = QString::number(uiStream->spinBox_year->value());
    QString input     = year+":"+runNumber;

    //make default settings: all 1f runs are summed, use default mode for 2e
    int     sum = 1, e2 = 0;
    QString kill = "";

    //specify number of graphs
    int nbGrs = 4;
    //specify the indices of each file //read bnmr.cpp to make sense of these
    QStringList subType[nbGrs],runList[nbGrs];
    subType[0]<<"0"<<"1"<<"2";//0:"Asy" 1:"Asy+" 2:"Asy-" 3:"AsyForR" 4:"AsyBorL"
    subType[1]<<"5"<<"6"<<"7";//5:"AsyN" 6:"AsyN+" 7:"AsyN-"
    subType[2]<<"8"<<"9"<<"10"<<"11";//8:"ForR+" 9:"BorL+" 10:"ForR-" 11:"BorL-"
    subType[3]<<"12"<<"13"<<"14"<<"15";//12:"NF+" 13:"NB+"  14:"NF+"   15:"NB-"

    QVector< QVector<QString> > files;
    files.resize(nbGrs);

    QString xlabel, ylabel;
    xlabel = "Bin";
    ylabel = "Histogram";
    QVector<QString> xLabels,yLabels;
    for(int i = 0; i < nbGrs; i++)
    {
        BNMR bnmr(input,subType[i],bin,x_min,x_max,sum,e2,kill);//This is defined in bnmr.cpp
        QStringList headers;
        QVector< QVector <QString> > headerValue;
        runList[i] = bnmr.bNMRfiles(headers,headerValue);//This is defined in bnmr.cpp
        for(int j = 0; j<runList[i].size(); j++)
            files[i].push_back(runList[i][j]);
        xLabels.push_back(xlabel);
        yLabels.push_back(ylabel);
    }
    //send to plot
    Plotting plot;
    plot.stream(uiStream->plotWidget,files,xLabels,yLabels);
}
Beispiel #21
0
void Faceshift::updateFakeCoefficients(float leftBlink, float rightBlink, float browUp,
        float jawOpen, float mouth2, float mouth3, float mouth4, QVector<float>& coefficients) const {
    const int MMMM_BLENDSHAPE = 34;
    const int FUNNEL_BLENDSHAPE = 40;
    const int SMILE_LEFT_BLENDSHAPE = 28;
    const int SMILE_RIGHT_BLENDSHAPE = 29;
    const int MAX_FAKE_BLENDSHAPE = 40;  //  Largest modified blendshape from above and below

    coefficients.resize(max((int)coefficients.size(), MAX_FAKE_BLENDSHAPE + 1));
    qFill(coefficients.begin(), coefficients.end(), 0.0f);
    coefficients[_leftBlinkIndex] = leftBlink;
    coefficients[_rightBlinkIndex] = rightBlink;
    coefficients[_browUpCenterIndex] = browUp;
    coefficients[_browUpLeftIndex] = browUp;
    coefficients[_browUpRightIndex] = browUp;
    coefficients[_jawOpenIndex] = jawOpen;
    coefficients[SMILE_LEFT_BLENDSHAPE] = coefficients[SMILE_RIGHT_BLENDSHAPE] = mouth4;
    coefficients[MMMM_BLENDSHAPE] = mouth2;
    coefficients[FUNNEL_BLENDSHAPE] = mouth3;
}
Beispiel #22
0
bool ImageIO::writeImage(QVector<Color4> &pixels, const QString &filePath, const LayerDesc &desc, int width, int height)
{
    assert(desc.numChannels() == 4);

    if(desc._layer_name == "rgba"){
        return writeImage(pixels,filePath,width,height);
    }else{
        QVector<float> image;
        image.resize(pixels.size()*4);
        float* data = image.data();
        for(int i=0; i<pixels.size(); i++){
            Color4 c = pixels.at(i);
            data[4*i]   = c.r;
            data[4*i+1] = c.g;
            data[4*i+2] = c.b;
            data[4*i+3] = c.a;
        }
        return writeImage(image,filePath,desc,width,height);
    }
}
Beispiel #23
0
void EventQueue::removeEvents(Agent* agent)
{
    if(myAgentEvents.contains(agent))
    {
        QList<Event*> events = myAgentEvents[agent];
        myAgentEvents[agent].clear();
        QVector<uint64_t> times;
        times.resize(events.size());
        for(int i=0;i<events.size();++i)
        {
            times[i]=events[i]->time();
            myQueue[events[i]->time()].removeAll(events[i]);
            delete events[i];
        }
        for(int i=0;i<times.size();++i)
        {
            if(myQueue[times[i]].size()==0)
                myQueue.remove(times[i]);
        }
    }
}
Beispiel #24
0
void ParseTimeLineCylinder(const QJsonObject& json, QVector<TimeLineCylinder>& vecCylinder)
{
	QJsonArray jaSubTime = json[szAttributeName[AN_TIME]].toArray();
	QJsonArray jaSubPriceLast = json[szAttributeName[AN_PRICELAST]].toArray();
	QJsonArray jaSubAmount = json[szAttributeName[AN_AMOUNT]].toArray();
	QJsonArray jaSubVolume = json[szAttributeName[AN_VOLUME]].toArray();
	QJsonArray jaSubCount = json[szAttributeName[AN_COUNT]].toArray();

	vecCylinder.resize(jaSubTime.size());

	for (int ix = 0; ix != vecCylinder.size(); ++ix)
	{
		TimeLineCylinder& cylinder = vecCylinder[ix];

		cylinder.tTime = jaSubTime[ix].toDouble();
		cylinder.dPriceLast = jaSubPriceLast[ix].toDouble();
		cylinder.dAmount = jaSubAmount[ix].toDouble();
		cylinder.dVolume = jaSubVolume[ix].toDouble();
		cylinder.nCount = jaSubCount[ix].toInt();
	}
}
Beispiel #25
0
void EFX::preview(QVector <QPoint>& polygon, Function::Direction direction, int startOffset) const
{
    int stepCount = 128;
    int step = 0;
    qreal stepSize = (qreal)(1) / ((qreal)(stepCount) / (M_PI * 2.0));

    qreal i = 0;
    qreal x = 0;
    qreal y = 0;

    /* Resize the array to contain stepCount points */
    polygon.resize(stepCount);

    /* Draw a preview of the effect */
    for (step = 0; step < stepCount; step++)
    {
        calculatePoint(direction, startOffset, i, &x, &y);
        polygon[step] = QPoint(int(x), int(y));
        i += stepSize;
    }
}
bool KITTIReader::ReadVelodyneData(QVector<TimedVelo> & velo, const QVector<int> & indexes) const
{
    velo.resize(indexes.size());
    bool success = true, tss1 = true, tss2 = true, tss3 = true;

    QStringList list, liststart, listend;

    if (!ReadTimestampFile(list, KITTI_VELO_TIMESTAMPS(bdir))) tss1 = false;
    if (!ReadTimestampFile(liststart, KITTI_VELO_TIMESTAMPS_START(bdir))) tss2 = false;
    if (!ReadTimestampFile(listend, KITTI_VELO_TIMESTAMPS_END(bdir))) tss3 = false;

    for (int j = 0; j < indexes.size(); j++)
    {
        if (!ReadVeloFile(velo[j].points, KITTI_VELO_NAME(bdir, indexes[j], fnw))) success = false;
        if (tss1) velo[j].tstamp = string2seconds(list.at(indexes[j]));
        if (tss2) velo[j].tstamp_start = string2seconds(liststart.at(indexes[j]));
        if (tss3) velo[j].tstamp_end = string2seconds(listend.at(indexes[j]));
    }

    return success & tss1 & tss2 & tss3;
}
QVector<cl_device_id> getDeviceList(cl_platform_id platform, cl_device_type type)
{
    QVector<cl_device_id> list;
    cl_int rv = CL_SUCCESS;
    cl_uint count = 0;

    rv = clGetDeviceIDs(platform, type, 0, NULL, &count);
    if (rv != CL_SUCCESS || !count)
    {
        return list;
    }

    list.resize(count);
    rv = clGetDeviceIDs(platform, type, list.size(), list.data(), NULL);
    if (rv != CL_SUCCESS)
    {
        list.clear();
    }

    return list;
}
Beispiel #28
0
QPair<Vector3D,Vector3D> calcBestAxisThroughPoints( const QVector<Vector3D>& points )
{
    float a[3], b[3];
    int n = points.count();
    QVector<float> buf;
    buf.resize(3*n);
    for (int i = 0; i < n; i++) {
        buf[i] = points[i].x;
        buf[n + i] = points[i].y;
        buf[2*n + i] = points[i].z;
    }

    least_squares(n, buf.data(), a, b);
    least_squares(n, buf.data() + n, a + 1, b + 1);
    least_squares(n, buf.data() + 2*n, a + 2, b + 2);

    Vector3D pointA(b[0], b[1], b[2]);
    Vector3D pointB(a[0]*(n-1) + b[0], a[1]*(n-1) + b[1], a[2]*(n-1) + b[2]);

    return QPair<Vector3D,Vector3D>(pointA, pointB);
}
Beispiel #29
0
void OnlineUsersModel::resetUsers()
{
    this->beginResetModel();

    m_users.clear();
    int n_users = 0;
    TT_GetServerUsers(ttInst, NULL, &n_users);
    if(n_users)
    {
        QVector<User> users;
        users.resize(n_users);
        TT_GetServerUsers(ttInst, &users[0], &n_users);

        for(int i=0;i<users.size();i++)
        {
            m_users.insert(users[i].nUserID, users[i]);
        }
    }

    this->endResetModel();
}
Beispiel #30
0
void QThreadStorageData::finish(void **p)
{
    QVector<void *> *tls = reinterpret_cast<QVector<void *> *>(p);
    if (!tls || tls->isEmpty() || !threadStorageMutex())
        return; // nothing to do

#ifdef THREADSTORAGE_DEBUG
    qtsDebug("QThreadStorageData: Destroying storage for thread %p", QThread::currentThread());
#endif
    while (!tls->isEmpty()) {
        void *&value = tls->last();
        void *q = value;
        value = 0;
        int i = tls->size() - 1;
        tls->resize(i);

        if (!q) {
            // data already deleted
            continue;
        }

        QMutexLocker locker(threadStorageMutex());
        void (*destructor)(void *) = destructors()->value(i);
        locker.unlock();

        if (!destructor) {
            if (QThread::currentThread())
                qWarning("QThreadStorage: Thread %p exited after QThreadStorage %d destroyed",
                         QThread::currentThread(), i);
            continue;
        }
        destructor(q); //crash here might mean the thread exited after qthreadstorage was destroyed

        if (tls->size() > i) {
            //re reset the tls in case it has been recreated by its own destructor.
            (*tls)[i] = 0;
        }
    }
    tls->clear();
}