Esempio n. 1
0
void Slider::_notification(int p_what) {


	switch(p_what) {

		case NOTIFICATION_MOUSE_ENTER: {

			mouse_inside=true;
			update();
		} break;
		case NOTIFICATION_MOUSE_EXIT: {

			mouse_inside=false;
			update();
		} break;
		case NOTIFICATION_DRAW: {
			RID ci = get_canvas_item();
			Size2i size = get_size();
			Ref<StyleBox> style = get_stylebox("slider");
			Ref<StyleBox> focus = get_stylebox("focus");
			Ref<Texture> grabber = get_icon(mouse_inside||has_focus()?"grabber_hilite":"grabber");
			Ref<Texture> tick = get_icon("tick");

			if (orientation==VERTICAL) {

				style->draw(ci,Rect2i(Point2i(),Size2i(style->get_minimum_size().width+style->get_center_size().width,size.height)));
				//if (mouse_inside||has_focus())
				//	focus->draw(ci,Rect2i(Point2i(),Size2i(style->get_minimum_size().width+style->get_center_size().width,size.height)));
				float areasize = size.height - grabber->get_size().height;
				if (ticks>1) {
					int tickarea = size.height - tick->get_height();
					for(int i=0;i<ticks;i++) {
					        if( ! ticks_on_borders && (i == 0 || i + 1 == ticks) ) continue;
						int ofs = i*tickarea/(ticks-1);
						tick->draw(ci,Point2(0,ofs));
					}

				}
				grabber->draw(ci,Point2i(size.width/2-grabber->get_size().width/2,size.height - get_unit_value()*areasize - grabber->get_size().height));
			} else {
				style->draw(ci,Rect2i(Point2i(),Size2i(size.width,style->get_minimum_size().height+style->get_center_size().height)));
				//if (mouse_inside||has_focus())
				//	focus->draw(ci,Rect2i(Point2i(),Size2i(size.width,style->get_minimum_size().height+style->get_center_size().height)));

				float areasize = size.width - grabber->get_size().width;
				if (ticks>1) {
					int tickarea = size.width - tick->get_width();
					for(int i=0;i<ticks;i++) {
					        if( (! ticks_on_borders) && ( (i == 0) || ((i + 1) == ticks)) ) continue;
						int ofs = i*tickarea/(ticks-1);
						tick->draw(ci,Point2(ofs,0));
					}

				}
				grabber->draw(ci,Point2i(get_unit_value()*areasize,size.height/2-grabber->get_size().height/2));
			}

		} break;
	}
}
Esempio n. 2
0
Size2 OS_X11::get_screen_size(int p_screen) const {
	// Using Xinerama Extension
	int event_base, error_base;
	const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
	if( !ext_okay ) return Size2i(0,0);

	int count;
	XineramaScreenInfo* xsi = XineramaQueryScreens(x11_display, &count);
	if( p_screen >= count ) return Size2i(0,0);

	Size2i size = Point2i(xsi[p_screen].width, xsi[p_screen].height);
	XFree(xsi);
	return size;
}
Esempio n. 3
0
Size2 OS_Haiku::get_screen_size(int p_screen) const {
	// TODO: make this work with the p_screen parameter
	BScreen *screen = new BScreen(window);
	BRect frame = screen->Frame();
	delete screen;
	return Size2i(frame.IntegerWidth() + 1, frame.IntegerHeight() + 1);
}
Esempio n. 4
0
    /// \remarks This method is called at the start of each unit test.
    libRocketDataGridTest() :
      VisualUnitTest( Size2i(768,448) )
    {
      // NOM_LOG_TRACE( NOM );

      // The frame image to compare against the reference image set
      this->append_screenshot_frame( 0 );
    }
Esempio n. 5
0
    /// \remarks Initialization callback for VisualUnitTest to act on, instead
    /// of its default rendering setup. A bit of additional setup is
    /// required for plumbing in libRocket into our setup.
    bool init_rendering()
    {
      int render_driver = -1;
      uint32 window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
      uint32 render_flags = SDL_RENDERER_ACCELERATED;

      if( nom::set_hint( SDL_HINT_RENDER_VSYNC, "0" ) == false )
      {
        NOM_LOG_INFO ( NOM, "Could not disable vertical refresh." );
      }

      if( nom::set_hint( SDL_HINT_RENDER_SCALE_QUALITY, "nearest" ) == false )
      {
        NOM_LOG_INFO( NOM, "Could not set scale quality to", "nearest" );
      }

      // Required as per our libRocket implementation
      render_driver = nom::available_render_driver("opengl");
      if( render_driver == -1 )
      {
        NOM_LOG_CRIT( NOM_LOG_CATEGORY_APPLICATION,
                      "Could not find an OpenGL rendering driver." );
        return false;
      }

      if( this->window_.create( this->test_case(),
                                this->resolution(),
                                window_flags,
                                render_driver,
                                render_flags ) == false )
      {
        NOM_LOG_CRIT( NOM_LOG_CATEGORY_APPLICATION, "Could not initialize rendering context and window." );
        return false;
      }

      if( nom::RocketSDL2RenderInterface::gl_init( this->window_.size().w, this->window_.size().h ) == false )
      {
        NOM_LOG_CRIT( NOM_LOG_CATEGORY_APPLICATION, "Could not initialize OpenGL for libRocket." );
        return false;
      }

      // Allow for automatic rescaling of the output window based on aspect
      // ratio (i.e.: handle fullscreen resizing); this will use letterboxing
      // when the aspect ratio is greater than what is available, or side-bars
      // when the aspect ratio is less than.
      this->render_window().set_logical_size( this->resolution() / Size2i(2,2) );
      // this->render_window().set_logical_size( this->resolution() );

      // Use pixel unit scaling; this gives us a one to two pixel ratio --
      // scale output display by a factor of two.
      this->render_window().set_scale( Point2f(2,2) );
      // this->render_window().set_scale( Point2f(1,1) );

      return true;
    }
