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;
}
Exemple #2
0
static void
print_column(OBJ *obj)
{
	struct stat *st;
	FTSENT      *p;
	FTSENT      **arr;	/* array of the files */

	int count_file;		/* count total number of file */
	int count_pre;		/* count the width of ino and block */
	int col_num;		/* how many columns to print */
	int *col_width_max;	/* max width for each column */
	int row_num;		/* number of rows */
	int last_row;		/* how rows in the last column */
	int i, j, t;

	count_pre = 0;

	if (f_ino)
		count_pre += obj->obj_ino_max + 1;
	if (f_block)
		count_pre += obj->obj_block_max + 1;
	if (f_char)
		count_pre++;

	count_file = 0;
	for (p = obj->obj_list; p != NULL; p = p->fts_link)
		if (p->fts_number != FTS_NO_PRINT)
			count_file++;

	/* first guess at column number, suppose all the file names are 1 */
	col_num = term_width / (count_pre + 1 + 2);

	/* at least one column */
	col_num = MAX(col_num, 1);

	if (count_file == 0) {
		return;
	}

	/* one column, use line print */
	if (count_file == 1 || col_num == 1) {
		print_line(obj);
		return;
	}

	col_width_max = (int *)malloc(col_num * sizeof(int));
	arr = (FTSENT **)malloc(count_file * sizeof(FTSENT *));

	if (col_width_max == NULL || arr == NULL) {
		free(col_width_max);
		free(arr);
		warn("failed to malloc");
		return;
	}

	/* copy files to array */
	for (p = obj->obj_list, i = 0; p!= NULL; p = p->fts_link) {
		if (p->fts_number == FTS_NO_PRINT)
			continue;
		arr[i++] = p;
	}

	/* how many rows needed to be printed */
	if (count_file % col_num == 0)
		row_num = count_file / col_num;
	else
		row_num = count_file / col_num + 1;

	row_num = MAX(row_num, 1);

	/*
	 * Try to find the best printing format, and the max width for each
	 * column.
	 */
	while (row_num < count_file) {
		/* max length of the column */
		int max_len;

		if (count_file % row_num == 0) {
			col_num = count_file / row_num;
			last_row = row_num;
		} else {
			col_num = count_file / row_num + 1;
			last_row = count_file % row_num;
		}

		for (i = 0; i < col_num; i++)
			col_width_max[i] = 0;

		for (i = 0, t = 0; i < col_num; i++) {
			int f;
			int tmp_count;
			f = (i == col_num - 1) ? last_row : row_num;
			for (j = 0; j < f; j++) {
				tmp_count = count_pre + 
					    strlen(arr[t++]->fts_name) + 2;

				if (f_char) 
					tmp_count++;

				col_width_max[i] = MAX(col_width_max[i], 
							tmp_count); 
			}
		}

		max_len = 0;

		for (i = 0; i < col_num; i++)
			max_len += col_width_max[i];

		/*
		 * If the total length of each row is less than the width
		 * of the terminal, then we stop.
		 */
		if (max_len <= term_width)
			break;

		row_num++;
	}

	/* one column, use line print */
	if (row_num == count_file) {
		free(arr);
		free(col_width_max);
		print_line(obj);
		return;
	}

	for (i = 0; i < row_num; i++) {
		int f;
		f = (i < last_row) ? col_num : (col_num - 1);
		for (j = 0; j < f; j++) {
			st = arr[i + j * row_num]->fts_statp;

			/* print inode */
			if (f_ino)
				printf("%*"PRIuMAX" ", obj->obj_ino_max,
					(uintmax_t)st->st_ino);
	
			/* print number of blocks */
			if (f_block) {	
				print_block(st->st_blocks * DEFAULT_BSIZE, 
					    obj->obj_block_max);
			}
	
			
			t = count_pre + print_name(arr[i + j * row_num], 0);

			while (t < col_width_max[j]) {
				putchar(' ');
				t++;
			}
		}
		putchar('\n');
	}

	free(arr);
	free(col_width_max);
}
Exemple #3
0
int 
main (int argc, char **argv)
{
  int last_argc = -1;
  int force = 0;

  struct sockaddr_un srvr_addr;
  socklen_t addrlen;
  int server;
  int flags;
  client_t client_list = NULL;
 
  if (argc)
    {
      argc--; argv++;
    }
  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--version"))
        print_version (0);
      else if (!strcmp (*argv, "--help"))
        print_version (1);
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--force"))
        {
          force = 1;
          argc--; argv++;
        }
    }          
 
  if (argc != 1)
    {
      fprintf (stderr, "usage: " PGM " socketname\n");
      exit (1);
    }


  if (verbose)
    fprintf (stderr, "opening socket `%s'\n", *argv);

  setvbuf (stdout, NULL, _IOLBF, 0);

  server = socket (PF_LOCAL, SOCK_STREAM, 0);
  if (server == -1)
    die ("socket() failed: %s\n", strerror (errno));

  /* We better set the listening socket to non-blocking so that we
     don't get bitten by race conditions in accept.  The should not
     happen for Unix Domain sockets but well, shit happens. */
  flags = fcntl (server, F_GETFL, 0);
  if (flags == -1)
    die ("fcntl (F_GETFL) failed: %s\n", strerror (errno));
  if ( fcntl (server, F_SETFL, (flags | O_NONBLOCK)) == -1)
    die ("fcntl (F_SETFL) failed: %s\n", strerror (errno));
  

  memset (&srvr_addr, 0, sizeof srvr_addr);
  srvr_addr.sun_family = AF_LOCAL;
  strncpy (srvr_addr.sun_path, *argv, sizeof (srvr_addr.sun_path) - 1);
  srvr_addr.sun_path[sizeof (srvr_addr.sun_path) - 1] = 0;
  addrlen = SUN_LEN (&srvr_addr);

  
 again:
  if (bind (server, (struct sockaddr *) &srvr_addr, addrlen))
    { 
      if (errno == EADDRINUSE && force)
        {
          force = 0;
          remove (srvr_addr.sun_path);
          goto again;
        }
      die ("bind to `%s' failed: %s\n", *argv, strerror (errno));
    }

  if (listen (server, 5))
    die ("listen failed: %s\n", strerror (errno));

  for (;;)
    {
      fd_set rfds;
      int max_fd;
      client_t client;

      /* Usually we don't have that many connections, thus it is okay
         to set them allways from scratch and don't maintain an active
         fd_set. */
      FD_ZERO (&rfds);
      FD_SET (server, &rfds);
      max_fd = server;
      for (client = client_list; client; client = client->next)
        if (client->fd != -1)
          {
            FD_SET (client->fd, &rfds);
            if (client->fd > max_fd)
              max_fd = client->fd;
          }

      if (select (max_fd + 1, &rfds, NULL, NULL, NULL) <= 0)
        continue;  /* Ignore any errors. */

      if (FD_ISSET (server, &rfds)) /* New connection. */
        { 
          struct sockaddr_un clnt_addr;
          int fd;

          addrlen = sizeof clnt_addr;
          fd = accept (server, (struct sockaddr *) &clnt_addr, &addrlen);
          if (fd == -1)
            {
              printf ("[accepting connection failed: %s]\n", strerror (errno));
            }
          else if (fd >= FD_SETSIZE)
            {
              close (fd);
              printf ("[connection request denied: too many connections]\n");
            }
          else 
            {
              for (client = client_list; client && client->fd != -1;
                   client = client->next)
                ;
              if (!client)
                {
                  client = xcalloc (1, sizeof *client);
                  client->next = client_list;
                  client_list = client;
                }
              client->fd = fd;
              printf ("[client at fd %d connected]\n", client->fd);
            }
        }
      for (client = client_list; client; client = client->next)
        if (client->fd != -1 && FD_ISSET (client->fd, &rfds))
          {
            char line[256];
            int n;
            
            n = read (client->fd, line, sizeof line - 1);
            if (n < 0)
              {
                int save_errno = errno;
                print_line (client, NULL); /* flush */
                printf ("[client at fd %d read error: %s]\n",
                        client->fd, strerror (save_errno));
                close (client->fd);
                client->fd = -1;
              }
            else if (!n) 
              {
                print_line (client, NULL); /* flush */
                close (client->fd);
                printf ("[client at fd %d disconnected]\n", client->fd);
                client->fd = -1;
              }
            else
              {
                line[n] = 0;
                print_line (client, line);
              }
          }
    }

  return 0;
}
Exemple #4
0
	virtual void init() {
		

		print_line("INITIALIZING TEST RENDER");
		VisualServer *vs=VisualServer::get_singleton();
		test_cube = vs->get_test_cube();
		scenario = vs->scenario_create();






		Vector<Vector3> vts;

/*
		DVector<Plane> sp = Geometry::build_sphere_planes(2,5,5);
		Geometry::MeshData md2 = Geometry::build_convex_mesh(sp);
		vts=md2.vertices;
*/
/*

		static const int s = 20;
		for(int i=0;i<s;i++) {
			Matrix3 rot(Vector3(0,1,0),i*Math_PI/s);

			for(int j=0;j<s;j++) {
				Vector3 v;
				v.x=Math::sin(j*Math_PI*2/s);
				v.y=Math::cos(j*Math_PI*2/s);

				vts.push_back( rot.xform(v*2 ) );
			}
		}*/
		/*for(int i=0;i<100;i++) {

			vts.push_back( Vector3(Math::randf()*2-1.0,Math::randf()*2-1.0,Math::randf()*2-1.0).normalized()*2);
		}*/
		/*
		vts.push_back(Vector3(0,0,1));
		vts.push_back(Vector3(0,0,-1));
		vts.push_back(Vector3(0,1,0));
		vts.push_back(Vector3(0,-1,0));
		vts.push_back(Vector3(1,0,0));
		vts.push_back(Vector3(-1,0,0));*/

		vts.push_back(Vector3(1,1,1));
		vts.push_back(Vector3(1,-1,1));
		vts.push_back(Vector3(-1,1,1));
		vts.push_back(Vector3(-1,-1,1));
		vts.push_back(Vector3(1,1,-1));
		vts.push_back(Vector3(1,-1,-1));
		vts.push_back(Vector3(-1,1,-1));
		vts.push_back(Vector3(-1,-1,-1));

		Geometry::MeshData md;
		Error err = QuickHull::build(vts,md);
		print_line("ERR: "+itos(err));
		test_cube = vs->mesh_create();
		vs->mesh_add_surface_from_mesh_data(test_cube,md);
		//vs->scenario_set_debug(scenario,VS::SCENARIO_DEBUG_WIREFRAME);

		/*
		RID sm = vs->shader_create();
		//vs->shader_set_fragment_code(sm,"OUT_ALPHA=mod(TIME,1);");
		//vs->shader_set_vertex_code(sm,"OUT_VERTEX=IN_VERTEX*mod(TIME,1);");
		vs->shader_set_fragment_code(sm,"OUT_DIFFUSE=vec3(1,0,1);OUT_GLOW=abs(sin(TIME));");
		RID tcmat = vs->mesh_surface_get_material(test_cube,0);
		vs->material_set_shader(tcmat,sm);
		*/


		List<String> cmdline = OS::get_singleton()->get_cmdline_args();
		int object_count = OBJECT_COUNT;
		if (cmdline.size() > 0 && cmdline[cmdline.size()-1].to_int()) {
			object_count = cmdline[cmdline.size()-1].to_int();
		};

		for (int i=0;i<object_count;i++) {
			
			InstanceInfo ii;
			
			
			ii.instance = vs->instance_create2( test_cube, scenario );
			
			
			ii.base.translate( Math::random(-20,20), Math::random(-20,20),Math::random(-20,18) );
			ii.base.rotate( Vector3(0,1,0), Math::randf() * Math_PI );
			ii.base.rotate( Vector3(1,0,0), Math::randf() * Math_PI );
			vs->instance_set_transform( ii.instance, ii.base );			
			
			ii.rot_axis = Vector3( Math::random(-1,1), Math::random(-1,1), Math::random(-1,1) ).normalized();
			
			instances.push_back(ii);
			
		}
		
		camera = vs->camera_create();
		
// 		vs->camera_set_perspective( camera, 60.0,0.1, 100.0 );

		viewport = vs->viewport_create();
		vs->viewport_attach_to_screen(viewport);
		vs->viewport_attach_camera( viewport, camera );
		vs->viewport_set_scenario( viewport, scenario );
		vs->camera_set_transform(camera, Transform( Matrix3(), Vector3(0,3,30 ) ) );
		vs->camera_set_perspective( camera, 60, 0.1, 1000);


		/*
		RID lightaux = vs->light_create( VisualServer::LIGHT_OMNI );
		vs->light_set_var( lightaux, VisualServer::LIGHT_VAR_RADIUS, 80 );
		vs->light_set_var( lightaux, VisualServer::LIGHT_VAR_ATTENUATION, 1 );
		vs->light_set_var( lightaux, VisualServer::LIGHT_VAR_ENERGY, 1.5 );
		light = vs->instance_create( lightaux );
		*/
		RID lightaux;

		//*
		lightaux = vs->light_create( VisualServer::LIGHT_DIRECTIONAL );
		vs->light_set_color( lightaux, VisualServer::LIGHT_COLOR_AMBIENT, Color(0.0,0.0,0.0) );
		vs->light_set_color( lightaux, VisualServer::LIGHT_COLOR_DIFFUSE, Color(1.0,1.0,1.0) );
		//vs->light_set_shadow( lightaux, true );
		light = vs->instance_create2( lightaux, scenario );
		Transform lla;
		//lla.set_look_at(Vector3(),Vector3(1,-1,1),Vector3(0,1,0));
		lla.set_look_at(Vector3(),Vector3(-0.000000,-0.836026,-0.548690),Vector3(0,1,0));

		vs->instance_set_transform( light, lla );
		//	*/

		//*
		lightaux = vs->light_create( VisualServer::LIGHT_OMNI );
		vs->light_set_color( lightaux, VisualServer::LIGHT_COLOR_AMBIENT, Color(0.0,0.0,1.0) );
		vs->light_set_color( lightaux, VisualServer::LIGHT_COLOR_DIFFUSE, Color(1.0,1.0,0.0) );
		vs->light_set_param( lightaux, VisualServer::LIGHT_PARAM_RADIUS, 4 );
		vs->light_set_param( lightaux, VisualServer::LIGHT_PARAM_ENERGY, 8 );
		//vs->light_set_shadow( lightaux, true );
		//light = vs->instance_create( lightaux );
		//	*/

		ofs=0;
		quit=false;
	}
