Пример #1
0
  Texture::Texture(Ref<Image> img, const std::string fileName)
    : width(unsigned(img->width)), height(unsigned(img->height)), format(RGBA8), bytesPerTexel(4), width_mask(0), height_mask(0), data(nullptr), fileName(fileName)
  {
    width_mask  = isPowerOf2(width) ? width-1 : 0;
    height_mask = isPowerOf2(height) ? height-1 : 0;

    data = alignedMalloc(4*width*height,64);
    img->convertToRGBA8((unsigned char*)data);
  }
Пример #2
0
  Texture::Texture (size_t width, size_t height, const Format format, const char* in)
    : width(width), height(height), format(format), bytesPerTexel(getFormatBytesPerTexel(format)), data(nullptr), width_mask(0), height_mask(0)
  {
    width_mask  = isPowerOf2(width) ? width-1 : 0;
    height_mask = isPowerOf2(height) ? height-1 : 0;

    data = _mm_malloc(bytesPerTexel*width*height,64);
    if (in) memcpy(data,in,bytesPerTexel*width*height);
    else    memset(data,0 ,bytesPerTexel*width*height);
  }
Пример #3
0
Filterbank* CreateSPFilterBank(int ncols, int nrows, int scales, int orientations, int nfeats)
{
    if(!isPowerOf2(ncols) || !isPowerOf2(nrows))
    {
        Error("The Steerable Pyramid filterbank must have rows and cols power of 2","CreateSPFilterBank");
    }
    if(scales == 0)
    {
        Error("The scale must be > 0","CreateSPFilterBank");
    }
    if(orientations == 0)
    {
        Error("The orientations must be > 0","CreateSPFilterBank");
    }
    if(nfeats < scales*orientations)
    {
        Error("The total number of feats shoud be at least scales*orientations","CreateSPFilterBank");
    }

    Filterbank* bank = (Filterbank*)calloc(1,sizeof(Filterbank));

    if(bank == NULL) Error(MSG1, "Filterbank");

    int size = scales*orientations;

    bank->m_pSpectralFilterBank = NULL;
    bank->m_pSpectralFilterBank = (Spectrum**)calloc(size,sizeof(Spectrum*));

    bank->m_pFeatures = NULL;
    bank->m_pFeatures = CreateFeatures(ncols,nrows,nfeats);

    bank->orientations = orientations;
    bank->scales = scales;

    int s,k;
    int width = ncols;
    int height = nrows;

    for(s = 0; s < scales; s++)
    {
        for(k = 0; k < orientations; k++)
        {
            Spectrum* filter = CreateBandPass(width,height,k+1,orientations);

            bank->m_pSpectralFilterBank[s*orientations + k] = filter;
        }
        width = width/2;
        height = height/2;
    }

    return bank;

}
Пример #4
0
int fft_2dim(double *signal_real, double *signal_imaginary, int signal_rows, int signal_cols, int inverse, int *buffer_data, int buffer_size)
{
    int error = 0;
    int one = 1;

    if (isPowerOf2(signal_rows) && signal_rows < POW2_15)
    {
        for (int i = 0 ; i < signal_cols ; i++)
        {
            C2F(fft842)(&inverse, &signal_rows, &(signal_real[signal_rows * i]), &(signal_imaginary[signal_rows * i]), &error);
        }
    }
    else
    {
        C2F(dfft2)(signal_real, signal_imaginary, &signal_cols, &signal_rows, &one, &inverse, &error, buffer_data, &buffer_size);
    }

    if (isPowerOf2(signal_cols) && signal_cols < POW2_15)
    {
        double* temp_real = NULL;
        double* temp_imaginary = NULL;

        temp_real = (double *)MALLOC(signal_cols * sizeof(double));
        temp_imaginary = (double *)MALLOC(signal_cols * sizeof(double));

        if (temp_real == NULL || temp_imaginary == NULL)
        {
            return 1;
        }

        for (int i = 0 ; i < signal_rows ; i++)
        {
            C2F(dcopy)(&signal_cols, &(signal_real[i]), &signal_rows, temp_real, &one);
            C2F(dcopy)(&signal_cols, &(signal_imaginary[i]), &signal_rows, temp_imaginary, &one);
            C2F(fft842)(&inverse, &signal_cols, temp_real, temp_imaginary, &error);
            C2F(dcopy)(&signal_cols, temp_real, &one, &(signal_real[i]), &signal_rows);
            C2F(dcopy)(&signal_cols, temp_imaginary, &one, &(signal_imaginary[i]), &signal_rows);
        }

        FREE(temp_imaginary);
        temp_imaginary = NULL;
        free(temp_real);
        temp_real = NULL;
    }
    else
    {
        /* erroneous implementation suspected */
        C2F(dfft2)(signal_real, signal_imaginary, &one, &signal_cols, &signal_rows, &inverse, &error, buffer_data, &buffer_size);
    }

    return error;
}
Пример #5
0
  Texture::Texture (unsigned width, unsigned height, const Format format, const char* in)
    : width(width), height(height), format(format), bytesPerTexel(getFormatBytesPerTexel(format)), width_mask(0), height_mask(0), data(nullptr)
  {
    width_mask  = isPowerOf2(width) ? width-1 : 0;
    height_mask = isPowerOf2(height) ? height-1 : 0;

    data = alignedMalloc(bytesPerTexel*width*height,64);
    if (in) {
      for (size_t i=0; i<bytesPerTexel*width*height; i++)
	((char*)data)[i] = in[i];
    }
    else {
      memset(data,0 ,bytesPerTexel*width*height);
    }   
  }
