Exemplo n.º 1
0
void SDLFontGL::createTexture() {
	// Create Big GL texture:
	glGenTextures(1,&GlyphCache);
	glBindTexture(GL_TEXTURE_2D, GlyphCache);

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

	// Set size of the texture, but no data.
	// We want 1 extra row of pixel data
	// so we can draw solid colors as part
	// of the same operations.
	texW = nextPowerOfTwo(nChars*nWidth);
	texH = nextPowerOfTwo(nFonts*nHeight + 1);
	int nMode = getGLFormat();
	glTexImage2D(GL_TEXTURE_2D,
			0, nMode,
			texW, texH,
			0, nMode,
			GL_UNSIGNED_BYTE, NULL);


	// Put a single white pixel at bottom of texture.
	// We use this as the 'texture' data for blitting
	// solid backgrounds.
	char whitepixel[] = { 255, 255, 255, 255 };
	assert(nFonts && nHeight);
	glTexSubImage2D(GL_TEXTURE_2D, 0,
			0,nFonts*nHeight,
			1, 1,
			GL_RGBA, GL_UNSIGNED_BYTE, whitepixel);
	checkGLError();
}
Exemplo n.º 2
0
bool opengl_init()
{
	transition_delta = screen_size_w / FPS * 3;

	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
	SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 0);
	SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);

	window = SDL_CreateWindow(NULL, 0, 0, screen_size_w, screen_size_h,
				  SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
				  SDL_WINDOW_BORDERLESS);

	context = SDL_GL_CreateContext(window);

	glDisable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glViewport(0, 0, screen_size_w, screen_size_h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	 
#ifdef USE_OPENGL
	glOrtho(0,
		screen_size_w,
		screen_size_h,
		0, 0.0, 1.0);
#else
	glOrthof((GLfloat) 0,
		 (GLfloat) screen_size_w,
		 (GLfloat) screen_size_h,
		 (GLfloat) 0, 0.0, 1.0);
#endif
	
	glMatrixMode(GL_MODELVIEW);

	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	/* Generate our screenshot texture for transitions */
	glGenTextures(1, &screenshot_tex);
	glBindTexture(GL_TEXTURE_2D, screenshot_tex);
	 
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, nextPowerOfTwo(screen_size_w), nextPowerOfTwo(screen_size_h), 0,
                     GL_RGBA, GL_UNSIGNED_SHORT_5_6_5, NULL);

	return true;
}
Exemplo n.º 3
0
// Palm -->
QRect QGeneralAreaAllocator::allocate(const QSize &size, bool *allocated)
// <-- Palm
{
    QSize rounded = roundAllocation(size);
    rounded = QSize(nextPowerOfTwo(rounded.width()),
                    nextPowerOfTwo(rounded.height()));
// Palm -->
    if (rounded.width() == 0 && rounded.height() == 0) {
        if (allocated) *allocated = true;
        return QRect();
    }
    if (rounded.width() <= 0 || rounded.width() > this->size().width() ||
            rounded.height() <= 0 || rounded.height() > this->size().height()) {
// <-- Palm
        if (allocated) *allocated = false;
        return QRect();
    }
    QPoint point = allocateFromNode(rounded, m_root);
// Palm -->
    if (point.x() >= 0) {
        if (allocated) *allocated = true;
        return QRect(point, size);
    } else {
        if (allocated) *allocated = false;
        return QRect();
    }
// <-- Palm
}
Exemplo n.º 4
0
void Mcfx_convolverAudioProcessor::setConvBufferSize(unsigned int bufsize)
{
    if (nextPowerOfTwo(bufsize) != _ConvBufferSize)
    {
        _ConvBufferSize = nextPowerOfTwo(bufsize);
        ReloadConfiguration();
    }
}
Exemplo n.º 5
0
void opengl_start_transition(bool direction)
{
	transition = true;
	transition_direction = direction;
	transition_w = screen_size_w;
	glBindTexture(GL_TEXTURE_2D, screenshot_tex);
	
	glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, nextPowerOfTwo(screen_size_w), nextPowerOfTwo(screen_size_h), 0);
}
Exemplo n.º 6
0
void Form::setSize(float width, float height)
{
    if (_autoWidth)
    {
        width = Game::getInstance()->getWidth();
    }

    if (_autoHeight)
    {
        height = Game::getInstance()->getHeight();
    }

    if (width != 0.0f && height != 0.0f &&
        (width != _bounds.width || height != _bounds.height))
    {
        // Width and height must be powers of two to create a texture.
        unsigned int w = nextPowerOfTwo(width);
        unsigned int h = nextPowerOfTwo(height);
        _u2 = width / (float)w;
        _v1 = height / (float)h;

        // Create framebuffer if necessary. TODO: Use pool to cache.
        if (_frameBuffer)
            SAFE_RELEASE(_frameBuffer)
        
        _frameBuffer = FrameBuffer::create(_id.c_str(), w, h);
        GP_ASSERT(_frameBuffer);

        // Re-create projection matrix.
        Matrix::createOrthographicOffCenter(0, width, height, 0, 0, 1, &_projectionMatrix);

        // Re-create sprite batch.
        SAFE_DELETE(_spriteBatch);
        _spriteBatch = SpriteBatch::create(_frameBuffer->getRenderTarget()->getTexture());
        GP_ASSERT(_spriteBatch);

        // Clear the framebuffer black
        Game* game = Game::getInstance();
        FrameBuffer* previousFrameBuffer = _frameBuffer->bind();
        Rectangle previousViewport = game->getViewport();

        game->setViewport(Rectangle(0, 0, width, height));
        _theme->setProjectionMatrix(_projectionMatrix);
        game->clear(Game::CLEAR_COLOR, Vector4::zero(), 1.0, 0);
        _theme->setProjectionMatrix(_defaultProjectionMatrix);

        previousFrameBuffer->bind();
        game->setViewport(previousViewport);
    }
    _bounds.width = width;
    _bounds.height = height;
    _dirty = true;
}
Exemplo n.º 7
0
void Tiled2DGraphics::Level::createTiles(CreateTileCallback& callback)
{
	unsigned int dest_level = std::max(nextPowerOfTwo(_numXTiles), nextPowerOfTwo(_numYTiles));
	unsigned int num_iterations = 0;
	unsigned int current_level = 1;
	while(current_level < dest_level) 
	{ 
		++num_iterations; current_level += current_level; 
	}
	
	std::vector<osg::Group*> result;
	
	if (dest_level > 1) {
		createQuadTree(result, this, num_iterations, 1);
	} else {
        osg::Group* g = new osg::Group();
        addChild(g);
		result.push_back(g);
	}
	double w(_parent->getSize()[0]), h(_parent->getSize()[1]);
	double t_w(_parent->getTileWidth());
	double t_h(_parent->getTileHeight());
	
	t_w = (t_w < 0) ? 1 / static_cast<float>(_numXTiles) * _parent->getSize()[0] : t_w / _zoomLevel;
	t_h = (t_h < 0) ? 1 / static_cast<float>(_numYTiles) * _parent->getSize()[1] : t_h / _zoomLevel;
	

	
	for(unsigned int y = 0; y < _numYTiles; ++y)
	{
		for(unsigned int x = 0; x < _numXTiles; ++x) 
        {
			Tile* tile = callback.createTile(x, y);
			if (_parent->getOrigin() == osg::Image::BOTTOM_LEFT){
				tile->setRect(x * t_w, y * t_h, std::min(t_w, w - (x*t_w)), std::min(t_h, h - (y*t_h)));
			} else {
				float t = std::min(t_h, h - (y*t_h));
				tile->setRect(x * t_w, h - t - y * t_h, std::min(t_w, w - (x*t_w)), t);
			}

			tile->setParentLevel(this);
            tile->setParentGroup(result[y*dest_level + x]);
            
			callback(result[y*dest_level + x], tile);
            
            _tiles.push_back(tile);
		}
	}
    _potSize = dest_level;
}
Exemplo n.º 8
0
bool opengl_clear()
{
	bool ret;
	if(!transition) {
		glClear(GL_COLOR_BUFFER_BIT);
		ret = false;
	} else {
		SDL_Rect pos;
		int draw_offset;

		transition_w -= transition_delta;

		if(transition_w <= 0) {
			transition_w = 0;
			transition = false;
		}

		/* Draw screenshot */
		glLoadIdentity();

		draw_offset = screen_size_w - transition_w;
		if(transition_direction) {
			draw_offset = -draw_offset;
		}
		glTranslatef(draw_offset, 0, 0);

		pos.x = 0;
		pos.y = screen_size_h - nextPowerOfTwo(screen_size_h);
		pos.w = nextPowerOfTwo(screen_size_w);
		pos.h = nextPowerOfTwo(screen_size_h);
		opengl_blit_reverse(screenshot_tex, &pos);

		/* Translate the rest */
		glLoadIdentity();

		draw_offset = transition_w;
		if(!transition_direction) {
			draw_offset = -draw_offset;
		}

		glTranslatef(draw_offset, 0, 0);

		ret = true;
	}

	return ret;
}
Exemplo n.º 9
0
static int getAllowedTextureSize (int x)
{
   #if JUCE_OPENGL_ALLOW_NON_POWER_OF_TWO_TEXTURES
    return x;
   #else
    return nextPowerOfTwo (x);
   #endif
}
Exemplo n.º 10
0
void SDLFontGL::updateColors() {
	clearGLColors();

	if (!m_openglActive || m_colors.empty()) return;

	unsigned int texWidth = nextPowerOfTwo(m_colors.size());
	unsigned char* texData = static_cast<unsigned char*>(malloc(texWidth * 4));
	assert(texData);
	memset(texData, 0, texWidth * 4);

	for (unsigned int i = 0; i < m_colors.size(); i++) {
		texData[4*i] = m_colors[i].r;
		texData[4*i+1] = m_colors[i].g;
		texData[4*i+2] = m_colors[i].b;
		texData[4*i+3] = 255;;
	}

	if (m_charShader.program) {
		glUseProgram(m_charShader.program);
		checkGLError();

		glUniform1f(m_charShader.aColorsize, 1.0/nextPowerOfTwo(m_colors.size()));
		checkGLError();
	}

	if (m_colorTex) {
		glDeleteTextures(1, &m_colorTex);
		checkGLError();
		m_colorTex = 0;
	}

	glActiveTexture(GL_TEXTURE2);
	glGenTextures(1, &m_colorTex);
	checkGLError();
	glBindTexture(GL_TEXTURE_2D, m_colorTex);
	checkGLError();

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	checkGLError();

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, texData);
	checkGLError();

	free(texData);
}
Exemplo n.º 11
0
int
MathUtilities::nearestPowerOfTwo(int x)
{
    if (isPowerOfTwo(x)) return x;
    int n0 = previousPowerOfTwo(x), n1 = nextPowerOfTwo(x);
    if (x - n0 < n1 - x) return n0;
    else return n1;
}
Exemplo n.º 12
0
            void work (const URIs& uris, const lvtk::Atom& atom) override
            {
                const File file (String::fromUTF8 (path.c_str()));
                if (ScopedXml xml = XmlDocument::parse (file))
                {
                    if (ScopedPointer<SamplerSynth> ss = SamplerSynth::create ())
                    {
                        if (ss->loadValueTreeXml (*xml))
                        {
#define compressd_json 1
#if compressd_json

                            var json;
                            const bool haveJson = ss->getNestedVariant (json);
#endif
                            uint8_t buf [2048];
                            getForge()->set_buffer (buf, 2048);
                            ObjectRef synth (*getForge(), uris.ksp1_SamplerSynth, ss.release());
                            respond (synth);

                            if (haveJson)
                            {
                                MemoryBlock block (0, false);
                                MemoryOutputStream stream (block, false);
                                GZIPCompressorOutputStream compressed (&stream, 9);
                                JSON::writeToStream (compressed, json, true);
                                compressed.flush();

                                if (block.getSize() > 0)
                                {
                                    Forge& f = *getForge();
                                    int bufSize = nextPowerOfTwo ((int) block.getSize());
                                    bufSize = nextPowerOfTwo (bufSize);
                                    MemoryBlock buffer ((size_t) bufSize, false);
                                    f.set_buffer ((uint8*) buffer.getData(), buffer.getSize());
                                    lvtk::Atom gzipped (f.write_atom (block.getSize(), 100100));
                                    f.write_raw (block.getData(), block.getSize());
                                    DBG ("SIZE: " << (int)block.getSize());
                                    respond (gzipped);
                                }
                            }
                        }
                    }
                }
            }