Exemple #5
0
void handle_line(char *line)
{
	float freq = 0.0;
	int octave = -1;
	char *check = NULL;
	check = get_arg_to("#reset",line);
	if (check)
	{
		step_prog = 0;
		free(check);
		return;
	}

	check = get_arg_to("#step ",line);
	if (check)
	{
		step_size = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#amp ",line);
	if (check)
	{
		amp = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#duty ",line);
	if (check)
	{
		duty = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#wave ",line);
	if (check)
	{
		wave_sel = (int)strtoul(check,NULL,0);
		free(check);
		return;
	}

	check = get_arg_to("#decay ",line);
	if (check)
	{
		decay_len = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#len ",line);
	if (check)
	{
		note_len = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#overclock ",line);
	if (check)
	{
		overclock = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#tmod ",line);
	if (check)
	{
		tmod_cnt++;
		tmod = (float)strtof(check,0);
		printf("\tfloat t%d = mod(t0,%f);\n",tmod_cnt,tmod);
		free(check);
		return;	
	}

	check = get_arg_to("#tune ",line);
	if (check)
	{
		tune = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#left ",line);
	if (check)
	{
		left_a = (float)strtof(check,0);	
		free(check);
		return;
	}

	check = get_arg_to("#right ",line);
	if (check)
	{
		right_a = (float)strtof(check,0);	
		free(check);
		return;
	}

	check = get_arg_to("#main",line);
	if (check)
	{	
		printf("vec2 mainSound(float t0)\n{\n");
		printf("\tt0 = t0 * %f;\n",overclock);
		printf("\tvec2 result = vec2(0.0,0.0);\n");
		free(check);
		return;
	}

	check = get_arg_to("#endmain",line);
	if (check)
	{
		printf("\n\treturn result;\n}\n\n");
		free(check);
		return;
	}

	check = get_arg_to("#func ",line);
	if (check)
	{
		tmod_cnt = 0;
		printf("float %s(float t%d)\n{\n\tfloat result = 0.0;\n",check,tmod_cnt);
		free(check);
		return;
	}

	check = get_arg_to("#endfunc",line);
	if (check)
	{
		printf("\n\treturn result;\n}\n\n");
		free(check);
		return;
	}

	check = get_arg_to("#call ",line);
	if (check)
	{
		printf("\tresult += vec2(%f,%f) * (%s(t%d));\n",left_a,right_a,check,tmod_cnt);
		free(check);
		return;
	}

// Notes
	check = get_arg_to("C#",line);
	if (check)
	{
		freq = NOTE_CS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("C",line);
	if (check)
	{
		freq = NOTE_C;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("D#",line);
	if (check)
	{
		freq = NOTE_DS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("D",line);
	if (check)
	{
		freq = NOTE_D;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("E",line);
	if (check)
	{
		freq = NOTE_E;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("F#",line);
	if (check)
	{
		freq = NOTE_FS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("F",line);
	if (check)
	{
		freq = NOTE_F;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("G#",line);
	if (check)
	{
		freq = NOTE_GS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("G",line);
	if (check)
	{
		freq = NOTE_G;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("A#",line);
	if (check)
	{
		freq = NOTE_AS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("A",line);
	if (check)
	{
		freq = NOTE_A;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("B",line);
	if (check)
	{
		freq = NOTE_B;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("-",line);
	if (check)
	{
		freq = 0;
		octave = -1;
		goto handle_line_finished;
	}

// Unrecognized token, or a comment, etc
	free(check);
	return;

handle_line_finished:
	if (check)
	{
		free(check);
		print_line(freq, octave);
		step_prog += step_size;
	}
	return;
	
}
Exemple #6
0
Variant _jobject_to_variant(JNIEnv * env, jobject obj) {

	jclass c = env->GetObjectClass(obj);
	bool array;
	String name = _get_class_name(env, c, &array);
	//print_line("name is " + name + ", array "+Variant(array));

	print_line("ARGNAME: "+name);
	if (name == "java.lang.String") {

		return String::utf8(env->GetStringUTFChars( (jstring)obj, NULL ));
	};


	if (name == "[Ljava.lang.String;") {

		jobjectArray arr = (jobjectArray)obj;
		int stringCount = env->GetArrayLength(arr);
		//print_line("String array! " + String::num(stringCount));
		DVector<String> sarr;

		for (int i=0; i<stringCount; i++) {
			jstring string = (jstring) env->GetObjectArrayElement(arr, i);
			const char *rawString = env->GetStringUTFChars(string, 0);
			sarr.push_back(String(rawString));
			env->DeleteLocalRef(string);

		}

		return sarr;
	};

	if (name == "java.lang.Boolean") {

		jmethodID boolValue = env->GetMethodID(c, "booleanValue", "()Z");
		bool ret = env->CallBooleanMethod(obj, boolValue);
		return ret;
	};

	if (name == "java.lang.Integer") {

		jclass nclass = env->FindClass("java/lang/Number");
		jmethodID intValue = env->GetMethodID(nclass, "intValue", "()I");
		int ret = env->CallIntMethod(obj, intValue);
		return ret;
	};

	if (name == "[I") {

		jintArray arr = (jintArray)obj;
		int fCount = env->GetArrayLength(arr);
		DVector<int> sarr;
		sarr.resize(fCount);

		DVector<int>::Write w = sarr.write();
		env->GetIntArrayRegion(arr,0,fCount,w.ptr());
		w = DVector<int>::Write();
		return sarr;
	};

	if (name == "[B") {

		jbyteArray arr = (jbyteArray)obj;
		int fCount = env->GetArrayLength(arr);
		DVector<uint8_t> sarr;
		sarr.resize(fCount);

		DVector<uint8_t>::Write w = sarr.write();
		env->GetByteArrayRegion(arr,0,fCount,reinterpret_cast<signed char*>(w.ptr()));
		w = DVector<uint8_t>::Write();
		return sarr;
	};

	if (name == "java.lang.Float" || name == "java.lang.Double") {

		jclass nclass = env->FindClass("java/lang/Number");
		jmethodID doubleValue = env->GetMethodID(nclass, "doubleValue", "()D");
		double ret = env->CallDoubleMethod(obj, doubleValue);
		return ret;
	};

	if (name == "[D") {

		jdoubleArray arr = (jdoubleArray)obj;
		int fCount = env->GetArrayLength(arr);
		RealArray sarr;
		sarr.resize(fCount);

		RealArray::Write w = sarr.write();

		for (int i=0; i<fCount; i++) {

			double n;
			env->GetDoubleArrayRegion(arr, i, 1, &n);
			w.ptr()[i] = n;

		};
		return sarr;
	};

	if (name == "[F") {

		jfloatArray arr = (jfloatArray)obj;
		int fCount = env->GetArrayLength(arr);
		RealArray sarr;
		sarr.resize(fCount);


		RealArray::Write w = sarr.write();

		for (int i=0; i<fCount; i++) {

			float n;
			env->GetFloatArrayRegion(arr, i, 1, &n);
			w.ptr()[i] = n;

		};
		return sarr;
	};


	if (name == "[Ljava.lang.Object;") {

		jobjectArray arr = (jobjectArray)obj;
		int objCount = env->GetArrayLength(arr);
		Array varr(true);

		for (int i=0; i<objCount; i++) {
			jobject jobj = env->GetObjectArrayElement(arr, i);
			Variant v = _jobject_to_variant(env, jobj);
			varr.push_back(v);
			env->DeleteLocalRef(jobj);

		}

		return varr;
	};

    if (name == "java.util.HashMap" || name == "org.godotengine.godot.Dictionary") {

		Dictionary ret(true);
		jclass oclass = c;
		jmethodID get_keys = env->GetMethodID(oclass, "get_keys", "()[Ljava/lang/String;");
		jobjectArray arr = (jobjectArray)env->CallObjectMethod(obj, get_keys);

		StringArray keys = _jobject_to_variant(env, arr);
		env->DeleteLocalRef(arr);

		jmethodID get_values = env->GetMethodID(oclass, "get_values", "()[Ljava/lang/Object;");
		arr = (jobjectArray)env->CallObjectMethod(obj, get_values);

		Array vals = _jobject_to_variant(env, arr);
		env->DeleteLocalRef(arr);

		//print_line("adding " + String::num(keys.size()) + " to Dictionary!");
		for (int i=0; i<keys.size(); i++) {

			ret[keys[i]] = vals[i];
		};


		return ret;
	};

	env->DeleteLocalRef(c);

	return Variant();
};
Exemple #7
0
RES ResourceFormatLoaderShader::load(const String &p_path,const String& p_original_path) {

	String fragment_code;
	String vertex_code;

	int mode=-1;

	Error err;
	FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);


	ERR_EXPLAIN("Unable to open shader file: "+p_path);
	ERR_FAIL_COND_V(err,RES());
	String base_path = p_path.get_base_dir();


	Ref<Shader> shader( memnew( Shader ) );

	int line=0;

	while(!f->eof_reached()) {

		String l = f->get_line();
		line++;

		if (mode<=0) {
			l = l.strip_edges();
			int comment = l.find(";");
			if (comment!=-1)
				l=l.substr(0,comment);
		}

		if (mode<1)
			vertex_code+="\n";
		if (mode<2)
			fragment_code+="\n";

		if (mode < 1 && l=="")
			continue;

		if (l.begins_with("[")) {
			l=l.strip_edges();
			if (l=="[params]") {
				if (mode>=0) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [params] section.");
					ERR_FAIL_V(RES());
				}
				mode=0;
			}  else if (l=="[vertex]") {
				if (mode>=1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [vertex] section.");
					ERR_FAIL_V(RES());
				}
				mode=1;
			}  else if (l=="[fragment]") {
				if (mode>=2) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [fragment] section.");
					ERR_FAIL_V(RES());
				}
				mode=1;
			} else {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
				ERR_FAIL_V(RES());
			}
			continue;
		}

		if (mode==0) {

			int eqpos = l.find("=");
			if (eqpos==-1) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='.");
				ERR_FAIL_V(RES());
			}


			String right=l.substr(eqpos+1,l.length()).strip_edges();
			if (right=="") {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='.");
				ERR_FAIL_V(RES());
			}

			Variant value;

			if (right=="true") {
				value = true;
			} else if (right=="false") {
				value = false;
			} else if (right.is_valid_float()) {
				//is number
				value = right.to_double();
			} else if (right.is_valid_html_color()) {
				//is html color
				value = Color::html(right);
			} else {
				//attempt to parse a constructor
				int popenpos = right.find("(");

				if (popenpos==-1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right);
					ERR_FAIL_V(RES());
				}

				int pclosepos = right.find_last(")");

				if (pclosepos==-1) {
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right);
					ERR_FAIL_V(RES());

				}

				String type = right.substr(0,popenpos);
				String param = right.substr(popenpos+1,pclosepos-popenpos-1).strip_edges();

				print_line("type: "+type+" param: "+param);

				if (type=="tex") {

					if (param=="") {

						value=RID();
					} else {

						String path;

						if (param.is_abs_path())
							path=param;
						else
							path=base_path+"/"+param;

						Ref<Texture> texture = ResourceLoader::load(path);
						if (!texture.is_valid()) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path);
							ERR_FAIL_V(RES());
						}

						value=texture;
					}

				} else if (type=="vec3") {

					if (param=="") {
						value=Vector3();
					} else {
						Vector<String> params = param.split(",");
						if (params.size()!=3) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for vec3(): '"+right+"'.");
							ERR_FAIL_V(RES());

						}

						Vector3 v;
						for(int i=0;i<3;i++)
							v[i]=params[i].to_double();
						value=v;
					}


				} else if (type=="xform") {

					if (param=="") {
						value=Transform();
					} else {

						Vector<String> params = param.split(",");
						if (params.size()!=12) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for xform(): '"+right+"'.");
							ERR_FAIL_V(RES());

						}

						Transform t;
						for(int i=0;i<9;i++)
							t.basis[i%3][i/3]=params[i].to_double();
						for(int i=0;i<3;i++)
							t.origin[i]=params[i-9].to_double();

						value=t;
					}

				} else {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'.");
					ERR_FAIL_V(RES());

				}

			}

			String left= l.substr(0,eqpos);

//			shader->set_param(left,value);
		} else if (mode==1) {

			vertex_code+=l;

		} else if (mode==2) {

			fragment_code+=l;
		}
	}

	shader->set_code(vertex_code,fragment_code);

	f->close();
	memdelete(f);

	return shader;
}
Exemple #8
0
int main()
{

	//creating a variable to track keystorkes 
	unsigned int key; 

	//holds 1 for player 1 and 2 for player 2
	int looser=0; 
	//detects collision 
	bool colide=0; 

	//this variable holds the opsition of the 'X' charachter 
	// that is located at the 24th row 
	int player1_position=40; 
	//this variable is the row number the charachter is going to appear at 
	int player1_row=15; 
	/* initialize random seed: */
  srand ( time(NULL) );

	/*for (int j=0; j<25; j++)
	for(int i=0; i<80;i++)
	cout<<"0"; */
	//creating rows 
	int* rows[25];
	//initializing rows to point at 25 different int arrays made of 80 elements 
	for (int j=0; j<25; j++)
	{
		rows[j]= new int[80];
	}
	//intiializing the individual arrays 
	for (int j=0; j<25; j++)
	{
		for (int i=0; i<80; i++)
		{
			if(i==0 || i==79)
		(rows[j])[i]=1;
			else (rows[j])[i]=0;
			
		}
	}

	//creating player1 
	(rows[player1_row])[player1_position]=2; 

	//printing the lines 
	for (int j=0; j<25; j++) print_line( rows[j] ); 


	//Just for debugging 
	{
		//creating new objects for the 0th line (top one)
	for(int i=1; i<79;i++)
		(rows[0])[i]=rand() % 2; 

	system("cls"); 
	//printing the lines 
	for (int j=0; j<25; j++) print_line( rows[j] ); 


	//resetting x
	
	}




	int x=0; 
	while(1)
	{
		//keyboard stuff
		//___________________________________
		//sampling keystorke 
		if(kbhit())  key = getch(); 
		else key=NULL; 
		if(key=='a' && player1_position!=0)
		{
			(rows[player1_row])[player1_position]=0;//erasing cursor 
			player1_position-- ;			//repositioning 
			(rows[player1_row])[player1_position]=2;//recreating
		}
		if(key=='d' && player1_position!=79)
		{
			(rows[player1_row])[player1_position]=0;//erasing cursor 
			player1_position++ ;			//repositioning 
			(rows[player1_row])[player1_position]=2;//recreating
		}

		//End of keyboard stuff
		//______________________________________________
		x++; 

		if(x==30 )
	{
		//creating new objects for the 0th line (top one)
	for(int i=1; i<79;i++)
		(rows[0])[i]=rand() % 2; 

	system("cls"); 
	//printing the lines 
	for (int j=0; j<25; j++) print_line( rows[j] ); 


	//resetting x
	x=0; 
	}

//shifting lines from bottom to top 
		for (int j=24; j>0; j--)
			for(int i=1; i<79;i++) 
			{	
				//checking for collision 
				if((rows[j])[i]==2 && (rows[j-1])[i]==1)
				{
					looser=1; 
					colide =1; 
				}
				//copying 
					(rows[j])[i]=(rows[j-1])[i]; 
					
			}
		
	//clearing the top line 
		for(int i=1; i<79;i++) (rows[0])[i]=0; 

	//repositioning the cursor 
	(rows[player1_row])[player1_position]=2;//recreating

	system("cls"); 
	//printing the lines 
	for (int j=0; j<25; j++) 
		print_line( rows[j] ); 

	

	
	if(colide) break;
	}

	if(looser==1)
	{
		system("cls"); 
		cout<<"player 1 looses "<<endl; 
	}


	return 0; 
}
Error EditorMeshImportPlugin::import(const String& p_path, const Ref<ResourceImportMetadata>& p_from){


	ERR_FAIL_COND_V(p_from->get_source_count()!=1,ERR_INVALID_PARAMETER);

	Ref<ResourceImportMetadata> from=p_from;

	String src_path=EditorImportPlugin::expand_source_path(from->get_source_path(0));
	FileAccessRef f = FileAccess::open(src_path,FileAccess::READ);
	ERR_FAIL_COND_V(!f,ERR_CANT_OPEN);

	Ref<Mesh> mesh;
	Map<String,Ref<Material> > name_map;

	if (FileAccess::exists(p_path)) {
		mesh=ResourceLoader::load(p_path,"Mesh");
		if (mesh.is_valid()) {
			for(int i=0;i<mesh->get_surface_count();i++) {

				if (!mesh->surface_get_material(i).is_valid())
					continue;
				String name;
				if (mesh->surface_get_name(i)!="")
					name=mesh->surface_get_name(i);
				else
					name=vformat(TTR("Surface %d"),i+1);

				name_map[name]=mesh->surface_get_material(i);
			}

			while(mesh->get_surface_count()) {
				mesh->surface_remove(0);
			}
		}
	}

	if (!mesh.is_valid())
		mesh = Ref<Mesh>( memnew( Mesh ) );


	bool generate_normals=from->get_option("generate/normals");
	bool generate_tangents=from->get_option("generate/tangents");
	bool flip_faces=from->get_option("force/flip_faces");
	bool force_smooth=from->get_option("force/smooth_shading");
	bool weld_vertices=from->get_option("force/weld_vertices");
	float weld_tolerance=from->get_option("force/weld_tolerance");
	Vector<Vector3> vertices;
	Vector<Vector3> normals;
	Vector<Vector2> uvs;
	String name;

	Ref<SurfaceTool> surf_tool = memnew( SurfaceTool) ;
	surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
	if (force_smooth)
		surf_tool->add_smooth_group(true);
	int has_index_data=false;

	while(true) {


		String l = f->get_line().strip_edges();

		if (l.begins_with("v ")) {
			//vertex
			Vector<String> v = l.split(" ",false);
			ERR_FAIL_COND_V(v.size()<4,ERR_INVALID_DATA);
			Vector3 vtx;
			vtx.x=v[1].to_float();
			vtx.y=v[2].to_float();
			vtx.z=v[3].to_float();
			vertices.push_back(vtx);
		} else  if (l.begins_with("vt ")) {
			//uv
			Vector<String> v = l.split(" ",false);
			ERR_FAIL_COND_V(v.size()<3,ERR_INVALID_DATA);
			Vector2 uv;
			uv.x=v[1].to_float();
			uv.y=1.0-v[2].to_float();
			uvs.push_back(uv);

		} else if (l.begins_with("vn ")) {
			//normal
			Vector<String> v = l.split(" ",false);
			ERR_FAIL_COND_V(v.size()<4,ERR_INVALID_DATA);
			Vector3 nrm;
			nrm.x=v[1].to_float();
			nrm.y=v[2].to_float();
			nrm.z=v[3].to_float();
			normals.push_back(nrm);
		} if (l.begins_with("f ")) {
				//vertex

			has_index_data=true;
			Vector<String> v = l.split(" ",false);
			ERR_FAIL_COND_V(v.size()<4,ERR_INVALID_DATA);

			//not very fast, could be sped up


			Vector<String> face[3];
			face[0] = v[1].split("/");
			face[1] = v[2].split("/");
			ERR_FAIL_COND_V(face[0].size()==0,ERR_PARSE_ERROR);
			ERR_FAIL_COND_V(face[0].size()!=face[1].size(),ERR_PARSE_ERROR);
			for(int i=2;i<v.size()-1;i++) {

				face[2] = v[i+1].split("/");
				ERR_FAIL_COND_V(face[0].size()!=face[2].size(),ERR_PARSE_ERROR);
				for(int j=0;j<3;j++) {

					int idx=j;

					if (!flip_faces && idx<2) {
						idx=1^idx;
					}


					if (face[idx].size()==3) {
						int norm = face[idx][2].to_int()-1;
						ERR_FAIL_INDEX_V(norm,normals.size(),ERR_PARSE_ERROR);
						surf_tool->add_normal(normals[norm]);
					}

					if (face[idx].size()>=2 && face[idx][1]!=String()) {

						int uv = face[idx][1].to_int()-1;
						ERR_FAIL_INDEX_V(uv,uvs.size(),ERR_PARSE_ERROR);
						surf_tool->add_uv(uvs[uv]);
					}

					int vtx = face[idx][0].to_int()-1;
					print_line("vtx: "+itos(vtx)+"/"+itos(vertices.size()));
					ERR_FAIL_INDEX_V(vtx,vertices.size(),ERR_PARSE_ERROR);

					Vector3 vertex = vertices[vtx];
					if (weld_vertices)
						vertex=vertex.snapped(weld_tolerance);
					surf_tool->add_vertex(vertex);
				}

				face[1]=face[2];
			}
		} else if (l.begins_with("s ") && !force_smooth) { //smoothing
			String what = l.substr(2,l.length()).strip_edges();
			if (what=="off")
				surf_tool->add_smooth_group(false);
			else
				surf_tool->add_smooth_group(true);

		} else if (l.begins_with("o ") || f->eof_reached()) { //new surface or done

			if (has_index_data) {
				//new object/surface
				if (generate_normals || force_smooth)
					surf_tool->generate_normals();
				if (uvs.size() && (normals.size() || generate_normals) && generate_tangents)
					surf_tool->generate_tangents();

				surf_tool->index();
				mesh = surf_tool->commit(mesh);
				if (name=="")
					name=vformat(TTR("Surface %d"),mesh->get_surface_count()-1);
				mesh->surface_set_name(mesh->get_surface_count()-1,name);
				name="";
				surf_tool->clear();
				surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
				if (force_smooth)
					surf_tool->add_smooth_group(true);

				has_index_data=false;

				if (f->eof_reached())
					break;
			}

			if (l.begins_with("o ")) //name
				name=l.substr(2,l.length()).strip_edges();
		}
	}


	from->set_source_md5(0,FileAccess::get_md5(src_path));
	from->set_editor(get_name());
	mesh->set_import_metadata(from);

	//re-apply materials if exist
	for(int i=0;i<mesh->get_surface_count();i++) {

		String n = mesh->surface_get_name(i);
		if (name_map.has(n))
			mesh->surface_set_material(i,name_map[n]);
	}

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

	return err;
}
Exemple #10
0
    void start(){
        cyOS::vector <char> buffer;
	    cyOS::vector <char> input;
	    char user[16] = "root@cyOS:$ \0\0";
	    uint name = 12;
	    uint pos = name;
        uint line = 0;
	    char c;
	    KEY k;
	    text_graphics::set_cursor_pos(name);
	    while (true){
            //clears screen, prints current input, and then waits for key press
	        text_graphics::clear();
	        print_line(user, name, input, line);
	        k = keyboard::get_key();
	        //non-character keys move cursor around screen and also position in buffer
	        if (!is_key_printable(k))
		    {
		        if ( (k == KEY_LEFT) && (text_graphics::cursor_pos() > name) ){
			        cursor_decrement(); 
			        pos--;
		        }
		        else if ( (k == KEY_RIGHT) && (text_graphics::cursor_pos() < input.size()+name) ){
			        cursor_increment();
			        pos++;
		        }
		        else if ( (k == KEY_UP) && (text_graphics::cursor_pos() > text_graphics::cols())){
			        text_graphics::set_cursor_pos(text_graphics::cursor_pos()-text_graphics::cols());
			        pos -= text_graphics::cols();
		        }
		        else if ( (k == KEY_DOWN) && (input.size() > text_graphics::cols()) && (text_graphics::cursor_pos()+text_graphics::cols()-1 < input.size()) ){
			        text_graphics::set_cursor_pos(text_graphics::cursor_pos()+text_graphics::cols());
			        pos += text_graphics::cols();
		        }
		        //should be KEY_DELTE
		        else if ( (k == KEY_F12)  && (pos < name+input.size())){
			        text_graphics::put_char(' ', pos);
			        input.erase(pos-name);
			        //print(input);
		        }
		        else if (k == KEY_HOME){
			        text_graphics::set_cursor_pos(name);
			        pos = name;
		        }
		        //should be KEY_END
		        else if (k == 1060480){
			        text_graphics::set_cursor_pos(input.size());
			        pos = input.size();
		        }
		    }
	        else{
		        c = keyboard::get_char();
		        //backspace
		        if (c == '\b'){
		            //if position is in the user's name, put it at the end of the user's name
		            if (pos <= name){
			            text_graphics::set_cursor_pos(name);
			            pos = name;
		            }
		            //otherwise delete the previous character from the vector
		            else {
			            //text_graphics::put_char(' ', pos-1);
			            if (input.size() > 0){
			                cursor_decrement();
			                pos--;
			            }
		                if (pos-name == input.size()){
		                    input.pop_back();
		                }
		                else{
		                    input.erase(pos-name);
		                }
		            }
		        }
		        //return/new line
		        else if (c == '\n' && pos == input.size()){
		            text_graphics::clear();
		            print_line(user, name, input, ++line);
		            text_graphics::set_cursor_pos(name);
		            if(function_call(input)==true){
			            text_graphics::clear();
			            char escape[] = "Exiting Shell...\0\0";
			            print_c(escape);
			            return;
		            }
		            pos = name;
		        }
		        //Checks for new line in middle of input
		        else {
		            if (c == '\n' || c== '\r')
			        c = '\0';
		            /*if (pos-name == input.size()){
			        text_graphics::put_char(c, text_graphics::cursor_pos());
			        input.push_back(c);
		            }
		            else{*/
			        input.insert(pos-name, c); //insert into input string
		            if (c == '\0'){
			            text_graphics::clear();
			            function_call(input); //parses and executes
			            pos = name;
                                    input.clear();
		            }
		            pos++;
		            cursor_increment();
		        }
	        }
	        //keeping cursor on the screen
	        if (text_graphics::cursor_pos() < name){
		        text_graphics::set_cursor_pos(name);
		        pos = name;
	        }
	        else if (text_graphics::cursor_pos() > (text_graphics::cols()*text_graphics::rows()) ){
		        text_graphics::set_cursor_pos(text_graphics::cols()*text_graphics::rows());
		        pos = text_graphics::cols()*text_graphics::rows();
	        }
	    }
    }
Exemple #11
0
bool PhysicsDirectSpaceStateSW::cast_motion(const RID& p_shape, const Transform& p_xform,const Vector3& p_motion,float p_margin,float &p_closest_safe,float &p_closest_unsafe, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask,ShapeRestInfo *r_info) {



	ShapeSW *shape = static_cast<PhysicsServerSW*>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
	ERR_FAIL_COND_V(!shape,false);

	AABB aabb = p_xform.xform(shape->get_aabb());
	aabb=aabb.merge(AABB(aabb.pos+p_motion,aabb.size)); //motion
	aabb=aabb.grow(p_margin);

	//if (p_motion!=Vector3())
	//	print_line(p_motion);

	int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);

	float best_safe=1;
	float best_unsafe=1;

	Transform xform_inv = p_xform.affine_inverse();
	MotionShapeSW mshape;
	mshape.shape=shape;
	mshape.motion=xform_inv.basis.xform(p_motion);

	bool best_first=true;

	Vector3 closest_A,closest_B;

	for(int i=0;i<amount;i++) {


		if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
			continue;

		if (p_exclude.has( space->intersection_query_results[i]->get_self()))
			continue; //ignore excluded


		const CollisionObjectSW *col_obj=space->intersection_query_results[i];
		int shape_idx=space->intersection_query_subindex_results[i];

		Vector3 point_A,point_B;
		Vector3 sep_axis=p_motion.normalized();

		Transform col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
		//test initial overlap, does it collide if going all the way?
		if (CollisionSolverSW::solve_distance(&mshape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,point_A,point_B,aabb,&sep_axis)) {
			//print_line("failed motion cast (no collision)");
			continue;
		}


		//test initial overlap
#if 0
		if (CollisionSolverSW::solve_static(shape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,NULL,NULL,&sep_axis)) {
			print_line("failed initial cast (collision at begining)");
			return false;
		}
#else
		sep_axis=p_motion.normalized();

		if (!CollisionSolverSW::solve_distance(shape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,point_A,point_B,aabb,&sep_axis)) {
			//print_line("failed motion cast (no collision)");
			return false;
		}
#endif


		//just do kinematic solving
		float low=0;
		float hi=1;
		Vector3 mnormal=p_motion.normalized();

		for(int i=0;i<8;i++) { //steps should be customizable..

			float ofs = (low+hi)*0.5;

			Vector3 sep=mnormal; //important optimization for this to work fast enough

			mshape.motion=xform_inv.basis.xform(p_motion*ofs);

			Vector3 lA,lB;

			bool collided = !CollisionSolverSW::solve_distance(&mshape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,lA,lB,aabb,&sep);

			if (collided) {

				//print_line(itos(i)+": "+rtos(ofs));
				hi=ofs;
			} else {

				point_A=lA;
				point_B=lB;
				low=ofs;
			}
		}

		if (low<best_safe) {
			best_first=true; //force reset
			best_safe=low;
			best_unsafe=hi;
		}

		if (r_info && (best_first || (point_A.distance_squared_to(point_B) < closest_A.distance_squared_to(closest_B) && low<=best_safe))) {
			closest_A=point_A;
			closest_B=point_B;
			r_info->collider_id=col_obj->get_instance_id();
			r_info->rid=col_obj->get_self();
			r_info->shape=shape_idx;
			r_info->point=closest_B;
			r_info->normal=(closest_A-closest_B).normalized();
			best_first=false;
			if (col_obj->get_type()==CollisionObjectSW::TYPE_BODY) {
				const BodySW *body=static_cast<const BodySW*>(col_obj);
				r_info->linear_velocity= body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - closest_B);
			}

		}


	}

	p_closest_safe=best_safe;
	p_closest_unsafe=best_unsafe;

	return true;
}
Error EditorExportPlatform::export_project_files(EditorExportSaveFunction p_func, void* p_udata,bool p_make_bundles) {

/* ALL FILES AND DEPENDENCIES */

	Vector<StringName> files=get_dependencies(p_make_bundles);

/* GROUP ATLAS */


	List<StringName> groups;

	EditorImportExport::get_singleton()->image_export_get_groups(&groups);

	Map<StringName,StringName> remap_files;
	Set<StringName> saved;

	int counter=0;

	for(List<StringName>::Element *E=groups.front();E;E=E->next()) {

		if (!EditorImportExport::get_singleton()->image_export_group_get_make_atlas(E->get()))
			continue; //uninterested, only process for atlas!

		List<StringName> atlas_images;
		EditorImportExport::get_singleton()->image_export_get_images_in_group(E->get(),&atlas_images);
		atlas_images.sort_custom<StringName::AlphCompare>();

		for (List<StringName>::Element *F=atlas_images.front();F;) {

			List<StringName>::Element *N=F->next();

			if (!FileAccess::exists(F->get())) {
				atlas_images.erase(F);
			}

			F=N;

		}

		if (atlas_images.size()<=1)
			continue;

		int group_format=0;
		float group_lossy_quality=EditorImportExport::get_singleton()->image_export_group_get_lossy_quality(E->get());
		int group_shrink=EditorImportExport::get_singleton()->image_export_group_get_shrink(E->get());

		switch(EditorImportExport::get_singleton()->image_export_group_get_image_action(E->get())) {
			case EditorImportExport::IMAGE_ACTION_NONE: {

				switch(EditorImportExport::get_singleton()->get_export_image_action()) {
					case EditorImportExport::IMAGE_ACTION_NONE: {

						group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_DISK_LOSSLESS; //?

					} break; //use default
					case EditorImportExport::IMAGE_ACTION_COMPRESS_DISK: {
						group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_DISK_LOSSY;
					} break; //use default
					case EditorImportExport::IMAGE_ACTION_COMPRESS_RAM: {
						group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_RAM;
					} break; //use default
				}

				group_lossy_quality=EditorImportExport::get_singleton()->get_export_image_quality();

			} break; //use default
			case EditorImportExport::IMAGE_ACTION_COMPRESS_DISK: {
				group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_DISK_LOSSY;
			} break; //use default
			case EditorImportExport::IMAGE_ACTION_COMPRESS_RAM: {
				group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_RAM;
			} break; //use default
		}

		String image_list_md5;

		{
			MD5_CTX ctx;
			MD5Init(&ctx);
			for (List<StringName>::Element *F=atlas_images.front();F;F=F->next()) {

				String p = F->get();
				MD5Update(&ctx,(unsigned char*)p.utf8().get_data(),p.utf8().length());

			}

			MD5Final(&ctx);
			image_list_md5=String::md5(ctx.digest);
		}
		//ok see if cached
		String md5;
		bool atlas_valid=true;
		String atlas_name;

		{
			MD5_CTX ctx;
			MD5Init(&ctx);
			String path = Globals::get_singleton()->get_resource_path()+"::"+String(E->get())+"::"+get_name();
			MD5Update(&ctx,(unsigned char*)path.utf8().get_data(),path.utf8().length());
			MD5Final(&ctx);
			md5 = String::md5(ctx.digest);
		}

		FileAccess *f=NULL;

		if (!FileAccess::exists(EditorSettings::get_singleton()->get_settings_path()+"/tmp/atlas-"+md5)) {
			print_line("NO MD5 INVALID");
			atlas_valid=false;
		}

		if (atlas_valid)
			f=FileAccess::open(EditorSettings::get_singleton()->get_settings_path()+"/tmp/atlas-"+md5,FileAccess::READ);

		if (atlas_valid) {
			//compare options
			Dictionary options;
			options.parse_json(f->get_line());
			if (!options.has("lossy_quality") || float(options["lossy_quality"])!=group_lossy_quality)
				atlas_valid=false;
			else if (!options.has("shrink") || int(options["shrink"])!=group_shrink)
				atlas_valid=false;
			else if (!options.has("image_format") || int(options["image_format"])!=group_format)
				atlas_valid=false;

			if (!atlas_valid)
				print_line("JSON INVALID");

		}


		if (atlas_valid) {
			//check md5 of list of image /names/
			if (f->get_line().strip_edges()!=image_list_md5) {
				atlas_valid=false;
				print_line("IMAGE MD5 INVALID!");
			}

		}

		Vector<Rect2> rects;
		bool resave_deps=false;

		if (atlas_valid) {

			//check if images were not modified
			for (List<StringName>::Element *F=atlas_images.front();F;F=F->next()) {

				Vector<String> slices = f->get_line().strip_edges().split("::");

				if (slices.size()!=10) {
					atlas_valid=false;
					print_line("CANT SLICE IN 10");
					break;
				}
				uint64_t mod_time = slices[0].to_int64();
				uint64_t file_mod_time = FileAccess::get_modified_time(F->get());
				if (mod_time!=file_mod_time) {

					String image_md5 = slices[1];
					String file_md5 = FileAccess::get_md5(F->get());

					if (image_md5!=file_md5) {
						atlas_valid=false;
						print_line("IMAGE INVALID "+slices[0]);
						break;
					} else {
						resave_deps=true;
					}
				}

				if (atlas_valid) {
					//push back region and margin
					rects.push_back(Rect2(slices[2].to_float(),slices[3].to_float(),slices[4].to_float(),slices[5].to_float()));
					rects.push_back(Rect2(slices[6].to_float(),slices[7].to_float(),slices[8].to_float(),slices[9].to_float()));
				}
			}

		}

		if (f) {
			memdelete(f);
			f=NULL;
		}

		print_line("ATLAS VALID? "+itos(atlas_valid)+" RESAVE DEPS? "+itos(resave_deps));
		if (!atlas_valid) {
			rects.clear();
			//oh well, atlas is not valid. need to make new one....

			String dst_file = EditorSettings::get_singleton()->get_settings_path()+"/tmp/atlas-"+md5+".tex";
			Ref<ResourceImportMetadata> imd = memnew( ResourceImportMetadata );
			//imd->set_editor();

			for (List<StringName>::Element *F=atlas_images.front();F;F=F->next()) {

				imd->add_source(EditorImportPlugin::validate_source_path(F->get()));
			}


			imd->set_option("format",group_format);


			int flags=0;

			if (Globals::get_singleton()->get("texture_import/filter"))
				flags|=EditorTextureImportPlugin::IMAGE_FLAG_FILTER;
			if (!Globals::get_singleton()->get("texture_import/gen_mipmaps"))
				flags|=EditorTextureImportPlugin::IMAGE_FLAG_NO_MIPMAPS;
			if (!Globals::get_singleton()->get("texture_import/repeat"))
				flags|=EditorTextureImportPlugin::IMAGE_FLAG_REPEAT;

			flags|=EditorTextureImportPlugin::IMAGE_FLAG_FIX_BORDER_ALPHA;

			imd->set_option("flags",flags);
			imd->set_option("quality",group_lossy_quality);
			imd->set_option("atlas",true);
			imd->set_option("crop",true);
			imd->set_option("shrink",group_shrink);



			Ref<EditorTextureImportPlugin> plugin = EditorImportExport::get_singleton()->get_import_plugin_by_name("texture_atlas");
			Error err = plugin->import2(dst_file,imd,get_image_compression(),true);
			if (err) {

				EditorNode::add_io_error("Error saving atlas! "+dst_file.get_file());
				return ERR_CANT_CREATE;
			}

			ERR_FAIL_COND_V(imd->get_option("rects")==Variant(),ERR_BUG);

			Array r_rects=imd->get_option("rects");
			rects.resize(r_rects.size());
			for(int i=0;i<r_rects.size();i++) {
				//get back region and margins

				rects[i]=r_rects[i];
			}


			resave_deps=true;
		}


		//atlas is valid (or it was just saved i guess), create the atex files and save them

		if (resave_deps) {
			f=FileAccess::open(EditorSettings::get_singleton()->get_settings_path()+"/tmp/atlas-"+md5,FileAccess::WRITE);
			Dictionary options;
			options["lossy_quality"]=group_lossy_quality;
			options["shrink"]=EditorImportExport::get_singleton()->image_export_group_get_shrink(E->get());
			options["image_format"]=group_format;
			f->store_line(options.to_json());
			f->store_line(image_list_md5);
		}

		//go through all ATEX files

		{
			Ref<ImageTexture> atlas = memnew( ImageTexture ); //fake atlas!
			String atlas_path="res://atlas-"+md5+".tex";
			atlas->set_path(atlas_path);
			int idx=0;
			for (List<StringName>::Element *F=atlas_images.front();F;F=F->next()) {

				String p = F->get();
				Ref<AtlasTexture> atex = memnew(AtlasTexture);
				atex->set_atlas(atlas);
				Rect2 region=rects[idx++];
				Rect2 margin=rects[idx++];
				atex->set_region(region);
				atex->set_margin(margin);

				String path = EditorSettings::get_singleton()->get_settings_path()+"/tmp/tmpatlas.atex";
				Error err = ResourceSaver::save(path,atex);
				if (err!=OK) {
					EditorNode::add_io_error("Could not save atlas subtexture: "+path);
					return ERR_CANT_CREATE;
				}
				Vector<uint8_t> data = FileAccess::get_file_as_array(path);
				String dst_path = F->get().operator String().basename()+".atex";
				err = p_func(p_udata,dst_path,data,counter++,files.size());
				saved.insert(dst_path);
				if (err)
					return err;

				if (f) {
					//recreating deps..
					String depline;
//					depline=String(F->get())+"::"+itos(FileAccess::get_modified_time(F->get()))+"::"+FileAccess::get_md5(F->get()); name unneccesary by top md5
					depline=itos(FileAccess::get_modified_time(F->get()))+"::"+FileAccess::get_md5(F->get());
					depline+="::"+itos(region.pos.x)+"::"+itos(region.pos.y)+"::"+itos(region.size.x)+"::"+itos(region.size.y);
					depline+="::"+itos(margin.pos.x)+"::"+itos(margin.pos.y)+"::"+itos(margin.size.x)+"::"+itos(margin.size.y);
					f->store_line(depline);
				}

				remap_files[F->get()]=dst_path;
			}

			Vector<uint8_t> atlas_data = FileAccess::get_file_as_array(EditorSettings::get_singleton()->get_settings_path()+"/tmp/atlas-"+md5+".tex");
			Error err = p_func(p_udata,atlas_path,atlas_data,counter,files.size());
			saved.insert(atlas_path);
			if (err)
				return err;

		}


		if (f) {
			memdelete(f);
		}

	}


	StringName engine_cfg="res://engine.cfg";

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

		if (remap_files.has(files[i]) || files[i]==engine_cfg) //gonna be remapped (happened before!)
			continue; //from atlas?
		String src=files[i];
		Vector<uint8_t> buf = get_exported_file(src);

		ERR_CONTINUE( saved.has(src) );

		Error err = p_func(p_udata,src,buf,counter++,files.size());
		if (err)
			return err;

		saved.insert(src);
		if (src!=String(files[i]))
			remap_files[files[i]]=src;

	}


	{

		//make binary engine.cfg config

		Map<String,Variant> custom;

		if (remap_files.size()) {
			Vector<String> remapsprop;
			for(Map<StringName,StringName>::Element *E=remap_files.front();E;E=E->next()) {
				remapsprop.push_back(E->key());
				remapsprop.push_back(E->get());
			}

			custom["remap/all"]=remapsprop;
		}
		String remap_file="engine.cfb";
		String engine_cfb =EditorSettings::get_singleton()->get_settings_path()+"/tmp/tmp"+remap_file;
		Globals::get_singleton()->save_custom(engine_cfb,custom);
		Vector<uint8_t> data = FileAccess::get_file_as_array(engine_cfb);

		Error err = p_func(p_udata,"res://"+remap_file,data,counter,files.size());
		if (err)
			return err;

	}

	return OK;
}
Vector<StringName> EditorExportPlatform::get_dependencies(bool p_bundles) const {


	Set<StringName> exported;

	if (FileAccess::exists("res://engine.cfg"))
		exported.insert("res://engine.cfg");

	if (EditorImportExport::get_singleton()->get_export_filter()!=EditorImportExport::EXPORT_SELECTED) {

		String filter;
		if (EditorImportExport::get_singleton()->get_export_filter()==EditorImportExport::EXPORT_ALL) {
			_add_filter_to_list(exported,"*");
		} else {
			_add_to_list(EditorFileSystem::get_singleton()->get_filesystem(),exported);
			_add_filter_to_list(exported,EditorImportExport::get_singleton()->get_export_custom_filter());

		}


	} else {


		Map<String,Map<String,String> > remapped_paths;

		Set<String> scene_extensions;
		Set<String> resource_extensions;

		{

			List<String> l;
	//		SceneLoader::get_recognized_extensions(&l);
	//		for(List<String>::Element *E=l.front();E;E=E->next()) {
	//
	//			scene_extensions.insert(E->get());
	//		}
			ResourceLoader::get_recognized_extensions_for_type("",&l);
			for(List<String>::Element *E=l.front();E;E=E->next()) {

				resource_extensions.insert(E->get());
			}
		}


		List<StringName> toexport;

		EditorImportExport::get_singleton()->get_export_file_list(&toexport);

		print_line("TO EXPORT: "+itos(toexport.size()));


		for (List<StringName>::Element *E=toexport.front();E;E=E->next()) {

			print_line("DEP: "+String(E->get()));
			exported.insert(E->get());
			if (p_bundles && EditorImportExport::get_singleton()->get_export_file_action(E->get())==EditorImportExport::ACTION_BUNDLE) {
				print_line("NO BECAUSE OF BUNDLE!");
				continue; //no dependencies needed to be copied
			}

			List<String> testsubs;
			testsubs.push_back(E->get());

			while(testsubs.size()) {
				//recursive subdep search!
				List<String> deplist;
				ResourceLoader::get_dependencies(testsubs.front()->get(),&deplist);
				testsubs.pop_front();

				List<String> subdeps;

				for (List<String>::Element *F=deplist.front();F;F=F->next()) {

					StringName dep = F->get();

					if (exported.has(dep) || EditorImportExport::get_singleton()->get_export_file_action(dep)!=EditorImportExport::ACTION_NONE)
						continue; //dependency added or to be added
					print_line(" SUBDEP: "+String(dep));

					exported.insert(dep);
					testsubs.push_back(dep);
				}
			}
		}

		_add_filter_to_list(exported,EditorImportExport::get_singleton()->get_export_custom_filter());

	}

	Vector<StringName> ret;
	ret.resize(exported.size());


	int idx=0;
	for(Set<StringName>::Element *E=exported.front();E;E=E->next()) {

		ret[idx++]=E->get();

	}

	SortArray<StringName,__EESortDepCmp> sort; //some platforms work better if this is sorted
	sort.sort(ret.ptr(),ret.size());

	return ret;

}
static int
pass_ForeachNode(void *self, Pass pass, int level, void *par)
{
   VAR(ForNode, np, self);
   switch (pass)
   {
   case Print:
      fprintfOffs(stdout, level, "ForeachNode : keys=%d\n", np->keys);
      break;
   case PrintSrc:
      {
	 yyerror("%s not allowed in CODESTR", np->node.name);
      }
      return 0;
   case CalcDeep:
      break;
   case CText:
      {
	 VAR(FILE, out, par);
	 int no = np->labelNo;

	 int saveNo = loopNo;

	 print_line(self, level, out);

	 np->init->pass(np->init, pass, level, par);
	 fprintfOffs(out, level, "if ((_ret=_clip_map_first( _mp, %d, &_if ))) goto _trap_%d;\n", np->keys, np->node.seqNo);
	 fprintfOffs(out, level, "if ( !_if ) goto _endloop_%d;\n", no);
	 fprintfOffs(out, level, "goto _lbeg_%d;\n", no);

	 fprintfOffs(out, level, "_loop_%d:\n", no);

	 np->init->pass(np->init, pass, level, par);
	 fprintfOffs(out, level, "if ((_ret=_clip_map_next( _mp, %d, &_if ))) goto _trap_%d;\n", np->keys, np->node.seqNo);
	 fprintfOffs(out, level, "if ( !_if ) goto _endloop_%d;\n", no);

	 fprintfOffs(out, level, "_lbeg_%d:\n", no);

	 fprintfOffs(out, level, "if ((_ret=_clip_assign( _mp, ");
	 np->var->pass(np->var, CTextLval, level, par);
	 fprintf(out, " ))) goto _trap_%d;\n", np->node.seqNo);

	 loopNo = no;
	 np->list->pass(np->list, pass, level, par);

	 fprintfOffs(out, level, "goto _loop_%d;\n", no);
	 fprintfOffs(out, level, "_endloop_%d:\n", no);
	 loopNo = saveNo;
      }
      return 0;
   case OText:
      {
	 VAR(StrBuf, out, par);
	 int jmp, eoffs, ibeg, lbeg, boffs;

	 LoopData ld;

	 put_line(self, level, out);
	 np->init->pass(np->init, pass, level, par);
	 putByte_StrBuf(out, CLIP_MAP_FIRST);
	 putByte_StrBuf(out, np->keys);
	 ibeg = out->ptr_of_StrBuf - out->buf_of_StrBuf;
	 putShort_StrBuf(out, 0);

	 putByte_StrBuf(out, CLIP_GOTO);
	 lbeg = out->ptr_of_StrBuf - out->buf_of_StrBuf;
	 putShort_StrBuf(out, 0);

	 boffs = out->ptr_of_StrBuf - out->buf_of_StrBuf;
	 put_line(self, level, out);
	 np->init->pass(np->init, pass, level, par);
	 putByte_StrBuf(out, CLIP_MAP_NEXT);
	 putByte_StrBuf(out, np->keys);
	 jmp = out->ptr_of_StrBuf - out->buf_of_StrBuf;
	 putShort_StrBuf(out, 0);

	 SETSHORT(out, lbeg, (out->ptr_of_StrBuf - out->buf_of_StrBuf) - (lbeg + sizeof(short)));

	 np->var->pass(np->var, OTextLval, level, par);
	 putByte_StrBuf(out, CLIP_ASSIGN);
	 np->list->pass(np->list, pass, level, par);

	 putByte_StrBuf(out, CLIP_GOTO);
	 eoffs = (out->ptr_of_StrBuf - out->buf_of_StrBuf) + sizeof(short);
	 putShort_StrBuf(out, boffs - eoffs);

	 SETSHORT(out, jmp, eoffs - (jmp + sizeof(short)));
	 SETSHORT(out, ibeg, eoffs - (ibeg + sizeof(short)));

	 ld.StrBuf_out_of_LoopData = out;
	 ld.boffs_of_LoopData = boffs;
	 ld.eoffs_of_LoopData = eoffs;
	 np->list->pass(np->list, OTextLoop, level, &ld);
      }
      return 0;
   case Traverse:
      {
	 VAR(TraversePar, tp, par);
	 tp->func((Node *) self, tp->par);
      }
      break;
   default:
      break;
   }

   np->var->pass(np->var, pass, level, par);
   np->init->pass(np->init, pass, level, par);
   np->list->pass(np->list, pass, level, par);

   return 0;
}
RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p_no_cache, Error *r_error) {

	if (r_error)
		*r_error=ERR_CANT_OPEN;

	String local_path;
	if (p_path.is_rel_path())
		local_path="res://"+p_path;
	else
		local_path = GlobalConfig::get_singleton()->localize_path(p_path);

	local_path=find_complete_path(local_path,p_type_hint);
	ERR_FAIL_COND_V(local_path=="",RES());

	if (!p_no_cache && ResourceCache::has(local_path)) {

		if (OS::get_singleton()->is_stdout_verbose())
			print_line("load resource: "+local_path+" (cached)");

		return RES( ResourceCache::get(local_path ) );
	}

	String remapped_path = PathRemap::get_singleton()->get_remap(local_path);

	if (OS::get_singleton()->is_stdout_verbose())
		print_line("load resource: "+remapped_path);

	String extension=remapped_path.extension();
	bool found=false;

	for (int i=0;i<loader_count;i++) {

		if (!loader[i]->recognize(extension))
			continue;
		if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
			continue;
		found=true;
		RES res = loader[i]->load(remapped_path,local_path,r_error);
		if (res.is_null())
			continue;
		if (!p_no_cache)
			res->set_path(local_path);
#ifdef TOOLS_ENABLED

		res->set_edited(false);
		if (timestamp_on_load) {
			uint64_t mt = FileAccess::get_modified_time(remapped_path);
			//printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
			res->set_last_modified_time(mt);
		}
#endif

		return res;
	}

	if (found) {
		ERR_EXPLAIN("Failed loading resource: "+p_path);
	} else {
		ERR_EXPLAIN("No loader found for resource: "+p_path);
	}
	ERR_FAIL_V(RES());
	return RES();
}
Exemple #16
0
int main(int argc, char **argv)
{
	int i;
	int in_offset=0;
	char *in_fill=NULL;
	FILE *pfile;
	char ltrs[] = "urls";
	int synt = 5;
	pfile = stdin;
	for(i=1;i<argc;i++)
	{
		if(argv[i][0]=='-')
		{
			if(argv[i][1]=='p')
				pfile = fopen(argv[++i],"r");
			else if(argv[i][1]=='i' && argv[i][2]=='o')
				sscanf(argv[++i], "%i", &in_offset);
			else if(argv[i][1]=='i' && argv[i][2]==0)
				in_fill=argv[++i];
			else if(argv[i][1]=='d')
				debug = 1;
			else if(argv[i][1]=='s')
			{
				if(argv[i][2]=='4' || argv[i][2]=='5')
					synt = argv[i][2]-'0';
				else
				{
					printf("Wrong syntax type!\n");
					return 0;
				};
			}
			else if(argv[i][1]=='h')
			{
				printf(USAGE_MSG);
				return 0;
			}
		}
	}
	if(in_fill)
	{
		data.pos = in_offset;
		while(*in_fill)
		{
			data_write(*in_fill);
			in_fill++;
			data.pos++;
		}
	}
	if(!pfile)
	{
		printf("Cant open program file.\n");
		return 0;
	}
	if(synt==5)
		feed_program(pfile);
	else	feed_program4(pfile);
	run();
	print_line();
	if(debug)
		for(i=0;i<prog_len;i++)
			printf("%2u,%c,%c,%c,%2u\n",	cmd_qF(prog[i]),
							cmd_cF(prog[i]),
							cmd_cT(prog[i]),
							ltrs[cmd_act(prog[i])>>16],
							cmd_qT(prog[i])
							);
	return 0;
}
Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path,const String& p_type_hint,bool p_no_cache,Error *r_error) {


	if (r_error)
		*r_error=ERR_CANT_OPEN;

	String local_path;
	if (p_path.is_rel_path())
		local_path="res://"+p_path;
	else
		local_path = GlobalConfig::get_singleton()->localize_path(p_path);

	local_path=find_complete_path(local_path,p_type_hint);
	ERR_FAIL_COND_V(local_path=="",Ref<ResourceInteractiveLoader>());



	if (!p_no_cache && ResourceCache::has(local_path)) {

		if (OS::get_singleton()->is_stdout_verbose())
			print_line("load resource: "+local_path+" (cached)");

		Ref<Resource> res_cached = ResourceCache::get(local_path);
		Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));

		ril->resource = res_cached;
		return ril;
	}

	if (OS::get_singleton()->is_stdout_verbose())
		print_line("load resource: ");

	String remapped_path = PathRemap::get_singleton()->get_remap(local_path);

	String extension=remapped_path.extension();
	bool found=false;

	for (int i=0;i<loader_count;i++) {

		if (!loader[i]->recognize(extension))
			continue;
		if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
			continue;
		found=true;
		Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(remapped_path,r_error);
		if (ril.is_null())
			continue;
		if (!p_no_cache)
			ril->set_local_path(local_path);

		return ril;
	}

	if (found) {
		ERR_EXPLAIN("Failed loading resource: "+p_path);
	} else {
		ERR_EXPLAIN("No loader found for resource: "+p_path);
	}
	ERR_FAIL_V(Ref<ResourceInteractiveLoader>());
	return Ref<ResourceInteractiveLoader>();

}
Exemple #18
0
void ScenesDock::_move_operation(const String& p_to_path) {

	if (p_to_path==path) {
		EditorNode::get_singleton()->show_warning("Same source and destination paths, doing nothing.");
		return;
	}

	//find files inside dirs to be moved

	Vector<String> inside_files;

	for(int i=0;i<move_dirs.size();i++) {
		if (p_to_path.begins_with(move_dirs[i])) {
			EditorNode::get_singleton()->show_warning("Can't move directories to within themselves");
			return;
		}

		EditorFileSystemDirectory *efsd=EditorFileSystem::get_singleton()->get_path(move_dirs[i]);
		if (!efsd)
			continue;
		_find_inside_move_files(efsd,inside_files);
	}

	//make list of remaps
	Map<String,String> renames;
	String repfrom=path=="res://"?path:String(path+"/");
	String repto=p_to_path=="res://"?p_to_path:String(p_to_path+"/");

	for(int i=0;i<move_files.size();i++) {
		renames[move_files[i]]=move_files[i].replace_first(repfrom,repto);
		print_line("move file "+move_files[i]+" -> "+renames[move_files[i]]);
	}
	for(int i=0;i<inside_files.size();i++) {
		renames[inside_files[i]]=inside_files[i].replace_first(repfrom,repto);
		print_line("inside file "+inside_files[i]+" -> "+renames[inside_files[i]]);
	}

	//make list of files that will be run the remapping
	List<String> remap;

	_find_remaps(EditorFileSystem::get_singleton()->get_filesystem(),renames,remap);
	print_line("found files to remap: "+itos(remap.size()));

	//perform remaps
	for(List<String>::Element *E=remap.front();E;E=E->next()) {

		Error err = ResourceLoader::rename_dependencies(E->get(),renames);
		print_line("remapping: "+E->get());

		if (err!=OK) {
			EditorNode::get_singleton()->add_io_error("Can't rename deps for:\n"+E->get()+"\n");
		}
	}

	//finally, perform moves

	DirAccess *da=DirAccess::create(DirAccess::ACCESS_RESOURCES);

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

		String to = move_files[i].replace_first(repfrom,repto);
		Error err = da->rename(move_files[i],to);
		print_line("moving file "+move_files[i]+" to "+to);
		if (err!=OK) {
			EditorNode::get_singleton()->add_io_error("Error moving file:\n"+move_files[i]+"\n");
		}
	}

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

		String to = p_to_path.plus_file(move_dirs[i].get_file());
		Error err = da->rename(move_dirs[i],to);
		print_line("moving dir "+move_dirs[i]+" to "+to);
		if (err!=OK) {
			EditorNode::get_singleton()->add_io_error("Error moving dir:\n"+move_dirs[i]+"\n");
		}
	}

	memdelete(da);
	//rescan everything
	print_line("call rescan!");
	_rescan();

}
Exemple #19
0
	virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {

		//print_line("attempt to call "+String(p_method));
		ERR_FAIL_COND_V(!instance,Variant());

		r_error.error=Variant::CallError::CALL_OK;

		Map<StringName,MethodData >::Element *E=method_map.find(p_method);
		if (!E) {

			print_line("no exists");
			r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
			return Variant();
		}



		int ac = E->get().argtypes.size();
		if (ac<p_argcount) {

			print_line("fewargs");
			r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
			r_error.argument=ac;
			return Variant();
		}

		if (ac>p_argcount) {

			print_line("manyargs");
			r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
			r_error.argument=ac;
			return Variant();
		}


		for(int i=0;i<p_argcount;i++) {

			if (!Variant::can_convert(p_args[i]->get_type(),E->get().argtypes[i])) {

				r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument=i;
				r_error.expected=E->get().argtypes[i];
			}
		}


		jvalue *v=NULL;

		if (p_argcount) {

			v=(jvalue*)alloca( sizeof(jvalue)*p_argcount );
		}

		JNIEnv *env = ThreadAndroid::get_env();

		int res = env->PushLocalFrame(16);

		ERR_FAIL_COND_V(res!=0,Variant());

		//print_line("argcount "+String::num(p_argcount));
		List<jobject> to_erase;
		for(int i=0;i<p_argcount;i++) {

			jvalret vr = _variant_to_jvalue(env, E->get().argtypes[i], p_args[i]);
			v[i] = vr.val;
			if (vr.obj)
				to_erase.push_back(vr.obj);
		}

		//print_line("calling method!!");

		Variant ret;

		switch(E->get().ret_type) {

			case Variant::NIL: {


				//print_line("call void");
				env->CallVoidMethodA(instance,E->get().method,v);
			} break;
			case Variant::BOOL: {

				ret = env->CallBooleanMethodA(instance,E->get().method,v);
				//print_line("call bool");
			} break;
			case Variant::INT: {

				ret = env->CallIntMethodA(instance,E->get().method,v);
				//print_line("call int");
			} break;
			case Variant::REAL: {

				ret = env->CallFloatMethodA(instance,E->get().method,v);
			} break;
			case Variant::STRING: {

				jobject o = env->CallObjectMethodA(instance,E->get().method,v);
				String str = env->GetStringUTFChars((jstring)o, NULL );
				ret=str;
				env->DeleteLocalRef(o);
			} break;
			case Variant::STRING_ARRAY: {

				jobjectArray arr = (jobjectArray)env->CallObjectMethodA(instance,E->get().method,v);

				ret = _jobject_to_variant(env, arr);

				env->DeleteLocalRef(arr);
			} break;
			case Variant::INT_ARRAY: {

				jintArray arr = (jintArray)env->CallObjectMethodA(instance,E->get().method,v);

				int fCount = env->GetArrayLength(arr);
				DVector<int> sarr;
				sarr.resize(fCount);

				DVector<int>::Write w = sarr.write();
				env->GetIntArrayRegion(arr,0,fCount,w.ptr());
				w = DVector<int>::Write();
				ret=sarr;
				env->DeleteLocalRef(arr);
			} break;
			case Variant::REAL_ARRAY: {

				jfloatArray arr = (jfloatArray)env->CallObjectMethodA(instance,E->get().method,v);

				int fCount = env->GetArrayLength(arr);
				DVector<float> sarr;
				sarr.resize(fCount);

				DVector<float>::Write w = sarr.write();
				env->GetFloatArrayRegion(arr,0,fCount,w.ptr());
				w = DVector<float>::Write();
				ret=sarr;
				env->DeleteLocalRef(arr);
			} break;

			case Variant::DICTIONARY: {

				//print_line("call dictionary");
				jobject obj = env->CallObjectMethodA(instance, E->get().method, v);
				ret = _jobject_to_variant(env, obj);
				env->DeleteLocalRef(obj);

			} break;
			default: {


				print_line("failure..");
				env->PopLocalFrame(NULL);
				ERR_FAIL_V(Variant());
			} break;
		}

		while (to_erase.size()) {
			env->DeleteLocalRef(to_erase.front()->get());
			to_erase.pop_front();
		}

		env->PopLocalFrame(NULL);
		//print_line("success");

		return ret;
	}