Пример #6
0
// ***************************************************************************
void	CVisualCollisionMesh::CStaticGrid::create(uint nbQuads, uint nbElts, const NLMISC::CAABBox &gridBBox)
{
	/* ***********************************************
	 *	WARNING: This Class/Method must be thread-safe (ctor/dtor/serial): no static access for instance
	 *	It can be loaded/called through CAsyncFileManager for instance
	 * ***********************************************/

	nlassert(nbQuads>0 && isPowerOf2(nbQuads));

	// init the grid
	_GridSize= nbQuads;
	_GridSizePower= getPowerOf2(nbQuads);
	_Grid.resize(_GridSize*_GridSize);
	// start with 0 elt in each case
	memset(_Grid.getPtr(), 0, _Grid.size() * sizeof(CCase));

	// init the Elt Build
	_EltBuild.resize(nbElts);

	// total size is 0
	_GridDataSize= 0;

	// bbox init
	_GridPos= gridBBox.getMin();
	_GridScale= gridBBox.getSize();
	_GridScale.x= _GridSize / _GridScale.x;
	_GridScale.y= _GridSize / _GridScale.y;

	// reset intersection data
	_ItSession= 0;
}
int
FastWalshTransform::setup()
{
    // make sure the length is the power of 2
    if(isPowerOf2(length))
    {
        length = roundToPowerOf2(length);
    }

    if(setupFastWalshTransform() != SDK_SUCCESS)
    {
        return SDK_FAILURE;
    }

    int timer = sampleTimer->createTimer();
    sampleTimer->resetTimer(timer);
    sampleTimer->startTimer(timer);

    if(setupCL() != SDK_SUCCESS)
    {
        return SDK_FAILURE;
    }

    sampleTimer->stopTimer(timer);
    setupTime = (cl_double)sampleTimer->readTimer(timer);

    return SDK_SUCCESS;
}
Пример #8
0
void OouraFFT::init(size_t nfft)
{
	assert(isPowerOf2(nfft));

	ip_.resize(2 + (size_t)std::sqrt(nfft / 2));
	sineTable_.resize(nfft / 2);
	buffer_.resize(nfft);
}
Пример #9
0
void FFT(std::complex<T>* inout, size_t size, FFTDirection direction)
{
    assert(isPowerOf2(size));
    int m = iFloorLog2(size);

    // do the bit reversal
    int i2 = size / 2;
    int j = 0;
    for (int i = 0; i < (int)size - 1; ++i)
    {
        if (i < j)
            std::swap(inout[i], inout[j]);

        int k = i2;
        while(k <= j)
        {
            j = j - k;
            k = k / 2;
        }
        j += k;
    }

    // compute the FFT
    std::complex<T> c = -1;
    int l2 = 1;
    for (int l = 0; l < m; ++l)
    {
        int l1 = l2;
        l2 = l2 * 2;
        std::complex<T> u = 1;
        for (int j2 = 0; j2 < l1; ++j2)
        {
            int i = j2;
            while (i < (int)size)
            {
                int i1 = i + l1;
                std::complex<T> t1 = u * inout[i1];
                inout[i1] = inout[i] - t1;
                inout[i] += t1;
                i += l2;
            }
            u = u * c;
        }

        T newImag = sqrt((1 - real(c)) / 2);
        if (direction == FFT_FORWARD)
            newImag = -newImag;
        T newReal = sqrt((1 + real(c)) / 2);
        c = std::complex<T>(newReal, newImag);
    }

    // scaling for forward transformation
    if (direction == FFT_FORWARD)
    {
        for (int i = 0; i < (int)size; ++i)
            inout[i] = inout[i] / std::complex<T>((T)size, 0);
    }
}
Пример #10
0
/**
* @brief makePowerOf2
* @param ints
*/
static void makePowerOf2(vector<double>& ints) {
    mz_uint n = ints.size();
    if ( ! isPowerOf2( n ) ) {
        mz_uint new_s = nextPowerOf2( n );
        while ( ints.size() != new_s ) {
            ints.push_back( 0.0 );
        }
    }
}
Пример #11
0
size_t DeviceManagerOpenSl::getFramesPerBlock( const DeviceRef &device )
{
	// Nodes require frames per block to to be power of 2, and most android devices don't want power of 2 blocksizes
	// So we round up, OutputDeviceNodeOpenSl will ask for hardware block size directly.
	size_t framesPerBlockHardware = getFramesPerBlockHardware( device );
	size_t framesPerBlockPow2 = ( isPowerOf2( framesPerBlockHardware ) ? framesPerBlockHardware : nextPowerOf2( framesPerBlockHardware ) );
	CI_LOG_I( "framesPerBlockHardware: " << framesPerBlockHardware << ", framesPerBlockPow2: " << framesPerBlockPow2 );
	return framesPerBlockPow2;
}
Пример #12
0
signed char log2pow2(unsigned long long powerOf2) {
  // make sure it's a power of 2.
  assert(isPowerOf2(powerOf2));
  signed char n = -1;
  while (powerOf2 > 0) {
    powerOf2 >>= 1;
    n++;
  }
  return n;
}
Пример #13
0
int main(){

	uint32_t num;
	printf("Enter number:");
	scanf("%d",&num);
	if(isPowerOf2(num))
		printf("Is power of 2");
	else
		printf("Is not** power of 2");
}
Пример #14
0
int32 swNic_init(uint32 nRxPkthdrDesc, uint32 nRxMbufDesc, uint32 nTxPkthdrDesc, 
                        uint32 clusterSize, 
                        proc_input_pkt_funcptr_t processInputPacket, 
                        int32 reserved(struct rtl_pktHdr *))
{
	uint32  exponent;

	//check input parameters.
	if(isPowerOf2(nRxPkthdrDesc, &exponent)==FALSE)
		return EINVAL;
	if(isPowerOf2(nRxMbufDesc, &exponent)==FALSE)
		return EINVAL;
	if(isPowerOf2(nTxPkthdrDesc, &totalTxPkthdrShift)==FALSE)
		return EINVAL;
    	if (processInputPacket == NULL)
		return EINVAL;

	//we only accept 2048 byte cluster now.
	if(clusterSize!=m_clusterSize) //mbuf should be init first and cluster size must equal to the number used in mbuf init
		return EINVAL;
	assert(m_clusterSize==2048); //mBuf should be init with 2048 as cluster value
	totalRxPkthdr = nRxPkthdrDesc;
	totalRxMbuf = nRxMbufDesc;
	totalTxPkthdr = nTxPkthdrDesc;
	rxRunoutIdx=-1;
	installedProcessInputPacket = processInputPacket;
	rxPkthdr_runout=0;

	/* Allocate Rx/Tx descriptor ring.*/
	RxPkthdrRing=(uint32 *)(UNCACHE_MASK|(uint32)kmalloc((totalRxPkthdr * sizeof(struct rtl_pktHdr *)),GFP_KERNEL));
	RxMbufRing = (uint32 *)(UNCACHE_MASK|(uint32)kmalloc((totalRxMbuf * sizeof(struct rtl_mBuf *)),GFP_KERNEL));
	TxPkthdrRing = (uint32 *)(UNCACHE_MASK|(uint32)kmalloc((totalTxPkthdr * sizeof(struct rtl_pktHdr *)),GFP_KERNEL));

	if(!RxPkthdrRing||!RxMbufRing||!TxPkthdrRing)
		return EINVAL;
	mBuf_setNICRxRingSize(totalRxPkthdr);
	/* Initialize interrupt statistics counter */
	rxIntNum = rxPkthdrRunoutSolved= txIntNum = rxPkthdrRunoutNum = rxMbufRunoutNum = rxPktErrorNum = txPktErrorNum = 0;
	rxPktCounter = txPktCounter = linkChanged=0;

	//All Ring buffers allocated. Now initialize all rings and swNic itself.
	return  swNic_setup(totalRxPkthdr,totalRxMbuf,totalTxPkthdr);
}
Пример #15
0
PropertyTable::PropertyTable(VM& vm, unsigned initialCapacity)
    : JSCell(vm, vm.propertyTableStructure.get())
    , m_indexSize(sizeForCapacity(initialCapacity))
    , m_indexMask(m_indexSize - 1)
    , m_index(static_cast<unsigned*>(fastZeroedMalloc(dataSize())))
    , m_keyCount(0)
    , m_deletedCount(0)
{
    ASSERT(isPowerOf2(m_indexSize));
}
Пример #16
0
  /*! read png texture from disk */
  OBJScene::Texture *loadTexture(const FileName& fileName)
  {
    OBJScene::Texture *texture = new OBJScene::Texture();
    
    std::string ext = strlwr(fileName.ext());
    if (ext == "ptx" ) return loadPtexTexture(fileName);

    Ref<Image> img = loadImage(fileName);

    texture->width         = img.ptr->width;
    texture->height        = img.ptr->height;    
    texture->format        = OBJScene::Texture::RGBA8;
    texture->bytesPerTexel = 4;
    texture->data          = _mm_malloc(sizeof(int)*texture->width*texture->height,64);
    texture->width_mask    = isPowerOf2(texture->width) ? texture->width-1 : 0;
    texture->height_mask   = isPowerOf2(texture->height) ? texture->height-1 : 0;
    img.ptr->convertToRGBA8((unsigned char*)texture->data);
    return texture;
  }
