示例#1
0
/**************************************************************
 *
 * * Entry: none
 *
 * * Exit: inflated dictionary with maxLength as its longest word(s)
 *
 * * Purpose: change word length to match difficulty
 *
 * ***************************************************************/
void SetDictionary ( int maxLength ) {
   myDict = Dictionary( maxLength );
   if ( !myDict.Filled() )
      myDict = PreFabDict::UsePreFabDict();
}
void EditorSceneImporterFBXConv::_parse_materials(State& state) {

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

		Dictionary material = state.materials[i];

		ERR_CONTINUE(!material.has("id"));
		String id = _id(material["id"]);

		Ref<FixedMaterial> mat = memnew( FixedMaterial );

		if (material.has("diffuse")) {
			mat->set_parameter(FixedMaterial::PARAM_DIFFUSE,_get_color(material["diffuse"]));
		}

		if (material.has("specular")) {
			mat->set_parameter(FixedMaterial::PARAM_SPECULAR,_get_color(material["specular"]));
		}

		if (material.has("emissive")) {
			mat->set_parameter(FixedMaterial::PARAM_EMISSION,_get_color(material["emissive"]));
		}

		if (material.has("shininess")) {
			float exp = material["shininess"];
			mat->set_parameter(FixedMaterial::PARAM_SPECULAR_EXP,exp);
		}

		if (material.has("opacity")) {
			Color c = mat->get_parameter(FixedMaterial::PARAM_DIFFUSE);
			c.a=material["opacity"];
			mat->set_parameter(FixedMaterial::PARAM_DIFFUSE,c);
		}


		if (material.has("textures")) {

			Array textures = material["textures"];
			for(int j=0;j<textures.size();j++) {

				Dictionary texture=textures[j];
				Ref<Texture> tex;
				if (texture.has("filename")) {


					String filename=texture["filename"];
					String path=state.base_path+"/"+filename.replace("\\","/");
					if (state.texture_cache.has(path)) {
						tex=state.texture_cache[path];
					} else {
						tex = ResourceLoader::load(path,"ImageTexture");
						if (tex.is_null()) {
							if (state.missing_deps)
								state.missing_deps->push_back(path);
						}
						state.texture_cache[path]=tex; //add anyway
					}
				}

				if (tex.is_valid() && texture.has("type")) {

					String type=texture["type"];
					if (type=="DIFFUSE")
						mat->set_texture(FixedMaterial::PARAM_DIFFUSE,tex);
					else if (type=="SPECULAR")
						mat->set_texture(FixedMaterial::PARAM_SPECULAR,tex);
					else if (type=="SHININESS")
						mat->set_texture(FixedMaterial::PARAM_SPECULAR_EXP,tex);
					else if (type=="NORMAL")
						mat->set_texture(FixedMaterial::PARAM_NORMAL,tex);
					else if (type=="EMISSIVE")
						mat->set_texture(FixedMaterial::PARAM_EMISSION,tex);
				}

			}
		}

		state.material_cache[id]=mat;

	}

}
Transform EditorSceneImporterFBXConv::_get_transform_mixed(const Dictionary& d,const Dictionary& dbase) {




	Array translation;

	if (d.has("translation"))
		translation=d["translation"];
	else if (dbase.has("translation"))
		translation=dbase["translation"];

	Array rotation;

	if (d.has("rotation"))
		rotation=d["rotation"];
	else if (dbase.has("rotation"))
		rotation=dbase["rotation"];

	Array scale;

	if (d.has("scale"))
		scale=d["scale"];
	else if (dbase.has("scale"))
		scale=dbase["scale"];

	Transform t;


	if (translation.size()) {
		Array tr = translation;
		if (tr.size()>=3) {
			t.origin.x=tr[0];
			t.origin.y=tr[1];
			t.origin.z=tr[2];
		}
	}

	if (rotation.size()) {

		Array r = rotation;
		if (r.size()>=4) {

			Quat q;
			q.x = r[0];
			q.y = r[1];
			q.z = r[2];
			q.w = r[3];
			t.basis=Matrix3(q);
		}
	}


	if (scale.size()) {

		Array sc = scale;
		if (sc.size()>=3) {
			Vector3 s;
			s.x=sc[0];
			s.y=sc[1];
			s.z=sc[2];
			t.basis.scale(s);
		}
	}

	return t;


}
示例#4
0
void NetworkConfig::_fromDictionary(const Dictionary &d)
{
	static const std::string zero("0");
	static const std::string one("1");

	// NOTE: d.get(name) throws if not found, d.get(name,default) returns default

	_nwid = Utils::hexStrToU64(d.get(ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID).c_str());
	if (!_nwid)
		throw std::invalid_argument("configuration contains zero network ID");

	_timestamp = Utils::hexStrToU64(d.get(ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP).c_str());
	_revision = Utils::hexStrToU64(d.get(ZT_NETWORKCONFIG_DICT_KEY_REVISION,"1").c_str()); // older controllers don't send this, so default to 1

	memset(_etWhitelist,0,sizeof(_etWhitelist));
	std::vector<std::string> ets(Utils::split(d.get(ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES).c_str(),",","",""));
	for(std::vector<std::string>::const_iterator et(ets.begin());et!=ets.end();++et) {
		unsigned int tmp = Utils::hexStrToUInt(et->c_str()) & 0xffff;
		_etWhitelist[tmp >> 3] |= (1 << (tmp & 7));
	}

	_issuedTo = Address(d.get(ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO));
	_multicastLimit = Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT,zero).c_str());
	if (_multicastLimit == 0) _multicastLimit = ZT_MULTICAST_DEFAULT_LIMIT;
	_allowPassiveBridging = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING,zero).c_str()) != 0);
	_private = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_PRIVATE,one).c_str()) != 0);
	_enableBroadcast = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST,one).c_str()) != 0);
	_name = d.get(ZT_NETWORKCONFIG_DICT_KEY_NAME);
	if (_name.length() > ZT1_MAX_NETWORK_SHORT_NAME_LENGTH)
		throw std::invalid_argument("network short name too long (max: 255 characters)");
	_description = d.get(ZT_NETWORKCONFIG_DICT_KEY_DESC,std::string());

	// In dictionary IPs are split into V4 and V6 addresses, but we don't really
	// need that so merge them here.
	std::string ipAddrs(d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC,std::string()));
	{
		std::string v6s(d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC,std::string()));
		if (v6s.length()) {
			if (ipAddrs.length())
				ipAddrs.push_back(',');
			ipAddrs.append(v6s);
		}
	}

	std::vector<std::string> ipAddrsSplit(Utils::split(ipAddrs.c_str(),",","",""));
	for(std::vector<std::string>::const_iterator ipstr(ipAddrsSplit.begin());ipstr!=ipAddrsSplit.end();++ipstr) {
		InetAddress addr(*ipstr);
		switch(addr.ss_family) {
			case AF_INET:
				if ((!addr.netmaskBits())||(addr.netmaskBits() > 32))
					continue;
				break;
			case AF_INET6:
				if ((!addr.netmaskBits())||(addr.netmaskBits() > 128))
					continue;
				break;
			default: // ignore unrecognized address types or junk/empty fields
				continue;
		}
		_staticIps.push_back(addr);
	}
	if (_staticIps.size() > ZT1_MAX_ZT_ASSIGNED_ADDRESSES)
		throw std::invalid_argument("too many ZT-assigned IP addresses");
	std::sort(_staticIps.begin(),_staticIps.end());
	std::unique(_staticIps.begin(),_staticIps.end());

	std::vector<std::string> activeBridgesSplit(Utils::split(d.get(ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES,"").c_str(),",","",""));
	for(std::vector<std::string>::const_iterator a(activeBridgesSplit.begin());a!=activeBridgesSplit.end();++a) {
		if (a->length() == ZT_ADDRESS_LENGTH_HEX) { // ignore empty or garbage fields
			Address tmp(*a);
			if (!tmp.isReserved())
				_activeBridges.push_back(tmp);
		}
	}
	std::sort(_activeBridges.begin(),_activeBridges.end());
	std::unique(_activeBridges.begin(),_activeBridges.end());

	Dictionary multicastRateEntries(d.get(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES,std::string()));
	for(Dictionary::const_iterator i(multicastRateEntries.begin());i!=multicastRateEntries.end();++i) {
		std::vector<std::string> params(Utils::split(i->second.c_str(),",","",""));
		if (params.size() >= 3)
			_multicastRates[MulticastGroup(i->first)] = MulticastRate(Utils::hexStrToUInt(params[0].c_str()),Utils::hexStrToUInt(params[1].c_str()),Utils::hexStrToUInt(params[2].c_str()));
	}

	std::vector<std::string> relaysSplit(Utils::split(d.get(ZT_NETWORKCONFIG_DICT_KEY_RELAYS,"").c_str(),",","",""));
	for(std::vector<std::string>::const_iterator r(relaysSplit.begin());r!=relaysSplit.end();++r) {
		std::size_t semi(r->find(';')); // address;ip/port,...
		if (semi == ZT_ADDRESS_LENGTH_HEX) {
			std::pair<Address,InetAddress> relay(
				Address(r->substr(0,semi)),
				((r->length() > (semi + 1)) ? InetAddress(r->substr(semi + 1)) : InetAddress()) );
			if ((relay.first)&&(!relay.first.isReserved()))
				_relays.push_back(relay);
		}
	}
	std::sort(_relays.begin(),_relays.end());
	std::unique(_relays.begin(),_relays.end());

	_com.fromString(d.get(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP,std::string()));
}
void EditorSceneImporterFBXConv::_add_surface(State& state,Ref<Mesh>& m,const Dictionary &part) {

	if (part.has("meshpartid")) {

		String id = part["meshpartid"];
		ERR_FAIL_COND(!state.surface_cache.has(id));


		Ref<Material> mat;
		if (part.has("materialid")) {
			String matid=part["materialid"];
			if (state.material_cache.has(matid)) {
				mat=state.material_cache[matid];
			}
		}
		int idx = m->get_surface_count();

		Array array = state.surface_cache[id].array;
		DVector<float> indices = array[Mesh::ARRAY_BONES];
		if (indices.size() && part.has("bones")) {


			Map<int,int> index_map;

			Array bones=part["bones"];

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

				Dictionary bone=bones[i];
				String name=_id(bone["node"]);

				if (state.bones.has(name)) {
					int idx=state.bones[name].skeleton->find_bone(name);
					if (idx==-1)
						idx=0;
					index_map[i]=idx;
				}
			}



			int ilen=indices.size();
			{
				DVector<float>::Write iw=indices.write();
				for(int j=0;j<ilen;j++) {
					int b = iw[j];
					ERR_CONTINUE(!index_map.has(b));
					b=index_map[b];
					iw[j]=b;
				}
			}

			array[Mesh::ARRAY_BONES]=indices;


		}

		m->add_surface(state.surface_cache[id].primitive,array);
		m->surface_set_material(idx,mat);
		m->surface_set_name(idx,id);
	}

}
示例#6
0
void CodecContext::open(Dictionary &options, const Codec &codec, error_code &ec)
{
    auto prt = options.release();
    open(codec, &prt, ec);
    options.assign(prt);
}
示例#7
0
int
main (int argc, char **argv)
{
  int c;
  char * restricted_files = NULL;
  char * output_file = NULL;
  char * dictionary_files = NULL;
     
  while (1)
    {
      static struct option long_options[] =
	{
	  /* These options set a flag. */
	  {"verbose", no_argument,       &verbose_flag, 1},
	  {"brief",   no_argument,       &verbose_flag, 0},
	  {"deobscure",   no_argument,       &deobscure_flag, 1},
	  /* These options don't set a flag.
	     We distinguish them by their indices. */
	  {"dictionary",    required_argument, 0, 'd'},
	  {"restricted",  required_argument, 0, 'e'},
	  {"output",    required_argument, 0, 'o'},
	  {0, 0, 0, 0}
	};
      /* getopt_long stores the option index here. */
      int option_index = 0;
     
      c = getopt_long (argc, argv, "d:e:o:",
		       long_options, &option_index);
     
      /* Detect the end of the options. */
      if (c == -1)
	break;
     
      switch (c)
	{
	case 0:
	  /* If this option set a flag, do nothing else now. */
	  if (long_options[option_index].flag != 0)
	    break;
	  printf ("option %s", long_options[option_index].name);
	  if (optarg)
	    printf (" with arg %s", optarg);
	  printf ("\n");
	  break;

     	case 'd':
	  dictionary_files = optarg;
	  printf ("option -d with value `%s'\n", optarg);
	  break;
     
     	case 'e':
	  restricted_files = optarg;
	  printf ("option -e with value `%s'\n", optarg);
	  break;
     
	case 'o':
	  output_file = optarg;
	  printf ("option -o with value `%s'\n", optarg);
	  break;
     
	case '?':
	  /* getopt_long already printed an error message. */
	  break;
     
	default:
	  abort ();
	}
    }
     
  /* Instead of reporting ‘--verbose’
     and ‘--brief’ as they are encountered,
     we report the final status resulting from them. */
  if (verbose_flag)
    puts ("verbose flag is set");
     
  char * files[1000];
  unsigned fileindex = 0;
  files[0] = NULL;
  /* Print any remaining command line arguments (not options). */
  if (optind < argc) {
      printf ("non-option ARGV-elements: ");
		while (optind < argc) {
			files[fileindex++] = argv[optind];
			printf ("%s ", argv[optind++]);
		}
		cout << fileindex << endl;
      files[fileindex] = NULL;
		cout << fileindex << endl;
    }

  char * ptr = NULL;
  if (deobscure_flag) {
    Dictionary d;
    d.loadFile(strtok(dictionary_files, ","));
    while ((ptr = strtok(NULL, ",")))
      d.loadFile(ptr);
  } else {
    Restricted r;
    r.loadFile(strtok(restricted_files, ","));
    while ((ptr = strtok(NULL, ",")))
      r.loadFile(ptr);
    Obscurator o;
		cout << fileindex << endl;
    o.obscure(files, output_file, r);
  }
  exit (0);
}
示例#8
0
void GDAPI godot_dictionary_erase(godot_dictionary *p_self, const godot_variant *p_key) {
	Dictionary *self = (Dictionary *)p_self;
	const Variant *key = (const Variant *)p_key;
	self->erase(*key);
}
示例#9
0
void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,const PropertyInfo& p_hint) {

	switch(p_property.get_type()) {

		case Variant::NIL: {

			f->store_32(VARIANT_NIL);
			// don't store anything
		} break;
		case Variant::BOOL: {

			f->store_32(VARIANT_BOOL);
			bool val=p_property;
			f->store_32(val);
		} break;
		case Variant::INT: {

			f->store_32(VARIANT_INT);
			int val=p_property;
			f->store_32(val);
		} break;
		case Variant::REAL: {

			f->store_32(VARIANT_REAL);
			real_t val=p_property;
			f->store_real(val);

		} break;
		case Variant::STRING: {

			f->store_32(VARIANT_STRING);
			String val=p_property;
			save_unicode_string(val);

		} break;
		case Variant::VECTOR2: {

			f->store_32(VARIANT_VECTOR2);
			Vector2 val=p_property;
			f->store_real(val.x);
			f->store_real(val.y);

		} break;
		case Variant::RECT2: {

			f->store_32(VARIANT_RECT2);
			Rect2 val=p_property;
			f->store_real(val.pos.x);
			f->store_real(val.pos.y);
			f->store_real(val.size.x);
			f->store_real(val.size.y);

		} break;
		case Variant::VECTOR3: {

			f->store_32(VARIANT_VECTOR3);
			Vector3 val=p_property;
			f->store_real(val.x);
			f->store_real(val.y);
			f->store_real(val.z);

		} break;
		case Variant::PLANE: {

			f->store_32(VARIANT_PLANE);
			Plane val=p_property;
			f->store_real(val.normal.x);
			f->store_real(val.normal.y);
			f->store_real(val.normal.z);
			f->store_real(val.d);

		} break;
		case Variant::QUAT: {

			f->store_32(VARIANT_QUAT);
			Quat val=p_property;
			f->store_real(val.x);
			f->store_real(val.y);
			f->store_real(val.z);
			f->store_real(val.w);

		} break;
		case Variant::_AABB: {

			f->store_32(VARIANT_AABB);
			AABB val=p_property;
			f->store_real(val.pos.x);
			f->store_real(val.pos.y);
			f->store_real(val.pos.z);
			f->store_real(val.size.x);
			f->store_real(val.size.y);
			f->store_real(val.size.z);

		} break;
		case Variant::MATRIX32: {

			f->store_32(VARIANT_MATRIX32);
			Matrix32 val=p_property;
			f->store_real(val.elements[0].x);
			f->store_real(val.elements[0].y);
			f->store_real(val.elements[1].x);
			f->store_real(val.elements[1].y);
			f->store_real(val.elements[2].x);
			f->store_real(val.elements[2].y);

		} break;
		case Variant::MATRIX3: {

			f->store_32(VARIANT_MATRIX3);
			Matrix3 val=p_property;
			f->store_real(val.elements[0].x);
			f->store_real(val.elements[0].y);
			f->store_real(val.elements[0].z);
			f->store_real(val.elements[1].x);
			f->store_real(val.elements[1].y);
			f->store_real(val.elements[1].z);
			f->store_real(val.elements[2].x);
			f->store_real(val.elements[2].y);
			f->store_real(val.elements[2].z);

		} break;
		case Variant::TRANSFORM: {

			f->store_32(VARIANT_TRANSFORM);
			Transform val=p_property;
			f->store_real(val.basis.elements[0].x);
			f->store_real(val.basis.elements[0].y);
			f->store_real(val.basis.elements[0].z);
			f->store_real(val.basis.elements[1].x);
			f->store_real(val.basis.elements[1].y);
			f->store_real(val.basis.elements[1].z);
			f->store_real(val.basis.elements[2].x);
			f->store_real(val.basis.elements[2].y);
			f->store_real(val.basis.elements[2].z);
			f->store_real(val.origin.x);
			f->store_real(val.origin.y);
			f->store_real(val.origin.z);

		} break;
		case Variant::COLOR: {

			f->store_32(VARIANT_COLOR);
			Color val=p_property;
			f->store_real(val.r);
			f->store_real(val.g);
			f->store_real(val.b);
			f->store_real(val.a);

		} break;
		case Variant::IMAGE: {

			f->store_32(VARIANT_IMAGE);
			Image val =p_property;
			if (val.empty()) {
				f->store_32(IMAGE_ENCODING_EMPTY);
				break;
			}

			int encoding=IMAGE_ENCODING_RAW;
			float quality=0.7;

			if (val.get_format() <= Image::FORMAT_INDEXED_ALPHA) {
				//can only compress uncompressed stuff

				if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSY && Image::lossy_packer) {
					encoding=IMAGE_ENCODING_LOSSY;
					float qs=p_hint.hint_string.to_double();
					if (qs!=0.0)
						quality=qs;

				} else if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS && Image::lossless_packer) {
					encoding=IMAGE_ENCODING_LOSSLESS;

				}
			}

			f->store_32(encoding); //raw encoding

			if (encoding==IMAGE_ENCODING_RAW) {


				f->store_32(val.get_width());
				f->store_32(val.get_height());
				f->store_32(val.get_mipmaps());
				switch(val.get_format()) {

					case Image::FORMAT_GRAYSCALE: f->store_32(IMAGE_FORMAT_GRAYSCALE ); break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255
					case Image::FORMAT_INTENSITY: f->store_32(IMAGE_FORMAT_INTENSITY ); break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255
					case Image::FORMAT_GRAYSCALE_ALPHA: f->store_32(IMAGE_FORMAT_GRAYSCALE_ALPHA ); break; ///< two bytes per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255. alpha 0-255
					case Image::FORMAT_RGB: f->store_32(IMAGE_FORMAT_RGB ); break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B
					case Image::FORMAT_RGBA: f->store_32(IMAGE_FORMAT_RGBA ); break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B: f->store_32(IMAGE_FORMAT_ ); break; one byte A
					case Image::FORMAT_INDEXED: f->store_32(IMAGE_FORMAT_INDEXED ); break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*3 bytes of palette
					case Image::FORMAT_INDEXED_ALPHA: f->store_32(IMAGE_FORMAT_INDEXED_ALPHA ); break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*4 bytes of palette (alpha)
					case Image::FORMAT_BC1: f->store_32(IMAGE_FORMAT_BC1 ); break; // DXT1
					case Image::FORMAT_BC2: f->store_32(IMAGE_FORMAT_BC2 ); break; // DXT3
					case Image::FORMAT_BC3: f->store_32(IMAGE_FORMAT_BC3 ); break; // DXT5
					case Image::FORMAT_BC4: f->store_32(IMAGE_FORMAT_BC4 ); break; // ATI1
					case Image::FORMAT_BC5: f->store_32(IMAGE_FORMAT_BC5 ); break; // ATI2
					case Image::FORMAT_PVRTC2: f->store_32(IMAGE_FORMAT_PVRTC2 ); break;
					case Image::FORMAT_PVRTC2_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC2_ALPHA ); break;
					case Image::FORMAT_PVRTC4: f->store_32(IMAGE_FORMAT_PVRTC4 ); break;
					case Image::FORMAT_PVRTC4_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC4_ALPHA ); break;
					case Image::FORMAT_ETC: f->store_32(IMAGE_FORMAT_ETC); break;
					case Image::FORMAT_ATC: f->store_32(IMAGE_FORMAT_ATC); break;
					case Image::FORMAT_ATC_ALPHA_EXPLICIT: f->store_32(IMAGE_FORMAT_ATC_ALPHA_EXPLICIT); break;
					case Image::FORMAT_ATC_ALPHA_INTERPOLATED: f->store_32(IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED); break;
					case Image::FORMAT_CUSTOM: f->store_32(IMAGE_FORMAT_CUSTOM ); break;
					default: {}

				}

				int dlen = val.get_data().size();
				f->store_32(dlen);
				DVector<uint8_t>::Read r = val.get_data().read();
				f->store_buffer(r.ptr(),dlen);
				_pad_buffer(dlen);
			} else {

				DVector<uint8_t> data;
				if (encoding==IMAGE_ENCODING_LOSSY) {
					data=Image::lossy_packer(val,quality);

				} else if (encoding==IMAGE_ENCODING_LOSSLESS) {
					data=Image::lossless_packer(val);

				}

				int ds=data.size();
				f->store_32(ds);
				if (ds>0) {
					DVector<uint8_t>::Read r = data.read();
					f->store_buffer(r.ptr(),ds);

					_pad_buffer(ds);

				}
			}

		} break;
		case Variant::NODE_PATH: {
			f->store_32(VARIANT_NODE_PATH);
			NodePath np=p_property;
			f->store_16(np.get_name_count());
			uint16_t snc = np.get_subname_count();
			if (np.is_absolute())
				snc|=0x8000;
			f->store_16(snc);
			for(int i=0;i<np.get_name_count();i++)
				f->store_32(get_string_index(np.get_name(i)));
			for(int i=0;i<np.get_subname_count();i++)
				f->store_32(get_string_index(np.get_subname(i)));
			f->store_32(get_string_index(np.get_property()));

		} break;
		case Variant::_RID: {

			f->store_32(VARIANT_RID);
			WARN_PRINT("Can't save RIDs");
			RID val = p_property;
			f->store_32(val.get_id());
		} break;
		case Variant::OBJECT: {

			f->store_32(VARIANT_OBJECT);
			RES res = p_property;
			if (res.is_null()) {
				f->store_32(OBJECT_EMPTY);
				return; // don't save it
			}

			if (res->get_path().length() && res->get_path().find("::")==-1) {
				f->store_32(OBJECT_EXTERNAL_RESOURCE);
				save_unicode_string(res->get_save_type());
				String path=relative_paths?local_path.path_to_file(res->get_path()):res->get_path();
				save_unicode_string(path);
			} else {

				if (!resource_map.has(res)) {
					f->store_32(OBJECT_EMPTY);
					ERR_EXPLAIN("Resource was not pre cached for the resource section, bug?");
					ERR_FAIL();
				}

				f->store_32(OBJECT_INTERNAL_RESOURCE);
				f->store_32(resource_map[res]);
				//internal resource
			}


		} break;
		case Variant::INPUT_EVENT: {

			f->store_32(VARIANT_INPUT_EVENT);
			WARN_PRINT("Can't save InputEvent (maybe it could..)");
		} break;
		case Variant::DICTIONARY: {

			f->store_32(VARIANT_DICTIONARY);
			Dictionary d = p_property;
			f->store_32(uint32_t(d.size())|(d.is_shared()?0x80000000:0));

			List<Variant> keys;
			d.get_key_list(&keys);

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

				//if (!_check_type(dict[E->get()]))
				//	continue;

				write_variant(E->get());
				write_variant(d[E->get()]);
			}


		} break;
		case Variant::ARRAY: {

			f->store_32(VARIANT_ARRAY);
			Array a=p_property;
			f->store_32(uint32_t(a.size())|(a.is_shared()?0x80000000:0));
			for(int i=0;i<a.size();i++) {

				write_variant(a[i]);
			}

		} break;
		case Variant::RAW_ARRAY: {

			f->store_32(VARIANT_RAW_ARRAY);
			DVector<uint8_t> arr = p_property;
			int len=arr.size();
			f->store_32(len);
			DVector<uint8_t>::Read r = arr.read();
			f->store_buffer(r.ptr(),len);
			_pad_buffer(len);

		} break;
		case Variant::INT_ARRAY: {

			f->store_32(VARIANT_INT_ARRAY);
			DVector<int> arr = p_property;
			int len=arr.size();
			f->store_32(len);
			DVector<int>::Read r = arr.read();
			for(int i=0;i<len;i++)
				f->store_32(r[i]);

		} break;
		case Variant::REAL_ARRAY: {

			f->store_32(VARIANT_REAL_ARRAY);
			DVector<real_t> arr = p_property;
			int len=arr.size();
			f->store_32(len);
			DVector<real_t>::Read r = arr.read();
			for(int i=0;i<len;i++) {
				f->store_real(r[i]);
			}

		} break;
		case Variant::STRING_ARRAY: {

			f->store_32(VARIANT_STRING_ARRAY);
			DVector<String> arr = p_property;
			int len=arr.size();
			f->store_32(len);
			DVector<String>::Read r = arr.read();
			for(int i=0;i<len;i++) {
				save_unicode_string(r[i]);
			}

		} break;
		case Variant::VECTOR3_ARRAY: {

			f->store_32(VARIANT_VECTOR3_ARRAY);
			DVector<Vector3> arr = p_property;
			int len=arr.size();
			f->store_32(len);
			DVector<Vector3>::Read r = arr.read();
			for(int i=0;i<len;i++) {
				f->store_real(r[i].x);
				f->store_real(r[i].y);
				f->store_real(r[i].z);
			}

		} break;
		case Variant::VECTOR2_ARRAY: {

			f->store_32(VARIANT_VECTOR2_ARRAY);
			DVector<Vector2> arr = p_property;
			int len=arr.size();
			f->store_32(len);
			DVector<Vector2>::Read r = arr.read();
			for(int i=0;i<len;i++) {
				f->store_real(r[i].x);
				f->store_real(r[i].y);
			}

		} break;
		case Variant::COLOR_ARRAY: {

			f->store_32(VARIANT_COLOR_ARRAY);
			DVector<Color> arr = p_property;
			int len=arr.size();
			f->store_32(len);
			DVector<Color>::Read r = arr.read();
			for(int i=0;i<len;i++) {
				f->store_real(r[i].r);
				f->store_real(r[i].g);
				f->store_real(r[i].b);
				f->store_real(r[i].a);
			}

		} break;
		default: {

			ERR_EXPLAIN("Invalid variant");
			ERR_FAIL();
		}
	}
}
示例#10
0
void FileSystemDock::_notification(int p_what) {

	switch(p_what) {

		case NOTIFICATION_RESIZED: {


			bool new_mode = get_size().height < get_viewport_rect().size.height*3/4;

			if (new_mode != split_mode ) {

				split_mode=new_mode;

				//print_line("SPLIT MODE? "+itos(split_mode));
				if (split_mode) {

					file_list_vb->hide();
					tree->set_custom_minimum_size(Size2(0,0));
					tree->set_v_size_flags(SIZE_EXPAND_FILL);
					button_back->show();
				} else {

					tree->show();
					file_list_vb->show();
					tree->set_custom_minimum_size(Size2(0,200)*EDSCALE);
					tree->set_v_size_flags(SIZE_FILL);
					button_back->hide();
					if (!EditorFileSystem::get_singleton()->is_scanning()) {
						_fs_changed();
					}
				}
			}


		} break;
		case NOTIFICATION_ENTER_TREE: {

			if (initialized)
				return;
			initialized=true;

			EditorFileSystem::get_singleton()->connect("filesystem_changed",this,"_fs_changed");
			EditorResourcePreview::get_singleton()->connect("preview_invalidated",this,"_preview_invalidated");

			button_reload->set_icon( get_icon("Reload","EditorIcons"));
			button_favorite->set_icon( get_icon("Favorites","EditorIcons"));
			//button_instance->set_icon( get_icon("Add","EditorIcons"));
			//button_open->set_icon( get_icon("Folder","EditorIcons"));
			button_back->set_icon( get_icon("Filesystem","EditorIcons"));
			if (display_mode == DISPLAY_THUMBNAILS) {
				button_display_mode->set_icon(get_icon("FileList","EditorIcons"));
			} else {
				button_display_mode->set_icon(get_icon("FileThumbnail","EditorIcons"));
			}
			button_display_mode->connect("pressed",this,"_change_file_display");
			//file_options->set_icon( get_icon("Tools","EditorIcons"));
			files->connect("item_activated",this,"_select_file");
			button_hist_next->connect("pressed",this,"_fw_history");
			button_hist_prev->connect("pressed",this,"_bw_history");
			search_icon->set_texture( get_icon("Zoom","EditorIcons"));

			button_hist_next->set_icon( get_icon("Forward","EditorIcons"));
			button_hist_prev->set_icon( get_icon("Back","EditorIcons"));
			file_options->connect("item_pressed",this,"_file_option");


			button_back->connect("pressed",this,"_go_to_tree",varray(),CONNECT_DEFERRED);
			current_path->connect("text_entered",this,"_go_to_dir");
			_update_tree(); //maybe it finished already

			if (EditorFileSystem::get_singleton()->is_scanning()) {
				_set_scannig_mode();
			}

		} break;
		case NOTIFICATION_PROCESS: {
			if (EditorFileSystem::get_singleton()->is_scanning()) {
				scanning_progress->set_val(EditorFileSystem::get_singleton()->get_scanning_progress()*100);
			}
		} break;
		case NOTIFICATION_EXIT_TREE: {

		} break;
		case NOTIFICATION_DRAG_BEGIN: {

			Dictionary dd = get_viewport()->gui_get_drag_data();
			if (tree->is_visible() && dd.has("type") ) {
				if  ( (String(dd["type"])=="files") || (String(dd["type"])=="files_and_dirs") || (String(dd["type"])=="resource")) {
					tree->set_drop_mode_flags(Tree::DROP_MODE_ON_ITEM);
				}
				if  ( (String(dd["type"])=="favorite") ) {
					tree->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN);
				}
			}


		} break;
		case NOTIFICATION_DRAG_END: {

			tree->set_drop_mode_flags(0);

		} break;
		case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {

			int new_mode = int(EditorSettings::get_singleton()->get("filesystem_dock/display_mode"));

			if (new_mode != display_mode) {
				set_display_mode(new_mode);
			} else {
				_update_files(true);
			}
		} break;
	}

}
示例#11
0
void GDAPI godot_dictionary_clear(godot_dictionary *p_self) {
	Dictionary *self = (Dictionary *)p_self;
	self->clear();
}
示例#12
0
bool Tokenizer<N, P>::open(const Param &param) {
  close();

  const std::string prefix = param.template get<std::string>("dicdir");

  CHECK_FALSE(unkdic_.open(create_filename
                                 (prefix, UNK_DIC_FILE).c_str()))
      << unkdic_.what();
  CHECK_FALSE(property_.open(param)) << property_.what();

  Dictionary *sysdic = new Dictionary;

  CHECK_FALSE(sysdic->open
                    (create_filename(prefix, SYS_DIC_FILE).c_str()))
      << sysdic->what();

  CHECK_FALSE(sysdic->type() == 0)
      << "not a system dictionary: " << prefix;

  property_.set_charset(sysdic->charset());
  dic_.push_back(sysdic);

  const std::string userdic = param.template get<std::string>("userdic");
  if (!userdic.empty()) {
    scoped_fixed_array<char, BUF_SIZE> buf;
    scoped_fixed_array<char *, BUF_SIZE> dicfile;
    std::strncpy(buf.get(), userdic.c_str(), buf.size());
    const size_t n = tokenizeCSV(buf.get(), dicfile.get(), dicfile.size());
    for (size_t i = 0; i < n; ++i) {
      Dictionary *d = new Dictionary;
      CHECK_FALSE(d->open(dicfile[i])) << d->what();
      CHECK_FALSE(d->type() == 1)
          << "not a user dictionary: " << dicfile[i];
      CHECK_FALSE(sysdic->isCompatible(*d))
          << "incompatible dictionary: " << dicfile[i];
      dic_.push_back(d);
    }
  }

  dictionary_info_ = 0;
  dictionary_info_freelist_.free();
  for (int i = static_cast<int>(dic_.size() - 1); i >= 0; --i) {
    DictionaryInfo *d = dictionary_info_freelist_.alloc();
    d->next          = dictionary_info_;
    d->filename      = dic_[i]->filename();
    d->charset       = dic_[i]->charset();
    d->size          = dic_[i]->size();
    d->lsize         = dic_[i]->lsize();
    d->rsize         = dic_[i]->rsize();
    d->type          = dic_[i]->type();
    d->version       = dic_[i]->version();
    dictionary_info_ = d;
  }

  unk_tokens_.clear();
  for (size_t i = 0; i < property_.size(); ++i) {
    const char *key = property_.name(i);
    const Dictionary::result_type n = unkdic_.exactMatchSearch(key);
    CHECK_FALSE(n.value != -1) << "cannot find UNK category: " << key;
    const Token *token = unkdic_.token(n);
    size_t size = unkdic_.token_size(n);
    unk_tokens_.push_back(std::make_pair(token, size));
  }

  space_ = property_.getCharInfo(0x20);  // ad-hoc

  bos_feature_.reset_string(param.template get<std::string>("bos-feature"));

  const std::string tmp = param.template get<std::string>("unk-feature");
  unk_feature_.reset(0);
  if (!tmp.empty()) {
    unk_feature_.reset_string(tmp);
  }

  CHECK_FALSE(*bos_feature_ != '\0')
      << "bos-feature is undefined in dicrc";

  max_grouping_size_ = param.template get<size_t>("max-grouping-size");
  if (max_grouping_size_ == 0) {
    max_grouping_size_ = DEFAULT_MAX_GROUPING_SIZE;
  }

  return true;
}
示例#13
0
void WordsWithTotalChoices::update(Dictionary const& dictionary, Word const guess)
{
	choices_.push_back(guess);
	count_ += dictionary.anagramCount(guess);
}
示例#14
0
int TreeScorerResult::Calculate(
                                Dictionary & dict,
                                const TreeScorerBoundVariables & bound_variables,
                                const ElapsedTimeConstraint & constraints,
                                TrTrace *trace_log
                               ) const
{
 if( type==NumberScoreType )
  return score;
 else if( type==NGramScoreType )
  {
   lem::MCollect<const Solarix::Word_Form*> vars;
   for( lem::Container::size_type i=0; i<args.size(); ++i )
   {
    const Solarix::Word_Form * wf = bound_variables.GetVariable( args[i] );
    if( wf==NULL )
     {
      lem::MemFormatter mem;
      mem.printf( "tree_scorer: can not find bound variable %us", args[i].c_str() );
      throw lem::E_BaseException( mem.string() );
     }

    vars.push_back(wf);
   }

   KB_CheckingResult res = dict.GetLexAuto().GetKnowledgeBase().Prove( id_fact, vars );
   if( res.IsMatched() )
    return res.GetInt();
   else
    return 0;
  }
 else if( type==FuncScoreType )
  {
   TrFunContext ctx0( (TrFunContext*)NULL );

   TrContextInvokation ctx2( &ctx0 );

   for( lem::Container::size_type i=0; i<args.size(); ++i )
   {
    const Solarix::Word_Form * wf = bound_variables.GetVariable( args[i] );
    if( wf==NULL )
     {
      lem::MemFormatter mem;
      mem.printf( "tree_scorer: can not find bound variable %us", args[i].c_str() );
      throw lem::E_BaseException( mem.string() );
     }

    lem::Ptr<TrValue> this_wordform( new TrValue( new Tree_Node(*wf), true ) );
    ctx2.AddVar( args[i], this_wordform );
   }

   lem::Ptr<TrValue> fun_res = score_fun->Run( constraints, dict.GetLexAuto(), ctx2, trace_log );

   if( fun_res->GetType().IsInt() )
    {
     int res_int = fun_res->GetInt();
     return res_int;
    }
   else
    {
     #if LEM_DEBUGGING==1
     if( trace_log!=NULL )
      trace_log->PrintStack(*lem::mout);
     #endif

     lem::UFString msg( lem::format_str( L"Score function must return int, not %s", fun_res->GetType().GetName().c_str() ) );
     throw E_BaseException(msg.c_str());
    }
  }
 else
  {
   LEM_STOPIT;
  }

 return 0;
}
示例#15
0
int main( int argc, char** argv )
{
    KApplication app(argc, argv, "KSpell2Test");

    Broker::Ptr broker = Broker::openBroker();

    kdDebug()<< "Clients are "   << broker->clients()   << endl;
    kdDebug()<< "Languages are " << broker->languages() << endl;

    Dictionary *dict = broker->dictionary( "en_US" );

    QStringList words;

    words << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted"
          << "hello" << "helo" << "enviroment" << "guvernment" << "farted";

    QTime mtime;
    mtime.start();
    for ( QStringList::Iterator itr = words.begin(); itr != words.end(); ++itr ) {
        if ( dict && !dict->check( *itr ) ) {
            //kdDebug()<<"Word " << *itr <<" is misspelled"<<endl;
            QStringList sug = dict->suggest( *itr );
            //kdDebug()<<"Suggestions : "<<sug<<endl;
        }
    }
    //mtime.stop();
    kdDebug()<<"Elapsed time is "<<mtime.elapsed()<<endl;

    delete dict;

    return 0;
}
示例#16
0
jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_arg, bool force_jobject = false) {

	jvalret v;

	switch(p_type) {

		case Variant::BOOL: {

			if (force_jobject) {
				jclass bclass = env->FindClass("java/lang/Boolean");
				jmethodID ctor = env->GetMethodID(bclass, "<init>", "(Z)V");
				jvalue val;
				val.z = (bool)(*p_arg);
				jobject obj = env->NewObjectA(bclass, ctor, &val);
				v.val.l = obj;
				v.obj=obj;
				env->DeleteLocalRef(bclass);
			} else {
				v.val.z=*p_arg;

			};
		} break;
		case Variant::INT: {

			if (force_jobject) {

				jclass bclass = env->FindClass("java/lang/Integer");
				jmethodID ctor = env->GetMethodID(bclass, "<init>", "(I)V");
				jvalue val;
				val.i = (int)(*p_arg);
				jobject obj = env->NewObjectA(bclass, ctor, &val);
				v.val.l = obj;
				v.obj=obj;
				env->DeleteLocalRef(bclass);

			} else {
				v.val.i=*p_arg;

			};
		} break;
		case Variant::REAL: {

			if (force_jobject) {

				jclass bclass = env->FindClass("java/lang/Double");
				jmethodID ctor = env->GetMethodID(bclass, "<init>", "(D)V");
				jvalue val;
				val.d = (double)(*p_arg);
				jobject obj = env->NewObjectA(bclass, ctor, &val);
				v.val.l = obj;
				v.obj=obj;
				env->DeleteLocalRef(bclass);

			} else {
				v.val.f=*p_arg;
			};
		} break;
		case Variant::STRING: {

			String s = *p_arg;
			jstring jStr = env->NewStringUTF(s.utf8().get_data());
			v.val.l=jStr;
			v.obj=jStr;
		} break;
		case Variant::STRING_ARRAY: {

			DVector<String> sarray = *p_arg;
			jobjectArray arr = env->NewObjectArray(sarray.size(),env->FindClass("java/lang/String"),env->NewStringUTF(""));

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

				jstring str = env->NewStringUTF( sarray[j].utf8().get_data() );
				env->SetObjectArrayElement(arr,j,str);
				env->DeleteLocalRef(str);
			}
			v.val.l=arr;
			v.obj=arr;

		} break;

		case Variant::DICTIONARY: {

			Dictionary dict = *p_arg;
			jclass dclass = env->FindClass("org/godotengine/godot/Dictionary");
			jmethodID ctor = env->GetMethodID(dclass, "<init>", "()V");
			jobject jdict = env->NewObject(dclass, ctor);

			Array keys = dict.keys();

			jobjectArray jkeys = env->NewObjectArray(keys.size(), env->FindClass("java/lang/String"), env->NewStringUTF(""));
			for (int j=0; j<keys.size(); j++) {
				jstring str = env->NewStringUTF(String(keys[j]).utf8().get_data());
				env->SetObjectArrayElement(jkeys, j, str);
				env->DeleteLocalRef(str);
			};

			jmethodID set_keys = env->GetMethodID(dclass, "set_keys", "([Ljava/lang/String;)V");
			jvalue val;
			val.l = jkeys;
			env->CallVoidMethodA(jdict, set_keys, &val);
			env->DeleteLocalRef(jkeys);

			jobjectArray jvalues = env->NewObjectArray(keys.size(), env->FindClass("java/lang/Object"), NULL);

			for (int j=0; j<keys.size(); j++) {
				Variant var = dict[keys[j]];
				jvalret v = _variant_to_jvalue(env, var.get_type(), &var, true);
				env->SetObjectArrayElement(jvalues, j, v.val.l);
				if (v.obj) {
					env->DeleteLocalRef(v.obj);
				}
			};

			jmethodID set_values = env->GetMethodID(dclass, "set_values", "([Ljava/lang/Object;)V");
			val.l = jvalues;
			env->CallVoidMethodA(jdict, set_values, &val);
			env->DeleteLocalRef(jvalues);
			env->DeleteLocalRef(dclass);

			v.val.l = jdict;
			v.obj=jdict;
		} break;

		case Variant::INT_ARRAY: {

			DVector<int> array = *p_arg;
			jintArray arr = env->NewIntArray(array.size());
			DVector<int>::Read r = array.read();
			env->SetIntArrayRegion(arr,0,array.size(),r.ptr());
			v.val.l=arr;
			v.obj=arr;

		} break;
		case Variant::RAW_ARRAY: {
			DVector<uint8_t> array = *p_arg;
			jbyteArray arr = env->NewByteArray(array.size());
			DVector<uint8_t>::Read r = array.read();
			env->SetByteArrayRegion(arr,0,array.size(),reinterpret_cast<const signed char*>(r.ptr()));
			v.val.l=arr;
			v.obj=arr;

		} break;
		case Variant::REAL_ARRAY: {

			DVector<float> array = *p_arg;
			jfloatArray arr = env->NewFloatArray(array.size());
			DVector<float>::Read r = array.read();
			env->SetFloatArrayRegion(arr,0,array.size(),r.ptr());
			v.val.l=arr;
			v.obj=arr;

		} break;
		default: {

			v.val.i = 0;
		} break;

	}
	return v;
};
示例#17
0
bool GameOverScene::initDict(cocos2d::CCDictionary *dic)
{
    ThirdPartyHelper::setAd(SET_AD_SHOW);
    godelay = 0;
    
    Size vs = Director::getInstance()->getVisibleSize();
    Vec2 vo = Director::getInstance()->getVisibleOrigin();
    
    int step = ((CCInteger*)dic->objectForKey("step"))->getValue();
    int level = ((CCInteger*)dic->objectForKey("level"))->getValue();
    
    UserDefault::getInstance()->setBoolForKey(StringUtils::format("level%d_lock",level+1).c_str(), false);
    UserDefault::getInstance()->flush();
    
    auto gameover = ui::Text::create(StringUtils::format("Level %d Pass!",level+1), Common_Font, 70);
    gameover->setPosition(Vec2(vs.width/2, vs.height/3*2 + vo.y));
    gameover->setColor(Color3B::BLACK);
    this->addChild(gameover);
    show(gameover);
    
    int best = UserDefault::getInstance()->getIntegerForKey(StringUtils::format("level%d_step",level).c_str(), INT16_MAX);
    if (step<best) {
        best = step;
        UserDefault::getInstance()->setIntegerForKey(StringUtils::format("level%d_step",level).c_str(), best);
    }
    
    auto scorelabel = ui::Text::create(StringUtils::format("Step:%d",step), Common_Font, 50);
    scorelabel->setPosition(Vec2(vs.width/2, vs.height/2+scorelabel->getContentSize().height/2 + vo.y));
    scorelabel->setColor(Color3B::BLACK);
    this->addChild(scorelabel);
    show(scorelabel);
    
    auto bestlabel = ui::Text::create(StringUtils::format("Best:%d",best), Common_Font, 50);
    bestlabel->setPosition(Vec2(vs.width/2, vs.height/2-bestlabel->getContentSize().height/2 + vo.y));
    bestlabel->setColor(Color3B::BLACK);
    this->addChild(bestlabel);
    show(bestlabel);
    
    float by = vs.height/6 + vo.y;
    float fs = 40;
    
    if (level >= LVCOUNT-1) {
        
    }else{
        auto replay = ui::Button::create("rb.png");
        replay->setTitleText("Next");
        replay->setTitleFontSize(fs);
        replay->setPosition(Vec2(vs.width/2, vs.height/3 + vo.y));
        replay->addTouchEventListener([level](Ref *ps,ui::Widget::TouchEventType type){
            if (type == ui::Widget::TouchEventType::ENDED) {
                Dictionary *dict = Dictionary::create();
                dict->setObject(CCInteger::create(level+1),"level");
                Director::getInstance()->replaceScene(PlayScene::createScene(dict));
            }
        });
        this->addChild(replay);
        show(replay);
    }
    
    auto back = ui::Button::create("rr.png");
    back->setPosition(Vec2(vs.width/3, by));
    back->setTitleFontSize(fs);
    back->setTitleText("Back");
    back->addTouchEventListener([](Ref *ps,ui::Widget::TouchEventType type){
        if (type == ui::Widget::TouchEventType::ENDED) {
            Director::getInstance()->replaceScene(HelloWorld::createScene());
        }
    });
    this->addChild(back);
    show(back);
    
    auto share = LHShareButton::defaultButton("rr.png","Lucky Puzzle!");
    share->setTitleFontSize(fs);
    share->setTitleText("Share");
    share->setPosition(Vec2(vs.width/3*2, by));
    this->addChild(share);
    show(share);
    
	return true;
}
示例#18
0
	static size_t Size(const Dictionary& dict)
	{
		return dict.Size();
	}