FrameworkSettings::FrameworkSettings(void)
{
    m_settingsName = "Framework";
    
    m_defaultValues.windowManager = "SDL";
    m_defaultValues.renderer = "OpenGL";
    m_defaultValues.windowTitle = "Framework Window";
    m_defaultValues.screenSize = Size2i(960, 600);
    m_defaultValues.fullscreen = false;
    m_defaultValues.vsync = true; 
}
Esempio n. 7
0
Size2i UIContext::size() const
{
  Rocket::Core::Vector2i dims( 0, 0 );

  NOM_ASSERT( this->context_ != nullptr );
  if( this->context_ )
  {
    dims = this->context_->GetDimensions();
  }

  return Size2i( dims.x, dims.y );
}
Esempio n. 8
0
void Sprite::_notification(int p_what) {

	switch(p_what) {

		case NOTIFICATION_DRAW: {

			if (texture.is_null())
				return;




			RID ci = get_canvas_item();

			/*
			texture->draw(ci,Point2());
			break;
			*/

			Size2i s;
			Rect2i src_rect;

			if (region) {

				s=region_rect.size;
				src_rect=region_rect;
			} else {
				s = texture->get_size();
				s=s/Size2i(hframes,vframes);

				src_rect.size=s;
				src_rect.pos.x+=(frame%hframes)*s.x;
				src_rect.pos.y+=(frame/hframes)*s.y;

			}

			Point2i ofs=offset;
			if (centered)
				ofs-=s/2;

			Rect2i dst_rect(ofs,s);

			if (hflip)
				dst_rect.size.x=-dst_rect.size.x;
			if (vflip)
				dst_rect.size.y=-dst_rect.size.y;

			texture->draw_rect_region(ci,dst_rect,src_rect,modulate);

		} break;
	}
}
Esempio n. 9
0
int TexturePacker::TryToPackFromSortVector(ImagePacker * packer,std::vector<SizeSortItem> & tempSortVector)
{
    int packedCount = 0;
    // Packing of sorted by size images
    for (int i = 0; i < (int)tempSortVector.size(); ++i)
    {
        DefinitionFile * defFile = tempSortVector[i].defFile;
        int frame = tempSortVector[i].frameIndex;
        if (packer->AddImage(Size2i(defFile->frameRects[frame].dx, defFile->frameRects[frame].dy), &defFile->frameRects[frame]))
        {
            packedCount++;
            tempSortVector.erase(tempSortVector.begin() + i);
            i--;
        }
    }
    return packedCount;
}
Esempio n. 10
0
bool TexturePacker::TryToPack(const Rect2i & textureRect, std::list<DefinitionFile*> & defsList)
{
    if (CommandLineParser::Instance()->GetVerbose())
        printf("%d x %d, ", textureRect.dx, textureRect.dy);
    ImagePacker * packer = new ImagePacker(textureRect);

//	for (std::list<DefinitionFile*>::iterator dfi = defsList.begin(); dfi != defsList.end(); ++dfi)
//	{
//		DefinitionFile * defFile = *dfi;
//		for (int frame = 0; frame < defFile->frameCount; ++frame)
//		{
//			if (!packer->AddImage(Size2i::Make(defFile->frameRects[frame].dx, defFile->frameRects[frame].dy), &defFile->frameRects[frame]))
//			{
//				SafeDelete(packer);
//				return false;
//			}
//		}
//	}

    // Packing of sorted by size images
    for (int i = 0; i < (int)sortVector.size(); ++i)
    {
        DefinitionFile * defFile = sortVector[i].defFile;
        int frame = sortVector[i].frameIndex;
        if (!packer->AddImage(Size2i(defFile->frameRects[frame].dx, defFile->frameRects[frame].dy), &defFile->frameRects[frame]))
        {
            SafeDelete(packer);
            return false;
        }
        if (CommandLineParser::Instance()->GetVerbose())
            printf("p: %s %d\n",defFile->filename.c_str(), frame);
    }
    if (CommandLineParser::Instance()->GetVerbose())
        printf("\n* %d x %d - success\n", textureRect.dx, textureRect.dy);

    if (lastPackedPacker)
    {
        SafeDelete(lastPackedPacker);
    }

    lastPackedPacker = packer;
    return true;
}
Esempio n. 11
0
float TexturePacker::TryToPackFromSortVectorWeight(ImagePacker * packer,std::vector<SizeSortItem> & tempSortVector)
{
    float weight = 0.0f;

    // Packing of sorted by size images
    for (int i = 0; i < (int)tempSortVector.size(); ++i)
    {
        DefinitionFile * defFile = tempSortVector[i].defFile;
        int frame = tempSortVector[i].frameIndex;
        if (packer->AddImage(Size2i(defFile->frameRects[frame].dx, defFile->frameRects[frame].dy), &defFile->frameRects[frame]))
        {
            //float weightCoeff = (float)(tempSortVector.size() - i) / (float)(tempSortVector.size());
            weight += (defFile->frameRects[frame].dx * defFile->frameRects[frame].dy);// * weightCoeff;
            tempSortVector.erase(tempSortVector.begin() + i);
            i--;
        }
    }
    return weight;
}
Esempio n. 12
0
NumberSpinner::NumberSpinner(string description, float intialValue, float delta, string _valueFormat, Point2i position, Size2i size) : GridLayout(size,Size2i(3,2),position)
{
	LOGD(LOGTAG_INPUT, "Enter NumberSpinner constructor");
	//Initialize grid base
	//gridSize = Size2i(3,2);
	//cellSize = Size_<int>((int)((float)size.width/gridSize.width),(int)((float)size.height/gridSize.height));
	//Position = position;
	//
	LOGD(LOGTAG_INPUT, "Cellsize = [%d,%d]",cellSize.width,cellSize.height);

	value = intialValue;
	clickDelta = delta;
	maxValue = MAXFLOAT;
	minValue = -MAXFLOAT;
	valueFormat = _valueFormat;


	Label * descriptionLabel = new Label(description,Point2i(0,0),Colors::Black,Colors::White);	
	descriptionLabel->FontScale = 0.9f;
	AddChild(descriptionLabel,Point2i(0,0),Size2i(3,1));

	char * str = new char[valueFormat.size()];
	sprintf(str,valueFormat.c_str(),value);
	valueLabel = new Label(string(str),Point2i(0,0),Colors::Black,Colors::White);	
	valueLabel->FontScale = 0.9f;
	GridLayout::AddChild(valueLabel,Point2i(1,1));
	delete str;


	Button * increase = new Button("+",Colors::MediumSeaGreen);	
	increase->AddClickDelegate(ClickEventDelegate::from_method<NumberSpinner,&NumberSpinner::IncreaseClick>(this));
	GridLayout::AddChild(increase,Point2i(2,1));
	
	Button * decrease = new Button("-",Colors::Gold);
	decrease->AddClickDelegate(ClickEventDelegate::from_method<NumberSpinner,&NumberSpinner::DecreaseClick>(this));
	GridLayout::AddChild(decrease,Point2i(0,1));
	
	LOGD(LOGTAG_INPUT, "NumberSpinner instantiated");

}
Esempio n. 13
0
Vector<Vector2> BitMap::_march_square(const Rect2i &rect, const Point2i &start) const {

	int stepx = 0;
	int stepy = 0;
	int prevx = 0;
	int prevy = 0;
	int startx = start.x;
	int starty = start.y;
	int curx = startx;
	int cury = starty;
	unsigned int count = 0;
	Set<Point2i> case9s;
	Set<Point2i> case6s;
	Vector<Vector2> _points;
	do {
		int sv = 0;
		{ //square value

			/*
			checking the 2x2 pixel grid, assigning these values to each pixel, if not transparent
			+---+---+
			| 1 | 2 |
			+---+---+
			| 4 | 8 | <- current pixel (curx,cury)
			+---+---+
			*/
			//NOTE: due to the way we pick points from texture, rect needs to be smaller, otherwise it goes outside 1 pixel
			Rect2i fixed_rect = Rect2i(rect.position, rect.size - Size2i(2, 2));
			Point2i tl = Point2i(curx - 1, cury - 1);
			sv += (fixed_rect.has_point(tl) && get_bit(tl)) ? 1 : 0;
			Point2i tr = Point2i(curx, cury - 1);
			sv += (fixed_rect.has_point(tr) && get_bit(tr)) ? 2 : 0;
			Point2i bl = Point2i(curx - 1, cury);
			sv += (fixed_rect.has_point(bl) && get_bit(bl)) ? 4 : 0;
			Point2i br = Point2i(curx, cury);
			sv += (fixed_rect.has_point(br) && get_bit(br)) ? 8 : 0;
			ERR_FAIL_COND_V(sv == 0 || sv == 15, Vector<Vector2>());
		}

		switch (sv) {

			case 1:
			case 5:
			case 13:
				/* going UP with these cases:
				1          5           13
				+---+---+  +---+---+  +---+---+
				| 1 |   |  | 1 |   |  | 1 |   |
				+---+---+  +---+---+  +---+---+
				|   |   |  | 4 |   |  | 4 | 8 |
				+---+---+  +---+---+  +---+---+
				*/
				stepx = 0;
				stepy = -1;
				break;

			case 8:
			case 10:
			case 11:
				/* going DOWN with these cases:
				8          10         11
				+---+---+  +---+---+  +---+---+
				|   |   |  |   | 2 |  | 1 | 2 |
				+---+---+  +---+---+  +---+---+
				|   | 8 |  |   | 8 |  |   | 8 |
				+---+---+  +---+---+  +---+---+
				*/
				stepx = 0;
				stepy = 1;
				break;

			case 4:
			case 12:
			case 14:
				/* going LEFT with these cases:
				4          12         14
				+---+---+  +---+---+  +---+---+
				|   |   |  |   |   |  |   | 2 |
				+---+---+  +---+---+  +---+---+
				| 4 |   |  | 4 | 8 |  | 4 | 8 |
				+---+---+  +---+---+  +---+---+
				*/
				stepx = -1;
				stepy = 0;
				break;

			case 2:
			case 3:
			case 7:
				/* going RIGHT with these cases:
				2          3          7
				+---+---+  +---+---+  +---+---+
				|   | 2 |  | 1 | 2 |  | 1 | 2 |
				+---+---+  +---+---+  +---+---+
				|   |   |  |   |   |  | 4 |   |
				+---+---+  +---+---+  +---+---+
				*/
				stepx = 1;
				stepy = 0;
				break;
			case 9:
				/*
				+---+---+
				| 1 |   |
				+---+---+
				|   | 8 |
				+---+---+
				this should normally go UP, but if we already been here, we go down
				*/
				if (case9s.has(Point2i(curx, cury))) {
					//found, so we go down, and delete from case9s;
					stepx = 0;
					stepy = 1;
					case9s.erase(Point2i(curx, cury));
				} else {
					//not found, we go up, and add to case9s;
					stepx = 0;
					stepy = -1;
					case9s.insert(Point2i(curx, cury));
				}
				break;
			case 6:
				/*
				6
				+---+---+
				|   | 2 |
				+---+---+
				| 4 |   |
				+---+---+
				this normally go RIGHT, but if its coming from UP, it should go LEFT
				*/
				if (case6s.has(Point2i(curx, cury))) {
					//found, so we go down, and delete from case6s;
					stepx = -1;
					stepy = 0;
					case6s.erase(Point2i(curx, cury));
				} else {
					//not found, we go up, and add to case6s;
					stepx = 1;
					stepy = 0;
					case6s.insert(Point2i(curx, cury));
				}
				break;
			default:
				ERR_PRINT("this shouldn't happen.");
		}
		//little optimization
		// if previous direction is same as current direction,
		// then we should modify the last vec to current
		curx += stepx;
		cury += stepy;
		if (stepx == prevx && stepy == prevy) {
			_points.write[_points.size() - 1].x = (float)(curx - rect.position.x);
			_points.write[_points.size() - 1].y = (float)(cury + rect.position.y);
		} else {
			_points.push_back(Vector2((float)(curx - rect.position.x), (float)(cury + rect.position.y)));
		}

		count++;
		prevx = stepx;
		prevy = stepy;

		ERR_FAIL_COND_V(count > width * height, _points);
	} while (curx != startx || cury != starty);
	return _points;
}
Esempio n. 14
0
Size2 OS_Haiku::get_window_size() const {
	BSize size = window->Size();
	return Size2i(size.IntegerWidth() + 1, size.IntegerHeight() + 1);
}
Error EditorTextureImportPlugin::import2(const String& p_path, const Ref<ResourceImportMetadata>& p_from,EditorExportPlatform::ImageCompression p_compr, bool p_external){



	ERR_FAIL_COND_V(p_from->get_source_count()==0,ERR_INVALID_PARAMETER);

	Ref<ResourceImportMetadata> from=p_from;

	Ref<ImageTexture> texture;
	Vector<Ref<AtlasTexture> > atlases;
	bool atlas = from->get_option("atlas");

	int flags=from->get_option("flags");
	uint32_t tex_flags=0;

	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_REPEAT)
		tex_flags|=Texture::FLAG_REPEAT;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_FILTER)
		tex_flags|=Texture::FLAG_FILTER;
	if (!(flags&EditorTextureImportPlugin::IMAGE_FLAG_NO_MIPMAPS))
		tex_flags|=Texture::FLAG_MIPMAPS;

	int shrink=1;
	if (from->has_option("shrink"))
		shrink=from->get_option("shrink");

	if (atlas) {

		//prepare atlas!
		Vector< Image > sources;
		bool alpha=false;
		bool crop = from->get_option("crop");

		EditorProgress ep("make_atlas","Build Atlas For: "+p_path.get_file(),from->get_source_count()+3);

		print_line("sources: "+itos(from->get_source_count()));
		for(int i=0;i<from->get_source_count();i++) {

			String path = EditorImportPlugin::expand_source_path(from->get_source_path(i));
			ep.step("Loading Image: "+path,i);
			print_line("source path: "+path);
			Image src;
			Error err = ImageLoader::load_image(path,&src);
			if (err) {
				EditorNode::add_io_error("Couldn't load image: "+path);
				return err;
			}

			if (src.detect_alpha())
				alpha=true;

			sources.push_back(src);
		}
		ep.step("Converting Images",sources.size());

		for(int i=0;i<sources.size();i++) {

			if (alpha) {
				sources[i].convert(Image::FORMAT_RGBA);
			} else {
				sources[i].convert(Image::FORMAT_RGB);
			}
		}

		//texturepacker is not really good for optimizing, so..
		//will at some point likely replace with my own
		//first, will find the nearest to a square packing
		int border=1;

		Vector<Size2i> src_sizes;
		Vector<Rect2> crops;

		ep.step("Cropping Images",sources.size()+1);

		for(int j=0;j<sources.size();j++) {

			Size2i s;
			if (crop) {
				Rect2 crop = sources[j].get_used_rect();
				print_line("CROP: "+crop);
				s=crop.size;
				crops.push_back(crop);
			} else {

				s=Size2i(sources[j].get_width(),sources[j].get_height());
			}
			s+=Size2i(border*2,border*2);
			src_sizes.push_back(s); //add a line to constraint width
		}

		Vector<Point2i> dst_positions;
		Size2i dst_size;
		EditorAtlas::fit(src_sizes,dst_positions,dst_size);

		print_line("size that workeD: "+itos(dst_size.width)+","+itos(dst_size.height));

		ep.step("Blitting Images",sources.size()+2);

		Image atlas;
		atlas.create(nearest_power_of_2(dst_size.width),nearest_power_of_2(dst_size.height),0,alpha?Image::FORMAT_RGBA:Image::FORMAT_RGB);

		for(int i=0;i<sources.size();i++) {

			int x=dst_positions[i].x;
			int y=dst_positions[i].y;

			Ref<AtlasTexture> at = memnew( AtlasTexture );
			Size2 sz = Size2(sources[i].get_width(),sources[i].get_height());
			if (crop && sz!=crops[i].size) {
				Rect2 rect = crops[i];
				rect.size=sz-rect.size;
				at->set_region(Rect2(x+border,y+border,crops[i].size.width,crops[i].size.height));
				at->set_margin(rect);
				atlas.blit_rect(sources[i],crops[i],Point2(x+border,y+border));
			} else {
				at->set_region(Rect2(x+border,y+border,sz.x,sz.y));
				atlas.blit_rect(sources[i],Rect2(0,0,sources[i].get_width(),sources[i].get_height()),Point2(x+border,y+border));
			}
			String apath = p_path.get_base_dir().plus_file(from->get_source_path(i).get_file().basename()+".atex");
			print_line("Atlas Tex: "+apath);
			at->set_path(apath);
			atlases.push_back(at);

		}
		if (ResourceCache::has(p_path)) {
			texture = Ref<ImageTexture> ( ResourceCache::get(p_path)->cast_to<ImageTexture>() );
		} else {
			texture = Ref<ImageTexture>( memnew( ImageTexture ) );
		}
		texture->create_from_image(atlas,tex_flags);

	} else {
		ERR_FAIL_COND_V(from->get_source_count()!=1,ERR_INVALID_PARAMETER);

		String src_path = EditorImportPlugin::expand_source_path(from->get_source_path(0));

		if (ResourceCache::has(p_path)) {
			Resource *r = ResourceCache::get(p_path);

			texture = Ref<ImageTexture> ( r->cast_to<ImageTexture>() );

			Image img;
			Error err = img.load(src_path);
			ERR_FAIL_COND_V(err!=OK,ERR_CANT_OPEN);
			texture->create_from_image(img);
		} else {
			texture=ResourceLoader::load(src_path,"ImageTexture");
		}

		ERR_FAIL_COND_V(texture.is_null(),ERR_CANT_OPEN);
		if (!p_external)
			from->set_source_md5(0,FileAccess::get_md5(src_path));

	}


	int format=from->get_option("format");
	float quality=from->get_option("quality");

	if (!p_external) {
		from->set_editor(get_name());
		texture->set_path(p_path);
		texture->set_import_metadata(from);
	}

	if (atlas) {

		if (p_external) {
			//used by exporter
			Array rects(true);
			for(int i=0;i<atlases.size();i++) {
				rects.push_back(atlases[i]->get_region());
				rects.push_back(atlases[i]->get_margin());
			}
			from->set_option("rects",rects);

		} else {
			//used by importer
			for(int i=0;i<atlases.size();i++) {
				String apath = atlases[i]->get_path();
				atlases[i]->set_atlas(texture);
				Error err = ResourceSaver::save(apath,atlases[i]);
				if (err) {
					EditorNode::add_io_error("Couldn't save atlas image: "+apath);
					return err;
				}
				from->set_source_md5(i,FileAccess::get_md5(apath));
			}
		}
	}


	if (format==IMAGE_FORMAT_COMPRESS_DISK_LOSSLESS || format==IMAGE_FORMAT_COMPRESS_DISK_LOSSY) {

		Image image=texture->get_data();
		ERR_FAIL_COND_V(image.empty(),ERR_INVALID_DATA);

		bool has_alpha=image.detect_alpha();
		if (!has_alpha && image.get_format()==Image::FORMAT_RGBA) {

			image.convert(Image::FORMAT_RGB);

		}

		if (image.get_format()==Image::FORMAT_RGBA && flags&IMAGE_FLAG_FIX_BORDER_ALPHA) {

			image.fix_alpha_edges();
		}


		if (shrink>1) {

			int orig_w=image.get_width();
			int orig_h=image.get_height();
			image.resize(orig_w/shrink,orig_h/shrink);
			texture->create_from_image(image,tex_flags);
			texture->set_size_override(Size2(orig_w,orig_h));


		} else {

			texture->create_from_image(image,tex_flags);
		}


		if (format==IMAGE_FORMAT_COMPRESS_DISK_LOSSLESS) {
			texture->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSLESS);
		} else {
			texture->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
		}



		texture->set_lossy_storage_quality(quality);

		Error err = ResourceSaver::save(p_path,texture);

		if (err!=OK) {
			EditorNode::add_io_error("Couldn't save converted texture: "+p_path);
			return err;
		}


	} else {

		print_line("compress...");
		Image image=texture->get_data();
		ERR_FAIL_COND_V(image.empty(),ERR_INVALID_DATA);


		bool has_alpha=image.detect_alpha();
		if (!has_alpha && image.get_format()==Image::FORMAT_RGBA) {

			image.convert(Image::FORMAT_RGB);

		}

		if (image.get_format()==Image::FORMAT_RGBA && flags&IMAGE_FLAG_FIX_BORDER_ALPHA) {

			image.fix_alpha_edges();
		}

		int orig_w=image.get_width();
		int orig_h=image.get_height();

		if (shrink>1) {
			image.resize(orig_w/shrink,orig_h/shrink);
			texture->create_from_image(image,tex_flags);
			texture->set_size_override(Size2(orig_w,orig_h));
		}

		if (!(flags&IMAGE_FLAG_NO_MIPMAPS)) {
			image.generate_mipmaps();

		}

		if (format!=IMAGE_FORMAT_UNCOMPRESSED) {

			compress_image(p_compr,image,flags&IMAGE_FLAG_COMPRESS_EXTRA);
		}


		print_line("COMPRESSED TO: "+itos(image.get_format()));
		texture->create_from_image(image,tex_flags);


		if (shrink>1) {
			texture->set_size_override(Size2(orig_w,orig_h));
		}

		uint32_t save_flags=ResourceSaver::FLAG_COMPRESS;

		Error err = ResourceSaver::save(p_path,texture,save_flags);
		if (err!=OK) {
			EditorNode::add_io_error("Couldn't save converted texture: "+p_path);
			return err;
		}

	}

	return OK;
}
Esempio n. 16
0
void LargeTexture::clear(){

	pieces.clear();
	size=Size2i();
}
Esempio n. 17
0
Size2i GraphicsFont::DrawString(float32 x, float32 y, const WideString & string, int32 justifyWidth)
{
    uint32 length = (uint32)string.length();
    if(length==0) return Size2i();

    uint16 prevChIndex = GraphicsFontDefinition::INVALID_CHARACTER_INDEX;
    Sprite::DrawState state;

    state.SetPerPixelAccuracyUsage(true);

    float32 currentX = x;
    float32 currentY = y;
    float32 sizeFix = 0.0f;
    //Logger::Debug("%S startX:%f", string.c_str(), currentX);
    RenderManager::Instance()->SetColor(color);
    for (uint32 indexInString = 0; indexInString < length; ++indexInString)
    {
        char16 c = string[indexInString];
        uint16 chIndex = fdef->CharacterToIndex(c);

        if (indexInString == 0)
        {
            sizeFix = fontSprite->GetRectOffsetValueForFrame(chIndex, Sprite::X_OFFSET_TO_ACTIVE) * fontScaleCoeff;
            currentX -= sizeFix;
        }

        if (chIndex == GraphicsFontDefinition::INVALID_CHARACTER_INDEX)
        {
            if(c != '\n')
                Logger::Debug("*** Error: can't find character %c in font", c);
            continue;
        }

        if (prevChIndex != GraphicsFontDefinition::INVALID_CHARACTER_INDEX)
        {
            //Logger::Debug("kern: %c-%c = %f", string[indexInString - 1], c,  GetDistanceFromAtoB(prevChIndex, chIndex));
            currentX += GetDistanceFromAtoB(prevChIndex, chIndex);
        }

        state.SetFrame(chIndex);
        // draw on baseline Y = currentY - fontSprite->GetHeight() + charTopBottomPadding + fontDescent

        float32 drawX = currentX;
        float32 drawY = currentY - fontSprite->GetHeight() * fontScaleCoeff + (fdef->charTopBottomPadding + fdef->fontDescent + fdef->fontAscent) * fontScaleCoeff;


        //if (indexInString != 0)
        drawX += fdef->characterPreShift[chIndex] * fontScaleCoeff;


        state.SetScale(fontScaleCoeff, fontScaleCoeff);
        state.SetPosition(drawX, drawY);

        fontSprite->Draw(&state);

//		RenderManager::Instance()->SetColor(1.0f, 0.0f, 0.0f, 1.0f);
//		RenderManager::Instance()->DrawRect(Rect(drawX + fontSprite->GetRectOffsetValueForFrame(chIndex, Sprite::X_OFFSET_TO_ACTIVE) * fontScaleCoeff, drawY + fontSprite->GetRectOffsetValueForFrame(chIndex, Sprite::Y_OFFSET_TO_ACTIVE) * fontScaleCoeff, fontSprite->GetRectOffsetValueForFrame(chIndex, Sprite::ACTIVE_WIDTH), fontSprite->GetHeight() * fontScaleCoeff));
//		RenderManager::Instance()->ResetColor();

        currentX += (fdef->characterWidthTable[chIndex] + horizontalSpacing) * fontScaleCoeff;
//		Logger::Debug("%c w:%f pos: %f\n", c, fdef->characterWidthTable[chIndex] * fontScaleCoeff, currentX);
//		if (c == ' ')currentX += fdef->characterWidthTable[chIndex] * fontScaleCoeff;
//		else currentX += fontSprite->GetRectOffsetValueForFrame(chIndex, Sprite::ACTIVE_WIDTH) * fontScaleCoeff;

        prevChIndex = chIndex;
    }
    RenderManager::Instance()->ResetColor();

    currentX -= (fdef->characterWidthTable[prevChIndex] + horizontalSpacing) * fontScaleCoeff;
    currentX += (fdef->characterPreShift[prevChIndex] + fontSprite->GetRectOffsetValueForFrame(prevChIndex, Sprite::ACTIVE_WIDTH)) * fontScaleCoeff; // characterWidthTable[prevChIndex];

//	Sprite::DrawState drwState;
//	float32 drawX = 100;
//	float32 drawY = 100;
//	drwState.SetFrame(1);
//	drwState.SetPosition(drawX, drawY);
//	fontSprite->Draw(&drwState);
//
//	RenderManager::Instance()->SetColor(1.0f, 0.0f, 0.0f, 1.0f);
//	RenderManager::Instance()->DrawRect(Rect(drawX + fontSprite->GetRectOffsetValueForFrame(1, Sprite::X_OFFSET_TO_ACTIVE) * fontScaleCoeff
//											 , drawY + fontSprite->GetRectOffsetValueForFrame(1, Sprite::Y_OFFSET_TO_ACTIVE) * fontScaleCoeff
//											 , fdef->characterWidthTable[1]
//											 , fontSprite->GetHeight() * fontScaleCoeff));
//	RenderManager::Instance()->ResetColor();


    return Size2i((int32)(currentX + sizeFix + 1.5f - x), GetFontHeight());
}
Esempio n. 18
0
void ScriptEditorDebugger::_performance_draw() {


	Vector<int> which;
	for(int i=0;i<perf_items.size();i++) {


		if (perf_items[i]->is_selected(0))
			which.push_back(i);
	}


	if(which.empty())
		return;

	Ref<StyleBox> graph_sb = get_stylebox("normal","TextEdit");
	Ref<Font> graph_font = get_font("font","TextEdit");

	int cols = Math::ceil(Math::sqrt(which.size()));
	int rows = (which.size()+1)/cols;
	if (which.size()==1)
		rows=1;


	int margin =3;
	int point_sep=5;
	Size2i s = Size2i(perf_draw->get_size())/Size2i(cols,rows);
	for(int i=0;i<which.size();i++) {

		Point2i p(i%cols,i/cols);
		Rect2i r(p*s,s);
		r.pos+=Point2(margin,margin);
		r.size-=Point2(margin,margin)*2.0;
		perf_draw->draw_style_box(graph_sb,r);
		r.pos+=graph_sb->get_offset();
		r.size-=graph_sb->get_minimum_size();
		int pi=which[i];
		Color c = Color(0.7,0.9,0.5);
		c.set_hsv(Math::fmod(c.get_h()+pi*0.7654,1),c.get_s(),c.get_v());

		c.a=0.8;
		perf_draw->draw_string(graph_font,r.pos+Point2(0,graph_font->get_ascent()),perf_items[pi]->get_text(0),c,r.size.x);
		c.a=0.6;
		perf_draw->draw_string(graph_font,r.pos+Point2(graph_font->get_char_size('X').width,graph_font->get_ascent()+graph_font->get_height()),perf_items[pi]->get_text(1),c,r.size.y);

		float spacing=point_sep/float(cols);
		float from = r.size.width;

		List<Vector<float> >::Element *E=perf_history.front();
		float prev=-1;
		while(from>=0 && E) {

			float m = perf_max[pi];
			if (m==0)
				m=0.00001;
			float h = E->get()[pi]/m;
			h=(1.0-h)*r.size.y;

			c.a=0.7;
			if (E!=perf_history.front())
				perf_draw->draw_line(r.pos+Point2(from,h),r.pos+Point2(from+spacing,prev),c,2.0);
			prev=h;
			E=E->next();
			from-=spacing;
		}

	}

}
Esempio n. 19
0
void CovariancePatchModel::updateBackgroundModel(GenericFeature *feature1) {
    CovariancePatchDescriptor *f1 = (CovariancePatchDescriptor *) feature1;

    //int min_radius = ceil( sqrt( pow(f1->m_rect.size.width/2,2)+pow(f1->m_rect.size.height/2,2) )*2);
    int min_radius = ceil(min(f1->m_rect.size.width,f1->m_rect.size.height));
    int randAngle = 0, x = 0, y = 0;
    int numMemorie = 20;

    /*
    //Mat tmp = this->m_last_img.clone();
    m_backgroundModel.clear();

    for (int i=0; i<numMemorie; i++) {
    	//randAngle = randint((360/numMemorie)*i, (360/numMemorie)*(i+1));
    	randAngle = (360/numMemorie)*i;

    	x = f1->m_rect.center.x + cos(randAngle)*min_radius;
    	y = f1->m_rect.center.y + sin(randAngle)*min_radius;

    	//cout << "x: "<<x<< " y: "<<y<<endl;

    	RotatedRect auxRect(Point2i(x,y),Size2i(f1->m_rect.size.width, f1->m_rect.size.height),0);
    	CovariancePatchDescriptor auxFeature(auxRect);
    	auxFeature.computeFeature(this);
    	//distance(&auxFeature);
    	m_backgroundModel.push_back(auxFeature);
    	//drawRotatedRect(tmp, auxRect,CV_RGB(0,0,255),1);
    	//imwrite(CreatefileNameString(), auxFeature.m_imgPatch);
    }
    //cvNamedWindow("Particle distribution");
    //imshow( "Particle distribution", tmp);
    //cvWaitKey();
    */


    if (m_backgroundModel.empty()) {
        for (int i=0; i<numMemorie; i++) {
            randAngle = randint((360/numMemorie)*i, (360/numMemorie)*(i+1));
            x = f1->m_rect.center.x + cos(randAngle)*min_radius;
            y = f1->m_rect.center.y + sin(randAngle)*min_radius;

            RotatedRect auxRect(Point2i(x,y),Size2i(f1->m_rect.size.width, f1->m_rect.size.height),0);
            CovariancePatchDescriptor auxFeature(auxRect,tracker_param);
            auxFeature.computeFeature(this);
            //distance(&auxFeature);
            m_backgroundModel.push_back(auxFeature);
        }
    }

    else {
        //sort (this->m_backgroundModel.begin(),this->m_backgroundModel.end(), compareFeaturesAsc);
        for (int i=0; i<numMemorie; i++) {
            randAngle = randint((360/numMemorie)*i, (360/numMemorie)*(i+1));
            x = f1->m_rect.center.x + cos(randAngle)*min_radius;
            y = f1->m_rect.center.y + sin(randAngle)*min_radius;

            RotatedRect auxRect(Point2i(x,y),Size2i(f1->m_rect.size.width, f1->m_rect.size.height),0);
            CovariancePatchDescriptor auxFeature(auxRect,tracker_param);
            auxFeature.computeFeature(this);
            //distance(&auxFeature);
            //cout << "p_ini: "<<m_backgroundModel[0].m_probability<<endl;
            //cout << "p_end: "<<m_backgroundModel[numMemorie-1].m_probability<<endl;
            //cout << "auxFeature.m_probability: "<<auxFeature.m_probability<<endl;
            m_backgroundModel.push_back(auxFeature);
            //if (this->m_backgroundModel[0].m_probability < auxFeature.m_probability+5){
            //	m_backgroundModel[0] = auxFeature;
            //	sort (this->m_backgroundModel.begin(),this->m_backgroundModel.end(), compareFeaturesAsc);
            //}
        }
    }


}
Esempio n. 20
0
Size2i GraphicsFont::GetStringSize(const WideString & string, Vector<int32> *charSizes)
{
    uint32 length = (uint32)string.length();
    if (length == 0)
        return Size2i(0, 0); //YZ: return size (0,0) for empty string

    uint16 prevChIndex = GraphicsFontDefinition::INVALID_CHARACTER_INDEX;
    Sprite::DrawState state;

    float32 currentX = 0;
    float32 prevX = 0;
    float32 sizeFix = 0.0f;
    for (uint32 indexInString = 0; indexInString < length; ++indexInString)
    {
        char16 c = string[indexInString];
        uint16 chIndex = fdef->CharacterToIndex(c);


        if (indexInString == 0)
        {
            DVASSERT(chIndex < fdef->tableLenght);
            sizeFix = fontSprite->GetRectOffsetValueForFrame(chIndex, Sprite::X_OFFSET_TO_ACTIVE) * fontScaleCoeff;
            currentX -= sizeFix;
        }

        if (chIndex == GraphicsFontDefinition::INVALID_CHARACTER_INDEX)
        {
            if(c != '\n')
                Logger::Debug("*** Error: can't find character %c in font", c);
            if (charSizes)charSizes->push_back(0); // push zero size if character is not available
            continue;
        }

        if (prevChIndex != GraphicsFontDefinition::INVALID_CHARACTER_INDEX)
        {
            //Logger::Debug("kern: %c-%c = %f", string[indexInString - 1], c,  GetDistanceFromAtoB(prevChIndex, chIndex));
            DVASSERT(chIndex < fdef->tableLenght);
            currentX += GetDistanceFromAtoB(prevChIndex, chIndex);
        }

        currentX += (fdef->characterWidthTable[chIndex] + horizontalSpacing) * fontScaleCoeff;
//		if (c == ' ')currentX += fdef->characterWidthTable[chIndex] * fontScaleCoeff;
//		else currentX += fontSprite->GetRectOffsetValueForFrame(chIndex, Sprite::ACTIVE_WIDTH) * fontScaleCoeff;

        // BORODA: Probably charSizes should be float???
        int32 newSize = (int32)(currentX + sizeFix - prevX);
        newSize = (int32)((float32)newSize*Core::GetVirtualToPhysicalFactor());
        if (charSizes)charSizes->push_back(newSize);
        prevX = currentX;
        prevChIndex = chIndex;
    }
    prevX = currentX;

    DVASSERT(prevChIndex < fdef->tableLenght);

    currentX -= (fdef->characterWidthTable[prevChIndex] + horizontalSpacing) * fontScaleCoeff;
    currentX += (fdef->characterPreShift[prevChIndex] + fontSprite->GetRectOffsetValueForFrame(prevChIndex, Sprite::ACTIVE_WIDTH)) * fontScaleCoeff; // characterWidthTable[prevChIndex];

//	float32 lastCharSize = fdef->characterWidthTable[prevChIndex] * fontScaleCoeff;
//	float32 lastCharSize = fontSprite->GetRectOffsetValueForFrame(prevChIndex, Sprite::ACTIVE_WIDTH) * fontScaleCoeff;
//	currentX += lastCharSize; // characterWidthTable[prevChIndex];
    if (charSizes)charSizes->push_back((int32)(currentX + sizeFix - prevX));
    return Size2i((int32)(currentX + sizeFix + 1.5f), GetFontHeight());
}
Esempio n. 21
0
Size2 OS_X11::get_window_size() const {
	XWindowAttributes xwa;
	XGetWindowAttributes(x11_display, x11_window, &xwa);
	return Size2i(xwa.width, xwa.height);
}
Error EditorTextureImportPlugin::import2(const String& p_path, const Ref<ResourceImportMetadata>& p_from,EditorExportPlatform::ImageCompression p_compr, bool p_external){



	ERR_FAIL_COND_V(p_from->get_source_count()==0,ERR_INVALID_PARAMETER);

	Ref<ResourceImportMetadata> from=p_from;

	Ref<ImageTexture> texture;
	Vector<Ref<AtlasTexture> > atlases;
	bool atlas = from->get_option("atlas");
	bool large = from->get_option("large");

	int flags=from->get_option("flags");
	int format=from->get_option("format");
	float quality=from->get_option("quality");

	uint32_t tex_flags=0;

	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_REPEAT)
		tex_flags|=Texture::FLAG_REPEAT;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_FILTER)
		tex_flags|=Texture::FLAG_FILTER;
	if (!(flags&EditorTextureImportPlugin::IMAGE_FLAG_NO_MIPMAPS))
		tex_flags|=Texture::FLAG_MIPMAPS;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_CONVERT_TO_LINEAR)
		tex_flags|=Texture::FLAG_CONVERT_TO_LINEAR;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_USE_ANISOTROPY)
		tex_flags|=Texture::FLAG_ANISOTROPIC_FILTER;

	print_line("path: "+p_path+" flags: "+itos(tex_flags));
	float shrink=1;
	if (from->has_option("shrink"))
		shrink=from->get_option("shrink");

	if (large) {
		ERR_FAIL_COND_V(from->get_source_count()!=1,ERR_INVALID_PARAMETER);

		String src_path = EditorImportPlugin::expand_source_path(from->get_source_path(0));


		int cell_size=from->get_option("large_cell_size");
		ERR_FAIL_COND_V(cell_size<128 || cell_size>16384,ERR_CANT_OPEN);

		EditorProgress pg("ltex","Import Large Texture",3);

		pg.step("Load Source Image",0);
		Image img;
		Error err = ImageLoader::load_image(src_path,&img);
		if (err) {
			return err;
		}

		pg.step("Slicing",1);

		Map<Vector2,Image> pieces;
		for(int i=0;i<img.get_width();i+=cell_size) {
			int w = MIN(img.get_width()-i,cell_size);
			for(int j=0;j<img.get_height();j+=cell_size) {
				int h = MIN(img.get_height()-j,cell_size);

				Image piece(w,h,0,img.get_format());
				piece.blit_rect(img,Rect2(i,j,w,h),Point2(0,0));
				if (!piece.is_invisible()) {
					pieces[Vector2(i,j)]=piece;
					//print_line("ADDING PIECE AT "+Vector2(i,j));
				}
			}
		}

		Ref<LargeTexture> existing;
		if (ResourceCache::has(p_path)) {
			existing = ResourceCache::get(p_path);
		}

		if (existing.is_valid()) {
			existing->clear();
		} else {
			existing = Ref<LargeTexture>(memnew( LargeTexture ));
		}

		existing->set_size(Size2(img.get_width(),img.get_height()));
		pg.step("Inserting",2);

		for (Map<Vector2,Image>::Element *E=pieces.front();E;E=E->next()) {

			Ref<ImageTexture> imgtex = Ref<ImageTexture>( memnew( ImageTexture ) );
			imgtex->create_from_image(E->get(),tex_flags);
			_process_texture_data(imgtex,format,quality,flags,p_compr,tex_flags,shrink);
			existing->add_piece(E->key(),imgtex);
		}

		if (!p_external) {
			from->set_editor(get_name());
			existing->set_path(p_path);
			existing->set_import_metadata(from);
		}
		pg.step("Saving",3);

		err = ResourceSaver::save(p_path,existing);
		if (err!=OK) {
			EditorNode::add_io_error("Couldn't save large texture: "+p_path);
			return err;
		}

		return OK;


	} else if (atlas) {

		//prepare atlas!
		Vector< Image > sources;
		Vector< Image > tsources;
		bool alpha=false;
		bool crop = from->get_option("crop");

		EditorProgress ep("make_atlas","Build Atlas For: "+p_path.get_file(),from->get_source_count()+3);

		print_line("sources: "+itos(from->get_source_count()));

		for(int i=0;i<from->get_source_count();i++) {

			String path = EditorImportPlugin::expand_source_path(from->get_source_path(i));
			String md5 = FileAccess::get_md5(path);
			from->set_source_md5(i,FileAccess::get_md5(path));
			ep.step("Loading Image: "+path,i);
			print_line("source path: "+path+" md5 "+md5);
			Image src;
			Error err = ImageLoader::load_image(path,&src);
			if (err) {
				EditorNode::add_io_error("Couldn't load image: "+path);
				return err;
			}

			if (src.detect_alpha())
				alpha=true;

			tsources.push_back(src);
		}
		ep.step("Converting Images",sources.size());

		int base_index=0;


		Map<uint64_t,int> source_md5;
		Map<int,List<int> > source_map;

		for(int i=0;i<tsources.size();i++) {

			Image src = tsources[i];

			if (alpha) {
				src.convert(Image::FORMAT_RGBA);
			} else {
				src.convert(Image::FORMAT_RGB);
			}

			DVector<uint8_t> data = src.get_data();
			MD5_CTX md5;
			DVector<uint8_t>::Read r=data.read();
			MD5Init(&md5);
			int len=data.size();
			for(int j=0;j<len;j++) {
				uint8_t b = r[j];
				b>>=2; //to aid in comparing
				MD5Update(&md5,(unsigned char*)&b,1);
			}
			MD5Final(&md5);
			uint64_t *cmp = (uint64_t*)md5.digest; //less bits, but still useful for this

			tsources[i]=Image(); //clear

			if (source_md5.has(*cmp)) {
				int sidx=source_md5[*cmp];
				source_map[sidx].push_back(i);
				print_line("REUSING "+from->get_source_path(i));

			} else {
				int sidx=sources.size();
				source_md5[*cmp]=sidx;
				sources.push_back(src);
				List<int> sm;
				sm.push_back(i);
				source_map[sidx]=sm;

			}


		}

		//texturepacker is not really good for optimizing, so..
		//will at some point likely replace with my own
		//first, will find the nearest to a square packing
		int border=1;

		Vector<Size2i> src_sizes;
		Vector<Rect2> crops;

		ep.step("Cropping Images",sources.size()+1);

		for(int j=0;j<sources.size();j++) {

			Size2i s;
			if (crop) {
				Rect2 crop = sources[j].get_used_rect();
				print_line("CROP: "+crop);
				s=crop.size;
				crops.push_back(crop);
			} else {

				s=Size2i(sources[j].get_width(),sources[j].get_height());
			}
			s+=Size2i(border*2,border*2);
			src_sizes.push_back(s); //add a line to constraint width
		}

		Vector<Point2i> dst_positions;
		Size2i dst_size;
		EditorAtlas::fit(src_sizes,dst_positions,dst_size);

		print_line("size that workeD: "+itos(dst_size.width)+","+itos(dst_size.height));

		ep.step("Blitting Images",sources.size()+2);

		bool blit_to_po2=tex_flags&Texture::FLAG_MIPMAPS;
		int atlas_w=dst_size.width;
		int atlas_h=dst_size.height;
		if (blit_to_po2) {
			atlas_w=nearest_power_of_2(dst_size.width);
			atlas_h=nearest_power_of_2(dst_size.height);
		}
		Image atlas;
		atlas.create(atlas_w,atlas_h,0,alpha?Image::FORMAT_RGBA:Image::FORMAT_RGB);


		atlases.resize(from->get_source_count());

		for(int i=0;i<sources.size();i++) {

			int x=dst_positions[i].x;
			int y=dst_positions[i].y;

			Size2 sz = Size2(sources[i].get_width(),sources[i].get_height());

			Rect2 region;
			Rect2 margin;

			if (crop && sz!=crops[i].size) {
				Rect2 rect = crops[i];
				rect.size=sz-rect.size;
				region=Rect2(x+border,y+border,crops[i].size.width,crops[i].size.height);
				margin=rect;
				atlas.blit_rect(sources[i],crops[i],Point2(x+border,y+border));
			} else {
				region=Rect2(x+border,y+border,sz.x,sz.y);
				atlas.blit_rect(sources[i],Rect2(0,0,sources[i].get_width(),sources[i].get_height()),Point2(x+border,y+border));
			}

			ERR_CONTINUE( !source_map.has(i) );
			for (List<int>::Element *E=source_map[i].front();E;E=E->next()) {

				String apath = p_path.get_base_dir().plus_file(from->get_source_path(E->get()).get_file().basename()+".atex");

				Ref<AtlasTexture> at;

				if (ResourceCache::has(apath)) {
					at = Ref<AtlasTexture>( ResourceCache::get(apath)->cast_to<AtlasTexture>() );
				} else {

					at = Ref<AtlasTexture>( memnew( AtlasTexture ) );
				}
				at->set_region(region);
				at->set_margin(margin);
				at->set_path(apath);
				atlases[E->get()]=at;
				print_line("Atlas Tex: "+apath);
			}
		}
		if (ResourceCache::has(p_path)) {
			texture = Ref<ImageTexture> ( ResourceCache::get(p_path)->cast_to<ImageTexture>() );
		} else {
			texture = Ref<ImageTexture>( memnew( ImageTexture ) );
		}
		texture->create_from_image(atlas,tex_flags);

	} else {
Esempio n. 23
0
void Layout::update(const AlbumItemContainer &items, const Size2i &clientSize, ImageCache &imageCache)
{
	updateCellLayout();

	lines_.clear();
	itemCount_ = items.size();
	columns_ = std::max(1, (clientSize.w + columnSpace_) / cellStepX_);

	typedef AlbumItemContainer::const_iterator ItemIt;

	class LineDivider
	{
		const unsigned int columns_;
		const ItemIt beg_;
		const ItemIt end_;
		ItemIt curr_;
	public:
		LineDivider(unsigned int columns, const ItemIt &beg, const ItemIt &end)
			: columns_(columns), beg_(beg), end_(end), curr_(beg) {}

		bool isTerminated() const { return curr_ == end_;}
		const ItemIt &getCurrent() const { return curr_;}
		ItemIt getLineEnd()
		{
			unsigned int count = 0;
			for(;;){
				if(curr_ == end_){
					return curr_;
				}
				if((*curr_)->isLineBreak()){
					const ItemIt lineEnd = curr_;
					++curr_;
					return lineEnd;
				}
				if(count++ >= columns_){
					return curr_;
				}
				++curr_;
			}
		}
	};

	LineDivider lineDivider(columns_, items.begin(), items.end());

	int lineTop = 0;
	while(!lineDivider.isTerminated()){
		const ItemIt lineBeg = lineDivider.getCurrent();
		const ItemIt lineEnd = lineDivider.getLineEnd();

		// 画像の高さがAUTOの場合、行内の最大の画像の高さを求める。
		if(isImageHeightAuto()){
			const int maxImageHeight = std::accumulate(lineBeg, lineEnd, 0, [&](int maxImageHeight, const AlbumItemPtr &item) -> int {
				switch(item->getType()){
				case AlbumItem::TYPE_LINE_BREAK:
					break;
				case AlbumItem::TYPE_PICTURE:
					if(const AlbumPicture *pic = dynamic_cast<const AlbumPicture *>(item.get())){
						if(const ImagePtr im = imageCache.getImage(pic->getFilePath(), Size2i(getImageWidth(), getImageHeight()))){
							return std::max(maxImageHeight, im->getHeight());
						}
					}
					break;
				}
				return maxImageHeight;
			});
			lines_.insert(LineContainer::value_type(lineBeg - items.begin(), LineInfo(lineTop, maxImageHeight)));
			lineTop += maxImageHeight + nameHeight_ + lineSpace_;
		}
		else{
			lines_.insert(LineContainer::value_type(lineBeg - items.begin(), LineInfo(lineTop, imageHeight_)));
			lineTop += cellStepY_;
		}

	}

	pageSize_.set(
		columns_ * cellStepX_ - columnSpace_,
		lineTop ? lineTop - lineSpace_ : 0);
}
Esempio n. 24
0
void Sprite3D::_draw() {

	RID immediate = get_immediate();

	VS::get_singleton()->immediate_clear(immediate);
	if (!texture.is_valid())
		return; //no texuture no life
	Vector2 tsize = texture->get_size();
	if (tsize.x==0 || tsize.y==0)
		return;

	Size2i s;
	Rect2i src_rect;

	if (region) {

		s=region_rect.size;
		src_rect=region_rect;
	} else {
		s = texture->get_size();
		s=s/Size2i(hframes,vframes);

		src_rect.size=s;
		src_rect.pos.x+=(frame%hframes)*s.x;
		src_rect.pos.y+=(frame/hframes)*s.y;

	}

	Point2i ofs=get_offset();
	if (is_centered())
		ofs-=s/2;

	Rect2i dst_rect(ofs,s);


	Rect2 final_rect;
	Rect2 final_src_rect;
	if (!texture->get_rect_region(dst_rect,src_rect,final_rect,final_src_rect))
		return;


	if (final_rect.size.x==0 || final_rect.size.y==0)
		return;

	Color color=_get_color_accum();
	color.a*=get_opacity();

	float pixel_size=get_pixel_size();

	Vector2 vertices[4]={

		(final_rect.pos+Vector2(0,final_rect.size.y)) * pixel_size,
		(final_rect.pos+final_rect.size) * pixel_size,
		(final_rect.pos+Vector2(final_rect.size.x,0)) * pixel_size,
		final_rect.pos * pixel_size,


	};
	Vector2 uvs[4]={
		final_src_rect.pos / tsize,
		(final_src_rect.pos+Vector2(final_src_rect.size.x,0)) / tsize,
		(final_src_rect.pos+final_src_rect.size) / tsize,
		(final_src_rect.pos+Vector2(0,final_src_rect.size.y)) / tsize,
	};

	if (is_flipped_h()) {
		SWAP(uvs[0],uvs[1]);
		SWAP(uvs[2],uvs[3]);
	}
	if (is_flipped_v()) {

		SWAP(uvs[0],uvs[3]);
		SWAP(uvs[1],uvs[2]);
	}


	Vector3 normal;
	int axis = get_axis();
	normal[axis]=1.0;

	RID mat = VS::get_singleton()->material_2d_get(get_draw_flag(FLAG_SHADED),get_draw_flag(FLAG_TRANSPARENT),get_alpha_cut_mode()==ALPHA_CUT_DISCARD,get_alpha_cut_mode()==ALPHA_CUT_OPAQUE_PREPASS);
	VS::get_singleton()->immediate_set_material(immediate,mat);

	VS::get_singleton()->immediate_begin(immediate,VS::PRIMITIVE_TRIANGLE_FAN,texture->get_rid());

	int x_axis = ((axis + 1) % 3);
	int y_axis = ((axis + 2) % 3);

	if (axis!=Vector3::AXIS_Z) {
		SWAP(x_axis,y_axis);

		for(int i=0;i<4;i++) {
			//uvs[i] = Vector2(1.0,1.0)-uvs[i];
			//SWAP(vertices[i].x,vertices[i].y);
			if (axis==Vector3::AXIS_Y) {
				vertices[i].y = - vertices[i].y;
			} else if (axis==Vector3::AXIS_X) {
				vertices[i].x = - vertices[i].x;
			}
		}
	}

	AABB aabb;

	for(int i=0;i<4;i++) {
		VS::get_singleton()->immediate_normal(immediate,normal);
		VS::get_singleton()->immediate_color(immediate,color);
		VS::get_singleton()->immediate_uv(immediate,uvs[i]);

		Vector3 vtx;
		vtx[x_axis]=vertices[i][0];
		vtx[y_axis]=vertices[i][1];
		VS::get_singleton()->immediate_vertex(immediate,vtx);
		if (i==0) {
			aabb.pos=vtx;
			aabb.size=Vector3();
		} else {
			aabb.expand_to(vtx);
		}
	}
	set_aabb(aabb);
	VS::get_singleton()->immediate_end(immediate);


}
void QRFinder::FindFinderPatterns(cv::Mat& inputImg, Rect regionOfInterest, vector<FinderPattern*> & finderPatterns, vector<Drawable*> & debugVector)
{
	struct timespec start,end;
	SET_TIME(&start);	

	//Get parameters from config
	edgeThreshold = config->GetIntegerParameter("EdgeThreshold");
	debugLevel = config->GetIntegerParameter("QR Debug Level");
	int verticalResolution = config->GetIntegerParameter("YResolution");
	nonMaxEnabled = config->GetBooleanParameter("EdgeNonMax");
	minimumFinderPatternScore = config->GetIntegerParameter("MinimumFPScore");
	detectorSize = config->GetIntegerParameter("DetectorSize");

	int yBorder = detectorSize;
	vector<Point3i> exclusionZones;
	
	//Calculate limits
	int maxColumn = regionOfInterest.x + regionOfInterest.width;
	maxColumn -= detectorSize;	
	int maxRow = regionOfInterest.y + regionOfInterest.height;
	int xStart = regionOfInterest.x;
	int yStart = regionOfInterest.y;
	xStart += detectorSize;
	yStart += detectorSize;
	maxColumn -= detectorSize;
	maxRow -= detectorSize;

	
	if (debugLevel > 0)
		debugVector.push_back(new DebugRectangle(Rect(Point2i(xStart,yStart),Point2i(maxColumn,maxRow)),Colors::Aqua,1));

	
	//Find horizontal edges
	SET_TIME(&start);
	FindEdgesClosed(inputImg,regionOfInterest,edgeArray,edgeThreshold,nonMaxEnabled,detectorSize);
	SET_TIME(&end);
	double edgeTime_local = calc_time_double(start,end);
	edgeTime = (edgeTime + edgeTime_local)/2.0;
	config->SetLabelValue("EdgeTime",(float)edgeTime/1000.0f);
	
	//If debug level set, find all vertical edges and draw them
	if (debugLevel <= -2)
	{
		for (int x = 1; x < verticalEdgeArray.rows-1; x ++)
		{
			FindEdgesVerticalClosed(inputImg,x);		
			const short * verticalEdgePtr = verticalEdgeArray.ptr<short>(x);
			for (int y = 0; y < (verticalEdgeArray.cols);y++)
			{
				short transition = verticalEdgePtr[y];
				if (transition < 0)
				{
					debugVector.push_back(new DebugCircle(Point2i(x,y),0,Colors::Fuchsia,true));
				}
				else if (transition > 0)
				{
					debugVector.push_back(new DebugCircle(Point2i(x,y),0,Colors::Cyan,true));
				}
			}
		}	
	}
	//END
	
	
	int bw[6] = { 0 };
	int k = 0;
	//LOGV(LOGTAG_QR,"ImgSize=[%d,%d] EdgeSize=[%d,%d]",inputImg.rows,inputImg.cols,edgeArray.rows,edgeArray.cols);

	int yDirection = 1;
	int yCenter = yStart + (maxRow - yStart)/2;
	int y = yStart, absOffset = 0;

	LOGV(LOGTAG_QR,"Beginning search. y[%d->%d], Center=%d, x[%d->%d]",yStart,maxRow,yCenter,xStart,maxColumn);
	
	while (y < maxRow && y >= yStart)
	{	
		y = yCenter + absOffset * yDirection;

		if (yDirection == 1) absOffset += verticalResolution;	//Increment every other frame		
		yDirection = -yDirection;								//Change direction every frame

		k = 0;
		bw[0] = bw[1] = bw[2] = bw[3] = bw[4] = bw[5] = 0;

		const short * edgeRowPtr = edgeArray.ptr<short>(y);
		for (int x = xStart; x < maxColumn; x++)
		{
			if (isInRadius(exclusionZones,Point2i(x,y)))
				continue;

			int transition =  edgeRowPtr[x]; //getTransition(Mi,x,threshold);

			
			if (k == 0) //Haven't found edge yet
			{
				if (transition < 0) /* Light->dark transistion */
				{					
					k++;
				}
			}
			else //Found at least one edge
			{
				if ((k & 1) == 1) //Counting dark
				{
					if (transition > 0) //dark to light
					{					
						++k;
					}
				}
				else //Counting light
				{
					if (transition < 0) //light to dark
					{					
						++k;
					}
				}
			}

			if (k > 0) ++bw[k-1];

			if (FP_DEBUG_ENABLED && (debugLevel == -1 || debugLevel == -2))
			{				
				if (transition < 0)
					debugVector.push_back(new DebugCircle(Point2i(x,y),0,Colors::Lime,true));
				else if (transition > 0)
					debugVector.push_back(new DebugCircle(Point2i(x,y),0,Colors::Yellow,true));

				
			}	


			if (k == 6)
			{		
				int result = 0;
				result = CheckRatios(bw,NULL);

				if (result == 1)
				{	
					//LOGV(LOGTAG_QR,"Ratio check pass");
					//Center based on initial ratio					
					float patternCenterWidth = (float)bw[2];
					int tempXCenter = (x - bw[4] - bw[3]) - (int)round(patternCenterWidth/2.0f); 
					float xOffset = (patternCenterWidth/6.0f);
					
					//y coordinate of center. If check fails, returns 0.
					int tempYCenterArray[] = {0,0,0};

					int * verticalPatternSizes[3];

					for (int i = 0;i < 3;i++)
						verticalPatternSizes[i] = new int[5];

					tempYCenterArray[0] = FindCenterVertical(inputImg, tempXCenter, y, bw, debugVector,verticalPatternSizes[0]);
					tempYCenterArray[1] = FindCenterVertical(inputImg, tempXCenter - xOffset, y, bw, debugVector,verticalPatternSizes[1]);
					tempYCenterArray[2] = FindCenterVertical(inputImg, tempXCenter + xOffset, y, bw, debugVector,verticalPatternSizes[2]);
										
					int tempYCenter = 0;
					int passCount = 0;
					float avgYSize = 0;

					int averageVerticalSize[5] = {0,0,0,0,0};

					for (int yTest = 0; yTest < 3; yTest++)
					{
						if (tempYCenterArray[yTest] > 0)
						{
							passCount++;
							tempYCenter += tempYCenterArray[yTest];
							for (int i=0;i<5;i++)
							{
								averageVerticalSize[i] += (verticalPatternSizes[yTest])[i];
								avgYSize += (verticalPatternSizes[yTest])[i]; 
							}
						}						
					}

					if (passCount >= 2)
					{
						//LOGV(LOGTAG_QR,"Vertical test pass-1");
						
						tempYCenter = (int)round((float)tempYCenter / (float)passCount);
						avgYSize = (float)avgYSize / (float)passCount;

						int allowedVariance = (int)avgYSize >> 2;
						bool yVarianceTest = true;
						for (int yTest = 0; yTest < 3; yTest++)
						{
							if (tempYCenterArray[yTest] > 0)
							{
								if (abs(tempYCenterArray[yTest] - tempYCenter) > allowedVariance)
								{
									yVarianceTest = false;
									break;
								}
							}						
						}

						if (yVarianceTest)
						{
							//LOGV(LOGTAG_QR,"Vertical test pass-2. Passcount=%d",passCount);
							//Average the vertical pattern sizes
							for (int i=0;i<5;i++)
							{
								averageVerticalSize[i] = idiv(averageVerticalSize[i],passCount);
							}
							//LOGV(LOGTAG_QR,"Averaged sizes. Center=%d",averageVerticalSize[2]);

							int tempXCenterArray[] = {0,0,0};
							int xSizeArray[] = {0,0,0};
							int yOffset = idiv(averageVerticalSize[2],6.0f);

							//LOGV(LOGTAG_QR,"Yoffset=%d,yCenter=%d",yOffset,tempYCenter);
							tempXCenterArray[0] = FindCenterHorizontal(tempXCenter, tempYCenter-yOffset, bw, xSizeArray[0], debugVector); 
							tempXCenterArray[1] = FindCenterHorizontal(tempXCenter, tempYCenter, bw, xSizeArray[1], debugVector); 
							tempXCenterArray[2] = FindCenterHorizontal(tempXCenter, tempYCenter+yOffset, bw, xSizeArray[2], debugVector); 

							tempXCenter = 0;
							passCount = 0;
							float avgXSize = 0;

							for (int xTest = 0; xTest < 3; xTest++)
							{
								if (tempXCenterArray[xTest] > 0)
								{
									passCount++;
									tempXCenter += tempXCenterArray[xTest];
									avgXSize += xSizeArray[xTest];
								}						
							}

							if (passCount >= 2)
							{
								
								//LOGV(LOGTAG_QR,"Horizontal test pass");
								tempXCenter = (int)round((float)tempXCenter / (float)passCount);
								avgXSize = (float)avgXSize/(float)passCount;
								//allowedVariance = (int)round((float)avgYSize/1.5f);
								float aspectRatio = avgXSize/avgYSize;
								
								if (aspectRatio > 0.33f && aspectRatio < 3.0f)
								{
									
									//LOGV(LOGTAG_QR,"Size test pass");
									Point2i finderPatternCenter = Point2i(tempXCenter,tempYCenter); //Center of finder pattern

									int finderPatternSize =  MAX(avgXSize,avgYSize);
									int fpRadius = (int)round((float)finderPatternSize/2.0f);
									int fpRadiusExclude = ipow(finderPatternSize,2);

									//LOGD(LOGTAG_QR,"Creating new pattern[%d,%d]",avgXSize,avgYSize);
									//Create a new pattern
									FinderPattern * newPattern = new FinderPattern(finderPatternCenter,Size2i(avgXSize,avgYSize));
									Size2f patternSearchSize = Size2f(avgXSize,avgYSize);

									vector<Point2i> corners;
									struct timespec fastStart,fastEnd;
									SET_TIME(&fastStart);
									fastQRFinder->LocateFPCorners(inputImg,newPattern,corners,debugVector);
//									fastQRFinder->CheckAlignmentPattern(inputImg,finderPatternCenter,patternSearchSize,corners,debugVector);
									SET_TIME(&fastEnd);
									double fastFPTime_Local = calc_time_double(fastStart,fastEnd);
									fastFPTime += fastFPTime_Local;
									if (corners.size() == 4)
									{
										//if (validatePattern(newPattern,finderPatterns))
										//{
										newPattern->patternCorners = corners;
										exclusionZones.push_back(Point3i(finderPatternCenter.x,finderPatternCenter.y, fpRadiusExclude));
										finderPatterns.push_back(newPattern);
										if (FP_DEBUG_ENABLED && debugLevel > 0)
										{
											debugVector.push_back(new DebugCircle(finderPatternCenter,fpRadius,Colors::MediumSpringGreen,1,true));
											for (int i=0;i<corners.size();i++)
											{
												if (FP_DEBUG_ENABLED && debugLevel > 0)
													debugVector.push_back(new DebugCircle(corners[i],10,Colors::DodgerBlue,2));
											}
										}
										//}
										//else
										//{
										//	//LOGV(LOGTAG_QR,"Compare check failed");
										//	if (FP_DEBUG_ENABLED && debugLevel > 0)
										//		debugVector.push_back(new DebugCircle(finderPatternCenter,fpRadius,Colors::HotPink,2));
										//}
									}
									else
									{
										
										//LOGV(LOGTAG_QR,"FAST check failed");
										if (FP_DEBUG_ENABLED && debugLevel > 0)
											debugVector.push_back(new DebugCircle(finderPatternCenter,fpRadius,Colors::Red,2));
										delete newPattern;
									}
								}
								else
								{
									//LOGV(LOGTAG_QR,"Size check failed");
									//Size check failed
									if (FP_DEBUG_ENABLED && debugLevel > 1)
										debugVector.push_back(new DebugCircle(Point2i(tempXCenter,tempYCenter),13, Colors::HotPink,1));
								}
							}
							else
							{
								//LOGV(LOGTAG_QR,"Horizontal check failed");
								//Vertical check succeeded, but horizontal re-check failed
								if (FP_DEBUG_ENABLED && debugLevel > 1)
									debugVector.push_back(new DebugCircle(Point2i(tempXCenter,tempYCenter),12, Colors::OrangeRed,1));
							}
						}
						else
						{
							//LOGV(LOGTAG_QR,"Variance test failed. AllowedVariance = %d, yCenters = %d,%d,%d [avg=%d], AvgYSize=%d",allowedVariance,tempYCenterArray[0],tempYCenterArray[1],tempYCenterArray[2],tempYCenter,avgYSize);
							//Vertical variance test failed
							if (FP_DEBUG_ENABLED && debugLevel > 1)
								debugVector.push_back(new DebugCircle(Point2i(tempXCenter,tempYCenter),14, Colors::MediumSpringGreen,1));
						}

					} else
					{
						//Ratios were correct but vertical check failed
						if (FP_DEBUG_ENABLED && debugLevel > 2)
						{
							if (tempYCenter == 0) //ratio fail
								debugVector.push_back(new DebugCircle(Point2i(tempXCenter,y),10,Colors::Aqua,1));
							else if (tempYCenter == -1)	//topcheck fail				
								debugVector.push_back(new DebugCircle(Point2i(tempXCenter,y),10,Colors::Orange,1));
							else if (tempYCenter == -2)	//bottomcheck fail							
								debugVector.push_back(new DebugCircle(Point2i(tempXCenter,y),10,Colors::Lime,1));
						}
					}
				}
Esempio n. 26
0
Size2i Texture2D::getMaxSizePriv() {
   int maxSize;
   glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);
   return Size2i(maxSize, maxSize);
}
Esempio n. 27
0
RES ResourceFormatPBM::load(const String &p_path,const String& p_original_path,Error *r_error) {

#define _RETURN(m_err)\
{\
	if (r_error)\
		*r_error=m_err;\
	ERR_FAIL_V(RES());\
}


	FileAccessRef f=FileAccess::open(p_path,FileAccess::READ);
	uint8_t saved=0;
	if (!f)
		_RETURN(ERR_CANT_OPEN);

	PoolVector<uint8_t> token;

	if (!_get_token(f,saved,token)) {
		_RETURN(ERR_PARSE_ERROR);
	}

	if (token.size()!=2) {
		_RETURN(ERR_FILE_CORRUPT);
	}
	if (token[0]!='P') {
		_RETURN(ERR_FILE_CORRUPT);
	}
	if (token[1]!='1' && token[1]!='4') {
		_RETURN(ERR_FILE_CORRUPT);
	}

	bool bits = token[1]=='4';

	if (!_get_token(f,saved,token)) {
		_RETURN(ERR_PARSE_ERROR);
	}

	int width = _get_number_from_token(token);
	if (width<=0) {
		_RETURN(ERR_FILE_CORRUPT);
	}


	if (!_get_token(f,saved,token)) {
		_RETURN(ERR_PARSE_ERROR);
	}

	int height = _get_number_from_token(token);
	if (height<=0) {
		_RETURN(ERR_FILE_CORRUPT);
	}


	Ref<BitMap> bm;
	bm.instance();
	bm->create(Size2i(width,height));

	if (!bits) {

		int required_bytes = width*height;
		if (!_get_token(f,saved,token,false,true)) {
			_RETURN(ERR_PARSE_ERROR);
		}

		if (token.size()<required_bytes) {
			_RETURN(ERR_FILE_CORRUPT);
		}

		PoolVector<uint8_t>::Read r=token.read();
			
		for(int i=0;i<height;i++) {
			for(int j=0;j<width;j++) {


				char num = r[i*width+j];
				bm->set_bit(Point2i(j,i),num=='0');
			}

		}



	} else {
		//a single, entire token of bits!
		if (!_get_token(f,saved,token,true)) {
			_RETURN(ERR_PARSE_ERROR);
		}
		int required_bytes = Math::ceil((width*height)/8.0);
		if (token.size()<required_bytes) {
			_RETURN(ERR_FILE_CORRUPT);
		}

		PoolVector<uint8_t>::Read r=token.read();
		int bitwidth = width;
		if (bitwidth % 8)
			bitwidth+=8-(bitwidth%8);

		for(int i=0;i<height;i++) {
			for(int j=0;j<width;j++) {

				int ofs = bitwidth*i+j;

				uint8_t byte = r[ofs/8];
				bool bit = (byte>>(7-(ofs%8)))&1;

				bm->set_bit(Point2i(j,i),!bit);

			}

		}

	}

	return bm;


}
Esempio n. 28
0
void Slider::_notification(int p_what) {

	switch (p_what) {

		case NOTIFICATION_MOUSE_ENTER: {

			mouse_inside = true;
			update();
		} break;
		case NOTIFICATION_MOUSE_EXIT: {

			mouse_inside = false;
			update();
		} break;
		case NOTIFICATION_VISIBILITY_CHANGED: // fallthrough
		case NOTIFICATION_EXIT_TREE: {

			mouse_inside = false;
			grab.active = false;
		} break;
		case NOTIFICATION_DRAW: {
			RID ci = get_canvas_item();
			Size2i size = get_size();
			Ref<StyleBox> style = get_stylebox("slider");
			Ref<StyleBox> focus = get_stylebox("focus");
			Ref<StyleBox> grabber_area = get_stylebox("grabber_area");
			Ref<Texture> grabber = get_icon(editable ? ((mouse_inside || has_focus()) ? "grabber_highlight" : "grabber") : "grabber_disabled");
			Ref<Texture> tick = get_icon("tick");

			if (orientation == VERTICAL) {

				int widget_width = style->get_minimum_size().width + style->get_center_size().width;
				float areasize = size.height - grabber->get_size().height;
				style->draw(ci, Rect2i(Point2i(size.width / 2 - widget_width / 2, 0), Size2i(widget_width, size.height)));
				grabber_area->draw(ci, Rect2i(Point2i((size.width - widget_width) / 2, size.height - areasize * get_as_ratio() - grabber->get_size().height / 2), Size2i(widget_width, areasize * get_as_ratio() + grabber->get_size().width / 2)));
				/*
				if (mouse_inside||has_focus())
					focus->draw(ci,Rect2i(Point2i(),Size2i(style->get_minimum_size().width+style->get_center_size().width,size.height)));
				*/
				if (ticks > 1) {
					int tickarea = size.height - tick->get_height();
					for (int i = 0; i < ticks; i++) {
						if (!ticks_on_borders && (i == 0 || i + 1 == ticks)) continue;
						int ofs = i * tickarea / (ticks - 1);
						tick->draw(ci, Point2i((size.width - widget_width) / 2, ofs));
					}
				}
				grabber->draw(ci, Point2i(size.width / 2 - grabber->get_size().width / 2, size.height - get_as_ratio() * areasize - grabber->get_size().height));
			} else {

				int widget_height = style->get_minimum_size().height + style->get_center_size().height;
				float areasize = size.width - grabber->get_size().width;

				style->draw(ci, Rect2i(Point2i(0, (size.height - widget_height) / 2), Size2i(size.width, widget_height)));
				grabber_area->draw(ci, Rect2i(Point2i(0, (size.height - widget_height) / 2), Size2i(areasize * get_as_ratio() + grabber->get_size().width / 2, widget_height)));
				/*
				if (mouse_inside||has_focus())
					focus->draw(ci,Rect2i(Point2i(),Size2i(size.width,style->get_minimum_size().height+style->get_center_size().height)));
				*/

				if (ticks > 1) {
					int tickarea = size.width - tick->get_width();
					for (int i = 0; i < ticks; i++) {
						if ((!ticks_on_borders) && ((i == 0) || ((i + 1) == ticks))) continue;
						int ofs = i * tickarea / (ticks - 1);
						tick->draw(ci, Point2i(ofs, (size.height - widget_height) / 2));
					}
				}
				grabber->draw(ci, Point2i(get_as_ratio() * areasize, size.height / 2 - grabber->get_size().height / 2));
			}

		} break;
	}
}
Esempio n. 29
0
RotatedRect searchFace(Mat& src, GenericModel *model, cv::Size2f scaleFactor, bool draw){
	
	GenericFeature *minFeature;
	Mat auxImg, auxImg2;
	resize(src, auxImg,cv::Size2i(scaleFactor.width*src.size().width, scaleFactor.height*src.size().height));
	auxImg2 = auxImg.clone();
	
	CvHaarClassifierCascade* cascade = (CvHaarClassifierCascade*) cvLoad (CASCADE_NAME, 0, 0, 0);
    CvMemStorage* storage = cvCreateMemStorage(0);
    assert (storage);
	if (! cascade)
        abort ();
	
	CvHaarClassifierCascade* cascadeProfile = (CvHaarClassifierCascade*) cvLoad (CASCADE_NAME_PROFILE, 0, 0, 0);
    CvMemStorage* storageProfile = cvCreateMemStorage(0);
    assert (storageProfile);
	if (! cascadeProfile)
        abort ();
	
	IplImage *gray_image = cvCreateImage(src.size(), IPL_DEPTH_8U, 1);
	IplImage aux = IplImage(src);
	
	cvCvtColor (&aux, gray_image, CV_BGR2GRAY);
	cvEqualizeHist( gray_image, gray_image );
	
	CvSeq* faces = cvHaarDetectObjects (gray_image, cascade, storage, 1.1, 3, CV_HAAR_DO_CANNY_PRUNING, cvSize (25, 25));
	CvSeq* facesProfiles = cvHaarDetectObjects (gray_image, cascadeProfile, storageProfile, 1.1, 3, CV_HAAR_DO_CANNY_PRUNING, cvSize (25, 25));
	
	double minValue = 10000.0;
	RotatedRect minRect;
	
	model->updateModel(auxImg);
	if (draw) cvNamedWindow("ROI");
	
	for (int i = 0; i < (faces ? faces->total : 0); i++){
		CvRect* r = (CvRect*) cvGetSeqElem (faces, i);
		RotatedRect auxRect(Point2i(r->x+r->width/2,r->y+r->height/2),Size2i(r->width,r->height),0);
		auxRect = scaleRect(auxRect, cv::Size2f(scaleFactor.width, scaleFactor.height));
		if (draw) drawRotatedRect(auxImg2, auxRect,CV_RGB(100,50,50) , 2);
		
		
		if(model->ModelType == COV_FULL_IMAGE){
			//minFeature = (GenericFeature *)new CovarianceFullDescriptor(auxRect,model->tracker_param);
			CV_Assert(false);
		}
		else if(model->ModelType == COV_SUB_WINDOWS)
			minFeature = (GenericFeature *)new CovariancePatchDescriptor(auxRect,model->tracker_param);
		else if(model->ModelType == COV_SUB_WINDOWS_B)
			minFeature = (GenericFeature *)new CovariancePatchDescriptor(auxRect,model->tracker_param);
		
		minFeature->computeFeature(model);
		double dist = model->distance(minFeature);
		
		if (dist<minValue) {
			minValue = dist;
			minRect = auxRect;
		}
		
		minFeature->clear();
		delete minFeature;
		if (draw){
			cout << "dist: "<<dist<<endl;
			imshow( "ROI", auxImg2);
			cvWaitKey();
		}
		
	}
	
	for (int i = 0; i < (facesProfiles ? facesProfiles->total : 0); i++){
		CvRect* r = (CvRect*) cvGetSeqElem (facesProfiles, i);
		RotatedRect auxRect(Point2i(r->x+r->width/2,r->y+r->height/2),Size2i(r->width,r->height),0);
		auxRect = scaleRect(auxRect, cv::Size2f(scaleFactor.width, scaleFactor.height));
		if (draw) drawRotatedRect(auxImg2, auxRect,CV_RGB(0,0,0) , 2);
		
		if(model->ModelType == COV_FULL_IMAGE){
			//minFeature = (GenericFeature *)new CovarianceFullDescriptor(auxRect,model->tracker_param);
			CV_Assert(false);
		}
		else if(model->ModelType == COV_SUB_WINDOWS)
			minFeature = (GenericFeature *)new CovariancePatchDescriptor(auxRect,model->tracker_param);
		else if(model->ModelType == COV_SUB_WINDOWS_B)
			minFeature = (GenericFeature *)new CovariancePatchDescriptor(auxRect,model->tracker_param);
		
		minFeature->computeFeature(model);
		double dist = model->distance(minFeature);
		
		
		if (dist<minValue) {
			minValue = dist;
			minRect = auxRect;
		}
		
		minFeature->clear();
		delete minFeature;
		if (draw){
			cout << "dist: "<<dist<<endl;
			imshow( "ROI", auxImg2);
			cvWaitKey();
		}	
	}	
	
	
	if (draw){
		drawRotatedRect(auxImg2, minRect,CV_RGB(255,0,0) , 3);	
		imshow( "ROI", auxImg2);
		cvWaitKey();
		cvDestroyWindow("ROI");
	}
	auxImg2.release();
	auxImg.release();
	
	cvReleaseImage(&gray_image);
	
	cvClearMemStorage(storage);
	cvClearMemStorage(storageProfile);
	
	return scaleRect(minRect, cv::Size2f(1/scaleFactor.width, 1/scaleFactor.height));	
}