Пример #17
0
int main()
{
    long long n;
    printf("Enter number to check\n");
    scanf("%lld", &n);
    if (isPowerOf2(n))
        printf("%lld Is a power of 2\n",n);
    else
        printf("%lld Not a power of 2\n",n);
    return 0;
}
Пример #18
0
void NoiseTable::noise( int maxgranu, float min, float max ) {
    assertmsg( isPowerOf2( (unsigned int) maxgranu), "need power of 2" );
    float m = max;
    int granu = maxgranu;
    for(;;){
        m /= 2.0;
        add( granu, min, m );
        granu /= 2;
        if( granu == 0 ) break;
    }
}
Пример #19
0
int nextPowerOf2(int n)
{
	if (isPowerOf2(n)) return n;

	int prevn = n;

	while(n &= n-1)
        prevn = n;
    return prevn * 2;

} 
Пример #20
0
void MonitorNode::initialize()
{
	if( ! mWindowSize )
		mWindowSize = getFramesPerBlock();
	else if( ! isPowerOf2( mWindowSize ) )
		mWindowSize = nextPowerOf2( static_cast<uint32_t>( mWindowSize ) );

	for( size_t ch = 0; ch < getNumChannels(); ch++ )
		mRingBuffers.emplace_back( mWindowSize * mRingBufferPaddingFactor );

	mCopiedBuffer = Buffer( mWindowSize, getNumChannels() );
}
Пример #21
0
/// @param stop       Upper bound for sieving.
/// @param sieveSize  Sieve size in bytes.
/// @param limit      Sieving primes in EratBig must be <= limit,
///                   usually limit = sqrt(stop).
///
EratBig::EratBig(uint64_t stop, uint_t sieveSize, uint_t limit) :
  Modulo210Wheel_t(stop, sieveSize),
  limit_(limit),
  log2SieveSize_(ilog2(sieveSize)),
  moduloSieveSize_(sieveSize - 1),
  stock_(NULL)
{
  // '>> log2SieveSize' requires a power of 2 sieveSize
  if (!isPowerOf2(sieveSize))
    throw primesieve_error("EratBig: sieveSize must be a power of 2");
  init(sieveSize);
}
Пример #22
0
void MonitorSpectralNode::initialize()
{
	MonitorNode::initialize();

	if( mFftSize < mWindowSize )
		mFftSize = mWindowSize;
	if( ! isPowerOf2( mFftSize ) )
		mFftSize = nextPowerOf2( static_cast<uint32_t>( mFftSize ) );
	
	mFft = unique_ptr<dsp::Fft>( new dsp::Fft( mFftSize ) );
	mFftBuffer = audio::Buffer( mFftSize );
	mBufferSpectral = audio::BufferSpectral( mFftSize );
	mMagSpectrum.resize( mFftSize / 2 );

	if( ! mWindowSize  )
		mWindowSize = mFftSize;
	else if( ! isPowerOf2( mWindowSize ) )
		mWindowSize = nextPowerOf2( static_cast<uint32_t>( mWindowSize ) );

	mWindowingTable = makeAlignedArray<float>( mWindowSize );
	generateWindow( mWindowType, mWindowingTable.get(), mWindowSize );
}
Пример #23
0
// Resize index table to the specified capacity.
void
NgramVector::_Reindex(size_t indexSize) {
    assert(indexSize >= size() && isPowerOf2(indexSize));
    _indices.reset(indexSize, Invalid);
    _hashMask = indexSize - 1;
    for (NgramIndex i = 0; i < (NgramIndex)size(); i++) {
        size_t     skip = 0;
        NgramIndex pos  = SuperFastHash(_hists[i], _words[i]) & _hashMask;
        while (_indices[pos] != Invalid)
            pos = (pos + ++skip) & _hashMask;
        _indices[pos] = i;
    }
}
Пример #24
0
	//Note: this function only works for inputs which are a power of two and not zero
	//If this is not the case then the output is undefined.
	uint8_t logBase2(uint32_t uInput)
	{
		//Debug mode validation
		assert(uInput != 0);
		assert(isPowerOf2(uInput));

		//Release mode validation
		if(uInput == 0)
		{
			throw std::invalid_argument("Cannot compute the log of zero.");
		}
		if(!isPowerOf2(uInput))
		{
			throw std::invalid_argument("Input must be a power of two in order to compute the log.");
		}

		uint32_t uResult = 0;
		while( (uInput >> uResult) != 0)
		{
			++uResult;
		}
		return static_cast<uint8_t>(uResult-1);
	}