示例#19
0
bool fillTestEventConstructorInit(TestEventConstructorInit& eventInit, const Dictionary& options)
{
    options.get("attr2", eventInit.attr2);
    return true;
}
示例#20
0
	static void SetItem(Dictionary& dict, const char* key, const Variant& value)
	{
		dict.Set(key, value);
	}
示例#21
0
Dictionary generateCustomDictionary(int nMarkers, int markerSize,
                                    const Dictionary &baseDictionary) {

    Dictionary out;
    out.markerSize = markerSize;

    // theoretical maximum intermarker distance
    // See S. Garrido-Jurado, R. Muñoz-Salinas, F. J. Madrid-Cuevas, and M. J. Marín-Jiménez. 2014.
    // "Automatic generation and detection of highly reliable fiducial markers under occlusion".
    // Pattern Recogn. 47, 6 (June 2014), 2280-2292. DOI=10.1016/j.patcog.2014.01.005
    int C = (int)std::floor(float(markerSize * markerSize) / 4.f);
    int tau = 2 * (int)std::floor(float(C) * 4.f / 3.f);

    // if baseDictionary is provided, calculate its intermarker distance
    if(baseDictionary.bytesList.rows > 0) {
        CV_Assert(baseDictionary.markerSize == markerSize);
        out.bytesList = baseDictionary.bytesList.clone();

        int minDistance = markerSize * markerSize + 1;
        for(int i = 0; i < out.bytesList.rows; i++) {
            Mat markerBytes = out.bytesList.rowRange(i, i + 1);
            Mat markerBits = Dictionary::getBitsFromByteList(markerBytes, markerSize);
            minDistance = min(minDistance, _getSelfDistance(markerBits));
            for(int j = i + 1; j < out.bytesList.rows; j++) {
                minDistance = min(minDistance, out.getDistanceToId(markerBits, j));
            }
        }
        tau = minDistance;
    }

    // current best option
    int bestTau = 0;
    Mat bestMarker;

    // after these number of unproductive iterations, the best option is accepted
    const int maxUnproductiveIterations = 5000;
    int unproductiveIterations = 0;

    while(out.bytesList.rows < nMarkers) {
        Mat currentMarker = _generateRandomMarker(markerSize);

        int selfDistance = _getSelfDistance(currentMarker);
        int minDistance = selfDistance;

        // if self distance is better or equal than current best option, calculate distance
        // to previous accepted markers
        if(selfDistance >= bestTau) {
            for(int i = 0; i < out.bytesList.rows; i++) {
                int currentDistance = out.getDistanceToId(currentMarker, i);
                minDistance = min(currentDistance, minDistance);
                if(minDistance <= bestTau) {
                    break;
                }
            }
        }

        // if distance is high enough, accept the marker
        if(minDistance >= tau) {
            unproductiveIterations = 0;
            bestTau = 0;
            Mat bytes = Dictionary::getByteListFromBits(currentMarker);
            out.bytesList.push_back(bytes);
        } else {
            unproductiveIterations++;

            // if distance is not enough, but is better than the current best option
            if(minDistance > bestTau) {
                bestTau = minDistance;
                bestMarker = currentMarker;
            }

            // if number of unproductive iterarions has been reached, accept the current best option
            if(unproductiveIterations == maxUnproductiveIterations) {
                unproductiveIterations = 0;
                tau = bestTau;
                bestTau = 0;
                Mat bytes = Dictionary::getByteListFromBits(bestMarker);
                out.bytesList.push_back(bytes);
            }
        }
    }

    // update the maximum number of correction bits for the generated dictionary
    out.maxCorrectionBits = (tau - 1) / 2;

    return out;
}
示例#22
0
	static void DelItem(Dictionary& dict, const char* key)
	{
		dict.Remove(key);
	}