Exemplo n.º 13
0
    //==============================================================================
    void initialise() override
    {
        // In this example the shader source codes are downloaded from a memory
        // structure, but they could be downloaded from a text file or any other
        // string structure
        createShaders();
#if DEFAULT_TEXTURE == 2
        // Use a 2-D texture (graphic) file or memory block to render (paint) the main object
        // Get memory data block created by IntroJucer in BinaryDaya.cpp file
        Image textureImage = ImageCache::getFromMemory (TEXTURE_DATA);
        // Image must have height and width equal to a power of 2 pixels to be more efficient
        // when used with older GPU architectures
        if (! (isPowerOfTwo (textureImage.getWidth()) && isPowerOfTwo (textureImage.getHeight())))
            textureImage = textureImage.rescaled (jmin (1024, nextPowerOfTwo (textureImage.getWidth())),
                                   jmin (1024, nextPowerOfTwo (textureImage.getHeight())));
        // Use that image as a 2-D texture for the object that will be painted
        texture.loadImage(textureImage);
#endif
    }
Exemplo n.º 14
0
UpdateAtlas::UpdateAtlas(Client& client, int dimension, CoordinatedSurface::Flags flags)
    : m_client(client)
{
    static uint32_t nextID = 0;
    m_ID = ++nextID;
    IntSize size = nextPowerOfTwo(IntSize(dimension, dimension));
    m_surface = CoordinatedSurface::create(size, flags);

    m_client.createUpdateAtlas(m_ID, m_surface.copyRef());
}
Exemplo n.º 15
0
/*
	loads the particle texture
 */