Пример #25
0
void Modifier::rehash() {
    auto totalCapacity = mPages.size() * ENTRIES_PER_PAGE;
    auto numPages = mPages.size();
    // Double number of pages if usage is above 80 percent, halve if below 20 percent
    if (4 * mSize / 5 > totalCapacity) {
        numPages *= 2;
    } else if (numPages > 3 && mSize / 5 < totalCapacity) {
        numPages /= 2;
    }
    LOG_ASSERT(numPages >= 3, "Need at least 3 pages");
    LOG_ASSERT(numPages % 3 == 0, "Number of pages must be divisible by 3");

    // Allocate pages
    std::vector<EntryT*> oldPages;
    oldPages.swap(mPages);
    mPages.reserve(numPages);
    for (decltype(numPages) i = 0; i < numPages; ++i) {
        auto page = mTable.mPageManager.alloc();
        if (!page) {
            LOG_ERROR("PageManager ran out of space");
            std::terminate();
        }
        mPages.emplace_back(reinterpret_cast<EntryT*>(page));
    }

    std::vector<bool> oldPageWasModified(numPages, true);
    oldPageWasModified.swap(pageWasModified);

    // Allocate hash functions
    auto hashCapacity = (numPages / 3) * ENTRIES_PER_PAGE;
    LOG_ASSERT(isPowerOf2(hashCapacity), "Hash capacity must be power of 2");
    hash1 = cuckoo_hash_function(hashCapacity);
    hash2 = cuckoo_hash_function(hashCapacity);
    hash3 = cuckoo_hash_function(hashCapacity);

    // Copy elements from old pages into new pages
    for (decltype(oldPages.size()) i = 0; i < oldPages.size(); ++i) {
        auto page = oldPages[i];
        for (size_t j = 0; j < ENTRIES_PER_PAGE; ++j) {
            if (page[j].second != nullptr)
                insert(page[j].first, page[j].second);
        }
        // If the page was modified it can be freed immediately (only the modifier had access to it)
        if (oldPageWasModified[i]) {
            mTable.mPageManager.free(page);
        } else {
            mToDelete.push_back(page);
        }
    }
}
Пример #26
0
int fft_1dim(double *signal_real, double *signal_imaginary, int signal_length, int inverse, int *buffer_data, int buffer_size)
{
    int error = 0;
    int one = 1;

    if (isPowerOf2(signal_length) && signal_length < POW2_15)
    {
        C2F(fft842)(&inverse, &signal_length, signal_real, signal_imaginary, &error);
    }
    else
    {
        C2F(dfft2)(signal_real, signal_imaginary, &one, &signal_length, &one, &inverse, &error, buffer_data, &buffer_size);
    }

    return error;
}
Пример #27
0
int ObjectControllerPrivate::flagToInt(const QMetaEnum &metaEnum, int flagValue) const
{
    if (!flagValue)
        return 0;
    int intValue = 0;
    QMap<int, int> valueMap; // dont show multiple enum values which have the same values
    int pos = 0;
    for (int i = 0; i < metaEnum.keyCount(); i++) {
        int value = metaEnum.value(i);
        if (!valueMap.contains(value) && isPowerOf2(value)) {
            if (isSubValue(flagValue, value))
                intValue |= (1 << pos);
            valueMap[value] = pos++;
        }
    }
    return intValue;
}
Пример #28
0
 void TableLookupOsc_::setLookupTable(SampleTable table){
   if (table.channels() != 1){
     error("TableLookupOsc expects lookup table with 1 channel only");
     return;
   }
   
   unsigned int nearestPo2;
   if (!isPowerOf2((unsigned int)table.size() - 1, &nearestPo2)){
     
     warning("TableLookUpOsc lookup tables must have a (power-of-two + 1) number of samples (example 2049 or 4097). Resizing to nearest power-of-two + 1");
     
     table.resample(nearestPo2, 1);
     table.resize(nearestPo2+1, 1);
     table.dataPointer()[nearestPo2] = table.dataPointer()[0]; // copy first sample to last
     
   }
   
   lookupTable_ = table;
 }
