TileMap::TileMap(CL_GraphicContext& gc, CL_ResourceManager& resmgr, const CL_String& tileset) : map_width(0), map_height(0), cur_map_x(0), cur_map_y(0) { CL_Resource res = resmgr.get_resource(tileset); if (res.get_type() != "tilemap") throw CL_Exception(cl_format("Resource %1 is not a tilemap", tileset)); CL_DomElement element = res.get_element(); levelname = element.get_attribute("name"); CL_String resource_name = element.get_attribute("resource"); map_width = element.get_attribute_int("width"); map_height = element.get_attribute_int("height"); tiles = CL_Sprite(gc, resource_name, &resmgr); float scalex, scaley; tiles.get_scale(scalex, scaley); tile_width = tiles.get_width() * scalex; tile_height = tiles.get_height() * scaley; auto layer_nodes = element.select_nodes("layer"); for (CL_DomNode& idx : layer_nodes) { CL_DomElement layer_element = idx.to_element(); CL_String layer_tiles = layer_element.get_first_child().get_node_value(); std::vector<CL_String> tile_indices = CL_StringHelp::split_text(layer_tiles, ","); MapLayer layer; layer.map.reserve(tile_indices.size()); for (auto& tile : tile_indices) layer.map.push_back(CL_StringHelp::text_to_int(tile)); layers.push_back(layer); } }
void BBN_Prob::load_from_xml(CL_DomElement element) { DEBUG_MSG("BBN_Prob::load_from_xml(CL_DomElement) - Called.") _probability = CL_StringHelp::text_to_float(element.get_attribute("value")); DEBUG_MSG("BBN_Prob::load_from_xml(CL_DomElement) - Prob value = '" + CL_StringHelp::float_to_text(_probability) + "'.") _option = static_cast<CL_String8>(element.get_attribute("option")); DEBUG_MSG("BBN_Prob::load_from_xml(CL_DomElement) - Prob option = '" + _option + "'.") }
void CL_FileDialog_Generic::on_set_options(const CL_DomElement &options) { if (options.has_attribute("file")) set_file(options.get_attribute("file"), false); if (options.has_attribute("filter")) set_filter(options.get_attribute("filter"), false); if (options.has_attribute("show_hidden")) show_hidden = CL_String::to_bool(options.get_attribute("show_hidden")); read_dir(); }
void CL_Collada_Effect_Texture_Impl::load_texture(CL_DomElement &profile_element, CL_DomElement &newparam_element, CL_DomElement &sampler2d_element, std::vector<CL_Collada_Image> &library_images) { sid = newparam_element.get_attribute("sid"); CL_DomElement source_element = sampler2d_element.named_item("source").to_element(); if (source_element.is_null()) throw CL_Exception("source is missing"); CL_String source_name = source_element.get_text(); // Find the corresponding surface CL_DomElement surface_element; CL_DomNode cur_child(profile_element.get_first_child()); while (!cur_child.is_null()) { if(cur_child.get_node_name() == "newparam") { CL_DomElement newparam_element = cur_child.to_element(); CL_String new_sid = newparam_element.get_attribute("sid"); if (new_sid == source_name) { surface_element = newparam_element.named_item("surface").to_element(); if (!surface_element.is_null()) break; // Found match } } cur_child = cur_child.get_next_sibling(); } if (surface_element.is_null()) throw CL_Exception("Cannot find the corresponding surface"); CL_DomElement init_from_element = surface_element.named_item("init_from").to_element(); if (init_from_element.is_null()) throw CL_Exception("Only init_from surfaces are supported"); CL_String image_name = init_from_element.get_text(); unsigned int size = library_images.size(); for (unsigned int cnt=0; cnt < size; cnt++) { if (library_images[cnt].get_id() == image_name) { image = library_images[cnt]; break; } } if (image.is_null()) throw CL_Exception("Cannot find requested image in the image library"); }
void CL_Collada_Material_Impl::load_material(CL_DomElement &material_element, std::vector<CL_Collada_Effect> &effects) { id = material_element.get_attribute("id"); CL_DomElement instance_effect_element = material_element.named_item("instance_effect").to_element(); if (instance_effect_element.is_null()) throw CL_Exception("Only instance_effect materials are supported"); CL_String url = instance_effect_element.get_attribute("url"); url = url.substr(1); // Remove the initial '#' symbol std::vector<CL_Collada_Effect>::size_type size, cnt; size = effects.size(); for (cnt=0; cnt< size; cnt++) { if (effects[cnt].get_id() == url) { effect = effects[cnt]; break; } } if (effect.is_null()) throw CL_Exception("Unable to find effect"); }
void TileMap::load(CL_GraphicContext &gc, const CL_String &level, CL_ResourceManager &resources) { CL_Resource resource = resources.get_resource(level); if (resource.get_type() != "tilemap") throw CL_Exception(cl_format("Resource %1 is not of type tilemap!", level)); CL_DomElement element = resource.get_element(); CL_String level_name = element.get_attribute("name"); CL_String resource_name = element.get_attribute("resource"); map_width = element.get_attribute_int("width"); map_height = element.get_attribute_int("height"); cl_log_event("Debug", "Loading level %1 (%2x%3)", level_name, map_width, map_height); sprite_tiles = CL_Sprite(gc, resource_name, &resources); tile_width = sprite_tiles.get_width(); tile_height = sprite_tiles.get_height(); cl_log_event("Debug", "Loaded resource %1 with %2 tiles", resource_name, sprite_tiles.get_frame_count()); std::vector<CL_DomNode> layer_nodes = element.select_nodes("layer"); for (size_t layer_index = 0; layer_index < layer_nodes.size(); layer_index++) { CL_DomElement layer_element = layer_nodes[layer_index].to_element(); CL_String layer_name = layer_element.get_attribute("name"); CL_String layer_tiles = layer_element.get_first_child().get_node_value(); std::vector<CL_String> tile_indices = CL_StringHelp::split_text(layer_tiles, ","); TileMapLayer layer; layer.map.reserve(tile_indices.size()); for(size_t i = 0; i < tile_indices.size(); ++i) layer.map.push_back(CL_StringHelp::text_to_int(tile_indices[i])); layers.push_back(layer); cl_log_event("Debug", "Loaded layer %1 with %2 tiles", layer_name, layer.map.size()); } current_map_position_x = 0; current_map_position_y = 0; }
void CL_Collada_Triangles_Impl::load_polylist(CL_DomElement &polylist_element, bool contains_vcount, std::vector<CL_Collada_Source> &sources, CL_Collada_Vertices &vertices, std::vector<CL_Collada_Material> &library_materials) { name = polylist_element.get_attribute("name"); // Find material if (polylist_element.has_attribute("material")) { CL_String material_name = polylist_element.get_attribute("material"); std::vector<CL_Collada_Material>::size_type size, cnt; size = library_materials.size(); for (cnt=0; cnt< size; cnt++) { if (library_materials[cnt].get_id() == material_name) { material = library_materials[cnt]; break; } } if (material.is_null()) throw CL_Exception("Unable to find material"); } triangle_count = polylist_element.get_attribute_int("count", 0); load_inputs(polylist_element, sources, vertices); if (contains_vcount) { CL_DomElement vcount_element = polylist_element.named_item("vcount").to_element(); if (!vcount_element.is_null()) validate_vcount(vcount_element); } CL_DomElement primitive_element = polylist_element.named_item("p").to_element(); if (!primitive_element.is_null()) load_primitive(primitive_element); }
void TestApp::test_resources(void) { CL_Console::write_line(" Header: resource.h"); CL_Console::write_line(" Class: CL_Resource"); // Construct resource manager. This will cause sig_resource_added() to be signalled for each // resource object located in the resource file. This means ResourceApp::on_resource_added will // get called for each resource. CL_ResourceManager resources("resources.xml"); // Lets try to access some of the clanlib objects in the resource file: CL_String config_name = resources.get_string_resource("Configuration/name", ""); int config_width = resources.get_integer_resource("Configuration/width", 0 ); int config_height = resources.get_integer_resource("Configuration/height", 0 ); CL_Console::write_line(CL_String("name = ") + config_name ); CL_Console::write_line(CL_String("width = ") + CL_StringHelp::int_to_text(config_width)); CL_Console::write_line(CL_String("height = ") + CL_StringHelp::int_to_text(config_height)); // Get a list over all classes std::vector<CL_String> v = resources.get_resource_names_of_type("uclass", "Classes"); std::vector<CL_String>::iterator it; for(it = v.begin(); it != v.end(); ++it) { // Get one of our custom resources: CL_Resource resource = resources.get_resource(*it); // Its possible to access the dom element object in the resource: CL_DomElement element = resource.get_element(); int strength = CL_StringHelp::text_to_int(element.get_attribute("strength")); int magic = CL_StringHelp::text_to_int(element.get_attribute("magic")); CL_Console::write_line(CL_String("\n") + "name = " + resource.get_name()); CL_Console::write_line(CL_String("strength = ") + CL_StringHelp::int_to_text(strength)); CL_Console::write_line(CL_String("magic = ") + CL_StringHelp::int_to_text(magic) ); } }
SpriteResource::SpriteResource(CL_Resource &resource) : mResource(resource) { GAME_ASSERT(mResource.get_type() == "sprite"); std::string basePath = mResource.get_manager().get_directory(mResource).get_file_system().get_path(); for (CL_DomElement element = mResource.get_element().get_first_child_element(); !element.is_null(); element = element.get_next_sibling_element()) if (element.get_tag_name() == "image") { std::string fileName = element.get_attribute("file"); if (fileName.empty()) throw Exception("Sprite '" + mResource.get_name() + "' has empty or missing 'file' attribute"); mFrames.insert(std::make_pair(basePath + fileName, Frame(fileName))); } if (mFrames.empty()) throw Exception("Sprite '" + mResource.get_name() + "' has no frames"); }
void CL_Button_Silver::on_set_options(const CL_DomElement &options) { if (options.has_attribute("surface_up")) set_surface_up(new CL_Surface(options.get_attribute("surface_up"), resources), true); if (options.has_attribute("surface_down")) set_surface_down(new CL_Surface(options.get_attribute("surface_down"), resources), true); if (options.has_attribute("surface_disabled")) set_surface_disabled(new CL_Surface(options.get_attribute("surface_disabled"), resources), true); if (options.has_attribute("surface_highlighted")) set_surface_highlighted(new CL_Surface(options.get_attribute("surface_highlighted"), resources), true); if (options.has_attribute("font")) set_font(new CL_Font(options.get_attribute("font"), resources), true); if (options.has_attribute("font_disabled")) set_font_disabled(new CL_Font(options.get_attribute("font_disabled"), resources), true); }
void CL_Component_Generic::on_set_options(const CL_DomElement &options) { int x = 0, y = 0, width = 0, height = 0; if (options.has_attribute("x")) x = CL_String::to_int(options.get_attribute("x")); if (options.has_attribute("y")) y = CL_String::to_int(options.get_attribute("y")); if (options.has_attribute("width")) width = CL_String::to_int(options.get_attribute("width")); if (options.has_attribute("height")) height = CL_String::to_int(options.get_attribute("height")); owner->set_position(CL_Rect(x, y, x + width, y + height)); if (options.has_attribute("visible")) owner->show(CL_String::to_bool(options.get_attribute("visible"))); if (options.has_attribute("enabled")) owner->enable(CL_String::to_bool(options.get_attribute("enabled"))); if (options.has_attribute("tab_id")) owner->set_tab_id(CL_String::to_int(options.get_attribute("tab_id"))); owner->update(); }
int ConsoleProgram::main(const std::vector<CL_String> &args) { // Setup clanCore: CL_SetupCore setup_core; // Initialize the ClanLib display component CL_SetupDisplay setup_display; // Create a console Window if one does not exist: CL_ConsoleWindow console_window("Console", 80, 600); try { //получение параметра запуска for (std::vector<CL_String>::const_iterator iter_args = args.begin(); iter_args != args.end(); ++iter_args) CL_Console::write_line( *iter_args ); //получение имени директории для сохранения CL_String workDirectoryName; if (args.size() > 1) { //полное имя рабочей директории workDirectoryName = args[1]; //конвертирование из CP-1251 в UTF-8 имени рабочей директории workDirectoryName = decode(workDirectoryName); } else { //получение полного пути к текущему каталогу workDirectoryName = CL_Directory::get_current(); } CL_Console::write_line("workDirectoryName: %1", workDirectoryName); //получение имени последней директории CL_String locationName = CL_PathHelp::remove_trailing_slash(workDirectoryName); locationName = CL_PathHelp::get_filename(locationName); CL_Console::write_line("locationName: %1", locationName); CL_String tempDir = CL_PathHelp::add_trailing_slash(workDirectoryName) + "temp\\"; CL_DirectoryScanner directoryScanner; directoryScanner.scan(tempDir, "*.export"); while (directoryScanner.next()) { //имя обрабатываемого файла CL_String fileName; if (directoryScanner.is_directory()) continue; //получение полного имени файла экспорта fileName = directoryScanner.get_pathname(); //конвертирование из CP-1251 в UTF-8 fileName = decode(fileName); CL_Console::write_line("find: %1", fileName); //открытие XML файла CL_File fileXML; bool is_opened = fileXML.open(fileName); if( !is_opened ) return PrintError( CL_String("Can't open file: ") + fileName ); //Создание объекта DOM парсера CL_DomDocument document(fileXML); //получение root узла CL_DomElement root = document.get_document_element(); if( root.get_local_name() != "resources") { CL_Console::write_line("Root name can't be: %1", root.get_local_name().c_str()); return PrintError(""); } //цикл по потомкам "resources" for (CL_DomNode cur = root.get_first_child(); !cur.is_null(); cur = cur.get_next_sibling()) { //загрузка только спрайтов if (cur.get_node_name() != "sprite") continue; CL_DomElement element = cur.to_element(); //проверка на обязательные параметры if (!element.has_attribute("name")) return PrintError("Error: can't find parametr \"name\""); CL_DomString name = element.get_attribute("name"); int x = element.get_attribute_int("x"); int y = element.get_attribute_int("y"); //добавление спрайта sprites.push_back( S_Sprite(name, CL_Vec2i(x, y) ) ); //цикл по "image" (формирование списка имен файлов) for (CL_DomNode cur_image = cur.get_first_child(); !cur_image.is_null(); cur_image = cur_image.get_next_sibling()) { //загрузка только image if (cur_image.get_node_name() != "image") continue; CL_DomElement element_image = cur_image.to_element(); CL_DomString file = element_image.get_attribute("file"); //конвертирование из CP-1251 в UTF-8 имени файла изображения file = decode(file); //добавление изображения для обработки (sprites.end()-1)->AddImage(file); } //цикл по "frame" (дополнение списка информацией о файле) for (CL_DomNode cur_frame = cur.get_first_child(); !cur_frame.is_null(); cur_frame = cur_frame.get_next_sibling()) { if (cur_frame.get_node_name() != "frame") continue; CL_DomElement element_frame = cur_frame.to_element(); //проверка на обязательные параметры if (!element_frame.has_attribute("nr")) return PrintError("Error: can't find parameter \"nr\""); size_t nr = element_frame.get_attribute_int("nr"); int speed = element_frame.get_attribute_int("speed"); int x_image = element_frame.get_attribute_int("x"); int y_image = element_frame.get_attribute_int("y"); (sprites.end()-1)->SetAnimationsParam(nr, speed, CL_Vec2i(x_image, y_image)); } } fileXML.close(); } //CL_Console::wait_for_key(); // TODO: //проверка на перекрытие ресурсных имен //return PrintError( CL_String("Error: This resourse already exist") ); //декодирование имени спрайта и генерация с декодированием полных имен файлов for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) { for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images) { //CL_Console::write_line("processing: %1 pos = %2 %3", iter_sprites->mName, iter_sprites->mPos.x, iter_sprites->mPos.y); //генерация полного имени файла iter_images->mSourceFullName = CL_PathHelp::make_absolute(tempDir, iter_images->mSourceFileName); //CL_Console::write_line("image: %1 pos = %2 %3", iter_images->mSourceFileName, iter_images->mOffset.x, iter_images->mOffset.y); CL_Console::write_line("image fullname: %1", iter_images->mSourceFullName); } } //CL_Console::wait_for_key(); //загрузка файлов-картинок for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images) iter_images->mImage = CL_ImageProviderFactory::load(iter_images->mSourceFullName).to_format(cl_rgba8); //CL_Console::wait_for_key(); //проход по всем спрайтам для определения необходимости разрезки на несколько спрайтов for(T_Sprites::size_type iSprites = 0; iSprites < sprites.size(); ++iSprites) { for(S_Sprite::T_Images::size_type iImages = 0; iImages < sprites[iSprites].mImages.size(); ++iImages) { //определение размеров CL_Size image_size = sprites[iSprites].mImages[iImages].mImage.get_size(); //Определение наличия прозрачности sprites[iSprites].mImages[iImages].mNoTransparent = testAlpha(sprites[iSprites].mImages[iImages].mImage); //высота превышает допустимую if(image_size.height > MAX_HEIGHT) return PrintError( CL_String("Error: image height is more then 1024") ); //ширина превышает допустимую if(image_size.width > MAX_WIDTH) { CL_Console::write_line("scussor: sprites[iSprites].mName: %1", sprites[iSprites].mName); //проверка на то что у этого спрайта один image if(sprites[iSprites].mImages.size() > 1) return PrintError( CL_String("Error: animation size can't be more than MAX_WIDTH*MAX_HEIGHT (1024*1024)") ); //сохранение высоты и ширины int h = image_size.height; int w = image_size.width; //определение кол-ва частей на разрезку int n; //кол-во частей на разрезку for(n = 2; n < 10; ++n) if (w > (n-1)*MAX_WIDTH - 2*(n-2) && w <= (n)*MAX_WIDTH - 2*(n-1)) break; T_Sprites::iterator addedSprite; switch (n) { case 2: //две части //спрайт слева (задание имени и позиции спрайта) addedSprite = sprites.insert( sprites.begin()+iSprites+1, S_Sprite(CL_String(sprites[iSprites].mName)+CL_StringHelp::int_to_text(0), sprites[iSprites].mPos+CL_Vec2i(0, 0) ) ); //создание одного Image в добавленом спрайте addedSprite->AddImage(sprites[iSprites].mImages[iImages].mSourceFileName); //создание изображения (задание зазмеров спрайта) addedSprite->mImages[0].mImage = CL_PixelBuffer(MAX_WIDTH, h, cl_rgba8); //наследование флага отсутствия прозрачности addedSprite->mImages[0].mNoTransparent = sprites[iSprites].mImages[iImages].mNoTransparent; //копирование куска изображения sprites[iSprites].mImages[iImages].mImage.convert(addedSprite->mImages[0].mImage, //(dst Rect, src Rect) CL_Rect(0, 0, MAX_WIDTH, h), CL_Rect(0, 0, MAX_WIDTH, h)); addedSprite->mImages[0].mDeltaGrid.left = 0; addedSprite->mImages[0].mDeltaGrid.right = -1; //спрайт справа (задание имени и позиции спрайта) addedSprite = sprites.insert( sprites.begin()+iSprites+1, S_Sprite(CL_String(sprites[iSprites].mName)+CL_StringHelp::int_to_text(1), sprites[iSprites].mPos+CL_Vec2i(MAX_WIDTH-1, 0) ) ); //создание одного Image в добавленом спрайте addedSprite->AddImage(sprites[iSprites].mImages[iImages].mSourceFileName); //создание изображения (задание зазмеров спрайта) addedSprite->mImages[0].mImage = CL_PixelBuffer(w-MAX_WIDTH+2, h, cl_rgba8); //наследование флага отсутствия прозрачности addedSprite->mImages[0].mNoTransparent = sprites[iSprites].mImages[iImages].mNoTransparent; //копирование куска изображения sprites[iSprites].mImages[iImages].mImage.convert(addedSprite->mImages[0].mImage, //(dst Rect, src Rect) CL_Rect(0, 0, w-MAX_WIDTH+2, h), CL_Rect(MAX_WIDTH-2, 0, w, h)); addedSprite->mImages[0].mDeltaGrid.left = +1; addedSprite->mImages[0].mDeltaGrid.right = -1; break; default: return PrintError( CL_String("Error: scussored on >2 part is't writen by C++ programmer") ); break; } /* //разделение изображения на части int x = 1; int residual = image_size.width; int left, right; int i = 0; do { x -= 1; left = x; x += min(MAX_WIDTH, residual); right = x; residual -= (right-left-1); i++; //добавление куска T_Sprites::iterator addedSprite = sprites.insert( sprites.begin()+iSprites+1, S_Sprite(CL_String(sprites[iSprites].mName)+CL_StringHelp::int_to_text(i), sprites[iSprites].mPos+CL_Vec2i(left, 0) ) ); //создание одного Image в добавленом спрайте addedSprite->AddImage(sprites[iSprites].mImages[iImages].mSourceFileName); //создание изображения addedSprite->mImages[0].mImage = CL_PixelBuffer(right-left, h, cl_rgba8); //наследование флага отсутствия прозрачности addedSprite->mImages[0].mNoTransparent = sprites[iSprites].mImages[iImages].mNoTransparent; //копирование куска изображения sprites[iSprites].mImages[iImages].mImage.convert(addedSprite->mImages[0].mImage, CL_Rect(0,0,right-left,h), CL_Rect(left, 0, right, h)); } while(residual != 1); */ //удаление исходного разрезаемого изображения sprites.erase( sprites.begin() + iSprites ); } } } // for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) // { // //определение размеров // CL_Size imageSize = iter_sprites->mImage.get_size(); // //Добавление несколько пикселей для границы спрайтов с дублированием граничных пикселей // iter_sprites->image = CL_PixelBufferHelp::add_border(iter_sprites->image, ADDING_BORDER, CL_Rect(0, 0, image_size.width, image_size.height) ); // } /////////////////////////////////////////////////////// //распределение картинок на текстурном атласе /////////////////////////////////////////////////////// for(T_Sprites::size_type iSprites = 0; iSprites < sprites.size(); ++iSprites) { for(S_Sprite::T_Images::size_type iImages = 0; iImages < sprites[iSprites].mImages.size(); ++iImages) { //переполучение размера CL_Size image_size = sprites[iSprites].mImages[iImages].mImage.get_size(); //помещение в отсортированый список указателя на image sortedList.insert( std::make_pair( max(image_size.width, image_size.height), S_ImagePointer(iSprites, iImages) ) ); } } //Проверка сортировки //for(T_SortedList::iterator iter_sortedList = sortedList.begin(); iter_sortedList != sortedList.end(); ++iter_sortedList) // CL_Console::write_line("sorted: %1, key=(%2, %3)", iter_sortedList->first, iter_sortedList->second.iSprite, iter_sortedList->second.iImage); //проход по всем спрайтам по убыванию большей стороны for(T_SortedList::reverse_iterator iter_sortedList = sortedList.rbegin(); iter_sortedList != sortedList.rend(); ++iter_sortedList) { //номер спрайта T_Sprites::size_type iSprite = iter_sortedList->second.iSprite; //номер изображения в спрайте S_Sprite::T_Images::size_type iImage = iter_sortedList->second.iImage; if( !sprites[iSprite].mImages[iImage].mNoTransparent ) pngNodes.ConnectTexture( S_ImagePointer(iSprite, iImage) ); else jpgNodes.ConnectTexture( S_ImagePointer(iSprite, iImage) ); //проверка добавления CL_Console::write_line("rects are %1 %2 %3 %4", sprites[iSprite].mImages[iImage].mSrcRect.left, sprites[iSprite].mImages[iImage].mSrcRect.top, sprites[iSprite].mImages[iImage].mSrcRect.right, sprites[iSprite].mImages[iImage].mSrcRect.bottom); } size_t textureW = MAX_WIDTH; size_t textureH = MAX_HEIGHT; //список текстур PNG std::vector<CL_PixelBuffer> endTexturesPNG; //список текстур JPG std::vector<CL_PixelBuffer> endTexturesJPG; //физическое создание конечных текстур size_t nTexture = pngNodes.GetNumberTextures(); for(size_t iTexture = 0; iTexture < nTexture; ++iTexture) endTexturesPNG.push_back( CL_PixelBuffer(textureW, textureH, cl_rgba8) ); nTexture = jpgNodes.GetNumberTextures(); for(size_t iTexture = 0; iTexture < nTexture; ++iTexture) endTexturesJPG.push_back( CL_PixelBuffer(textureW, textureH, cl_rgb8) ); //обнуление цвета и альфы конечных текстур PNG for(std::vector<CL_PixelBuffer>::iterator iterEndTexture = endTexturesPNG.begin(); iterEndTexture != endTexturesPNG.end(); ++iterEndTexture) memset( (void *)iterEndTexture->get_data(), 0, iterEndTexture->get_pitch()*iterEndTexture->get_height() ); //обнуление цвета конечных текстуры JPG for(std::vector<CL_PixelBuffer>::iterator iterEndTexture = endTexturesJPG.begin(); iterEndTexture != endTexturesJPG.end(); ++iterEndTexture) memset( (void *)iterEndTexture->get_data(), 0, iterEndTexture->get_pitch()*iterEndTexture->get_height() ); //копирование подтекстур в конечные текстуры for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) { for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images) { //размеры добавляемого прямоугольника CL_Rect srcRect = CL_Rect(0, 0, iter_images->mImage.get_width(), iter_images->mImage.get_height()); //номер текстуры size_t iTexture = iter_images->mITexture; if( !iter_images->mNoTransparent ) iter_images->mImage.convert(endTexturesPNG[iTexture], iter_images->mSrcRect, srcRect); else iter_images->mImage.convert(endTexturesJPG[iTexture], iter_images->mSrcRect, srcRect); } } //сохранение текстур PNG std::vector<CL_PixelBuffer>::size_type iEndTexture, nEndTexture; nEndTexture = endTexturesPNG.size(); for(iEndTexture = 0; iEndTexture < nEndTexture; ++iEndTexture) { //Предумножение на альфу endTexturesPNG[iEndTexture].premultiply_alpha(); //сохранение CL_PNGProvider::save(endTexturesPNG[iEndTexture], CL_PathHelp::make_absolute(workDirectoryName, OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iEndTexture) + ".png") ); CL_Console::write_line("saved %1", CL_PathHelp::make_absolute(workDirectoryName, OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iEndTexture) + ".png")); } //сохранение текстур JPG nEndTexture = endTexturesJPG.size(); for(iEndTexture = 0; iEndTexture < nEndTexture; ++iEndTexture) { //сохранение CL_JPEGProvider::save(endTexturesJPG[iEndTexture], CL_PathHelp::make_absolute(workDirectoryName, OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iEndTexture) + ".jpg")); CL_Console::write_line("saved %1", CL_PathHelp::make_absolute(workDirectoryName, OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iEndTexture) + ".jpg")); } //CL_Console::wait_for_key(); #if SAVE_COLLISION != 0 //Запись файлов - контуров//////////////////////////////////////////////////////// //удаление старых файлов for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) { for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images) { CL_String currentOutlineFileName = iter_images->mCollision.GetCollisionFileName(); if ( CL_FileHelp::file_exists(currentOutlineFileName) ) CL_FileHelp::delete_file(currentOutlineFileName); } } //объекты файлов для записи в них данных контуров std::map<CL_String, CL_File> outlineFiles; //открытие файлов for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) { for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images) { CL_String currentOutlineFileName = iter_images->mCollision.GetCollisionFileName(); std::map<CL_String, CL_File>::iterator iterOutlineFiles = outlineFiles.find(currentOutlineFileName); if (iterOutlineFiles == outlineFiles.end()) { CL_File outlineFile; //формирование полного имени файла CL_String currentOutlineFullName = CL_PathHelp::make_absolute(workDirectoryName, currentOutlineFileName); //открытие файла CL_Console::write_line("open outline file: %1", currentOutlineFullName); bool is_opened = outlineFile.open(currentOutlineFullName, CL_File::open_always, CL_File::access_write); if (!is_opened) return PrintError( CL_String("I Can't open file: ") + currentOutlineFullName ); //добавление файла в список открытых файлов outlineFiles.insert( std::make_pair(currentOutlineFileName, outlineFile) ); CL_Console::write_line("-inserted %1", currentOutlineFileName); } } } //сохранение в бинарные файлы данных о контуре for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) { for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images) { CL_String currentOutlineFileName = iter_images->mCollision.GetCollisionFileName(); //сохранение информации о коллизии saveCollision(iter_images->mImage, outlineFiles[currentOutlineFileName]); //установка смещения для последующих таких имён for(T_Sprites::iterator iter_sprites2 = iter_sprites; iter_sprites2 != sprites.end(); ++iter_sprites2) { S_Sprite::T_Images::iterator iter_images2; if(iter_sprites2 == iter_sprites) iter_images2 = iter_images + 1; else iter_images2 = iter_sprites2->mImages.begin(); for(; iter_images2 != iter_sprites2->mImages.end(); ++iter_images2) if(iter_images->mCollision.GetCollisionFileName() == iter_images2->mCollision.GetCollisionFileName()) //CL_Console::write_line("+size %1", outlineFiles[currentOutlineFileName].get_position() ); iter_images2->mCollision.mFileOffset = outlineFiles[currentOutlineFileName].get_position(); } CL_Console::write_line("saved %1: %2 %3", iter_images->mSourceFileName, currentOutlineFileName, iter_images->mCollision.mFileOffset); } } //закрытие файлов for(std::map<CL_String, CL_File>::iterator iterOutlineFiles = outlineFiles.begin(); iterOutlineFiles != outlineFiles.end(); ++iterOutlineFiles) iterOutlineFiles->second.close(); #endif //CL_Console::wait_for_key(); ////////////////////////////////////////////////////////// //формирование имени файла //CL_String fileResourceName = CL_PathHelp::make_absolute(workDirectoryName, locationName + ".xml"); CL_String fileResourceName = CL_PathHelp::make_absolute(workDirectoryName, RESOURCES_FILE_NAME); CL_Console::write_line("fileResourceName: %1", fileResourceName); //открытие файла XML CL_File fileResourceXML; bool is_opened = fileResourceXML.open(fileResourceName, CL_File::create_always, CL_File::access_write); if( !is_opened ) return PrintError( CL_String("I Can't open file: ") + fileResourceName ); //запись файл заголовка fileResourceXML.write_string_text("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); //Создание объекта DOM парсера CL_DomDocument resourceXML; //корневой узел - resources CL_DomElement resourcesElement(resourceXML, "resources"); resourceXML.append_child(resourcesElement); //узлы bitmap std::map<CL_String, CL_String> complianceCollisions; //формирование map-ы bitmap for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images) complianceCollisions.insert( std::make_pair(iter_images->mCollision.GetCollisionFileName(), iter_images->mCollision.GetCollisionName()) ); #if SAVE_COLLISION != 0 //запись в XML файл ресурсов битовых масок for(std::map<CL_String, CL_String>::iterator iterComplianceCollisions = complianceCollisions.begin(); iterComplianceCollisions != complianceCollisions.end(); ++iterComplianceCollisions) { CL_DomElement bitmapElement(resourceXML, "bitmap"); bitmapElement.set_attribute("name", iterComplianceCollisions->second); bitmapElement.set_attribute("file", iterComplianceCollisions->first); resourcesElement.append_child(bitmapElement); } #endif //запись в XML файл ресурсов результирующих прямоугольников for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) { CL_String currentResourceName = iter_sprites->mName; //узел - sprite CL_DomElement spriteElement(resourceXML, "sprite"); spriteElement.set_attribute("name", currentResourceName); resourcesElement.append_child(spriteElement); //тэг image for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images) { CL_Rect currentSrcRect = iter_images->mSrcRect; //узел - image CL_DomElement imageElement(resourceXML, "image"); if( !iter_images->mNoTransparent ) imageElement.set_attribute("file", OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iter_images->mITexture) + ".png"); else imageElement.set_attribute("file", OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iter_images->mITexture) + ".jpg"); spriteElement.append_child(imageElement); #if SAVE_COLLISION != 0 //сохранение коллизий imageElement.set_attribute("bitmap", iter_images->mCollision.GetCollisionName()); imageElement.set_attribute_int("offset", iter_images->mCollision.mFileOffset); #endif //элемент grid CL_DomElement GridElement(resourceXML, "grid"); GridElement.set_attribute("pos", cl_format("%1,%2", currentSrcRect.left + iter_images->mDeltaGrid.left, currentSrcRect.top + iter_images->mDeltaGrid.top) ); GridElement.set_attribute("size", cl_format("%1,%2", currentSrcRect.right-currentSrcRect.left + iter_images->mDeltaGrid.right, currentSrcRect.bottom-currentSrcRect.top + iter_images->mDeltaGrid.bottom) ); imageElement.append_child(GridElement); } //прервать выполнение сохранения, если анимации нет if (!iter_sprites->mIsFrame) continue; for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images) { //элемент frame CL_DomElement frameElement(resourceXML, "frame"); frameElement.set_attribute_int("nr", iter_images - iter_sprites->mImages.begin()); if (iter_images->mDelay != 0) frameElement.set_attribute_int("speed", iter_images->mDelay); frameElement.set_attribute_int("x", iter_images->mOffset.x); frameElement.set_attribute_int("y", iter_images->mOffset.y); spriteElement.append_child(frameElement); } } //подключение всех файлов с дополнительными ресурсами directoryScanner.scan(workDirectoryName, "*.xml"); while (directoryScanner.next()) { //проверка валидности файла if (directoryScanner.is_directory() || directoryScanner.get_name() == RESOURCES_FILE_NAME) continue; //открытие ресурсного XML файла CL_Console::write_line("include xml file: " + directoryScanner.get_pathname()); CL_File file(directoryScanner.get_pathname()); CL_DomDocument doc(file); CL_DomElement root = doc.get_document_element(); if (root.get_tag_name() != "resources") { CL_Console::write_line("Root name can't be: %1", root.get_tag_name()); return PrintError(""); } //добавление всех ресурсов в текущий документ for (CL_DomElement element = root.get_first_child_element(); !element.is_null(); element = element.get_next_sibling_element()) resourcesElement.append_child(cloneElement(element, resourceXML)); } //сохранение в файл XML структуры resourceXML.save(fileResourceXML); //закрытие файла fileResourceXML.close(); //сохранение координат спрайтов и инициализации/деинициализации в lua скрипте //формирование имени файла //CL_String luaFileName = CL_PathHelp::make_absolute(workDirectoryName, locationName + ".lua"); CL_String luaFileName = CL_PathHelp::make_absolute(workDirectoryName, LUA_SCRIPT_NAME); CL_File luaFile; is_opened = luaFile.open(luaFileName, CL_File::create_always, CL_File::access_write); if( !is_opened ) return PrintError( CL_String("Can't open file: ") + luaFileName); luaFile.write_string_text( cl_format("function %1_createSprites()", locationName) ); //запись в XML файл ресурсов результирующих прямоугольников for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) { CL_String currentResourceName = iter_sprites->mName; int x = iter_sprites->mPos.x; int y = iter_sprites->mPos.y; luaFile.write_string_text( cl_format("\t%1 = Sprite(\"%2\", %3, %4)", currentResourceName, currentResourceName, x, y) ); } luaFile.write_string_text( cl_format("end") ); luaFile.write_string_text(CL_String("")); luaFile.write_string_text( cl_format("function %1_deleteSprites()", locationName) ); //запись в XML файл ресурсов результирующих прямоугольников for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites) { CL_String currentResourceName = iter_sprites->mName; luaFile.write_string_text( cl_format("\t%1 = nil", currentResourceName) ); } luaFile.write_string_text( cl_format("end") ); /* function Location01_createSprites() sprite1 = Sprite("sprite1", 10, 20) sprite2 = Sprite("sprite2", 13, 666) ... spriten = Sprite("spriten", 999, 0) end function Location01_deleteSprites() sprite1 = nil sprite2 = nil ... spriten = nil end */ luaFile.close(); CL_Console::write_line("Press any key..."); CL_Console::wait_for_key(); } catch(CL_Exception &exception) { CL_Console::write_line("Exception caught: " + exception.get_message_and_stack_trace()); CL_Console::wait_for_key(); return -1; } return 0; }
void CL_Label_Generic::on_set_options(const CL_DomElement &options) { if (options.has_attribute("text")) text = options.get_attribute("text"); }
void CL_GUIXMLLoaderVersion_1_0::load(CL_DomElement &element, CL_GUIComponent *parent) { CL_DomElement e = element.get_first_child().to_element(); dialog_width = 0; dialog_height = 0; while (e.is_element()) { CL_String tag = e.get_tag_name(); CL_GUIComponent *new_comp = 0; if (tag == "button") { CL_PushButton *co = new CL_PushButton(parent); if (e.has_attribute("text")) co->set_text(e.get_attribute("text")); new_comp = co; } else if (tag == "checkbox") { CL_CheckBox *co = new CL_CheckBox(parent); if (e.has_attribute("text")) co->set_text(e.get_attribute("text")); new_comp = co; } else if (tag == "radiobutton") { CL_RadioButton *co = new CL_RadioButton(parent); if (e.has_attribute("text")) co->set_text(e.get_attribute("text")); if (e.has_attribute("group")) co->set_group_name(e.get_attribute("group")); new_comp = co; } else if (tag == "label") { CL_Label *co = new CL_Label(parent); if (e.has_attribute("text")) co->set_text(e.get_attribute("text")); new_comp = co; } else if (tag == "toolbar") { CL_ToolBar *co = new CL_ToolBar(parent); new_comp = co; } else if (tag == "progressbar") { CL_ProgressBar *co = new CL_ProgressBar(parent); new_comp = co; } else if (tag == "lineedit") { CL_LineEdit *co = new CL_LineEdit(parent); if (e.has_attribute("text")) co->set_text(e.get_attribute("text")); new_comp = co; } else if (tag == "slider") { CL_Slider *co = new CL_Slider(parent); co->set_min(CL_StringHelp::text_to_int(e.get_attribute("min"))); co->set_max(CL_StringHelp::text_to_int(e.get_attribute("max"))); co->set_tick_count(CL_StringHelp::text_to_int(e.get_attribute("ticks"))); co->set_page_step(CL_StringHelp::text_to_int(e.get_attribute("page_step"))); new_comp = co; } else if (tag == "listview") { CL_ListView *co = new CL_ListView(parent); CL_ListViewHeader *header = co->get_header(); std::vector<CL_DomNode> columns_nodes = e.select_nodes("listview_header/listview_column"); for(size_t i = 0; i < columns_nodes.size(); ++i) { CL_DomElement column_element = columns_nodes[i].to_element(); CL_String id = column_element.get_attribute("col_id"); CL_String caption = column_element.get_attribute("caption"); int width = column_element.get_attribute_int("width"); CL_ListViewColumnHeader column = header->create_column(id, caption); column.set_width(width); header->append(column); } new_comp = co; } else if (tag == "tab") { CL_Tab *co = new CL_Tab(parent); new_comp = co; CL_DomElement tab_child = e.get_first_child().to_element(); while (tab_child.is_element()) { if (tab_child.get_tag_name() == "tabpage") { CL_String label = tab_child.get_attribute("label", "Error: NO LABEL!"); int id = CL_StringHelp::text_to_int(tab_child.get_attribute("id", "0")); CL_TabPage *tab_page = co->add_page(label, id); CL_GUILayoutCorners tabpage_layout; tab_page->set_layout(tabpage_layout); load(tab_child, tab_page); } tab_child = tab_child.get_next_sibling().to_element(); } } else if (tag == "statusbar") { CL_StatusBar *co = new CL_StatusBar(parent); new_comp = co; } else if (tag == "menubar") { CL_MenuBar *co = new CL_MenuBar(parent); new_comp = co; } else if (tag == "combobox") { CL_ComboBox *co = new CL_ComboBox(parent); new_comp = co; } else if (tag == "scrollbar") { CL_ScrollBar *co = new CL_ScrollBar(parent); new_comp = co; } else if (tag == "spin") { CL_Spin *co = new CL_Spin(parent); new_comp = co; } else if (tag == "imageview") { CL_ImageView *co = new CL_ImageView(parent); new_comp = co; } else if (tag == "frame") { CL_Frame *co = new CL_Frame(parent); if (e.has_attribute("text")) co->set_header_text(e.get_attribute("text")); new_comp = co; CL_GUILayoutCorners layout_corners; co->set_layout(layout_corners); load(e, co); } else if (tag == "dialog") { dialog_width = CL_StringHelp::text_to_int(e.get_attribute("width")); dialog_height = CL_StringHelp::text_to_int(e.get_attribute("height")); } else // unknown tag... try create a custom_component { CL_GUIComponent *co = 0; if (create_custom_callback && !create_custom_callback->is_null()) { co = create_custom_callback->invoke(parent, tag); } new_comp = co; } if (new_comp) { new_comp->set_id_name(e.get_attribute("id")); new_comp->set_class_name(e.get_attribute("class")); new_comp->set_enabled(e.get_attribute_bool("enabled", true)); CL_String str = e.get_attribute("geom"); std::vector<CL_String> split = CL_StringHelp::split_text(str, ","); CL_Rect g; g.left = CL_StringHelp::text_to_int(split[0]); g.top = CL_StringHelp::text_to_int(split[1]); g.right = CL_StringHelp::text_to_int(split[2]); g.bottom = CL_StringHelp::text_to_int(split[3]); new_comp->set_geometry(g); CL_GUILayout parent_layout = parent->get_layout(); if (!parent_layout.is_null()) { parent_layout.get_provider(); CL_GUILayoutProvider_Corners *corner_provider_layout = dynamic_cast<CL_GUILayoutProvider_Corners*>(parent_layout.get_provider()); if (corner_provider_layout) { int dist_tl_x = CL_StringHelp::text_to_int(e.get_attribute("dist_tl_x")); int dist_tl_y = CL_StringHelp::text_to_int(e.get_attribute("dist_tl_y")); int dist_rb_x = CL_StringHelp::text_to_int(e.get_attribute("dist_br_x")); int dist_rb_y = CL_StringHelp::text_to_int(e.get_attribute("dist_br_y")); CL_ComponentAnchorPoint ap_tl = (CL_ComponentAnchorPoint)CL_StringHelp::text_to_int(e.get_attribute("anchor_tl")); CL_ComponentAnchorPoint ap_br = (CL_ComponentAnchorPoint)CL_StringHelp::text_to_int(e.get_attribute("anchor_br")); corner_provider_layout->add_component(new_comp, ap_tl, dist_tl_x, dist_tl_y, ap_br, dist_rb_x, dist_rb_y); } } } e = e.get_next_sibling().to_element(); } CL_GUILayout parent_layout = parent->get_layout(); if (!parent_layout.is_null()) { parent_layout.set_geometry(parent->get_size()); } }