void
initializeTexture()
{

    int bpp;                    /* texture bits per pixel */
    Uint32 Rmask, Gmask, Bmask, Amask;  /* masks for pixel format passed into OpenGL */
    SDL_Surface *bmp_surface;   /* the bmp is loaded here */
    SDL_Surface *bmp_surface_rgba8888;  /* this serves as a destination to convert the BMP
                                           to format passed into OpenGL */

    bmp_surface = SDL_LoadBMP("stroke.bmp");
    if (bmp_surface == NULL) {
        fatalError("could not load stroke.bmp");
    }

    /* Grab info about format that will be passed into OpenGL */
    SDL_PixelFormatEnumToMasks(SDL_PIXELFORMAT_ABGR8888, &bpp, &Rmask, &Gmask,
                               &Bmask, &Amask);
    /* Create surface that will hold pixels passed into OpenGL */
    bmp_surface_rgba8888 =
        SDL_CreateRGBSurface(0, bmp_surface->w, bmp_surface->h, bpp, Rmask,
                             Gmask, Bmask, Amask);
    /* Blit to this surface, effectively converting the format */
    SDL_BlitSurface(bmp_surface, NULL, bmp_surface_rgba8888, NULL);

    glGenTextures(1, &particleTextureID);
    glBindTexture(GL_TEXTURE_2D, particleTextureID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
                 nextPowerOfTwo(bmp_surface->w),
                 nextPowerOfTwo(bmp_surface->h),
                 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    /* this is where we actually pass in the pixel data */
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bmp_surface->w, bmp_surface->h, 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, bmp_surface_rgba8888->pixels);

    /* free bmp surface and converted bmp surface */
    SDL_FreeSurface(bmp_surface);
    SDL_FreeSurface(bmp_surface_rgba8888);

}
Exemplo n.º 16
0
Grid::Grid(unsigned width, unsigned height)
{
	this->width = width;
	this->height = height;
	
	textureWidth = nextPowerOfTwo(width);
	textureHeight = nextPowerOfTwo(height);
	
	cells = new bool[width*height];
	textureData = new GLubyte[textureWidth*textureHeight*3];
	
	for(unsigned i=0; i<width*height; i++)
	{
		cells[i] = false;
	}
	for(unsigned i=0; i<textureWidth*textureHeight*3; i++)
	{
		textureData[i] = 0;
	}
}
Exemplo n.º 17
0
void SDLFontGL::updateCells() {
	clearGLCells();

	if (0 == m_cols || 0 == m_rows) return;

	m_cellsWidth = nextPowerOfTwo(m_cols);
	assert(m_cellsWidth >= m_cols);
	m_cellsWidth = (m_cellsWidth+3) & ~0x3; /* align at four bytes */
	m_cellsHeight = nextPowerOfTwo(m_rows);
	assert(m_cellsHeight >= m_rows);

	if (!m_openglActive) return;

	syslog(LOG_DEBUG, "updateCells: rows = %i, cols = %i, width = %i, height = %i", m_rows, m_cols, m_cellsWidth, m_cellsHeight);

	glActiveTexture(GL_TEXTURE0);
	glGenTextures(1, &m_cellsTex);
	checkGLError();
	glBindTexture(GL_TEXTURE_2D, m_cellsTex);
	checkGLError();

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	checkGLError();

	m_cellData = static_cast<unsigned char*>(malloc(4*m_cellsWidth * m_cellsHeight));
	assert(m_cellData);
	clearText();

	// set size
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_cellsWidth, m_cellsHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
	checkGLError();

	if (m_charShader.program) {
		glUseProgram(m_charShader.program);
		checkGLError();

		glUniform2f(m_charShader.aCellsize, 1.0/(float)m_cellsWidth, 1.0/(float)m_cellsHeight);
		checkGLError();
	}
}
Exemplo n.º 18
0
static uint binarySearchExclusive(uint val, uint *data, uint L, uint sortDir){
    if(L == 0)
        return 0;

    uint pos = 0;
    for(uint stride = nextPowerOfTwo(L); stride > 0; stride >>= 1){
        uint newPos = umin(pos + stride, L);
        if( (sortDir && (data[newPos - 1] < val)) || (!sortDir && (data[newPos - 1] > val)) )
            pos = newPos;
    }

    return pos;
}
Exemplo n.º 19
0
UpdateAtlas::UpdateAtlas(UpdateAtlasClient* client, int dimension, CoordinatedSurface::Flags flags)
    : m_client(client)
    , m_inactivityInSeconds(0)
{
    static uint32_t nextID = 0;
    m_ID = ++nextID;
    IntSize size = nextPowerOfTwo(IntSize(dimension, dimension));
    m_surface = CoordinatedSurface::create(size, flags);

    // FIXME: Currently, if sending the message fails, UpdateAtlas gives up drawing anything implicitly.
    if (!m_client->createUpdateAtlas(m_ID, m_surface))
        m_surface.clear();
}
Exemplo n.º 20
0
void UnmappableBuffer::resizeBuffer(GLsizeiptr size) {
    GLuint newBuffer;

    size = nextPowerOfTwo(size);

    glCreateBuffers(1, &newBuffer);
    glNamedBufferData(newBuffer, size, nullptr, mUsage);
    glCopyNamedBufferSubData(mId, newBuffer, 0, 0, mSize);
    glDeleteBuffers(1, &mId);

    mId = newBuffer;
    mSize = size;
}
Exemplo n.º 21
0
void
hashMapResize(Thread* t, object map, uint32_t (*hash)(Thread*, object),
              unsigned size)
{
  PROTECT(t, map);

  object newArray = 0;

  if (size) {
    object oldArray = hashMapArray(t, map);
    PROTECT(t, oldArray);

    unsigned newLength = nextPowerOfTwo(size);
    if (oldArray and arrayLength(t, oldArray) == newLength) {
      return;
    }

    newArray = makeArray(t, newLength);

    if (oldArray != hashMapArray(t, map)) {
      // a resize was performed during a GC via the makeArray call
      // above; nothing left to do
      return;
    }

    if (oldArray) {
      bool weak = objectClass(t, map) == type(t, Machine::WeakHashMapType);
      for (unsigned i = 0; i < arrayLength(t, oldArray); ++i) {
        object next;
        for (object p = arrayBody(t, oldArray, i); p; p = next) {
          next = tripleThird(t, p);

          object k = tripleFirst(t, p);
          if (weak) {
            k = jreferenceTarget(t, k);
            if (k == 0) {
              continue;
            }
          }

          unsigned index = hash(t, k) & (newLength - 1);

          set(t, p, TripleThird, arrayBody(t, newArray, index));
          set(t, newArray, ArrayBody + (index * BytesPerWord), p);
        }
      }
    }
  }
  
  set(t, map, HashMapArray, newArray);
}
Exemplo n.º 22
0
/*!
    \internal

    Constructs a general area allocator that is initially \a size pixels
    in size.  The \a size will be rounded up to the next power of two,
    to simplify the internal allocation policy.

    This constructor sets minimumAllocation() to (8, 8) to reduce the
    housekeeping overhead of the internal data structures.
*/
QGeneralAreaAllocator::QGeneralAreaAllocator(const QSize &size)
    : QAreaAllocator(nextPowerOfTwo(size))
{
    m_root = new Node();
// Palm -->
    m_root->rect = QRect(0, 0, this->size().width(), this->size().height());
    m_root->largestFree = this->size();
// <-- Palm
    m_root->parent = 0;
    m_root->left = 0;
    m_root->right = 0;
    m_nodeCount = 1;
    setMinimumAllocation(QSize(8, 8));
}
Exemplo n.º 23
0
inline unsigned int nearestPowerOfTwo(unsigned int v)
{
	const unsigned int np2 = nextPowerOfTwo(v);
	const unsigned int pp2 = previousPowerOfTwo(v);

	if (np2 - v <= v - pp2)
	{
		return np2;
	}
	else
	{
		return pp2;
	}
}
Exemplo n.º 24
0
UnmappableBuffer::UnmappableBuffer(GLsizeiptr size, void *data, GLenum usage) :
    mSize(nextPowerOfTwo(size)),
    mUsage(usage) {
    glCreateBuffers(1, &mId);
    glNamedBufferData(mId, mSize, nullptr, mUsage);

    if(data != nullptr) {
        glNamedBufferSubData(mId, 0, size, data);
        mOffset = size;
    }

    else
        mOffset = 0;
}
Exemplo n.º 25
0
void MeshBuilder::addMesh(Mesh* mesh) {
	if(iSize + mesh->getIndexCount() > iData.getIndexCount())
		iData.allocate(nextPowerOfTwo(iSize + mesh->getIndexCount()));
	if(vSize + mesh->getVertexCount() > vData.getVertexCount())
		vData.allocate(nextPowerOfTwo(vSize + mesh->getVertexCount()), description);
	
	const auto& id = mesh->openIndexData();
	const auto& vd = mesh->openVertexData();
	
	if(mesh->getIndexCount() > 0) {
		std::copy(id.data(), id.data() + id.getIndexCount(), iData.data() + iSize);	
		if(vSize > 0) {
			for(uint32_t i=0; i<mesh->getIndexCount(); ++i) {
				iData[iSize+i] += vSize;
			}
		}
	}
		
	if(description == mesh->getVertexDescription()) {
		std::copy(vd.data(), vd.data() + vd.dataSize(), vData.data() + vSize*description.getVertexSize());
	} else {
		std::unique_ptr<MeshVertexData> newVd(MeshUtils::convertVertices(vd, description));
		std::copy(newVd->data(), newVd->data() + newVd->dataSize(), vData.data() + vSize*description.getVertexSize());
	}
	
	if(transMat) {
		VertexAccessor va(vData);
		for(uint32_t i=0; i<mesh->getVertexCount(); ++i) {
			va.setPosition(i+vSize, transMat->transformPosition(va.getPosition(i+vSize)));
			va.setNormal(i+vSize, transMat->transformDirection(va.getNormal(i+vSize)));
		}
	}
	
	iSize += mesh->getIndexCount();
	vSize += mesh->getVertexCount();
}
Exemplo n.º 26
0
bool GLTexture2D::Create() {
	
	arx_assert(!tex, "leaking OpenGL texture");
	
	glGenTextures(1, &tex);
	
	// Set our state to the default OpenGL state
	wrapMode = TextureStage::WrapRepeat;
	mipFilter = TextureStage::FilterLinear;
	minFilter = TextureStage::FilterNearest;
	magFilter = TextureStage::FilterLinear;
	
	Vec2i nextPowerOfTwo(GetNextPowerOf2(size.x), GetNextPowerOf2(size.y));
	storedSize = renderer->hasTextureNPOT() ? size : nextPowerOfTwo;
	isNPOT = (size != nextPowerOfTwo);
	
	return (tex != GL_NONE);
}
Exemplo n.º 27
0
void mulMatrix_StrassenAlgSse(MATRIX_TYPE** first, MATRIX_TYPE** second, MATRIX_TYPE** result, size_t size) {
	unsigned int newSize = nextPowerOfTwo(size);

	MATRIX_TYPE** firstPrep = getEmptyMatrix(newSize);
	MATRIX_TYPE** secondPrep = getEmptyMatrix(newSize);
	MATRIX_TYPE** resultPrep = getEmptyMatrix(newSize);

	for (size_t i = 0; i < size; i++) {
		for (size_t j = 0; j < size; j++) {
			firstPrep[i][j] = 0;
			secondPrep[i][j] = 0;
		}
	}

	for (size_t i = 0; i < size; i++) {
		for (size_t j = 0; j < size; j++) {
			firstPrep[i][j] = first[i][j];
			secondPrep[i][j] = second[i][j];
		}
	}

	doStrassenAlgSse(firstPrep, secondPrep, resultPrep, newSize);

	for (size_t i = 0; i < size; i++) {
		for (size_t j = 0; j < size; j++) {
			result[i][j] = resultPrep[i][j];
		}
	}

	for (size_t i = 0; i < size; i++) {
		_aligned_free(firstPrep[i]);
		_aligned_free(secondPrep[i]);
		_aligned_free(resultPrep[i]);

	}
	_aligned_free(firstPrep);
	_aligned_free(secondPrep);
	_aligned_free(resultPrep);
}
Exemplo n.º 28
0
FFT32 *FFT32_new(size_t FFTFrameSize, FFTWindowType windowType)
{
    FFT32 *self = calloc(1, sizeof(FFT32));
    
    if (FFTFrameSize < FFT_minimumFFTFrameSize) {
        
        printf("FFTFrameSize specified is lower than minimum, defaulting to minimum\n");
        FFTFrameSize = FFT_minimumFFTFrameSize;
    }
    
    self->FFTFrameSize = nextPowerOfTwo(FFTFrameSize);
    self->FFTFrameSizeOver2 = self->FFTFrameSize / 2;
    self->log2n = log2f((Float32)FFTFrameSize);
    self->frameBuffer = calloc(self->FFTFrameSize, sizeof(Float32));
    self->window = calloc(self->FFTFrameSize, sizeof(Float32));
    self->interlacedPolar = calloc(self->FFTFrameSize, sizeof(Float32));
    self->splitComplex.realp = calloc(self->FFTFrameSizeOver2, sizeof(Float32));
    self->splitComplex.imagp = calloc(self->FFTFrameSizeOver2, sizeof(Float32));
    self->FFTData = vDSP_create_fftsetup(self->log2n, FFT_RADIX2);
    
    FFT32_configureWindow(self, windowType);
    
    return self;
}
Exemplo n.º 29
0
std::tr1::shared_ptr<ATexture> ATextureLoader::LoadFile(const std::string& path)
{
	// try to retrieve the texture from the cache, if it exists
	std::tr1::shared_ptr<ATexture> texture_sp = ATextureCache::GetInstance()->Get(path);
	if(texture_sp != nullptr){
		return texture_sp;
	}

	unsigned int width, contentWidth, height, contentHeight;

	ILuint imageID = ilGenImage();
	ilBindImage(imageID);

	if(!ilLoadImage(path.c_str())){
		std::string error = "Fail to load file: " + path;
		throw std::exception(error.c_str());
		return nullptr;
	}

	// The content in
	width = contentWidth = ilGetInteger(IL_IMAGE_WIDTH);
	height = contentHeight = ilGetInteger(IL_IMAGE_HEIGHT);
	ILint bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);

	// Actual texture  size padded with extra pixels, ensure width and height are power of two.
	if(!isPowerOfTwo(contentWidth))
		width = nextPowerOfTwo(contentWidth);
	if(!isPowerOfTwo(contentHeight))
		height = nextPowerOfTwo(contentHeight);

	// default background colour will be solid black
	ilClearColour(0.0f, 0.0f, 0.0f, 1.0f);

	// TODO: there is still some confusion here.......
	// flip texture problem is mentioned here: http://www.gamedev.net/topic/308200-devil-textures-upside-down/

	// Together with the ilOriginFunc in the graphics_engine.h initialize function, and followed by iLuFlipImage(). 
	// They ensure the image data will be correctly loaded and place on top left corner. And the data will be always stored from top left corner.
	iluImageParameter(ILU_PLACEMENT, ILU_UPPER_LEFT);
	// bitmap image seems like storing data upside down, its origin is on the lower left.
	// jpg, png data seems like using upper left as the origin.
	if (ilGetInteger(IL_IMAGE_ORIGIN) == IL_ORIGIN_UPPER_LEFT){
		// This is for fixing the loaded image upside down in OpenGL...
		iluFlipImage();
	}

	// set the canvas size.
	iluEnlargeCanvas(width, height, bpp);

	// Allocate the memory for the image data.
	GLubyte* buffer = new GLubyte[width * height * bpp];
	// Copy the loaded image data into the texture data depending on how many bytes per pixel
	if(bpp == 4){
		ilCopyPixels(0, 0, 0, width, height, 1, IL_RGBA, GL_UNSIGNED_BYTE, buffer);
	}
	else if(bpp == 3){
		ilCopyPixels(0, 0, 0, width, height, 1, IL_RGB, GL_UNSIGNED_BYTE, buffer);
	}
	else{
		std::string error = "Loading process, byte per pixel error, bpp: "+bpp;
		throw std::exception(error.c_str());	
	}

	// Delete the devIL image data
	ilDeleteImage(imageID);

	// create a brand new texture to use
	// put the texture into the texture cache.
	texture_sp = ATextureCache::GetInstance()->Cache(path, new ATexture(buffer, contentWidth, contentHeight, width, height, GL_RGBA, bpp));

	// after texture is created, the buffer data will be uploaded to OpenGL, so no long needed.
	delete[] buffer;

	// This is a pointer to the loaded image data
	return texture_sp;
}
Exemplo n.º 30
0
    World::World(Ogre::SceneManager* sceneMgr,
                     Storage* storage, int visibilityFlags, bool distantLand, bool shaders, Alignment align, float minBatchSize, float maxBatchSize)
        : mStorage(storage)
        , mMinBatchSize(minBatchSize)
        , mMaxBatchSize(maxBatchSize)
        , mSceneMgr(sceneMgr)
        , mVisibilityFlags(visibilityFlags)
        , mDistantLand(distantLand)
        , mShaders(shaders)
        , mVisible(true)
        , mAlign(align)
        , mMaxX(0)
        , mMinX(0)
        , mMaxY(0)
        , mMinY(0)
        , mChunksLoading(0)
        , mWorkQueueChannel(0)
        , mCache(storage->getCellVertices())
        , mLayerLoadPending(true)
    {
#if TERRAIN_USE_SHADER == 0
        if (mShaders)
            std::cerr << "Compiled Terrain without shader support, disabling..." << std::endl;
        mShaders = false;
#endif

        mCompositeMapSceneMgr = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC);

        /// \todo make composite map size configurable
        Ogre::Camera* compositeMapCam = mCompositeMapSceneMgr->createCamera("a");
        mCompositeMapRenderTexture = Ogre::TextureManager::getSingleton().createManual(
                    "terrain/comp/rt", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
            Ogre::TEX_TYPE_2D, 128, 128, 0, Ogre::PF_A8B8G8R8, Ogre::TU_RENDERTARGET);
        mCompositeMapRenderTarget = mCompositeMapRenderTexture->getBuffer()->getRenderTarget();
        mCompositeMapRenderTarget->setAutoUpdated(false);
        mCompositeMapRenderTarget->addViewport(compositeMapCam);

        storage->getBounds(mMinX, mMaxX, mMinY, mMaxY);

        int origSizeX = mMaxX-mMinX;
        int origSizeY = mMaxY-mMinY;

        // Dividing a quad tree only works well for powers of two, so round up to the nearest one
        int size = nextPowerOfTwo(std::max(origSizeX, origSizeY));

        // Adjust the center according to the new size
        float centerX = (mMinX+mMaxX)/2.f + (size-origSizeX)/2.f;
        float centerY = (mMinY+mMaxY)/2.f + (size-origSizeY)/2.f;

        mRootSceneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();

        // While building the quadtree, remember leaf nodes since we need to load their layers
        LayersRequestData data;
        data.mPack = getShadersEnabled();

        mRootNode = new QuadTreeNode(this, Root, size, Ogre::Vector2(centerX, centerY), NULL);
        buildQuadTree(mRootNode, data.mNodes);
        //loadingListener->indicateProgress();
        mRootNode->initAabb();
        //loadingListener->indicateProgress();
        mRootNode->initNeighbours();
        //loadingListener->indicateProgress();

        Ogre::WorkQueue* wq = Ogre::Root::getSingleton().getWorkQueue();
        mWorkQueueChannel = wq->getChannel("LargeTerrain");
        wq->addRequestHandler(mWorkQueueChannel, this);
        wq->addResponseHandler(mWorkQueueChannel, this);

        // Start loading layers in the background (for leaf nodes)
        wq->addRequest(mWorkQueueChannel, REQ_ID_LAYERS, Ogre::Any(data));
    }