Пример #29
0
PropertyTable::PropertyTable(VM& vm, const PropertyTable& other)
    : JSCell(vm, vm.propertyTableStructure.get())
    , m_indexSize(other.m_indexSize)
    , m_indexMask(other.m_indexMask)
    , m_index(static_cast<unsigned*>(fastMalloc(dataSize())))
    , m_keyCount(other.m_keyCount)
    , m_deletedCount(other.m_deletedCount)
{
    ASSERT(isPowerOf2(m_indexSize));

    memcpy(m_index, other.m_index, dataSize());

    iterator end = this->end();
    for (iterator iter = begin(); iter != end; ++iter)
        iter->key->ref();

    // Copy the m_deletedOffsets vector.
    Vector<PropertyOffset>* otherDeletedOffsets = other.m_deletedOffsets.get();
    if (otherDeletedOffsets)
        m_deletedOffsets = std::make_unique<Vector<PropertyOffset>>(*otherDeletedOffsets);
}
Пример #30
0
PropertyTable::PropertyTable(VM& vm, JSCell* owner, const PropertyTable& other)
    : JSCell(vm, vm.propertyTableStructure.get())
    , m_indexSize(other.m_indexSize)
    , m_indexMask(other.m_indexMask)
    , m_index(static_cast<unsigned*>(fastMalloc(dataSize())))
    , m_keyCount(other.m_keyCount)
    , m_deletedCount(other.m_deletedCount)
{
    ASSERT(isPowerOf2(m_indexSize));

    memcpy(m_index, other.m_index, dataSize());

    iterator end = this->end();
    for (iterator iter = begin(); iter != end; ++iter) {
        iter->key->ref();
        Heap::writeBarrier(owner, iter->specificValue.get());
    }

    // Copy the m_deletedOffsets vector.
    Vector<PropertyOffset>* otherDeletedOffsets = other.m_deletedOffsets.get();
    if (otherDeletedOffsets)
        m_deletedOffsets = adoptPtr(new Vector<PropertyOffset>(*otherDeletedOffsets));
}