示例#23
0
void CodecContext2::open(Dictionary &options, const Codec &codec, OptionalErrorCode ec)
{
    auto prt = options.release();
    open(codec, &prt, ec);
    options.assign(prt);
}
示例#24
0
	static bool Contains(const Dictionary& dict, const char* key)
	{
		return dict.Get(key) != NULL;
	}
Error EditorSceneImporterFBXConv::_parse_nodes(State& state,const Array &p_nodes,Node* p_base) {

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

		Dictionary n = p_nodes[i];
		Spatial *node=NULL;
		bool skip=false;

		String id;
		if (n.has("id")) {
			id=_id(n["id"]);
		}

		print_line("ID: "+id);

		if (state.skeletons.has(id)) {

			Skeleton *skeleton = state.skeletons[id];
			node=skeleton;
			skeleton->localize_rests();
			print_line("IS SKELETON! ");
		} else if (state.bones.has(id)) {
			if (p_base)
				node=p_base->cast_to<Spatial>();
			if (!state.bones[id].has_anim_chan) {
				print_line("no has anim "+id);
			}
			skip=true;
		} else if (n.has("parts")) {
			//is a mesh
			MeshInstance *mesh = memnew( MeshInstance );
			node=mesh;

			Array parts=n["parts"];
			String long_identifier;
			for(int j=0;j<parts.size();j++) {

				Dictionary part=parts[j];
				if (part.has("meshpartid")) {
					String partid=part["meshpartid"];
					long_identifier+=partid;
				}
			}

			Ref<Mesh> m;

			if (state.mesh_cache.has(long_identifier)) {
				m=state.mesh_cache[long_identifier];
			} else {
				m = Ref<Mesh>( memnew( Mesh ) );

				//and parts are surfaces
				for(int j=0;j<parts.size();j++) {

					Dictionary part=parts[j];
					if (part.has("meshpartid")) {
						_add_surface(state,m,part);
					}
				}


				state.mesh_cache[long_identifier]=m;
			}

			mesh->set_mesh(m);
		}

		if (!skip) {

			if (!node) {
				node = memnew( Spatial );
			}

			node->set_name(id);
			node->set_transform(_get_transform(n));
			p_base->add_child(node);
			node->set_owner(state.scene);
		}


		if (n.has("children")) {
			Error err = _parse_nodes(state,n["children"],node);
			if (err)
				return err;
		}
	}

	return OK;
}
示例#26
0
Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len, bool p_object_as_id) {

	uint8_t *buf = r_buffer;

	r_len = 0;

	uint32_t flags = 0;

	switch (p_variant.get_type()) {

		case Variant::INT: {
			int64_t val = p_variant;
			if (val > 0x7FFFFFFF || val < -0x80000000) {
				flags |= ENCODE_FLAG_64;
			}
		} break;
		case Variant::REAL: {

			double d = p_variant;
			float f = d;
			if (double(f) != d) {
				flags |= ENCODE_FLAG_64; //always encode real as double
			}
		} break;
		case Variant::OBJECT: {
			if (p_object_as_id) {
				flags |= ENCODE_FLAG_OBJECT_AS_ID;
			}
		} break;
	}

	if (buf) {
		encode_uint32(p_variant.get_type() | flags, buf);
		buf += 4;
	}
	r_len += 4;

	switch (p_variant.get_type()) {

		case Variant::NIL: {

			//nothing to do
		} break;
		case Variant::BOOL: {

			if (buf) {
				encode_uint32(p_variant.operator bool(), buf);
			}

			r_len += 4;

		} break;
		case Variant::INT: {

			int64_t val = p_variant;
			if (val > 0x7FFFFFFF || val < -0x80000000) {
				//64 bits
				if (buf) {
					encode_uint64(val, buf);
				}

				r_len += 8;
			} else {
				if (buf) {
					encode_uint32(int32_t(val), buf);
				}

				r_len += 4;
			}
		} break;
		case Variant::REAL: {

			double d = p_variant;
			float f = d;
			if (double(f) != d) {
				if (buf) {
					encode_double(p_variant.operator double(), buf);
				}

				r_len += 8;

			} else {

				if (buf) {
					encode_float(p_variant.operator float(), buf);
				}

				r_len += 4;
			}

		} break;
		case Variant::NODE_PATH: {

			NodePath np = p_variant;
			if (buf) {
				encode_uint32(uint32_t(np.get_name_count()) | 0x80000000, buf); //for compatibility with the old format
				encode_uint32(np.get_subname_count(), buf + 4);
				uint32_t flags = 0;
				if (np.is_absolute())
					flags |= 1;
				if (np.get_property() != StringName())
					flags |= 2;

				encode_uint32(flags, buf + 8);

				buf += 12;
			}

			r_len += 12;

			int total = np.get_name_count() + np.get_subname_count();
			if (np.get_property() != StringName())
				total++;

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

				String str;

				if (i < np.get_name_count())
					str = np.get_name(i);
				else if (i < np.get_name_count() + np.get_subname_count())
					str = np.get_subname(i - np.get_subname_count());
				else
					str = np.get_property();

				CharString utf8 = str.utf8();

				int pad = 0;

				if (utf8.length() % 4)
					pad = 4 - utf8.length() % 4;

				if (buf) {
					encode_uint32(utf8.length(), buf);
					buf += 4;
					copymem(buf, utf8.get_data(), utf8.length());
					buf += pad + utf8.length();
				}

				r_len += 4 + utf8.length() + pad;
			}

		} break;
		case Variant::STRING: {

			_encode_string(p_variant, buf, r_len);

		} break;
		// math types

		case Variant::VECTOR2: {

			if (buf) {
				Vector2 v2 = p_variant;
				encode_float(v2.x, &buf[0]);
				encode_float(v2.y, &buf[4]);
			}

			r_len += 2 * 4;

		} break; // 5
		case Variant::RECT2: {

			if (buf) {
				Rect2 r2 = p_variant;
				encode_float(r2.position.x, &buf[0]);
				encode_float(r2.position.y, &buf[4]);
				encode_float(r2.size.x, &buf[8]);
				encode_float(r2.size.y, &buf[12]);
			}
			r_len += 4 * 4;

		} break;
		case Variant::VECTOR3: {

			if (buf) {
				Vector3 v3 = p_variant;
				encode_float(v3.x, &buf[0]);
				encode_float(v3.y, &buf[4]);
				encode_float(v3.z, &buf[8]);
			}

			r_len += 3 * 4;

		} break;
		case Variant::TRANSFORM2D: {

			if (buf) {
				Transform2D val = p_variant;
				for (int i = 0; i < 3; i++) {
					for (int j = 0; j < 2; j++) {

						copymem(&buf[(i * 2 + j) * 4], &val.elements[i][j], sizeof(float));
					}
				}
			}

			r_len += 6 * 4;

		} break;
		case Variant::PLANE: {

			if (buf) {
				Plane p = p_variant;
				encode_float(p.normal.x, &buf[0]);
				encode_float(p.normal.y, &buf[4]);
				encode_float(p.normal.z, &buf[8]);
				encode_float(p.d, &buf[12]);
			}

			r_len += 4 * 4;

		} break;
		case Variant::QUAT: {

			if (buf) {
				Quat q = p_variant;
				encode_float(q.x, &buf[0]);
				encode_float(q.y, &buf[4]);
				encode_float(q.z, &buf[8]);
				encode_float(q.w, &buf[12]);
			}

			r_len += 4 * 4;

		} break;
		case Variant::RECT3: {

			if (buf) {
				Rect3 aabb = p_variant;
				encode_float(aabb.position.x, &buf[0]);
				encode_float(aabb.position.y, &buf[4]);
				encode_float(aabb.position.z, &buf[8]);
				encode_float(aabb.size.x, &buf[12]);
				encode_float(aabb.size.y, &buf[16]);
				encode_float(aabb.size.z, &buf[20]);
			}

			r_len += 6 * 4;

		} break;
		case Variant::BASIS: {

			if (buf) {
				Basis val = p_variant;
				for (int i = 0; i < 3; i++) {
					for (int j = 0; j < 3; j++) {

						copymem(&buf[(i * 3 + j) * 4], &val.elements[i][j], sizeof(float));
					}
				}
			}

			r_len += 9 * 4;

		} break;
		case Variant::TRANSFORM: {

			if (buf) {
				Transform val = p_variant;
				for (int i = 0; i < 3; i++) {
					for (int j = 0; j < 3; j++) {

						copymem(&buf[(i * 3 + j) * 4], &val.basis.elements[i][j], sizeof(float));
					}
				}

				encode_float(val.origin.x, &buf[36]);
				encode_float(val.origin.y, &buf[40]);
				encode_float(val.origin.z, &buf[44]);
			}

			r_len += 12 * 4;

		} break;

		// misc types
		case Variant::COLOR: {

			if (buf) {
				Color c = p_variant;
				encode_float(c.r, &buf[0]);
				encode_float(c.g, &buf[4]);
				encode_float(c.b, &buf[8]);
				encode_float(c.a, &buf[12]);
			}

			r_len += 4 * 4;

		} break;
		/*case Variant::RESOURCE: {

			ERR_EXPLAIN("Can't marshallize resources");
			ERR_FAIL_V(ERR_INVALID_DATA); //no, i'm sorry, no go
		} break;*/
		case Variant::_RID: {

		} break;
		case Variant::OBJECT: {

			if (p_object_as_id) {

				if (buf) {

					Object *obj = p_variant;
					ObjectID id = 0;
					if (obj && ObjectDB::instance_validate(obj)) {
						id = obj->get_instance_id();
					}

					encode_uint64(id, buf);
				}

				r_len += 8;

			} else {
				Object *obj = p_variant;
				if (!obj) {
					if (buf) {
						encode_uint32(0, buf);
						buf += 4;
						r_len += 4;
					}
				} else {
					_encode_string(obj->get_class(), buf, r_len);

					List<PropertyInfo> props;
					obj->get_property_list(&props);

					int pc = 0;
					for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {

						if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
							continue;
						pc++;
					}

					if (buf) {
						encode_uint32(pc, buf);
						buf += 4;
					}

					r_len += 4;

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

						if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
							continue;

						_encode_string(E->get().name, buf, r_len);

						int len;
						Error err = encode_variant(obj->get(E->get().name), buf, len, p_object_as_id);
						if (err)
							return err;
						ERR_FAIL_COND_V(len % 4, ERR_BUG);
						r_len += len;
						if (buf)
							buf += len;
					}
				}
			}

		} break;
		case Variant::DICTIONARY: {

			Dictionary d = p_variant;

			if (buf) {
				encode_uint32(uint32_t(d.size()), buf);
				buf += 4;
			}
			r_len += 4;

			List<Variant> keys;
			d.get_key_list(&keys);

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

				/*
				CharString utf8 = E->->utf8();

				if (buf) {
					encode_uint32(utf8.length()+1,buf);
					buf+=4;
					copymem(buf,utf8.get_data(),utf8.length()+1);
				}

				r_len+=4+utf8.length()+1;
				while (r_len%4)
					r_len++; //pad
				*/
				int len;
				encode_variant(E->get(), buf, len, p_object_as_id);
				ERR_FAIL_COND_V(len % 4, ERR_BUG);
				r_len += len;
				if (buf)
					buf += len;
				encode_variant(d[E->get()], buf, len, p_object_as_id);
				ERR_FAIL_COND_V(len % 4, ERR_BUG);
				r_len += len;
				if (buf)
					buf += len;
			}

		} break;
		case Variant::ARRAY: {

			Array v = p_variant;

			if (buf) {
				encode_uint32(uint32_t(v.size()), buf);
				buf += 4;
			}

			r_len += 4;

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

				int len;
				encode_variant(v.get(i), buf, len, p_object_as_id);
				ERR_FAIL_COND_V(len % 4, ERR_BUG);
				r_len += len;
				if (buf)
					buf += len;
			}

		} break;
		// arrays
		case Variant::POOL_BYTE_ARRAY: {

			PoolVector<uint8_t> data = p_variant;
			int datalen = data.size();
			int datasize = sizeof(uint8_t);

			if (buf) {
				encode_uint32(datalen, buf);
				buf += 4;
				PoolVector<uint8_t>::Read r = data.read();
				copymem(buf, &r[0], datalen * datasize);
			}

			r_len += 4 + datalen * datasize;
			while (r_len % 4)
				r_len++;

		} break;
		case Variant::POOL_INT_ARRAY: {

			PoolVector<int> data = p_variant;
			int datalen = data.size();
			int datasize = sizeof(int32_t);

			if (buf) {
				encode_uint32(datalen, buf);
				buf += 4;
				PoolVector<int>::Read r = data.read();
				for (int i = 0; i < datalen; i++)
					encode_uint32(r[i], &buf[i * datasize]);
			}

			r_len += 4 + datalen * datasize;

		} break;
		case Variant::POOL_REAL_ARRAY: {

			PoolVector<real_t> data = p_variant;
			int datalen = data.size();
			int datasize = sizeof(real_t);

			if (buf) {
				encode_uint32(datalen, buf);
				buf += 4;
				PoolVector<real_t>::Read r = data.read();
				for (int i = 0; i < datalen; i++)
					encode_float(r[i], &buf[i * datasize]);
			}

			r_len += 4 + datalen * datasize;

		} break;
		case Variant::POOL_STRING_ARRAY: {

			PoolVector<String> data = p_variant;
			int len = data.size();

			if (buf) {
				encode_uint32(len, buf);
				buf += 4;
			}

			r_len += 4;

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

				CharString utf8 = data.get(i).utf8();

				if (buf) {
					encode_uint32(utf8.length() + 1, buf);
					buf += 4;
					copymem(buf, utf8.get_data(), utf8.length() + 1);
					buf += utf8.length() + 1;
				}

				r_len += 4 + utf8.length() + 1;
				while (r_len % 4) {
					r_len++; //pad
					if (buf)
						buf++;
				}
			}

		} break;
		case Variant::POOL_VECTOR2_ARRAY: {

			PoolVector<Vector2> data = p_variant;
			int len = data.size();

			if (buf) {
				encode_uint32(len, buf);
				buf += 4;
			}

			r_len += 4;

			if (buf) {

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

					Vector2 v = data.get(i);

					encode_float(v.x, &buf[0]);
					encode_float(v.y, &buf[4]);
					buf += 4 * 2;
				}
			}

			r_len += 4 * 2 * len;

		} break;
		case Variant::POOL_VECTOR3_ARRAY: {

			PoolVector<Vector3> data = p_variant;
			int len = data.size();

			if (buf) {
				encode_uint32(len, buf);
				buf += 4;
			}

			r_len += 4;

			if (buf) {

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

					Vector3 v = data.get(i);

					encode_float(v.x, &buf[0]);
					encode_float(v.y, &buf[4]);
					encode_float(v.z, &buf[8]);
					buf += 4 * 3;
				}
			}

			r_len += 4 * 3 * len;

		} break;
		case Variant::POOL_COLOR_ARRAY: {

			PoolVector<Color> data = p_variant;
			int len = data.size();

			if (buf) {
				encode_uint32(len, buf);
				buf += 4;
			}

			r_len += 4;

			if (buf) {

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

					Color c = data.get(i);

					encode_float(c.r, &buf[0]);
					encode_float(c.g, &buf[4]);
					encode_float(c.b, &buf[8]);
					encode_float(c.a, &buf[12]);
					buf += 4 * 4;
				}
			}

			r_len += 4 * 4 * len;

		} break;
		default: { ERR_FAIL_V(ERR_BUG); }
	}

	return OK;
}
void EditorSceneImporterFBXConv::_parse_surfaces(State& state) {

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

		Dictionary mesh = state.meshes[i];

		ERR_CONTINUE(!mesh.has("attributes"));
		ERR_CONTINUE(!mesh.has("vertices"));
		ERR_CONTINUE(!mesh.has("parts"));

		print_line("MESH #"+itos(i));

		Array attrlist=mesh["attributes"];
		Array vertices=mesh["vertices"];
		bool exists[Mesh::ARRAY_MAX];
		int ofs[Mesh::ARRAY_MAX];
		int weight_max=0;
		int binormal_ofs=-1;
		int weight_ofs[4];

		for(int j=0;j<Mesh::ARRAY_MAX;j++) {
			exists[j]=false;
			ofs[j]=0;
		}
		exists[Mesh::ARRAY_INDEX]=true;
		float stride=0;

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

			String attr=attrlist[j];
			if (attr=="POSITION") {
				exists[Mesh::ARRAY_VERTEX]=true;
				ofs[Mesh::ARRAY_VERTEX]=stride;
				stride+=3;
			} else if (attr=="NORMAL") {
				exists[Mesh::ARRAY_NORMAL]=true;
				ofs[Mesh::ARRAY_NORMAL]=stride;
				stride+=3;
			} else if (attr=="COLOR") {
				exists[Mesh::ARRAY_COLOR]=true;
				ofs[Mesh::ARRAY_COLOR]=stride;
				stride+=4;
			} else if (attr=="COLORPACKED") {
				stride+=1; //ignore
			} else if (attr=="TANGENT") {
				exists[Mesh::ARRAY_TANGENT]=true;
				ofs[Mesh::ARRAY_TANGENT]=stride;
				stride+=3;
			} else if (attr=="BINORMAL") {
				binormal_ofs=stride;
				stride+=3;
			} else if (attr=="TEXCOORD0") {
				exists[Mesh::ARRAY_TEX_UV]=true;
				ofs[Mesh::ARRAY_TEX_UV]=stride;
				stride+=2;
			} else if (attr=="TEXCOORD1") {
				exists[Mesh::ARRAY_TEX_UV2]=true;
				ofs[Mesh::ARRAY_TEX_UV2]=stride;
				stride+=2;
			} else if (attr.begins_with("TEXCOORD")) {
				stride+=2;
			} else if (attr.begins_with("BLENDWEIGHT")) {
				int idx=attr.replace("BLENDWEIGHT","").to_int();
				if (idx==0) {
					exists[Mesh::ARRAY_BONES]=true;
					ofs[Mesh::ARRAY_BONES]=stride;
					exists[Mesh::ARRAY_WEIGHTS]=true;
					ofs[Mesh::ARRAY_WEIGHTS]=stride+1;
				} if (idx<4) {
					weight_ofs[idx]=stride;
					weight_max=MAX(weight_max,idx+1);
				}

				stride+=2;
			}

			print_line("ATTR "+attr+" OFS: "+itos(stride));

		}

		Array parts=mesh["parts"];

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



			Dictionary part=parts[j];
			ERR_CONTINUE(!part.has("indices"));
			ERR_CONTINUE(!part.has("id"));

			print_line("PART: "+String(part["id"]));
			Array indices=part["indices"];
			Map<int,int> iarray;
			Map<int,int> array;

			for(int k=0;k<indices.size();k++) {

				int idx = indices[k];
				if (!iarray.has(idx)) {
					int map_to=array.size();
					iarray[idx]=map_to;
					array[map_to]=idx;
				}
			}

			print_line("indices total "+itos(indices.size())+" vertices used: "+itos(array.size()));

			Array arrays;
			arrays.resize(Mesh::ARRAY_MAX);



			for(int k=0;k<Mesh::ARRAY_MAX;k++) {


				if (!exists[k])
					continue;
				print_line("exists: "+itos(k));
				int lofs = ofs[k];
				switch(k) {

					case Mesh::ARRAY_VERTEX:
					case Mesh::ARRAY_NORMAL: {

						DVector<Vector3> vtx;
						vtx.resize(array.size());
						{
							int len=array.size();
							DVector<Vector3>::Write w = vtx.write();
							for(int l=0;l<len;l++) {

								int pos = array[l];
								w[l].x=vertices[pos*stride+lofs+0];
								w[l].y=vertices[pos*stride+lofs+1];
								w[l].z=vertices[pos*stride+lofs+2];
							}
						}
						arrays[k]=vtx;

					} break;
					case Mesh::ARRAY_TANGENT: {

						if (binormal_ofs<0)
							break;

						DVector<float> tangents;
						tangents.resize(array.size()*4);
						{
							int len=array.size();

							DVector<float>::Write w = tangents.write();
							for(int l=0;l<len;l++) {

								int pos = array[l];
								Vector3 n;
								n.x=vertices[pos*stride+ofs[Mesh::ARRAY_NORMAL]+0];
								n.y=vertices[pos*stride+ofs[Mesh::ARRAY_NORMAL]+1];
								n.z=vertices[pos*stride+ofs[Mesh::ARRAY_NORMAL]+2];
								Vector3 t;
								t.x=vertices[pos*stride+lofs+0];
								t.y=vertices[pos*stride+lofs+1];
								t.z=vertices[pos*stride+lofs+2];
								Vector3 bi;
								bi.x=vertices[pos*stride+binormal_ofs+0];
								bi.y=vertices[pos*stride+binormal_ofs+1];
								bi.z=vertices[pos*stride+binormal_ofs+2];
								float d = bi.dot(n.cross(t));

								w[l*4+0]=t.x;
								w[l*4+1]=t.y;
								w[l*4+2]=t.z;
								w[l*4+3]=d;

							}
						}
						arrays[k]=tangents;

					} break;
					case Mesh::ARRAY_COLOR: {

						DVector<Color> cols;
						cols.resize(array.size());
						{
							int len=array.size();
							DVector<Color>::Write w = cols.write();
							for(int l=0;l<len;l++) {

								int pos = array[l];
								w[l].r=vertices[pos*stride+lofs+0];
								w[l].g=vertices[pos*stride+lofs+1];
								w[l].b=vertices[pos*stride+lofs+2];
								w[l].a=vertices[pos*stride+lofs+3];
							}
						}
						arrays[k]=cols;

					} break;
					case Mesh::ARRAY_TEX_UV:
					case Mesh::ARRAY_TEX_UV2: {

						DVector<Vector2> uvs;
						uvs.resize(array.size());
						{
							int len=array.size();
							DVector<Vector2>::Write w = uvs.write();
							for(int l=0;l<len;l++) {

								int pos = array[l];
								w[l].x=vertices[pos*stride+lofs+0];
								w[l].y=vertices[pos*stride+lofs+1];
								w[l].y=1.0-w[l].y;
							}
						}
						arrays[k]=uvs;

					} break;
					case Mesh::ARRAY_BONES:
					case Mesh::ARRAY_WEIGHTS: {

						DVector<float> arr;
						arr.resize(array.size()*4);
						int po=k==Mesh::ARRAY_WEIGHTS?1:0;
						lofs=ofs[Mesh::ARRAY_BONES];
						{
							int len=array.size();

							DVector<float>::Write w = arr.write();
							for(int l=0;l<len;l++) {

								int pos = array[l];

								for(int m=0;m<4;m++) {

									float val=0;
									if (m<=weight_max)
										val=vertices[pos*stride+lofs+m*2+po];
									w[l*4+m]=val;
								}
							}
						}

						arrays[k]=arr;
					} break;
					case Mesh::ARRAY_INDEX: {

						DVector<int> arr;
						arr.resize(indices.size());
						{
							int len=indices.size();

							DVector<int>::Write w = arr.write();
							for(int l=0;l<len;l++) {

								w[l]=iarray[ indices[l] ];
							}
						}

						arrays[k]=arr;

					} break;


				}


			}

			Mesh::PrimitiveType pt=Mesh::PRIMITIVE_TRIANGLES;

			if (part.has("type")) {
				String type=part["type"];
				if (type=="LINES")
					pt=Mesh::PRIMITIVE_LINES;
				else if (type=="POINTS")
					pt=Mesh::PRIMITIVE_POINTS;
				else if (type=="TRIANGLE_STRIP")
					pt=Mesh::PRIMITIVE_TRIANGLE_STRIP;
				else if (type=="LINE_STRIP")
					pt=Mesh::PRIMITIVE_LINE_STRIP;
			}

			if (pt==Mesh::PRIMITIVE_TRIANGLES) {
				DVector<int> ia=arrays[Mesh::ARRAY_INDEX];
				int len=ia.size();
				{
					DVector<int>::Write w=ia.write();
					for(int l=0;l<len;l+=3) {
						SWAP(w[l+1],w[l+2]);
					}
				}
				arrays[Mesh::ARRAY_INDEX]=ia;


			}
			SurfaceInfo si;
			si.array=arrays;
			si.primitive=pt;
			state.surface_cache[_id(part["id"])]=si;

		}
	}
}
示例#28
0
bool GridMap::_set(const StringName &p_name, const Variant &p_value) {

	String name = p_name;

	if (name == "theme") {

		set_theme(p_value);
	} else if (name == "cell_size") {
		set_cell_size(p_value);
	} else if (name == "cell_octant_size") {
		set_octant_size(p_value);
	} else if (name == "cell_center_x") {
		set_center_x(p_value);
	} else if (name == "cell_center_y") {
		set_center_y(p_value);
	} else if (name == "cell_center_z") {
		set_center_z(p_value);
	} else if (name == "cell_scale") {
		set_cell_scale(p_value);
		/*	} else if (name=="cells") {
		PoolVector<int> cells = p_value;
		int amount=cells.size();
		PoolVector<int>::Read r = cells.read();
		ERR_FAIL_COND_V(amount&1,false); // not even
		cell_map.clear();
		for(int i=0;i<amount/3;i++) {


			IndexKey ik;
			ik.key=decode_uint64(&r[i*3]);
			Cell cell;
			cell.cell=uint32_t(r[i*+1]);
			cell_map[ik]=cell;

		}
		_recreate_octant_data();*/
	} else if (name == "data") {

		Dictionary d = p_value;

		if (d.has("cells")) {

			PoolVector<int> cells = d["cells"];
			int amount = cells.size();
			PoolVector<int>::Read r = cells.read();
			ERR_FAIL_COND_V(amount % 3, false); // not even
			cell_map.clear();
			for (int i = 0; i < amount / 3; i++) {

				IndexKey ik;
				ik.key = decode_uint64((const uint8_t *)&r[i * 3]);
				Cell cell;
				cell.cell = decode_uint32((const uint8_t *)&r[i * 3 + 2]);
				cell_map[ik] = cell;
			}
		}
		_recreate_octant_data();

	} else if (name.begins_with("areas/")) {
		int which = name.get_slicec('/', 1).to_int();
		String what = name.get_slicec('/', 2);
		if (what == "bounds") {
			ERR_FAIL_COND_V(area_map.has(which), false);
			create_area(which, p_value);
			return true;
		}

		ERR_FAIL_COND_V(!area_map.has(which), false);

		if (what == "name")
			area_set_name(which, p_value);
		else if (what == "disable_distance")
			area_set_portal_disable_distance(which, p_value);
		else if (what == "exterior_portal")
			area_set_portal_disable_color(which, p_value);
		else
			return false;
	} else
		return false;

	return true;
}
Error EditorSceneImporterFBXConv::_parse_animations(State& state) {

	AnimationPlayer *ap = memnew( AnimationPlayer );

	state.scene->add_child(ap);
	ap->set_owner(state.scene);

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

		Dictionary anim = state.animations[i];
		ERR_CONTINUE(!anim.has("id"));
		Ref<Animation> an = memnew( Animation );
		an->set_name(_id(anim["id"]));


		if (anim.has("bones")) {

			Array bone_tracks = anim["bones"];
			for(int j=0;j<bone_tracks.size();j++) {
				Dictionary bone_track=bone_tracks[j];
				String bone = bone_track["boneId"];
				if (!bone_track.has("keyframes"))
					continue;
				if (!state.bones.has(bone))
					continue;

				Skeleton *sk = state.bones[bone].skeleton;

				if (!sk)
					continue;
				int bone_idx=sk->find_bone(bone);
				if (bone_idx==-1)
					continue;



				String path = state.scene->get_path_to(sk);
				path+=":"+bone;
				an->add_track(Animation::TYPE_TRANSFORM);
				int tidx = an->get_track_count()-1;
				an->track_set_path(tidx,path);


				Dictionary parent_xform_dict;
				Dictionary xform_dict;

				if (state.bones.has(bone)) {
					xform_dict=state.bones[bone].node;
				}


				Array parent_keyframes;
				if (sk->get_bone_parent(bone_idx)!=-1) {
					String parent_name = sk->get_bone_name(sk->get_bone_parent(bone_idx));
					if (state.bones.has(parent_name)) {
						parent_xform_dict=state.bones[parent_name].node;
					}

					print_line("parent for "+bone+"? "+parent_name+" XFD: "+String(Variant(parent_xform_dict)));
					for(int k=0;k<bone_tracks.size();k++) {
						Dictionary d = bone_tracks[k];
						if (d["boneId"]==parent_name) {
							parent_keyframes=d["keyframes"];
							print_line("found keyframes");
							break;
						}
					}


				}

				print_line("BONE XFD "+String(Variant(xform_dict)));

				Array keyframes=bone_track["keyframes"];

				for(int k=0;k<keyframes.size();k++) {

					Dictionary key=keyframes[k];
					Transform xform=_get_transform_mixed(key,xform_dict);
					float time = key["keytime"];
					time=time/1000.0;
#if 0
					if (parent_keyframes.size()) {
						//localize
						print_line(itos(k)+" localizate for: "+bone);

						float prev_kt=-1;
						float kt;
						int idx=0;

						for(int l=0;l<parent_keyframes.size();l++) {

							Dictionary d=parent_keyframes[l];
							kt=d["keytime"];
							kt=kt/1000.0;
							if (kt>time)
								break;
							prev_kt=kt;
							idx++;

						}

						Transform t;
						if (idx==0) {
							t=_get_transform_mixed(parent_keyframes[0],parent_xform_dict);
						} else if (idx==parent_keyframes.size()){
							t=_get_transform_mixed(parent_keyframes[idx-1],parent_xform_dict);
						} else {
							t=_get_transform_mixed(parent_keyframes[idx-1],parent_xform_dict);
							float d = (time-prev_kt)/(kt-prev_kt);
							if (d>0) {
								Transform t2=_get_transform_mixed(parent_keyframes[idx],parent_xform_dict);
								t=t.interpolate_with(t2,d);
							} else {
								print_line("exact: "+rtos(kt));
							}
						}

						xform = t.affine_inverse() * xform; //localize
					} else if (!parent_xform_dict.empty()) {
						Transform t = _get_transform(parent_xform_dict);
						xform = t.affine_inverse() * xform; //localize
					}
#endif

					xform = sk->get_bone_rest(bone_idx).affine_inverse() * xform;


					Quat q = xform.basis;
					q.normalize();
					Vector3 s = xform.basis.get_scale();
					Vector3 l = xform.origin;



					an->transform_track_insert_key(tidx,time,l,q,s);

				}

			}


		}


		ap->add_animation(_id(anim["id"]),an);

	}

	return OK;
}
  static int run(int argc, char **argv) {
    static const MeCab::Option long_options[] = {
      { "dicdir",  'd',  ".",   "DIR", "set DIR as dicdir(default \".\" )" },
      { "outdir",  'o',  ".",   "DIR", "set DIR as output dir" },
      { "model",   'm',  0,     "FILE",   "use FILE as model file" },
      { "version", 'v',  0,   0,  "show the version and exit"  },
      { "training-algorithm", 'a',  "crf",    "(crf|hmm)",
        "set training algorithm" },
      { "default-emission-cost", 'E', "4000", "INT",
        "set default emission cost for HMM" },
      { "default-transition-cost", 'T', "4000", "INT",
        "set default transition cost for HMM" },
      { "help",    'h',  0,   0,  "show this help and exit."      },
      { 0, 0, 0, 0 }
    };

    Param param;

    if (!param.open(argc, argv, long_options)) {
      std::cout << param.what() << "\n\n" <<  COPYRIGHT
                << "\ntry '--help' for more information." << std::endl;
      return -1;
    }

    if (!param.help_version()) return 0;

    ContextID cid;
    DecoderFeatureIndex fi;
    DictionaryRewriter rewrite;

    const std::string dicdir = param.get<std::string>("dicdir");
    const std::string outdir = param.get<std::string>("outdir");
    const std::string model = param.get<std::string>("model");

#define DCONF(file) create_filename(dicdir, std::string(file)).c_str()
#define OCONF(file) create_filename(outdir, std::string(file)).c_str()

    CHECK_DIE(param.load(DCONF(DICRC)))
        << "no such file or directory: " << DCONF(DICRC);

    std::string charset;
    {
      Dictionary dic;
      CHECK_DIE(dic.open(DCONF(SYS_DIC_FILE), "r"));
      charset = dic.charset();
      CHECK_DIE(!charset.empty());
    }

    int default_emission_cost = 0;
    int default_transition_cost = 0;

    std::string type = param.get<std::string>("training-algorithm");
    toLower(&type);

    if (type == "hmm") {
      default_emission_cost =
          param.get<int>("default-emission-cost");
      default_transition_cost =
          param.get<int>("default-transition-cost");
      CHECK_DIE(default_transition_cost > 0)
          << "default transition cost must be > 0";
      CHECK_DIE(default_emission_cost > 0)
          << "default transition cost must be > 0";
      param.set("identity-template", 1);
    }

    CharProperty property;
    CHECK_DIE(property.open(param));
    property.set_charset(charset.c_str());

    const std::string bos = param.get<std::string>("bos-feature");
    const int factor = param.get<int>("cost-factor");

    std::vector<std::string> dic;
    enum_csv_dictionaries(dicdir.c_str(), &dic);

    {
      CHECK_DIE(dicdir != outdir) <<
          "output directory = dictionary directory! "
          "Please specify different directory.";
      CHECK_DIE(!outdir.empty()) << "output directory is empty";
      CHECK_DIE(!model.empty()) << "model file is empty";
      CHECK_DIE(fi.open(param)) << fi.what();
      CHECK_DIE(factor > 0)   << "cost factor needs to be positive value";
      CHECK_DIE(!bos.empty()) << "bos-feature is empty";
      CHECK_DIE(dic.size()) << "no dictionary is found in " << dicdir;
      CHECK_DIE(rewrite.open(DCONF(REWRITE_FILE)));
    }

    gencid_bos(bos, &rewrite, &cid);
    gencid(DCONF(UNK_DEF_FILE), &rewrite, &cid);

    for (std::vector<std::string>::const_iterator it = dic.begin();
         it != dic.end();
         ++it) {
      gencid(it->c_str(), &rewrite, &cid);
    }

    std::cout << "emitting "
              << OCONF(LEFT_ID_FILE) << "/ "
              << OCONF(RIGHT_ID_FILE) << std::endl;

    cid.build();
    cid.save(OCONF(LEFT_ID_FILE), OCONF(RIGHT_ID_FILE));

    gendic(DCONF(UNK_DEF_FILE), OCONF(UNK_DEF_FILE), property,
           &rewrite, cid, &fi, true, factor, default_emission_cost);

    for (std::vector<std::string>::const_iterator it = dic.begin();
         it != dic.end();
         ++it) {
      std::string file =  *it;
      remove_pathname(&file);
      gendic(it->c_str(), OCONF(file.c_str()), property,
             &rewrite, cid, &fi, false, factor, default_emission_cost);
    }

    genmatrix(OCONF(MATRIX_DEF_FILE), cid, &fi,
              factor, default_transition_cost);

    copy(DCONF(CHAR_PROPERTY_DEF_FILE), OCONF(CHAR_PROPERTY_DEF_FILE));
    copy(DCONF(REWRITE_FILE), OCONF(REWRITE_FILE));
    copy(DCONF(DICRC), OCONF(DICRC));

    if (type == "crf")
      copy(DCONF(FEATURE_FILE), OCONF(FEATURE_FILE));

#undef OCONF
#undef DCONF

    std::cout <<  "\ndone!\n";

    return 0;
  }