Exemple #20
0
void Navigation::_navmesh_link(int p_id) {

	ERR_FAIL_COND(!navmesh_map.has(p_id));
	NavMesh &nm=navmesh_map[p_id];
	ERR_FAIL_COND(nm.linked);

	print_line("LINK");

	DVector<Vector3> vertices=nm.navmesh->get_vertices();
	int len = vertices.size();
	if (len==0)
		return;

	DVector<Vector3>::Read r=vertices.read();

	for(int i=0;i<nm.navmesh->get_polygon_count();i++) {

		//build

		List<Polygon>::Element *P=nm.polygons.push_back(Polygon());
		Polygon &p=P->get();

		Vector<int> poly = nm.navmesh->get_polygon(i);
		int plen=poly.size();
		const int *indices=poly.ptr();
		bool valid=true;
		p.edges.resize(plen);

		Vector3 center;

		for(int j=0;j<plen;j++) {

			int idx = indices[j];
			if (idx<0 || idx>=len) {
				valid=false;
				break;
			}

			Polygon::Edge e;
			Vector3 ep=nm.xform.xform(r[idx]);
			center+=ep;
			e.point=_get_point(ep);
			p.edges[j]=e;
		}

		if (!valid) {
			nm.polygons.pop_back();
			ERR_CONTINUE(!valid);
			continue;
		}

		p.center=center/plen;

		//connect

		for(int j=0;j<plen;j++) {

			int next = (j+1)%plen;
			EdgeKey ek(p.edges[j].point,p.edges[next].point);

			Map<EdgeKey,Connection>::Element *C=connections.find(ek);
			if (!C) {

				Connection c;
				c.A=&p;
				c.A_edge=j;
				c.B=NULL;
				c.B_edge=-1;
				connections[ek]=c;
			} else {

				if (C->get().B!=NULL) {
					print_line(String()+_get_vertex(ek.a)+" -> "+_get_vertex(ek.b));
				}
				ERR_CONTINUE(C->get().B!=NULL); //wut

				C->get().B=&p;
				C->get().B_edge=j;
				C->get().A->edges[C->get().A_edge].C=&p;
				C->get().A->edges[C->get().A_edge].C_edge=j;;
				p.edges[j].C=C->get().A;
				p.edges[j].C_edge=C->get().A_edge;
				//connection successful.
			}
		}
	}

	nm.linked=true;

}
Exemple #21
0
/*
 * Display text from a file in a dialog box.
 */
