SDL_Texture *CreateTexture( Renderer * renderer, SDL_Surface * surface ) { SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer->GetRenderingContext(), surface); SDL_assert_release(texture != nullptr); SDL_FreeSurface(surface); return texture; }
FIBITMAP *GraphicsHelps::loadImageRC(const char *file) { unsigned char *memory = nullptr; size_t fileSize = 0; SDL_assert_release(RES_getMem(file, memory, fileSize)); //{ //pLogCritical("Resource file \"%s\" is not found!", file); //return nullptr; //} FIMEMORY *imgMEM = FreeImage_OpenMemory(memory, static_cast<FI_DWORD>(fileSize)); FREE_IMAGE_FORMAT formato = FreeImage_GetFileTypeFromMemory(imgMEM); if(formato == FIF_UNKNOWN) return nullptr; FIBITMAP *img = FreeImage_LoadFromMemory(formato, imgMEM, 0); FreeImage_CloseMemory(imgMEM); if(!img) return nullptr; FIBITMAP *temp; temp = FreeImage_ConvertTo32Bits(img); if(!temp) return nullptr; FreeImage_Unload(img); img = temp; return img; }
static Value methodCall(Context *ctx, const List<Value>& args) { if (args.getCount() < 1) { ctx->throwException(createException(ExcType::ValueError, "Method call requires at least 1 argument.")); } if (args[0].type != ValueType::Object) { ctx->throwException(createException(ExcType::TypeError, "Method call requires (method) object as first parameter.")); } HashMap<Str, Value>& members = ((ObjectData *)args[0].p)->members; Value func; Value obj; try { func = members.get("__func__"); obj = members.get("__obj__"); } catch (LookupException& e) { ctx->throwException(createException(ExcType::ValueError, "Invalid method object.")); SDL_assert_release(false); } List<Value> args2; args2.append(obj); args2.append(args.getCount()-1, args.getData()+1); return call(ctx, func, args2); }
void *Manageable::callocPulled(size_t size) { void *mem = lite3d_calloc_pooled(LITE3D_POOL_NO2, size); SDL_assert_release(mem); return mem; }
static Value mathAbs(Context *ctx, const List<Value>& args) { if (args.getCount() != 1) { ctx->throwException(createException(ExcType::ValueError, "abs takes only one argument.")); } switch (args[0].type) { case ValueType::Float: { return createFloat(std::abs(args[0].f)); } case ValueType::Int: { return createInt(std::llabs(args[0].i)); } default: { ctx->throwException(createException(ExcType::TypeError, "Value is not convertable to float.")); } } SDL_assert_release(false); return createInt(0); }
void *Manageable::calloc(size_t size) { void *mem = lite3d_calloc(size); SDL_assert_release(mem); return mem; }
// Push texture pointer as userdata, followed by width and height of texture. // This is currently used only by texture_from_font but could be used by other functions in future. static int texture_from_surface(lua_State * L, SDL_Surface * surface) { SDL_Texture * texture; SDL_Texture ** ud; int w; int h; SDL_BlendMode blend_mode; texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); if (!texture) { luaL_error(L, "%s", SDL_GetError()); } if (SDL_GetTextureBlendMode(texture, &blend_mode)) { luaL_error(L, "%s", SDL_GetError()); } SDL_assert_release(blend_mode == SDL_BLENDMODE_BLEND); ud = (SDL_Texture **) lua_newuserdata(L, sizeof(SDL_Texture *)); if (ud == NULL) { luaL_error(L, "Failed to create userdata in texture_from_surface."); } *ud = texture; SDL_QueryTexture(texture, NULL, NULL, &w, &h); lua_pushinteger(L, w); lua_pushinteger(L, h); return 3; }
void TtfFont::printText(const std::string &text, int32_t x, int32_t y, float Red, float Green, float Blue, float Alpha, uint32_t fontSize) { SDL_assert_release(g_ft); if(text.empty()) return; uint32_t offsetX = 0; uint32_t offsetY = 0; const char *strIt = text.c_str(); const char *strEnd = strIt + text.size(); for(; strIt < strEnd; strIt++) { const char &cx = *strIt; UTF8 ucx = static_cast<unsigned char>(cx); switch(cx) { case '\n': offsetX = 0; offsetY += (fontSize * 1.5); continue; case '\t': //Fake tabulation offsetX += offsetX + offsetX % uint32_t(fontSize * 1.5); continue; // case ' ': // offsetX += m_spaceWidth + m_interLetterSpace / 2; // continue; } TheGlyph &glyph = getGlyph(fontSize, get_utf8_char(&cx)); GlRenderer::setTextureColor(Red, Green, Blue, Alpha); int32_t glyph_x = x + static_cast<int32_t>(offsetX); int32_t glyph_y = y + static_cast<int32_t>(offsetY + fontSize); GlRenderer::renderTexture(glyph.tx, static_cast<float>(glyph_x + glyph.left), static_cast<float>(glyph_y - glyph.top), glyph.width, glyph.height ); offsetX += uint32_t(glyph.advance>>6); strIt += static_cast<size_t>(trailingBytesForUTF8[ucx]); } }
bool TtfFont::loadFont(const char *mem, size_t size) { SDL_assert_release(g_ft); FT_Error error = FT_New_Memory_Face(g_ft, reinterpret_cast<const FT_Byte *>(mem), static_cast<FT_Long>(size), 0, &m_face); SDL_assert(error == 0); if(error) return false; error = FT_Set_Pixel_Sizes(m_face, 0, m_recentPixelSize); SDL_assert(error == 0); if(error) return false; error = FT_Select_Charmap(m_face, ft_encoding_unicode); SDL_assert(error == 0); if(error) return false; m_isReady = true; return true; }
static double asNumber(Context *ctx, const Value& value) { switch (value.type) { case ValueType::Float: { return value.f; } case ValueType::Int: { return value.i; } default: { ctx->throwException(createException(ExcType::TypeError, "Value is not convertable to float.")); } } SDL_assert_release(false); return 0.0; }
bool TtfFont::loadFont(const std::string &path) { SDL_assert_release(g_ft); FT_Error error = FT_New_Face(g_ft, path.c_str(), 0, &m_face); SDL_assert(error == 0); if(error) return false; error = FT_Set_Pixel_Sizes(m_face, 0, m_recentPixelSize); SDL_assert(error == 0); if(error) return false; error = FT_Select_Charmap(m_face, ft_encoding_unicode); SDL_assert(error == 0); if(error) return false; m_fontName.append(m_face->family_name); m_fontName.push_back(' '); m_fontName.append(m_face->style_name); m_isReady = true; return true; }
int main() { SDL_Log("%s", "start programm"); debug_init(); SDL_Log("%s", "debug init"); int result = SDL_Init(SDL_INIT_EVERYTHING); SDL_assert_release(result >= 0); SDL_Log("%s", "sdl init"); SDL_Surface * screen = SDL_SetVideoMode(640, 480, 32, SDL_OPENGL); SDL_assert(NULL != screen); SDL_Log("%s", "create window"); bool loop = true; while (loop) { SDL_Event event = {0}; while(SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) { loop = false; } else if (event.key.keysym.sym == SDLK_SPACE) { int * ptr = 0; *ptr = 0; // Make crush! Test debug print stack } } else if (event.type == SDL_WINDOWEVENT and event.window.event == SDL_WINDOWEVENT_CLOSE) { loop = false; } } SDL_Delay(0); // do not use all CPU } SDL_FreeSurface(screen); SDL_Log("%s", "destroy window"); SDL_Quit(); return EXIT_SUCCESS; }
LevelScene::LevelScene() : Scene(Level), m_isInit(false), m_isInitFailed(false), m_isWarpEntrance(false), m_cameraStartDirected(false), m_cameraStartDirection(0), m_newPlayerID(1), /*********Exit*************/ m_isLevelContinues(true), m_warpToLevelFile(""), m_lastWarpID(0), m_warpToArrayID(0), m_warpToWorld(false), m_exitLevelDelay(3000), m_exitLevelCode(LvlExit::EXIT_Closed), /**************************/ m_characterSwitchers(this), m_data(FileFormats::CreateLevelData()), /*********Physics**********/ m_globalGravity(1.0), /**************************/ m_luaEngine(this) { //m_tree.RemoveAll(); m_qtree.clear(); m_layers.m_scene = this; m_events.m_scene = this; m_data.meta.ReadFileValid = false; m_zCounter = 0.0L; /**************************/ m_placingMode = false; m_placingMode_item_type = 0; m_placingMode_block = FileFormats::CreateLvlBlock(); m_placingMode_bgo = FileFormats::CreateLvlBgo(); m_placingMode_npc = FileFormats::CreateLvlNpc(); m_placingMode_animatorID = 0; m_placingMode_animated = false; m_placingMode_sizableBlock = false; m_placingMode_rect_draw = false; /**************************/ /*********Default players number*************/ m_numberOfPlayers = 2; /*********Default players number*************/ /*********Loader*************/ m_loaderIsWorks = false; /*********Loader*************/ /*********Fader*************/ m_fader.setFull(); /*********Fader*************/ /*********Controller********/ m_player1Controller = g_AppSettings.openController(1); m_player2Controller = g_AppSettings.openController(2); SDL_assert_release(m_player1Controller);//At least one controller must be defined /*********Controller********/ /*********Pause menu*************/ initPauseMenu1(); /*********Pause menu*************/ m_frameSkip = g_AppSettings.frameSkip; m_messages.m_scene = this; m_errorMsg = ""; m_gameState = nullptr; m_debug_player_jumping = false; m_debug_player_onground = false; m_debug_player_foots = 0; m_debug_render_delay = 0; m_debug_phys_delay = 0; m_debug_event_delay = 0; }
bool App::Init( bool bFullScreen, unsigned int displayWidth, unsigned int displayHeight ) { if( SDL_Init( SDL_INIT_EVERYTHING ) != 0) { fprintf( stderr, "SDL failed to initialise: %s\n",SDL_GetError() ); return false; } printf( "SDL initialised\n" ); SDL_version compiledVersion; SDL_version linkedVersion; SDL_VERSION( &compiledVersion ); SDL_GetVersion( &linkedVersion ); print_SDL_version( "Compiled against SDL version", compiledVersion ); print_SDL_version( "Linking against SDL version", linkedVersion ); SDL_assert_release( (compiledVersion == linkedVersion) ); int numDisplays = SDL_GetNumVideoDisplays(); printf( "%d video displays\n", numDisplays ); for( int i = 0; i < numDisplays; ++i ) { SDL_DisplayMode displayMode; if( SDL_GetCurrentDisplayMode(i, &displayMode) != 0 ) { fprintf( stderr, "Failed to get display mode for video display %d: %s", i, SDL_GetError() ); continue; } printf( "Display %d: w=%d, h=%d refresh_rate=%d\n", i, displayMode.w, displayMode.h, displayMode.refresh_rate ); } #ifdef GL_ES_VERSION_2_0 SetGLAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SetGLAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SetGLAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); #endif const char* title = "SDL Window"; if( bFullScreen ) { HP_FATAL_ERROR("Just checking"); m_pWindow = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP ); } else { m_pWindow = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, displayWidth, displayHeight, SDL_WINDOW_SHOWN /*| SDL_WINDOW_OPENGL*/ ); } if( !m_pWindow ) { printf( "Failed to create SDL window: %s\n", SDL_GetError() ); return false; } #ifdef GL_ES_VERSION_2_0 // Let's see if we can use OpenGL ES 2 on Raspberry Pi SDL_GLContext gl_context = SDL_GL_CreateContext(m_pWindow); printf("GL_VERSION: "); PrintGLString(GL_VERSION); printf("GL_RENDERER: "); PrintGLString(GL_RENDERER); printf("GL_SHADING_LANGUAGE_VERSION: "); PrintGLString(GL_SHADING_LANGUAGE_VERSION); printf("GL_EXTENSIONS: "); PrintGLString(GL_EXTENSIONS); SDL_GL_DeleteContext(gl_context); #endif // SDL2_ttf if( TTF_Init() == -1 ) { fprintf( stderr, "Failed to initialise SDL2_ttf: %s\n", TTF_GetError() ); return false; } printf( "SDL_ttf initialised\n" ); SDL_TTF_VERSION( &compiledVersion ); const SDL_version *pLinkedVersion = TTF_Linked_Version(); print_SDL_version( "Compiled against SDL_ttf version", compiledVersion ); print_SDL_version( "Linking against SDL_ttf version", *pLinkedVersion ); unsigned int logicalWidth = 1280; unsigned int logicalHeight = 720; m_pRenderer = new Renderer( *m_pWindow, logicalWidth, logicalHeight ); m_pGame = new Game(); if( !m_pGame->Init() ) { fprintf( stderr, "ERROR - Game failed to initialise\n" ); return false; } return true; }
TtfFont::TtfFont() : BaseFontEngine() { SDL_assert_release(g_ft); }
bool initializeFreeType() { FT_Error error = FT_Init_FreeType(&g_ft); SDL_assert_release(error == 0); return true; }
lite3d_mesh_chunk *lite3d_mesh_append_chunk(lite3d_mesh *mesh, const lite3d_mesh_layout *layout, uint32_t layoutCount, uint32_t stride, uint16_t componentType, uint32_t indexesCount, size_t indexesSize, size_t indexesOffset, uint32_t verticesCount, size_t verticesSize, size_t verticesOffset) { lite3d_mesh_chunk *meshChunk; uint32_t attribIndex = 0, i = 0; size_t vOffset = verticesOffset; meshChunk = (lite3d_mesh_chunk *) lite3d_malloc_pooled(LITE3D_POOL_NO1, sizeof (lite3d_mesh_chunk)); SDL_assert_release(meshChunk); if (!lite3d_mesh_chunk_init(meshChunk, LITE3D_TRUE)) { lite3d_free_pooled(LITE3D_POOL_NO1, meshChunk); return NULL; } meshChunk->mesh = mesh; meshChunk->layout = (lite3d_mesh_layout *) lite3d_malloc(sizeof (lite3d_mesh_layout) * layoutCount); SDL_assert_release(meshChunk->layout); /* VAO set current */ glBindVertexArray(meshChunk->vao.vaoID); /* use single VBO to store all data */ glBindBuffer(mesh->vertexBuffer.role, mesh->vertexBuffer.vboID); /* bind all arrays and attribs into the current VAO */ for (; i < layoutCount; ++i) { glEnableVertexAttribArray(attribIndex); glVertexAttribPointer(attribIndex++, layout[i].count, GL_FLOAT, GL_FALSE, stride, LITE3D_BUFFER_OFFSET(vOffset)); vOffset += layout[i].count * sizeof (GLfloat); meshChunk->layout[i] = layout[i]; } // setup buffers for instancing rendering if (mesh->auxBuffer) { glBindBuffer(mesh->vertexBuffer.role, mesh->auxBuffer->vboID); for(i = 0; i < 4; ++i) { glEnableVertexAttribArray(attribIndex); glVertexAttribPointer(attribIndex, 4, GL_FLOAT, GL_FALSE, sizeof(kmMat4), LITE3D_BUFFER_OFFSET(i * sizeof(kmVec4))); glVertexAttribDivisor(attribIndex++, 1); } } if (indexesCount > 0 && indexesSize > 0) { glBindBuffer(mesh->indexBuffer.role, mesh->indexBuffer.vboID); meshChunk->hasIndexes = LITE3D_TRUE; } else { meshChunk->hasIndexes = LITE3D_FALSE; } /* end VAO binding */ glBindVertexArray(0); meshChunk->vao.indexesOffset = indexesOffset; meshChunk->vao.indexType = componentType; meshChunk->vao.indexesCount = indexesCount; meshChunk->vao.indexesSize = indexesSize; meshChunk->vao.verticesCount = verticesCount; meshChunk->vao.verticesSize = verticesSize; meshChunk->vao.verticesOffset = verticesOffset; meshChunk->layoutEntriesCount = layoutCount; meshChunk->vao.elementsCount = (indexesCount > 0 ? indexesCount : verticesCount) / 3; memset(&meshChunk->boundingVol, 0, sizeof (meshChunk->boundingVol)); lite3d_list_add_last_link(&meshChunk->node, &mesh->chunks); mesh->chunkCount++; SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "MESH: %p: chunk %p: %s, cv/ov/sv %d/%ldb/%udb, ci/oi %d/%ldb", (void *) mesh, (void *) meshChunk, "TRIANGLES", meshChunk->vao.verticesCount, meshChunk->vao.verticesOffset, stride, meshChunk->vao.indexesCount, meshChunk->vao.indexesOffset); return meshChunk; }
SDL_Surface *CreateSurface(int width, int height) { auto surface = SDL_CreateRGBSurface(0, width, height, 32, RMASK, GMASK, BMASK, AMASK); SDL_assert_release(surface != nullptr); return surface; }
int initGraphics( int w, int h, int fullscreen ) { int result = SDL_Init( /*SDL_INIT_TIMER |*/ SDL_INIT_AUDIO | SDL_INIT_VIDEO ); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); g_window = SDL_CreateWindow(NULL, 100, 100, w, h, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN/* | SDL_WINDOW_BORDERLESS*/ | (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0)); #ifdef GJ_OS_WINDOWS SDL_SysWMinfo info; SDL_VERSION(&info.version); // initialize info structure with SDL version info SDL_bool get_win_info = SDL_GetWindowWMInfo(g_window, &info); SDL_assert_release(get_win_info); EGLNativeWindowType hWnd = info.info.win.window; g_context = new ESContext(); g_context->width = w; g_context->height = h; g_context->hWnd = hWnd; EGLint configAttribList[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8 /*: EGL_DONT_CARE*/, EGL_DEPTH_SIZE, EGL_DONT_CARE, EGL_STENCIL_SIZE, EGL_DONT_CARE, EGL_SAMPLE_BUFFERS, 0, EGL_NONE }; EGLint surfaceAttribList[] = { // attribute, value EGL_NONE, EGL_NONE }; if ( !g_context ) { //throw std::runtime_error("can't create opengl es 2.0 context, NULL es_context"); } EGLBoolean is_context_created = CreateEGLContext(g_context->hWnd, &g_context->eglDisplay, &g_context->eglContext, &g_context->eglSurface, configAttribList, surfaceAttribList); if (is_context_created == 0) { //throw std::runtime_error("can't create opengl es 2.0 context"); } #else g_context = SDL_GL_CreateContext(g_window); //int result = SDL_GL_SetSwapInterval(0); //SDL_assert(0 == result); #endif initGLESExtensions(); return 0; }
PGE_Size TtfFont::textSize(std::string &text, uint32_t max_line_lenght, bool cut, uint32_t fontSize) { SDL_assert_release(g_ft); if(text.empty()) return PGE_Size(0, 0); size_t lastspace = 0; //!< index of last found space character size_t count = 1; //!< Count of lines uint32_t maxWidth = 0; //!< detected maximal width of message uint32_t widthSumm = 0; uint32_t widthSummMax = 0; if(cut) { std::string::size_type i = text.find('\n'); if(i != std::string::npos) text.erase(i, text.size() - i); } /****************Word wrap*********************/ uint32_t x = 0; for(size_t i = 0; i < text.size(); i++, x++) { char &cx = text[i]; UTF8 uch = static_cast<unsigned char>(cx); switch(cx) { case '\r': break; case '\t': { //Fake tabulation size_t space = (4 * fontSize); widthSumm += (space - ((widthSumm / space) % 4)); if(widthSumm > widthSummMax) widthSummMax = widthSumm; break; } case '\n': { lastspace = 0; if((maxWidth < x) && (maxWidth < max_line_lenght)) maxWidth = x; x = 0; widthSumm = 0; count++; break; } default: { if(' ' == cx) lastspace = x; TheGlyph &glyph = getGlyph(fontSize, get_utf8_char(&cx)); widthSumm += uint32_t(glyph.advance>>6); if(widthSumm > widthSummMax) widthSummMax = widthSumm; break; } }//Switch if((max_line_lenght > 0) && (x >= max_line_lenght)) //If lenght more than allowed { maxWidth = x; if(lastspace > 0) { text[lastspace] = '\n'; i = lastspace - 1; lastspace = 0; } else { text.insert(i, 1, '\n'); x = 0; count++; } } i += static_cast<size_t>(trailingBytesForUTF8[uch]); } if(count == 1) maxWidth = static_cast<uint32_t>(text.length()); /****************Word wrap*end*****************/ return PGE_Size(static_cast<int32_t>(widthSummMax), static_cast<int32_t>((fontSize * 1.5) * count)); }
TtfFont::TheGlyph &TtfFont::loadGlyph(uint32_t fontSize, char32_t character) { FT_Error error = 0; TheGlyph t_glyph; if(m_recentPixelSize != fontSize) { error = FT_Set_Pixel_Sizes(m_face, 0, fontSize); SDL_assert_release(error == 0); m_recentPixelSize = fontSize; } error = FT_Load_Char(m_face, character, FT_LOAD_RENDER); SDL_assert_release(error == 0); //FIXME: return dummy glypg instead FT_GlyphSlot glyph = m_face->glyph; FT_Bitmap &bitmap = glyph->bitmap; uint32_t width = bitmap.width; uint32_t height = bitmap.rows; uint8_t *image = new uint8_t[4 * width * height]; if(bitmap.pitch >= 0) { for(uint32_t w = 0; w < width; w++) { for(uint32_t h = 0; h < height; h++) { uint8_t color = bitmap.buffer[static_cast<uint32_t>(bitmap.pitch) * ((height - 1) - h) + w]; image[(4 * width) * (height - 1 - h) + (4 * w)] = color; image[(4 * width) * (height - 1 - h) + (4 * w + 1)] = color; image[(4 * width) * (height - 1 - h) + (4 * w + 2)] = color; image[(4 * width) * (height - 1 - h) + (4 * w + 3)] = color; } } } else if(bitmap.pitch < 0) { for(uint32_t w = 0; w < width; w++) { for(uint32_t h = 0; h < height; h++) { uint8_t color = *(bitmap.buffer - (static_cast<uint32_t>(bitmap.pitch) * (h)) + w); image[(4 * width)*h + (4 * w)] = color; image[(4 * width)*h + (4 * w + 1)] = color; image[(4 * width)*h + (4 * w + 2)] = color; image[(4 * width)*h + (4 * w + 3)] = color; } } } m_texturesBank.emplace_back(); PGE_Texture &texture = m_texturesBank.back(); texture.nOfColors = GL_RGBA; texture.format = GL_BGRA; GlRenderer::loadRawTextureP(texture, image, width, height); t_glyph.tx = &texture; t_glyph.width = width; t_glyph.height = height; t_glyph.left = glyph->bitmap_left; t_glyph.top = glyph->bitmap_top; t_glyph.advance = glyph->advance.x; t_glyph.glyph_width = glyph->advance.x; delete [] image; SizeCharMap::iterator fSize = m_charMap.find(fontSize); if(fSize == m_charMap.end()) { m_charMap.insert({fontSize, CharMap()}); fSize = m_charMap.find(fontSize); SDL_assert_release(fSize != m_charMap.end()); } fSize->second.insert({character, t_glyph}); CharMap::iterator rc = fSize->second.find(character); SDL_assert_release(rc != fSize->second.end()); return rc->second; }