int
dialog_textbox(const char *title, const char *file, int height, int width)
{
    /* *INDENT-OFF* */
    static DLG_KEYS_BINDING binding[] = {
	HELPKEY_BINDINGS,
	ENTERKEY_BINDINGS,
	DLG_KEYS_DATA( DLGK_GRID_DOWN,  'J' ),
	DLG_KEYS_DATA( DLGK_GRID_DOWN,  'j' ),
	DLG_KEYS_DATA( DLGK_GRID_DOWN,  KEY_DOWN ),
	DLG_KEYS_DATA( DLGK_GRID_LEFT,  'H' ),
	DLG_KEYS_DATA( DLGK_GRID_LEFT,  'h' ),
	DLG_KEYS_DATA( DLGK_GRID_LEFT,  KEY_LEFT ),
	DLG_KEYS_DATA( DLGK_GRID_RIGHT, 'L' ),
	DLG_KEYS_DATA( DLGK_GRID_RIGHT, 'l' ),
	DLG_KEYS_DATA( DLGK_GRID_RIGHT, KEY_RIGHT ),
	DLG_KEYS_DATA( DLGK_GRID_UP,    'K' ),
	DLG_KEYS_DATA( DLGK_GRID_UP,    'k' ),
	DLG_KEYS_DATA( DLGK_GRID_UP,    KEY_UP ),
	DLG_KEYS_DATA( DLGK_PAGE_FIRST, 'g' ),
	DLG_KEYS_DATA( DLGK_PAGE_FIRST, KEY_HOME ),
	DLG_KEYS_DATA( DLGK_PAGE_LAST,  'G' ),
	DLG_KEYS_DATA( DLGK_PAGE_LAST,  KEY_END ),
	DLG_KEYS_DATA( DLGK_PAGE_LAST,  KEY_LL ),
	DLG_KEYS_DATA( DLGK_PAGE_NEXT,  ' ' ),
	DLG_KEYS_DATA( DLGK_PAGE_NEXT,  KEY_NPAGE ),
	DLG_KEYS_DATA( DLGK_PAGE_PREV,  'B' ),
	DLG_KEYS_DATA( DLGK_PAGE_PREV,  'b' ),
	DLG_KEYS_DATA( DLGK_PAGE_PREV,  KEY_PPAGE ),
	DLG_KEYS_DATA( DLGK_BEGIN,	'0' ),
	DLG_KEYS_DATA( DLGK_BEGIN,	KEY_BEG ),
	DLG_KEYS_DATA( DLGK_FIELD_NEXT, TAB ),
	DLG_KEYS_DATA( DLGK_FIELD_PREV, KEY_BTAB ),
	END_KEYS_BINDING
    };
    /* *INDENT-ON* */

#ifdef KEY_RESIZE
    int old_height = height;
    int old_width = width;
#endif
    long fpos;
    int x, y, cur_x, cur_y;
    int key = 0, fkey;
    int next = 0;
    int i, code, passed_end;
    char search_term[MAX_LEN + 1];
    MY_OBJ obj;
    WINDOW *dialog;
    bool moved;
    int result = DLG_EXIT_UNKNOWN;
    int button = dialog_vars.extra_button ? dlg_defaultno_button() : 0;
    int min_width = 12;

    search_term[0] = '\0';	/* no search term entered yet */

    memset(&obj, 0, sizeof(obj));

    obj.begin_reached = TRUE;
    obj.buffer_first = TRUE;
    obj.end_reached = FALSE;
    obj.buttons = dlg_exit_label();

    /* Open input file for reading */
    if ((obj.fd = open(file, O_RDONLY)) == -1)
        dlg_exiterr("Can't open input file %s", file);

    /* Get file size. Actually, 'file_size' is the real file size - 1,
       since it's only the last byte offset from the beginning */
    obj.file_size = lseek_obj(&obj, 0L, SEEK_END);

    /* Restore file pointer to beginning of file after getting file size */
    lseek_obj(&obj, 0L, SEEK_SET);

    read_high(&obj, BUF_SIZE);

    dlg_button_layout(obj.buttons, &min_width);

#ifdef KEY_RESIZE
retry:
#endif
    moved = TRUE;

    dlg_auto_sizefile(title, file, &height, &width, 2, min_width);
    dlg_print_size(height, width);
    dlg_ctl_size(height, width);

    x = dlg_box_x_ordinate(width);
    y = dlg_box_y_ordinate(height);

    dialog = dlg_new_window(height, width, y, x);
    dlg_register_window(dialog, "textbox", binding);
    dlg_register_buttons(dialog, "textbox", obj.buttons);

    dlg_mouse_setbase(x, y);

    /* Create window for text region, used for scrolling text */
    obj.text = dlg_sub_window(dialog, PAGE_LENGTH, PAGE_WIDTH, y + 1, x + 1);

    /* register the new window, along with its borders */
    dlg_mouse_mkbigregion(0, 0, PAGE_LENGTH + 2, width, KEY_MAX, 1, 1, 1 /* lines */ );
    dlg_draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
    dlg_draw_bottom_box(dialog);
    dlg_draw_title(dialog, title);

    dlg_draw_buttons(dialog, PAGE_LENGTH + 2, 0, obj.buttons, button, FALSE, width);
    (void) wnoutrefresh(dialog);
    getyx(dialog, cur_y, cur_x);	/* Save cursor position */

    dlg_attr_clear(obj.text, PAGE_LENGTH, PAGE_WIDTH, dialog_attr);

    while (result == DLG_EXIT_UNKNOWN) {

        /*
         * Update the screen according to whether we shifted up/down by a line
         * or not.
         */
        if (moved) {
            if (next < 0) {
                (void) scrollok(obj.text, TRUE);
                (void) scroll(obj.text);	/* Scroll text region up one line */
                (void) scrollok(obj.text, FALSE);
                print_line(&obj, PAGE_LENGTH - 1, PAGE_WIDTH);
                (void) wnoutrefresh(obj.text);
            } else if (next > 0) {
                /*
                 * We don't call print_page() here but use scrolling to ensure
                 * faster screen update.  However, 'end_reached' and
                 * 'page_length' should still be updated, and 'in_buf' should
                 * point to start of next page.  This is done by calling
                 * get_line() in the following 'for' loop.
                 */
                (void) scrollok(obj.text, TRUE);
                (void) wscrl(obj.text, -1);	/* Scroll text region down one line */
                (void) scrollok(obj.text, FALSE);
                obj.page_length = 0;
                passed_end = 0;
                for (i = 0; i < PAGE_LENGTH; i++) {
                    if (!i) {
                        print_line(&obj, 0, PAGE_WIDTH);	/* print first line of page */
                        (void) wnoutrefresh(obj.text);
                    } else
                        (void) get_line(&obj);	/* Called to update 'end_reached' and 'in_buf' */
                    if (!passed_end)
                        obj.page_length++;
                    if (obj.end_reached && !passed_end)
                        passed_end = 1;
                }
            } else {
                print_page(&obj, PAGE_LENGTH, PAGE_WIDTH);
            }
            print_position(&obj, dialog, height, width);
            (void) wmove(dialog, cur_y, cur_x);		/* Restore cursor position */
            wrefresh(dialog);
        }
        moved = FALSE;		/* assume we'll not move */
        next = 0;		/* ...but not scroll by a line */

        key = dlg_mouse_wgetch(dialog, &fkey);
        if (dlg_result_key(key, fkey, &result))
            break;

        if (!fkey && (code = dlg_char_to_button(key, obj.buttons)) >= 0) {
            result = dlg_ok_buttoncode(code);
            break;
        }

        if (fkey) {
            switch (key) {
            default:
                if (is_DLGK_MOUSE(key)) {
                    result = dlg_exit_buttoncode(key - M_EVENT);
                    if (result < 0)
                        result = DLG_EXIT_OK;
                } else {
                    beep();
                }
                break;
            case DLGK_FIELD_NEXT:
                button = dlg_next_button(obj.buttons, button);
                if (button < 0)
                    button = 0;
                dlg_draw_buttons(dialog,
                                 height - 2, 0,
                                 obj.buttons, button,
                                 FALSE, width);
                break;
            case DLGK_FIELD_PREV:
                button = dlg_prev_button(obj.buttons, button);
                if (button < 0)
                    button = 0;
                dlg_draw_buttons(dialog,
                                 height - 2, 0,
                                 obj.buttons, button,
                                 FALSE, width);
                break;
            case DLGK_ENTER:
                if (dialog_vars.nook)
                    result = DLG_EXIT_OK;
                else
                    result = dlg_exit_buttoncode(button);
                break;
            case DLGK_PAGE_FIRST:
                if (!obj.begin_reached) {
                    obj.begin_reached = 1;
                    /* First page not in buffer? */
                    fpos = ftell_obj(&obj);

                    if (fpos > obj.fd_bytes_read) {
                        /* Yes, we have to read it in */
                        lseek_obj(&obj, 0L, SEEK_SET);

                        read_high(&obj, BUF_SIZE);
                    }
                    obj.in_buf = 0;
                    moved = TRUE;
                }
                break;
            case DLGK_PAGE_LAST:
                obj.end_reached = TRUE;
                /* Last page not in buffer? */
                fpos = ftell_obj(&obj);

                if (fpos < obj.file_size) {
                    /* Yes, we have to read it in */
                    lseek_obj(&obj, -BUF_SIZE, SEEK_END);

                    read_high(&obj, BUF_SIZE);
                }
                obj.in_buf = obj.bytes_read;
                back_lines(&obj, (long) PAGE_LENGTH);
                moved = TRUE;
                break;
            case DLGK_GRID_UP:	/* Previous line */
                if (!obj.begin_reached) {
                    back_lines(&obj, obj.page_length + 1);
                    next = 1;
                    moved = TRUE;
                }
                break;
            case DLGK_PAGE_PREV:	/* Previous page */
            case DLGK_MOUSE(KEY_PPAGE):
                if (!obj.begin_reached) {
                    back_lines(&obj, obj.page_length + PAGE_LENGTH);
                    moved = TRUE;
                }
                break;
            case DLGK_GRID_DOWN:	/* Next line */
                if (!obj.end_reached) {
                    obj.begin_reached = 0;
                    next = -1;
                    moved = TRUE;
                }
                break;
            case DLGK_PAGE_NEXT:	/* Next page */
            case DLGK_MOUSE(KEY_NPAGE):
                if (!obj.end_reached) {
                    obj.begin_reached = 0;
                    moved = TRUE;
                }
                break;
            case DLGK_BEGIN:	/* Beginning of line */
                if (obj.hscroll > 0) {
                    obj.hscroll = 0;
                    /* Reprint current page to scroll horizontally */
                    back_lines(&obj, obj.page_length);
                    moved = TRUE;
                }
                break;
            case DLGK_GRID_LEFT:	/* Scroll left */
                if (obj.hscroll > 0) {
                    obj.hscroll--;
                    /* Reprint current page to scroll horizontally */
                    back_lines(&obj, obj.page_length);
                    moved = TRUE;
                }
                break;
            case DLGK_GRID_RIGHT:	/* Scroll right */
                if (obj.hscroll < MAX_LEN) {
                    obj.hscroll++;
                    /* Reprint current page to scroll horizontally */
                    back_lines(&obj, obj.page_length);
                    moved = TRUE;
                }
                break;
#ifdef KEY_RESIZE
            case KEY_RESIZE:
                /* reset data */
                height = old_height;
                width = old_width;
                back_lines(&obj, obj.page_length);
                moved = TRUE;
                /* repaint */
                dlg_clear();
                dlg_del_window(dialog);
                refresh();
                dlg_mouse_free_regions();
                goto retry;
#endif
            }
        } else {
            switch (key) {
            case '/':		/* Forward search */
            case 'n':		/* Repeat forward search */
            case '?':		/* Backward search */
            case 'N':		/* Repeat backward search */
                moved = perform_search(&obj, height, width, key, search_term);
                fkey = FALSE;
                break;
            default:
                beep();
                break;
            }
        }
    }

    dlg_del_window(dialog);
    free(obj.buf);
    (void) close(obj.fd);
    dlg_mouse_free_regions();
    return result;
}
void EditorAssetLibraryItemDownload::_http_download_completed(int p_status, int p_code, const StringArray& headers, const ByteArray& p_data) {


	String error_text;
	print_line("COMPLETED: "+itos(p_status)+" code: "+itos(p_code)+" data size: "+itos(p_data.size()));

	switch(p_status) {

		case HTTPRequest::RESULT_CANT_RESOLVE: {
			error_text=("Can't resolve hostname: "+host);
			status->set_text("Can't resolve.");
		} break;
		case HTTPRequest::RESULT_BODY_SIZE_LIMIT_EXCEEDED:
		case HTTPRequest::RESULT_CONNECTION_ERROR:
		case HTTPRequest::RESULT_CHUNKED_BODY_SIZE_MISMATCH: {
			error_text=("Connection error, please try again.");
			status->set_text("Can't connect.");
		} break;
		case HTTPRequest::RESULT_SSL_HANDSHAKE_ERROR:
		case HTTPRequest::RESULT_CANT_CONNECT: {
			error_text=("Can't connect to host: "+host);
			status->set_text("Can't connect.");
		} break;
		case HTTPRequest::RESULT_NO_RESPONSE: {
			error_text=("No response from host: "+host);
			status->set_text("No response.");
		} break;
		case HTTPRequest::RESULT_REQUEST_FAILED: {
			error_text=("Request failed, return code: "+itos(p_code));
			status->set_text("Req. Failed.");
		} break;
		case HTTPRequest::RESULT_REDIRECT_LIMIT_REACHED: {
			error_text=("Request failed, too many redirects");
			status->set_text("Redirect Loop.");
		} break;
		default: {
			if (p_code!=200) {
				error_text=("Request failed, return code: "+itos(p_code));
				status->set_text("Failed: "+itos(p_code));
			} else if(sha256 != "") {
				String download_sha256 = FileAccess::get_sha256(download->get_download_file());
				if(sha256 != download_sha256) {
					error_text="Bad download hash, assuming file has been tampered with.\nExpected: " + sha256 + "\nGot: " + download_sha256;
					status->set_text("Failed sha256 hash check");
				}
			}
		} break;

	}

	if (error_text!=String()) {
		download_error->set_text("Asset Download Error:\n"+error_text);
		download_error->popup_centered_minsize();
		return;

	}

	progress->set_max( download->get_body_size() );
	progress->set_val(download->get_downloaded_bytes());

	print_line("max: "+itos(download->get_body_size())+" bytes: "+itos(download->get_downloaded_bytes()));
	install->set_disabled(false);

	progress->set_val(download->get_downloaded_bytes());

	status->set_text("Success! ("+String::humanize_size(download->get_downloaded_bytes())+")");
	set_process(false);
}
Exemple #23
0
int main(int argc, char *argv[])
{
	int o;
	unsigned short old_rows;
	struct slab_info *slab_list = NULL;
	int run_once = 0, retval = EXIT_SUCCESS;

	static const struct option longopts[] = {
		{ "delay",	required_argument, NULL, 'd' },
		{ "sort",	required_argument, NULL, 's' },
		{ "once",	no_argument,	   NULL, 'o' },
		{ "help",	no_argument,	   NULL, 'h' },
		{ "version",	no_argument,	   NULL, 'V' },
		{  NULL, 0, NULL, 0 }
	};

#ifdef HAVE_PROGRAM_INVOCATION_NAME
	program_invocation_name = program_invocation_short_name;
#endif
	setlocale (LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	sort_func = DEF_SORT_FUNC;

	while ((o = getopt_long(argc, argv, "d:s:ohV", longopts, NULL)) != -1) {
		switch (o) {
		case 'd':
			errno = 0;
			delay = strtol_or_err(optarg, _("illegal delay"));
			if (delay < 1)
				xerrx(EXIT_FAILURE,
					_("delay must be positive integer"));
			break;
		case 's':
			sort_func = (int (*)(const struct slab_info*,
				const struct slab_info *)) set_sort_func(optarg[0]);
			break;
		case 'o':
			run_once=1;
			delay = 0;
			break;
		case 'V':
			printf(PROCPS_NG_VERSION);
			return EXIT_SUCCESS;
		case 'h':
			usage(stdout);
		default:
			usage(stderr);
		}
	}

	if (tcgetattr(STDIN_FILENO, &saved_tty) == -1)
		xwarn(_("terminal setting retrieval"));

	old_rows = rows;
	term_size(0);
	if (!run_once) {
		initscr();
		resizeterm(rows, cols);
		signal(SIGWINCH, term_size);
	}
	signal(SIGINT, sigint_handler);

	do {
		struct slab_info *curr;
		struct slab_stat stats;
		struct timeval tv;
		fd_set readfds;
		char c;
		int i;
		memset(&stats, 0, sizeof(struct slab_stat));

		if (get_slabinfo(&slab_list, &stats)) {
			retval = EXIT_FAILURE;
			break;
		}

		if (!run_once && old_rows != rows) {
			resizeterm(rows, cols);
			old_rows = rows;
		}

		move(0, 0);
		print_line(" %-35s: %d / %d (%.1f%%)\n"
		       " %-35s: %d / %d (%.1f%%)\n"
		       " %-35s: %d / %d (%.1f%%)\n"
		       " %-35s: %.2fK / %.2fK (%.1f%%)\n"
		       " %-35s: %.2fK / %.2fK / %.2fK\n\n",
		       /* Translation Hint: Next five strings must not
			* exceed 35 length in characters.  */
		       /* xgettext:no-c-format */
		       _("Active / Total Objects (% used)"),
		       stats.nr_active_objs, stats.nr_objs,
		       100.0 * stats.nr_active_objs / stats.nr_objs,
	               /* xgettext:no-c-format */
		       _("Active / Total Slabs (% used)"),
		       stats.nr_active_slabs, stats.nr_slabs,
		       100.0 * stats.nr_active_slabs / stats.nr_slabs,
	               /* xgettext:no-c-format */
		       _("Active / Total Caches (% used)"),
		       stats.nr_active_caches, stats.nr_caches,
		       100.0 * stats.nr_active_caches / stats.nr_caches,
	               /* xgettext:no-c-format */
		       _("Active / Total Size (% used)"),
		       stats.active_size / 1024.0, stats.total_size / 1024.0,
		       100.0 * stats.active_size / stats.total_size,
		       _("Minimum / Average / Maximum Object"),
		       stats.min_obj_size / 1024.0, stats.avg_obj_size / 1024.0,
		       stats.max_obj_size / 1024.0);

		slab_list = slabsort(slab_list);

		attron(A_REVERSE);
		/* Translation Hint: Please keep alignment of the
		 * following intact. */
		print_line("%-78s\n", _("  OBJS ACTIVE  USE OBJ SIZE  SLABS OBJ/SLAB CACHE SIZE NAME"));
		attroff(A_REVERSE);

		curr = slab_list;
		for (i = 0; i < rows - 8 && curr->next; i++) {
			print_line("%6u %6u %3u%% %7.2fK %6u %8u %9uK %-23s\n",
				curr->nr_objs, curr->nr_active_objs, curr->use,
				curr->obj_size / 1024.0, curr->nr_slabs,
				curr->objs_per_slab, (unsigned)(curr->cache_size / 1024),
				curr->name);
			curr = curr->next;
		}

		put_slabinfo(slab_list);
		if (!run_once) {
			refresh();
			FD_ZERO(&readfds);
			FD_SET(STDIN_FILENO, &readfds);
			tv.tv_sec = delay;
			tv.tv_usec = 0;
			if (select(STDOUT_FILENO, &readfds, NULL, NULL, &tv) > 0) {
				if (read(STDIN_FILENO, &c, 1) != 1)
					break;
				parse_input(c);
			}
		}
	} while (delay);

	tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_tty);
	free_slabinfo(slab_list);
	if (!run_once)
		endwin();
	return retval;
}
Exemple #24
0
static void
print_cmp_test(int n, char *frmt, ...)
{
    int res = -1;
    static char clib_buf[BUF_SIZE];
    static unsigned char the_erts_buf[BUF_SIZE];
    char *erts_buf = (char *) &the_erts_buf[FENCE_SIZE]; 
    va_list args;

    if (outfile) {
	char *fp, *tp;
	va_start(args, frmt);
	if (n < 0)
	    res = vsprintf(erts_buf, frmt, args);
	else {
#ifdef HAVE_VSNPRINTF
	    res = vsnprintf(erts_buf, (size_t) n, frmt, args);
#else
	    fail("No vsnprintf()");
#endif
	}
	va_end(args);
	ASSERT(res >= 0);
	fp = erts_buf;
	tp = clib_buf;
	while (*fp) {
	    switch (*fp) {
	    case '\a':	*(tp++) = '\\';	*(tp++) = 'a';	break;
	    case '\b':	*(tp++) = '\\';	*(tp++) = 'b';	break;
	    case '\f':	*(tp++) = '\\';	*(tp++) = 'f';	break;
	    case '\n':	*(tp++) = '\\';	*(tp++) = 'n';	break;
	    case '\r':	*(tp++) = '\\';	*(tp++) = 'r';	break;
	    case '\t':	*(tp++) = '\\';	*(tp++) = 't';	break;
	    case '\v':	*(tp++) = '\\';	*(tp++) = 'v';	break;
	    case '\"':	*(tp++) = '\\';	*(tp++) = '\"';	break;
	    case '\\':	*(tp++) = '\\';	*(tp++) = '\\';	break;
	    default:	*(tp++) = *fp;			break;
	    }
	    fp++;
	}
	*tp = '\0';
	res = fprintf(outfile, "\t\"%s\",\n", clib_buf);
	ASSERT(res >= 0);
    }
    else {
	char *xres;
	va_start(args, frmt);
	if (n < 0)
	    res = erts_vsprintf(erts_buf, frmt, args);
	else {
	    int i;
	    int chk_sz = 2*FENCE_SIZE + n;
	    for (i = 0; i < chk_sz; i++)
		the_erts_buf[i] = 0xeb;
	    res = erts_vsnprintf(erts_buf, (size_t) n, frmt, args);
	    for (i = 0; i < chk_sz; i++)
		if ((((char *) &the_erts_buf[i]) < erts_buf
		     || erts_buf + n <= ((char *) &the_erts_buf[i]))
		    && the_erts_buf[i] != 0xeb) {
		    int j;
		    for (j = 0; j < chk_sz; j++)
			print(j ? ",%x(%d)" : "%x(%d)",
			      (unsigned) the_erts_buf[j], j - FENCE_SIZE);
		    print_eol();
		    fail("Garbage written out of bounds (%d,%d)",
			 i - FENCE_SIZE, n);
		}
	}
	va_end(args);
	ASSERT(res >= 0);

	if (expected_result) {
	    ASSERT(*expected_result);
	    xres = *expected_result;
	    expected_result++;
	}
	else {
	    va_start(args, frmt);
	    if (n < 0)
		res = vsprintf(clib_buf, frmt, args);
	    else {
#ifdef HAVE_VSNPRINTF
		res = vsnprintf(clib_buf, (size_t) n, frmt, args);
#else
		fail("No vsnprintf()");
#endif
	    }
	    va_end(args);
	    ASSERT(res >= 0);
	    xres = clib_buf;
	}

	if (strcmp(xres, erts_buf) != 0) {
	    print_line("expected result : \"%s\"", xres);
	    print_line("erts_buf        : \"%s\"", erts_buf);
	    fail("\"%s\" != \"%s\" (format=\"%s\")", xres, erts_buf, frmt);
	}

	print_line("Checked format \"%s\" with result: \"%s\"", frmt, erts_buf);
    }
}
Exemple #25
0
int print_line(struct list *files, int ind)
{
    register char *frmt;
    char out_str[PATH_MAX + 5];
    int i;
    int prt_limit;
    int numrows = 0;

    if (Single) {
#ifdef S_IFLNK
        if (Current == LNK_ONLY) {
            if (*(Lnksn.names + ind) != (char *) NULL)
                (void) printf("    %s -> %s\n",
                              *(Lnks.names + ind), *(Lnksn.names + ind));
            else
                (void) printf("    %s -> %s\n",
                              *(Lnks.names + ind), "UNRESOLVED");
            ind++;
            return (ind);
        }
#endif
        (void) puts(*(files->names + ind));
        ind++;
    }
    else if (Maxlen > ((Screen_width - 4) / 2)) {
        (void) printf("    %s\n", *(files->names + ind));
        ind++;
    }
    else {
         frmt = out_str;
         for (i = 0; i < 4; i++)
              *frmt++ = ' ';

        /* The prt_limit may need to be smarter */

         prt_limit = (Screen_width - 4) / (Maxlen + 1);

         /*  sort by columns */
#ifdef S_IFLNK
         if (Sort_down && Current != LNK_ONLY) {
#else       
         if (Sort_down) {
#endif
             numrows = (int)( (float)files->num / (float)prt_limit + 1.0);
             prt_limit = (int) ( (float)files->num / (float)numrows + (float)(numrows - 1) / (float)numrows);
         }

         if (Maxlen == 3 || Maxlen == 1)
             prt_limit--;

         while ((ind < files->num) && (prt_limit-- > 0)) {
              i = 0;
              do {
                   if (*(*(files->names + ind) + i) == '\0') {
                       while (i++ <= Maxlen)
                             *frmt++ = ' ';
                   }
                   else
                       *frmt++ = *(*(files->names + ind) + i);
                   i++;
              } while (i <= Maxlen);
#ifdef S_IFLNK
              if (Sort_down && Current != LNK_ONLY)
#else       
              if (Sort_down)
#endif
                 ind += numrows;
              else
                 ind++;
         }
         *frmt = '\0';
         while (*--frmt == ' ')  /* strip trailing blanks */
             *frmt = '\0';
        
         (void) puts(out_str);
    }
    return (ind);
}

/* S T R _ C M P
 *
 *  str_cmp is the comparison routine used by
 *  qsort(3) to order the filenames inplace.
 */

int str_cmp(const void *p1, const void *p2)
{
    const char *const *s1 = p1;
    const char *const *s2 = p2;
    /* inode/file sizes */
 
    return strcmp(&**s1 + Sort_offset, &**s2 + Sort_offset);
}

/* P R _ I N F O
 *
 *  pr_info() is used to sort the data if required
 *  and then pass it to print_line to actually output
 *  the data.`
 */

int pr_info(char *strng, struct list *files, int flg, int sort_needed)
{
    int pnum = 0;

#ifdef LENS
    Maxlen = files->maxlen;
#endif

#ifdef S_IFLNK
    if (!Single || Current == LNK_ONLY) {
        if (flg)
            (void) puts("");
        (void) puts(strng);
    }
#else
    if (!Single) {
        if (flg)
            (void) puts("");
        (void) puts(strng);
    }
#endif

    if (sort_needed)
        qsort((char *) (files->names), files->num, sizeof(char *), str_cmp);

    /* sort by columns */
    Maxlen++; /* this is to force an extra space between columns */
#ifdef S_IFLNK
    if (Sort_down && Current != LNK_ONLY) {
#else
    if (Sort_down) {
#endif
        int numcols = (Screen_width - 4) / (Maxlen + 1);
        int numrows = (int)( (float)files->num / (float)numcols + 1.0);
         
        numcols = (int) ( (float)files->num / (float)numrows + (float)(numrows - 1) / (float)numrows);
 
        do {
                (void) print_line(files, pnum);
                pnum++;
        } while (pnum < numrows);
    }    
    else {
        do {
            pnum = print_line(files, pnum);
        } while (pnum < files->num);
    }    
    return (1);
}


/* P R I N T _ I N F O
 *
 *  print_info() is called to display all the filenames
 *  located in the directory reading and storage functions.
 */

void print_info()
{
    int flag = 0;

#ifdef S_IFLNK
    int ssing;

    Current = 0;

    if (Lnks.num > 0 && (Disp_links == TRUE || Only & LNK_ONLY)) {
        ssing = Single;
        Single = TRUE;
        Current = LNK_ONLY;
        flag = pr_info("Symbolic Links: ", &Lnks, flag, FALSE);
        Single = ssing;
        Current = 0;
    }
#endif

#ifdef S_IFSOCK
    if (Socks.num > 0 && (Only == 0 || Only & SOCK_ONLY))
        flag = pr_info("Sockets: ", &Socks, flag, Sort_wanted);
#endif

#ifdef S_IFNAM
    if (Sems.num > 0 && (Only == 0 || Only & SEM_ONLY))
        flag = pr_info("Semaphore Files: ", &Sems, flag, Sort_wanted);

    if (Sds.num > 0 && (Only == 0 || Only & SD_ONLY))
        flag = pr_info("Shared Data Files: ", &Sds, flag, Sort_wanted);
#endif

#ifndef apollo
# ifdef S_IFIFO
    if (Fifos.num > 0 && (Only == 0 || Only & FIFO_ONLY))
        flag = pr_info("Fifo Files: ", &Fifos, flag, Sort_wanted);
# endif
#endif

#ifdef S_IFCHR
    if (Chrs.num > 0 && (Only == 0 || Only & CHAR_ONLY))
        flag = pr_info("Character Special Files: ", &Chrs, flag, Sort_wanted);
#endif

#ifdef S_IFBLK
    if (Blks.num > 0 && (Only == 0 || Only & BLOCK_ONLY))
        flag = pr_info("Block Special Files: ", &Blks, flag, Sort_wanted);
#endif

    if (Dirs.num > 0 && (Only == 0 || Only & DIR_ONLY))
        flag = pr_info("Directories: ", &Dirs, flag, Sort_wanted);

    if (Fls.num > 0 && (Only == 0 || Only & FILE_ONLY))
        flag = pr_info("Files: ", &Fls, flag, Sort_wanted);

    return;
}
Exemple #26
0
/*
 * Display text from a file in a dialog box.
 */
int
dialog_textbox (const char *title, const char *file, int height, int width)
{
    int i, x, y, cur_x, cur_y, fpos, key = 0;
    int passed_end;
    char search_term[MAX_LEN + 1];
    WINDOW *dialog, *text;

    search_term[0] = '\0';	/* no search term entered yet */

    /* Open input file for reading */
    if ((fd = open (file, O_RDONLY)) == -1)
    {
        endwin ();
        fprintf (stderr,
                 "\nCan't open input file in dialog_textbox().\n");
        exit (-1);
    }
    /* Get file size. Actually, 'file_size' is the real file size - 1,
       since it's only the last byte offset from the beginning */
    if ((file_size = lseek (fd, 0, SEEK_END)) == -1)
    {
        endwin ();
        fprintf (stderr, "\nError getting file size in dialog_textbox().\n");
        exit (-1);
    }
    /* Restore file pointer to beginning of file after getting file size */
    if (lseek (fd, 0, SEEK_SET) == -1)
    {
        endwin ();
        fprintf (stderr, "\nError moving file pointer in dialog_textbox().\n");
        exit (-1);
    }
    /* Allocate space for read buffer */
    if ((buf = malloc (BUF_SIZE + 1)) == NULL)
    {
        endwin ();
        fprintf (stderr, "\nCan't allocate memory in dialog_textbox().\n");
        exit (-1);
    }
    if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1)
    {
        endwin ();
        fprintf (stderr, "\nError reading file in dialog_textbox().\n");
        exit (-1);
    }
    buf[bytes_read] = '\0';	/* mark end of valid data */
    page = buf;			/* page is pointer to start of page to be displayed */

    /* center dialog box on screen */
    x = (COLS - width) / 2;
    y = (LINES - height) / 2;


    draw_shadow (stdscr, y, x, height, width);

    dialog = newwin (height, width, y, x);
    keypad (dialog, TRUE);

    /* Create window for text region, used for scrolling text */
    text = subwin (dialog, height - 4, width - 2, y + 1, x + 1);
    wattrset (text, dialog_attr);
    wbkgdset (text, dialog_attr & A_COLOR);

    keypad (text, TRUE);

    /* register the new window, along with its borders */
    draw_box (dialog, 0, 0, height, width, dialog_attr, border_attr);

    wattrset (dialog, border_attr);
    mvwaddch (dialog, height-3, 0, ACS_LTEE);
    for (i = 0; i < width - 2; i++)
        waddch (dialog, ACS_HLINE);
    wattrset (dialog, dialog_attr);
    wbkgdset (dialog, dialog_attr & A_COLOR);
    waddch (dialog, ACS_RTEE);

    if (title != NULL && strlen(title) >= width-2 )
    {
        /* truncate long title -- mec */
        char * title2 = malloc(width-2+1);
        memcpy( title2, title, width-2 );
        title2[width-2] = '\0';
        title = title2;
    }

    if (title != NULL)
    {
        wattrset (dialog, title_attr);
        mvwaddch (dialog, 0, (width - strlen(title))/2 - 1, ' ');
        waddstr (dialog, (char *)title);
        waddch (dialog, ' ');
    }
    print_button (dialog, " Exit ", height - 2, width / 2 - 4, TRUE);
    wnoutrefresh (dialog);
    getyx (dialog, cur_y, cur_x);	/* Save cursor position */

    /* Print first page of text */
    attr_clear (text, height - 4, width - 2, dialog_attr);
    print_page (text, height - 4, width - 2);
    print_position (dialog, height, width);
    wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
    wrefresh (dialog);

    while ((key != ESC) && (key != '\n'))
    {
        key = wgetch (dialog);
        switch (key)
        {
        case 'E':		/* Exit */
        case 'e':
        case 'X':
        case 'x':
            delwin (dialog);
            free (buf);
            close (fd);
            return 0;
        case 'g':		/* First page */
        case KEY_HOME:
            if (!begin_reached)
            {
                begin_reached = 1;
                /* First page not in buffer? */
                if ((fpos = lseek (fd, 0, SEEK_CUR)) == -1)
                {
                    endwin ();
                    fprintf (stderr,
                             "\nError moving file pointer in dialog_textbox().\n");
                    exit (-1);
                }
                if (fpos > bytes_read)  	/* Yes, we have to read it in */
                {
                    if (lseek (fd, 0, SEEK_SET) == -1)
                    {
                        endwin ();
                        fprintf (stderr, "\nError moving file pointer in "
                                 "dialog_textbox().\n");
                        exit (-1);
                    }
                    if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1)
                    {
                        endwin ();
                        fprintf (stderr,
                                 "\nError reading file in dialog_textbox().\n");
                        exit (-1);
                    }
                    buf[bytes_read] = '\0';
                }
                page = buf;
                print_page (text, height - 4, width - 2);
                print_position (dialog, height, width);
                wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
                wrefresh (dialog);
            }
            break;
        case 'G':		/* Last page */
        case KEY_END:

            end_reached = 1;
            /* Last page not in buffer? */
            if ((fpos = lseek (fd, 0, SEEK_CUR)) == -1)
            {
                endwin ();
                fprintf (stderr,
                         "\nError moving file pointer in dialog_textbox().\n");
                exit (-1);
            }
            if (fpos < file_size)  	/* Yes, we have to read it in */
            {
                if (lseek (fd, -BUF_SIZE, SEEK_END) == -1)
                {
                    endwin ();
                    fprintf (stderr,
                             "\nError moving file pointer in dialog_textbox().\n");
                    exit (-1);
                }
                if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1)
                {
                    endwin ();
                    fprintf (stderr,
                             "\nError reading file in dialog_textbox().\n");
                    exit (-1);
                }
                buf[bytes_read] = '\0';
            }
            page = buf + bytes_read;
            back_lines (height - 4);
            print_page (text, height - 4, width - 2);
            print_position (dialog, height, width);
            wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
            wrefresh (dialog);
            break;
        case 'K':		/* Previous line */
        case 'k':
        case KEY_UP:
            if (!begin_reached)
            {
                back_lines (page_length + 1);

                /* We don't call print_page() here but use scrolling to ensure
                   faster screen update. However, 'end_reached' and
                   'page_length' should still be updated, and 'page' should
                   point to start of next page. This is done by calling
                   get_line() in the following 'for' loop. */
                scrollok (text, TRUE);
                wscrl (text, -1);	/* Scroll text region down one line */
                scrollok (text, FALSE);
                page_length = 0;
                passed_end = 0;
                for (i = 0; i < height - 4; i++)
                {
                    if (!i)
                    {
                        /* print first line of page */
                        print_line (text, 0, width - 2);
                        wnoutrefresh (text);
                    }
                    else
                        /* Called to update 'end_reached' and 'page' */
                        get_line ();
                    if (!passed_end)
                        page_length++;
                    if (end_reached && !passed_end)
                        passed_end = 1;
                }

                print_position (dialog, height, width);
                wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
                wrefresh (dialog);
            }
            break;
        case 'B':		/* Previous page */
        case 'b':
        case KEY_PPAGE:
            if (begin_reached)
                break;
            back_lines (page_length + height - 4);
            print_page (text, height - 4, width - 2);
            print_position (dialog, height, width);
            wmove (dialog, cur_y, cur_x);
            wrefresh (dialog);
            break;
        case 'J':		/* Next line */
        case 'j':
        case KEY_DOWN:
            if (!end_reached)
            {
                begin_reached = 0;
                scrollok (text, TRUE);
                scroll (text);	/* Scroll text region up one line */
                scrollok (text, FALSE);
                print_line (text, height - 5, width - 2);
                wnoutrefresh (text);
                print_position (dialog, height, width);
                wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
                wrefresh (dialog);
            }
            break;
        case KEY_NPAGE:		/* Next page */
        case ' ':
            if (end_reached)
                break;

            begin_reached = 0;
            print_page (text, height - 4, width - 2);
            print_position (dialog, height, width);
            wmove (dialog, cur_y, cur_x);
            wrefresh (dialog);
            break;
        case '0':		/* Beginning of line */
        case 'H':		/* Scroll left */
        case 'h':
        case KEY_LEFT:
            if (hscroll <= 0)
                break;

            if (key == '0')
                hscroll = 0;
            else
                hscroll--;
            /* Reprint current page to scroll horizontally */
            back_lines (page_length);
            print_page (text, height - 4, width - 2);
            wmove (dialog, cur_y, cur_x);
            wrefresh (dialog);
            break;
        case 'L':		/* Scroll right */
        case 'l':
        case KEY_RIGHT:
            if (hscroll >= MAX_LEN)
                break;
            hscroll++;
            /* Reprint current page to scroll horizontally */
            back_lines (page_length);
            print_page (text, height - 4, width - 2);
            wmove (dialog, cur_y, cur_x);
            wrefresh (dialog);
            break;
        case ESC:
            break;
        }
    }

    delwin (dialog);
    free (buf);
    close (fd);
    return -1;			/* ESC pressed */
}
Exemple #27
0
static void
print_colacross(OBJ *obj)
{
	struct stat *st;
	FTSENT      *p;

	int count_file;		/* count total number of file */
	int count_pre;		/* count the width of ino and block */
	int col_num;		/* how many columns to print */
	int *col_width_max;	/* max width for each column */
	int row_num;		/* how many columns in the last row */
	int i, j, m, t;
	count_pre = 0;

	if (f_ino)
		count_pre += obj->obj_ino_max + 1;
	if (f_block)
		count_pre += obj->obj_block_max + 1;
	if (f_char)
		count_pre++;

	count_file = 0;

	for (p = obj->obj_list; p != NULL; p = p->fts_link)
		if (p->fts_number != FTS_NO_PRINT) 
			count_file++;

	/* first guess at column number, suppose all the file names are 1 */
	col_num = term_width / (count_pre + 1 + 2);

	/* at least one column */
	col_num = MAX(col_num, 1);

	if (count_file == 0) {
		putchar('\n');
		return;
	}

	if (count_file == 1 || col_num == 1) {
		print_line(obj);
		return;
	}

	col_width_max = (int *)malloc(col_num * sizeof(int));

	if (col_width_max == NULL) {
		free(col_width_max);
		warn("failed to malloc");
		return;
	}

	/*
	 * Try to find the best printing format, and the max width for each
	 * column.
	 */
	while (col_num > 1) {
		/* max length of the column */
		int max_len;

		if (count_file % col_num == 0)
			row_num = count_file / col_num;
		else
			row_num = count_file / col_num + 1;

		for (i = 0; i < col_num; i++)
			col_width_max[i] = 0;

		for (i = 0, t = 0, p = obj->obj_list; i < row_num; i++) {
			int tmp_count;
			for (j = 0; j < col_num && t < count_file; 
			     j++, t++, p = p->fts_link) {
				while (p->fts_number == FTS_NO_PRINT)
					p = p->fts_link;

				tmp_count = count_pre + 
    					strlen(p->fts_name) + 2;

				if (f_char) 
					tmp_count++;

				col_width_max[j] = MAX(col_width_max[j], 
							tmp_count); 
			}
		}

		max_len = 0;

		for (i = 0; i < col_num; i++)
			max_len += col_width_max[i];

		/*
		 * If the total length of each row is less than the width
		 * of the terminal, then we stop.
		 */
		if (max_len <= term_width)
			break;
		col_num--;
	}

	if (col_num == 1) {
		free(col_width_max);
		print_line(obj);
		return;
	}

	for (i = 0, t = 0, p = obj->obj_list; i < row_num; i++) {
		for (j = 0; j < col_num && t < count_file; 
		     j++, t++, p = p->fts_link) {
			while (p->fts_number == FTS_NO_PRINT)
				p = p->fts_link;

			st = p->fts_statp;

			/* print inode */
			if (f_ino)
				printf("%*"PRIuMAX" ", obj->obj_ino_max,
					(uintmax_t)st->st_ino);
	
			/* print number of blocks */
			if (f_block) {	
				print_block(st->st_blocks * DEFAULT_BSIZE, 
					    obj->obj_block_max);
			}
	
			
			m = count_pre + print_name(p, 0);

			while (m < col_width_max[j]) {
				putchar(' ');
				m++;
			}
		}
		putchar('\n');
	}

	free(col_width_max);
}
Exemple #28
0
static int
pre_it(DECL_ARGS)
{
	const struct roff_node *bln;

	switch (n->type) {
	case ROFFT_HEAD:
		outflags |= MMAN_PP | MMAN_nl;
		bln = n->parent->parent;
		if (0 == bln->norm->Bl.comp ||
		    (NULL == n->parent->prev &&
		     NULL == bln->parent->prev))
			outflags |= MMAN_sp;
		outflags &= ~MMAN_br;
		switch (bln->norm->Bl.type) {
		case LIST_item:
			return 0;
		case LIST_inset:
		case LIST_diag:
		case LIST_ohang:
			if (bln->norm->Bl.type == LIST_diag)
				print_line(".B \"", 0);
			else
				print_line(".BR \\& \"", 0);
			outflags &= ~MMAN_spc;
			return 1;
		case LIST_bullet:
		case LIST_dash:
		case LIST_hyphen:
			print_width(&bln->norm->Bl, NULL);
			TPremain = 0;
			outflags |= MMAN_nl;
			font_push('B');
			if (LIST_bullet == bln->norm->Bl.type)
				print_word("\\(bu");
			else
				print_word("-");
			font_pop();
			outflags |= MMAN_nl;
			return 0;
		case LIST_enum:
			print_width(&bln->norm->Bl, NULL);
			TPremain = 0;
			outflags |= MMAN_nl;
			print_count(&bln->norm->Bl.count);
			outflags |= MMAN_nl;
			return 0;
		case LIST_hang:
			print_width(&bln->norm->Bl, n->child);
			TPremain = 0;
			outflags |= MMAN_nl;
			return 1;
		case LIST_tag:
			print_width(&bln->norm->Bl, n->child);
			putchar('\n');
			outflags &= ~MMAN_spc;
			return 1;
		default:
			return 1;
		}
	default:
		break;
	}
	return 1;
}
Exemple #29
0
DVector< Face3 > Geometry::wrap_geometry( DVector< Face3 > p_array,float *p_error ) {

#define _MIN_SIZE 1.0
#define _MAX_LENGTH 20

	int face_count=p_array.size();
	DVector<Face3>::Read facesr=p_array.read();
	const Face3 *faces = facesr.ptr();

	AABB global_aabb;

	for(int i=0;i<face_count;i++) {

		if (i==0) {

			global_aabb=faces[i].get_aabb();
		} else {

			global_aabb.merge_with( faces[i].get_aabb() );
		}
	}
	
	global_aabb.grow_by(0.01); // avoid numerical error

	// determine amount of cells in grid axis
	int div_x,div_y,div_z;

	if (global_aabb.size.x/_MIN_SIZE<_MAX_LENGTH)
		div_x=(int)(global_aabb.size.x/_MIN_SIZE)+1;
	else
		div_x=_MAX_LENGTH;

	if (global_aabb.size.y/_MIN_SIZE<_MAX_LENGTH)
		div_y=(int)(global_aabb.size.y/_MIN_SIZE)+1;
	else
		div_y=_MAX_LENGTH;

	if (global_aabb.size.z/_MIN_SIZE<_MAX_LENGTH)
		div_z=(int)(global_aabb.size.z/_MIN_SIZE)+1;
	else
		div_z=_MAX_LENGTH;

	Vector3 voxelsize=global_aabb.size;
	voxelsize.x/=div_x;
	voxelsize.y/=div_y;
	voxelsize.z/=div_z;


	// create and initialize cells to zero
	print_line("Wrapper: Initializing Cells");

	uint8_t ***cell_status=memnew_arr(uint8_t**,div_x);
	for(int i=0;i<div_x;i++) {

		cell_status[i]=memnew_arr(uint8_t*,div_y);

		for(int j=0;j<div_y;j++) {

			cell_status[i][j]=memnew_arr(uint8_t,div_z);

			for(int k=0;k<div_z;k++) {

				cell_status[i][j][k]=0;
			}
		}
	}

	// plot faces into cells
	print_line("Wrapper (1/6): Plotting Faces");
	
	for (int i=0;i<face_count;i++) {

		Face3 f=faces[i];
		for (int j=0;j<3;j++) {

			f.vertex[j]-=global_aabb.pos;
		}
		_plot_face(cell_status,0,0,0,div_x,div_y,div_z,voxelsize,f);
	}


	// determine which cells connect to the outside by traversing the outside and recursively flood-fill marking

	print_line("Wrapper (2/6) Flood Filling");

	for (int i=0;i<div_x;i++) {
		
		for (int j=0;j<div_y;j++) {
		
			_mark_outside(cell_status,i,j,0,div_x,div_y,div_z);
			_mark_outside(cell_status,i,j,div_z-1,div_x,div_y,div_z);
		}
	}
	
	for (int i=0;i<div_z;i++) {
		
		for (int j=0;j<div_y;j++) {
		
			_mark_outside(cell_status,0,j,i,div_x,div_y,div_z);
			_mark_outside(cell_status,div_x-1,j,i,div_x,div_y,div_z);
		}
	}
	
	for (int i=0;i<div_x;i++) {
		
		for (int j=0;j<div_z;j++) {
		
			_mark_outside(cell_status,i,0,j,div_x,div_y,div_z);
			_mark_outside(cell_status,i,div_y-1,j,div_x,div_y,div_z);
		}
	}
	
	// build faces for the inside-outside cell divisors
	
	print_line("Wrapper (3/6): Building Faces");

	DVector<Face3> wrapped_faces;
	
	for (int i=0;i<div_x;i++) {
		
		for (int j=0;j<div_y;j++) {
		
			for (int k=0;k<div_z;k++) {
			
				_build_faces(cell_status,i,j,k,div_x,div_y,div_z,wrapped_faces);				
			}
		}
	}
	
	print_line("Wrapper (4/6): Transforming Back Vertices");

	// transform face vertices to global coords
	
	int wrapped_faces_count=wrapped_faces.size();
	DVector<Face3>::Write wrapped_facesw=wrapped_faces.write();
	Face3* wrapped_faces_ptr=wrapped_facesw.ptr();
	
	for(int i=0;i<wrapped_faces_count;i++) {
	
		for(int j=0;j<3;j++) {
		
			Vector3& v = wrapped_faces_ptr[i].vertex[j];
			v=v*voxelsize;
			v+=global_aabb.pos;
		}
	}
	
	// clean up grid 
	print_line("Wrapper (5/6): Grid Cleanup");

	for(int i=0;i<div_x;i++) {

		for(int j=0;j<div_y;j++) {

			memdelete_arr( cell_status[i][j] );
		}
		
		memdelete_arr( cell_status[i] );
	}
	
	memdelete_arr(cell_status);
	if (p_error)
		*p_error=voxelsize.length();
	
	print_line("Wrapper (6/6): Finished.");
	return wrapped_faces;
}
Vector<uint8_t> EditorTextureImportPlugin::custom_export(const String& p_path, const Ref<EditorExportPlatform> &p_platform) {


	Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(p_path);

	if (rimd.is_null()) {

		StringName group = EditorImportExport::get_singleton()->image_get_export_group(p_path);

		if (group!=StringName()) {
			//handled by export group
			rimd = Ref<ResourceImportMetadata>( memnew( ResourceImportMetadata ) );

			int group_format=0;
			float group_lossy_quality=EditorImportExport::get_singleton()->image_export_group_get_lossy_quality(group);
			int group_shrink=EditorImportExport::get_singleton()->image_export_group_get_shrink(group);
			group_shrink*=EditorImportExport::get_singleton()->get_export_image_shrink();

			switch(EditorImportExport::get_singleton()->image_export_group_get_image_action(group)) {
				case EditorImportExport::IMAGE_ACTION_NONE: {

					switch(EditorImportExport::get_singleton()->get_export_image_action()) {
						case EditorImportExport::IMAGE_ACTION_NONE: {

							group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_DISK_LOSSLESS; //?

						} break; //use default
						case EditorImportExport::IMAGE_ACTION_COMPRESS_DISK: {
							group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_DISK_LOSSY;
						} break; //use default
						case EditorImportExport::IMAGE_ACTION_COMPRESS_RAM: {
							group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_RAM;
						} break; //use default
					}

					group_lossy_quality=EditorImportExport::get_singleton()->get_export_image_quality();

				} break; //use default
				case EditorImportExport::IMAGE_ACTION_COMPRESS_DISK: {
					group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_DISK_LOSSY;
				} break; //use default
				case EditorImportExport::IMAGE_ACTION_COMPRESS_RAM: {
					group_format=EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_RAM;
				} break; //use default
			}


			int flags=0;

			if (Globals::get_singleton()->get("texture_import/filter"))
				flags|=IMAGE_FLAG_FILTER;
			if (!Globals::get_singleton()->get("texture_import/gen_mipmaps"))
				flags|=IMAGE_FLAG_NO_MIPMAPS;
			if (!Globals::get_singleton()->get("texture_import/repeat"))
				flags|=IMAGE_FLAG_REPEAT;

			flags|=IMAGE_FLAG_FIX_BORDER_ALPHA;

			print_line("group format"+itos(group_format));
			rimd->set_option("format",group_format);
			rimd->set_option("flags",flags);
			rimd->set_option("quality",group_lossy_quality);
			rimd->set_option("atlas",false);
			rimd->set_option("shrink",group_shrink);
			rimd->add_source(EditorImportPlugin::validate_source_path(p_path));

		} else if (EditorImportExport::get_singleton()->get_image_formats().has(p_path.extension().to_lower()) && EditorImportExport::get_singleton()->get_export_image_action()!=EditorImportExport::IMAGE_ACTION_NONE) {
			//handled by general image export settings

			rimd = Ref<ResourceImportMetadata>( memnew( ResourceImportMetadata ) );

			switch(EditorImportExport::get_singleton()->get_export_image_action()) {
				case EditorImportExport::IMAGE_ACTION_COMPRESS_DISK: rimd->set_option("format",IMAGE_FORMAT_COMPRESS_DISK_LOSSY); break;
				case EditorImportExport::IMAGE_ACTION_COMPRESS_RAM: rimd->set_option("format",IMAGE_FORMAT_COMPRESS_RAM); break;
			}

			int flags=0;

			if (Globals::get_singleton()->get("texture_import/filter"))
				flags|=IMAGE_FLAG_FILTER;
			if (!Globals::get_singleton()->get("texture_import/gen_mipmaps"))
				flags|=IMAGE_FLAG_NO_MIPMAPS;
			if (!Globals::get_singleton()->get("texture_import/repeat"))
				flags|=IMAGE_FLAG_REPEAT;

			flags|=IMAGE_FLAG_FIX_BORDER_ALPHA;

			rimd->set_option("shrink",EditorImportExport::get_singleton()->get_export_image_shrink());
			rimd->set_option("flags",flags);
			rimd->set_option("quality",EditorImportExport::get_singleton()->get_export_image_quality());
			rimd->set_option("atlas",false);
			rimd->add_source(EditorImportPlugin::validate_source_path(p_path));

		} else {
			return Vector<uint8_t>();
		}
	}

	int fmt = rimd->get_option("format");

	if (fmt!=IMAGE_FORMAT_COMPRESS_RAM && fmt!=IMAGE_FORMAT_COMPRESS_DISK_LOSSY)  {
		print_line("no compress ram or lossy");
		return Vector<uint8_t>(); //pointless to do anything, since no need to reconvert
	}

	uint32_t flags = rimd->get_option("flags");
	uint8_t shrink = rimd->has_option("shrink") ? rimd->get_option("shrink"): Variant(1);
	uint8_t format = rimd->get_option("format");
	uint8_t comp = (format==EditorTextureImportPlugin::IMAGE_FORMAT_COMPRESS_RAM)?uint8_t(p_platform->get_image_compression()):uint8_t(255);

	MD5_CTX ctx;
	uint8_t f4[4];
	encode_uint32(flags,&f4[0]);
	MD5Init(&ctx);
	String gp = Globals::get_singleton()->globalize_path(p_path);
	CharString cs = gp.utf8();
	MD5Update(&ctx,(unsigned char*)cs.get_data(),cs.length());
	MD5Update(&ctx,f4,4);
	MD5Update(&ctx,&format,1);
	MD5Update(&ctx,&comp,1);
	MD5Update(&ctx,&shrink,1);
	MD5Final(&ctx);

	uint64_t sd=0;
	String smd5;

	String md5 = String::md5(ctx.digest);

	String tmp_path = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp/");

	bool valid=false;
	{
		//if existing, make sure it's valid
		FileAccessRef f = FileAccess::open(tmp_path+"imgexp-"+md5+".txt",FileAccess::READ);
		if (f) {

			uint64_t d = f->get_line().strip_edges().to_int64();
			sd = FileAccess::get_modified_time(p_path);

			if (d==sd) {
				valid=true;
			} else {
				String cmd5 = f->get_line().strip_edges();
				smd5 = FileAccess::get_md5(p_path);
				if (cmd5==smd5) {
					valid=true;
				}
			}


		}
	}

	if (!valid) {
		//cache failed, convert
		Error err = import2(tmp_path+"imgexp-"+md5+".tex",rimd,p_platform->get_image_compression(),true);
		ERR_FAIL_COND_V(err!=OK,Vector<uint8_t>());
		FileAccessRef f = FileAccess::open(tmp_path+"imgexp-"+md5+".txt",FileAccess::WRITE);

		if (sd==0)
			sd = FileAccess::get_modified_time(p_path);
		if (smd5==String())
			smd5 = FileAccess::get_md5(p_path);

		f->store_line(String::num(sd));
		f->store_line(smd5);
		f->store_line(gp); //source path for reference
	}


	Vector<uint8_t> ret;
	FileAccessRef f = FileAccess::open(tmp_path+"imgexp-"+md5+".tex",FileAccess::READ);
	ERR_FAIL_COND_V(!f,ret);

	ret.resize(f->get_len());
	f->get_buffer(ret.ptr(),ret.size());

	return ret;
}