Example #1
0
	virtual void init() {

		VisualServer *vs = VisualServer::get_singleton();
		Physics2DServer *ps = Physics2DServer::get_singleton();



		space=ps->space_create();
		ps->space_set_active(space,true);
		ps->set_active(true);
		ps->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY_VECTOR,Vector2(0,1));
		ps->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY,98);

		{

			RID vp = vs->viewport_create();
			canvas = vs->canvas_create();
			vs->viewport_attach_canvas(vp,canvas);
			vs->viewport_attach_to_screen(vp);
			Matrix32 smaller;
			//smaller.scale(Vector2(0.6,0.6));
			//smaller.elements[2]=Vector2(100,0);

			//view_xform = smaller;
			vs->viewport_set_canvas_transform(vp,canvas,view_xform);

		}

		ray = vs->canvas_item_create();
		vs->canvas_item_set_parent(ray,canvas);
		//ray_query = ps->query_create(this,"_ray_query_callback",Variant());
		//ps->query_intersection(ray_query,space);

		_create_body_shape_data();

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

			Physics2DServer::ShapeType types[4]={
				Physics2DServer::SHAPE_CIRCLE,
				Physics2DServer::SHAPE_CAPSULE,
				Physics2DServer::SHAPE_RECTANGLE,
				Physics2DServer::SHAPE_CONVEX_POLYGON,

			};

			Physics2DServer::ShapeType type = types[i%4];
//			type=Physics2DServer::SHAPE_SEGMENT;
			RID b = _add_body(type,Matrix32(i*0.8,Point2(152+i*40,100-40*i)));
			//if (i==0)
			//	ps->body_set_mode(b,Physics2DServer::BODY_MODE_STATIC);
		}

		//RID b= _add_body(Physics2DServer::SHAPE_CIRCLE,Matrix32(0,Point2(101,140)));
		//ps->body_set_mode(b,Physics2DServer::BODY_MODE_STATIC);

		Point2 prev;

		Vector<Point2> parr;
		for(int i=0;i<30;i++) {

			Point2 p(i*60,Math::randf() * 70+340);
			if (i>0) {
				parr.push_back(prev);
				parr.push_back(p);
			}
			prev=p;
		}

		_add_concave(parr);
		//_add_plane(Vector2(0.0,-1).normalized(),-300);
		//_add_plane(Vector2(1,0).normalized(),50);
		//_add_plane(Vector2(-1,0).normalized(),-600);

	}
Example #2
0
void SceneTree::call_group(uint32_t p_call_flags,const StringName& p_group,const StringName& p_function,VARIANT_ARG_DECLARE) {

	Map<StringName,Group>::Element *E=group_map.find(p_group);
	if (!E)
		return;
	Group &g=E->get();
	if (g.nodes.empty())
		return;

	_update_group_order(g);


	if (p_call_flags&GROUP_CALL_UNIQUE && !(p_call_flags&GROUP_CALL_REALTIME)) {

		ERR_FAIL_COND(ugc_locked);

		UGCall ug;
		ug.call=p_function;
		ug.group=p_group;

		if (unique_group_calls.has(ug))
			return;

		VARIANT_ARGPTRS;

		Vector<Variant> args;
		for(int i=0;i<VARIANT_ARG_MAX;i++) {
			if (argptr[i]->get_type()==Variant::NIL)
				break;
			args.push_back(*argptr[i]);
		}

		unique_group_calls[ug]=args;
		return;
	}

	Vector<Node*> nodes_copy = g.nodes;
	Node **nodes = &nodes_copy[0];
	int node_count=nodes_copy.size();

	call_lock++;

	if (p_call_flags&GROUP_CALL_REVERSE) {

		for(int i=node_count-1;i>=0;i--) {

			if (call_lock && call_skip.has(nodes[i]))
				continue;

			if (p_call_flags&GROUP_CALL_REALTIME) {
				if (p_call_flags&GROUP_CALL_MULIILEVEL)
					nodes[i]->call_multilevel(p_function,VARIANT_ARG_PASS);
				else
					nodes[i]->call(p_function,VARIANT_ARG_PASS);
			} else
				MessageQueue::get_singleton()->push_call(nodes[i],p_function,VARIANT_ARG_PASS);

		}

	} else {

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

			if (call_lock && call_skip.has(nodes[i]))
				continue;

			if (p_call_flags&GROUP_CALL_REALTIME) {
				if (p_call_flags&GROUP_CALL_MULIILEVEL)
					nodes[i]->call_multilevel(p_function,VARIANT_ARG_PASS);
				else
					nodes[i]->call(p_function,VARIANT_ARG_PASS);
			} else
				MessageQueue::get_singleton()->push_call(nodes[i],p_function,VARIANT_ARG_PASS);			
		}

	}

	call_lock--;
	if (call_lock==0)
		call_skip.clear();
}
void ScriptEditorDebugger::_performance_draw() {


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


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


	if(which.empty())
		return;

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

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


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

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

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

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

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

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

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

	}

}
Error ResourceImporterCSVTranslation::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files) {

	bool compress = p_options["compress"];
	FileAccessRef f = FileAccess::open(p_source_file, FileAccess::READ);

	ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER);

	Vector<String> line = f->get_csv_line();
	if (line.size() <= 1) {
		return ERR_PARSE_ERROR;
	}

	Vector<String> locales;
	Vector<Ref<Translation> > translations;

	for (int i = 1; i < line.size(); i++) {

		String locale = line[i];
		if (!TranslationServer::is_locale_valid(locale)) {
			return ERR_PARSE_ERROR;
		}

		locales.push_back(locale);
		Ref<Translation> translation;
		translation.instance();
		translation->set_locale(locale);
		translations.push_back(translation);
	}

	line = f->get_csv_line();

	while (line.size() == locales.size() + 1) {

		String key = line[0];
		if (key != "") {

			for (int i = 1; i < line.size(); i++) {
				translations[i - 1]->add_message(key, line[i]);
			}
		}

		line = f->get_csv_line();
	}

	for (int i = 0; i < translations.size(); i++) {
		Ref<Translation> xlt = translations[i];

		if (compress) {
			Ref<PHashTranslation> cxl = memnew(PHashTranslation);
			cxl->generate(xlt);
			xlt = cxl;
		}

		String save_path = p_source_file.get_basename() + "." + translations[i]->get_locale() + ".translation";

		ResourceSaver::save(save_path, xlt);
		if (r_gen_files) {
			r_gen_files->push_back(save_path);
		}
	}

	return OK;
}
void vector_test_template(unsigned int num_iterations, unsigned int num_elements, bool csv_output)
{
   typedef typename Allocator::template rebind<MyInt>::other IntAllocator;
   unsigned int numalloc = 0, numexpand = 0;

   #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS
      typedef stats_traits<Vector> stats_traits_t;
   #endif

   cpu_timer timer;
   timer.resume();

   unsigned int capacity = 0;
   for(unsigned int r = 0; r != num_iterations; ++r){
      Vector<MyInt, IntAllocator> v;
      #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS
         stats_traits_t::reset_alloc_stats(v);
      #endif
      //v.reserve(num_elements);
      //MyInt a[3];
/*
      for(unsigned int e = 0; e != num_elements/3; ++e){
         v.insert(v.end(), &a[0], &a[0]+3);
      }*/
/*
      for(unsigned int e = 0; e != num_elements/3; ++e){
         v.insert(v.end(), 3, MyInt(e));
      }*/
/*
      for(unsigned int e = 0; e != num_elements/3; ++e){
         v.insert(v.empty() ? v.end() : --v.end(), &a[0], &a[0]+3);
      }*/
/*
      for(unsigned int e = 0; e != num_elements/3; ++e){
         v.insert(v.empty() ? v.end() : --v.end(), 3, MyInt(e));
      }*/
/*
      for(unsigned int e = 0; e != num_elements/3; ++e){
         v.insert(v.size() >= 3 ? v.end()-3 : v.begin(), &a[0], &a[0]+3);
      }*/
/*
      for(unsigned int e = 0; e != num_elements/3; ++e){
         v.insert(v.size() >= 3 ? v.end()-3 : v.begin(), 3, MyInt(e));
      }*/
/*
      for(unsigned int e = 0; e != num_elements; ++e){
         v.insert(v.end(), MyInt(e));
      }*/
/*
      for(unsigned int e = 0; e != num_elements; ++e){
         v.insert(v.empty() ? v.end() : --v.end(), MyInt(e));
      }*/

      for(unsigned int e = 0; e != num_elements; ++e){
         v.push_back(MyInt(e));
      }

      #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS
         numalloc  += stats_traits_t::get_num_alloc(v);
         numexpand += stats_traits_t::get_num_expand(v);
      #endif
      capacity = static_cast<unsigned int>(v.capacity());
   }

   timer.stop();
   nanosecond_type nseconds = timer.elapsed().wall;

   if(csv_output){
      std::cout   << get_allocator_name<Allocator>::get()
                  << ";"
                  << num_iterations
                  << ";"
                  << num_elements
                  << ";"
                  << capacity
                  << ";"
                  << float(nseconds)/(num_iterations*num_elements)
                  << ";"
                  << (float(numalloc) + float(numexpand))/num_iterations
                  << ";"
                  << float(numalloc)/num_iterations
                  << ";"
                  << float(numexpand)/num_iterations
                  << std::endl;
   }
   else{
      std::cout   << std::endl
                  << "Allocator: " << get_allocator_name<Allocator>::get()
                  << std::endl
                  << "  push_back ns:              "
                  << float(nseconds)/(num_iterations*num_elements)
                  << std::endl
                  << "  capacity  -  alloc calls (new/expand):  "
                     << (unsigned int)capacity << "  -  "
                     << (float(numalloc) + float(numexpand))/num_iterations
                     << "(" << float(numalloc)/num_iterations << "/" << float(numexpand)/num_iterations << ")"
                  << std::endl << std::endl;
   }
   boost_cont_trim(0);
}
Matrix<std::string> SimulatedAnnealingOrder::to_string_matrix(void) const
{
    std::ostringstream buffer;

    Vector<std::string> labels;
    Vector<std::string> values;

   // Minimum order

   labels.push_back("Minimum order");

   buffer.str("");
   buffer << minimum_order;

   values.push_back(buffer.str());

   // Maximum order

   labels.push_back("Maximum order");

   buffer.str("");
   buffer << maximum_order;

   values.push_back(buffer.str());

   // Step

   labels.push_back("Cooling Rate");

   buffer.str("");
   buffer << cooling_rate;

   values.push_back(buffer.str());

   // Trials number

   labels.push_back("Trials number");

   buffer.str("");
   buffer << trials_number;

   values.push_back(buffer.str());

   // Tolerance

   labels.push_back("Tolerance");

   buffer.str("");
   buffer << tolerance;

   values.push_back(buffer.str());

   // Selection performance goal

   labels.push_back("Selection performance goal");

   buffer.str("");
   buffer << selection_performance_goal;

   values.push_back(buffer.str());

   // Maximum generalization failures

   labels.push_back("Maximum generalization failures");

   buffer.str("");
   buffer << maximum_selection_failures;

   values.push_back(buffer.str());

   // Minimum temperature

   labels.push_back("Minimum temperature");

   buffer.str("");
   buffer << minimum_temperature;

   values.push_back(buffer.str());

   // Maximum iterations number

   labels.push_back("Maximum iterations number");

   buffer.str("");
   buffer << maximum_iterations_number;

   values.push_back(buffer.str());

   // Maximum time

   labels.push_back("Maximum time");

   buffer.str("");
   buffer << maximum_time;

   values.push_back(buffer.str());

   // Plot training performance history

   labels.push_back("Plot training performance history");

   buffer.str("");
   buffer << reserve_performance_data;

   values.push_back(buffer.str());

   // Plot selection performance history

   labels.push_back("Plot selection performance history");

   buffer.str("");
   buffer << reserve_generalization_performance_data;

   values.push_back(buffer.str());

   const size_t rows_number = labels.size();
   const size_t columns_number = 2;

   Matrix<std::string> string_matrix(rows_number, columns_number);

   string_matrix.set_column(0, labels);
   string_matrix.set_column(1, values);

    return(string_matrix);
}
Example #7
0
static bool _guess_expression_type(GDCompletionContext& context,const GDParser::Node* p_node,int p_line,GDCompletionIdentifier &r_type) {


	if (p_node->type==GDParser::Node::TYPE_CONSTANT) {

		const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(p_node);

		r_type=_get_type_from_variant(cn->value);

		return true;
	} else if (p_node->type==GDParser::Node::TYPE_DICTIONARY) {

		r_type.type=Variant::DICTIONARY;


		//what the heck, fill it anyway
		const GDParser::DictionaryNode *an = static_cast<const GDParser::DictionaryNode *>(p_node);
		Dictionary d;
		for(int i=0;i<an->elements.size();i++) {
			GDCompletionIdentifier k;
			if (_guess_expression_type(context,an->elements[i].key,p_line,k) && k.value.get_type()!=Variant::NIL) {
				GDCompletionIdentifier v;
				if (_guess_expression_type(context,an->elements[i].value,p_line,v)) {
					d[k.value]=v.value;
				}

			}
		}
		r_type.value=d;
		return true;
	} else if (p_node->type==GDParser::Node::TYPE_ARRAY) {

		r_type.type=Variant::ARRAY;
		//what the heck, fill it anyway
		const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(p_node);
		Array arr;
		arr.resize(an->elements.size());
		for(int i=0;i<an->elements.size();i++) {
			GDCompletionIdentifier ci;
			if (_guess_expression_type(context,an->elements[i],p_line,ci)) {
				arr[i]=ci.value;
			}
		}
		r_type.value=arr;
		return true;

	} else if (p_node->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) {

		MethodInfo mi = GDFunctions::get_info(static_cast<const GDParser::BuiltInFunctionNode*>(p_node)->function);
		r_type=_get_type_from_pinfo(mi.return_val);

		return true;
	} else if (p_node->type==GDParser::Node::TYPE_IDENTIFIER) {

		return _guess_identifier_type(context,p_line-1,static_cast<const GDParser::IdentifierNode *>(p_node)->name,r_type);
	} else if (p_node->type==GDParser::Node::TYPE_SELF) {
		//eeh...

		r_type=_get_native_class(context);
		return r_type.type!=Variant::NIL;

	} else if (p_node->type==GDParser::Node::TYPE_OPERATOR) {


		const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_node);
		if (op->op==GDParser::OperatorNode::OP_CALL) {
			if (op->arguments[0]->type==GDParser::Node::TYPE_TYPE) {

				const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode *>(op->arguments[0]);
				r_type.type=tn->vtype;
				return true;
			} else if (op->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) {


				const GDParser::BuiltInFunctionNode *bin = static_cast<const GDParser::BuiltInFunctionNode *>(op->arguments[0]);
				return _guess_expression_type(context,bin,p_line,r_type);

			} else if (op->arguments.size()>1 && op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) {


				GDCompletionIdentifier base;
				if (!_guess_expression_type(context,op->arguments[0],p_line,base))
					return false;

				StringName id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name;

				if (base.type==Variant::OBJECT) {

					if (id.operator String()=="new" && base.value.get_type()==Variant::OBJECT) {
						Object *obj = base.value;
						if (obj && obj->cast_to<GDNativeClass>()) {
							GDNativeClass *gdnc = obj->cast_to<GDNativeClass>();
							r_type.type=Variant::OBJECT;
							r_type.value=Variant();
							r_type.obj_type=gdnc->get_name();
							return true;
						}
					}

					if (ObjectTypeDB::has_method(base.obj_type,id)) {

#ifdef TOOLS_ENABLED
						MethodBind *mb = ObjectTypeDB::get_method(base.obj_type,id);
						PropertyInfo pi = mb->get_argument_info(-1);

						//try calling the function if constant and all args are constant, should not crash..
						Object *baseptr = base.value;

						if (baseptr && mb->is_const() && pi.type==Variant::OBJECT) {
							bool all_valid=true;
							Vector<Variant> args;
							for(int i=2;i<op->arguments.size();i++) {
								GDCompletionIdentifier arg;

								if (_guess_expression_type(context,op->arguments[i],p_line,arg)) {
									if (arg.value.get_type()!=Variant::NIL && arg.value.get_type()!=Variant::OBJECT) { // calling with object seems dangerous, i don' t know
										args.push_back(arg.value);
									} else {
										all_valid=false;
										break;
									}
								} else {
									all_valid=false;
								}
							}
							if (all_valid) {
								Vector<const Variant*> argptr;
								for(int i=0;i<args.size();i++) {
									argptr.push_back(&args[i]);
								}

								Variant::CallError ce;
								Variant ret=mb->call(baseptr,argptr.ptr(),argptr.size(),ce);


								if (ce.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) {

									if (ret.get_type()!=Variant::OBJECT || ret.operator Object*()!=NULL) {

										r_type=_get_type_from_variant(ret);
										return true;
									}
								}

							}
						}

						r_type.type=pi.type;
						if (pi.hint==PROPERTY_HINT_RESOURCE_TYPE) {
							r_type.obj_type=pi.hint_string;
						}



						return true;
#else
						return false;
#endif
					} else {
						return false;
					}
				} else {
					//method for some variant..
					Variant::CallError ce;
					Variant v = Variant::construct(base.type,NULL,0,ce);
					List<MethodInfo> mi;
					v.get_method_list(&mi);
					for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) {

						if (!E->get().name.begins_with("_") && E->get().name==id.operator String()) {


							MethodInfo mi = E->get();
							r_type.type=mi.return_val.type;
							if (mi.return_val.hint==PROPERTY_HINT_RESOURCE_TYPE) {
								r_type.obj_type=mi.return_val.hint_string;
							}
							return true;
						}
					}

				}


			}
		} else if (op->op==GDParser::OperatorNode::OP_INDEX || op->op==GDParser::OperatorNode::OP_INDEX_NAMED) {

			GDCompletionIdentifier p1;
			GDCompletionIdentifier p2;



			if (op->op==GDParser::OperatorNode::OP_INDEX_NAMED) {

				if (op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) {
					String id = static_cast<const GDParser::IdentifierNode*>(op->arguments[1])->name;
					p2.type=Variant::STRING;
					p2.value=id;
				}

			} else {
				if (op->arguments[1]) {
					if (!_guess_expression_type(context,op->arguments[1],p_line,p2)) {

						return false;
					}
				}
			}

			if (op->arguments[0]->type==GDParser::Node::TYPE_ARRAY) {

				const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(op->arguments[0]);
				if (p2.value.is_num()) {
					int index = p2.value;
					if (index<0 || index>=an->elements.size())
						return false;
					return _guess_expression_type(context,an->elements[index],p_line,r_type);
				}

			} else if (op->arguments[0]->type==GDParser::Node::TYPE_DICTIONARY) {

				const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode *>(op->arguments[0]);

				if (p2.value.get_type()==Variant::NIL)
					return false;

				for(int i=0;i<dn->elements.size();i++) {

					GDCompletionIdentifier k;

					if (!_guess_expression_type(context,dn->elements[i].key,p_line,k)) {

						return false;
					}

					if (k.value.get_type()==Variant::NIL)
						return false;

					if (k.value==p2.value) {

						return _guess_expression_type(context,dn->elements[i].value,p_line,r_type);
					}
				}

			} else {

				if (op->arguments[0]) {
					if (!_guess_expression_type(context,op->arguments[0],p_line,p1)) {

						return false;
					}

				}

				if (p1.value.get_type()==Variant::OBJECT) {
					//??
				} else if (p1.value.get_type()!=Variant::NIL) {

					bool valid;
					Variant ret = p1.value.get(p2.value,&valid);
					if (valid) {
						r_type=_get_type_from_variant(ret);
						return true;
					}

				} else {
					if (p1.type!=Variant::NIL) {
						Variant::CallError ce;
						Variant base = Variant::construct(p1.type,NULL,0,ce);
						bool valid;
						Variant ret = base.get(p2.value,&valid);
						if (valid) {
							r_type=_get_type_from_variant(ret);
							return true;
						}
					}
				}
			}

		} else {


			Variant::Operator vop = Variant::OP_MAX;
			switch(op->op) {
				case GDParser::OperatorNode::OP_ADD: vop=Variant::OP_ADD; break;
				case GDParser::OperatorNode::OP_SUB: vop=Variant::OP_SUBSTRACT; break;
				case GDParser::OperatorNode::OP_MUL: vop=Variant::OP_MULTIPLY; break;
				case GDParser::OperatorNode::OP_DIV: vop=Variant::OP_DIVIDE; break;
				case GDParser::OperatorNode::OP_MOD: vop=Variant::OP_MODULE; break;
				case GDParser::OperatorNode::OP_SHIFT_LEFT: vop=Variant::OP_SHIFT_LEFT; break;
				case GDParser::OperatorNode::OP_SHIFT_RIGHT: vop=Variant::OP_SHIFT_RIGHT; break;
				case GDParser::OperatorNode::OP_BIT_AND: vop=Variant::OP_BIT_AND; break;
				case GDParser::OperatorNode::OP_BIT_OR: vop=Variant::OP_BIT_OR; break;
				case GDParser::OperatorNode::OP_BIT_XOR: vop=Variant::OP_BIT_XOR; break;
				default:{}

			}



			if (vop==Variant::OP_MAX)
				return false;



			GDCompletionIdentifier p1;
			GDCompletionIdentifier p2;

			if (op->arguments[0]) {
				if (!_guess_expression_type(context,op->arguments[0],p_line,p1)) {

					return false;
				}

			}

			if (op->arguments.size()>1) {
				if (!_guess_expression_type(context,op->arguments[1],p_line,p2)) {

					return false;
				}
			}

			Variant::CallError ce;
			bool v1_use_value = p1.value.get_type()!=Variant::NIL && p1.value.get_type()!=Variant::OBJECT;
			Variant v1 = (v1_use_value)?p1.value:Variant::construct(p1.type,NULL,0,ce);
			bool v2_use_value = p2.value.get_type()!=Variant::NIL && p2.value.get_type()!=Variant::OBJECT;
			Variant v2 = (v2_use_value)?p2.value:Variant::construct(p2.type,NULL,0,ce);
			// avoid potential invalid ops
			if ((vop==Variant::OP_DIVIDE || vop==Variant::OP_MODULE) && v2.get_type()==Variant::INT) {
				v2=1;
				v2_use_value=false;
			}
			if (vop==Variant::OP_DIVIDE && v2.get_type()==Variant::REAL) {
				v2=1.0;
				v2_use_value=false;
			}

			Variant r;
			bool valid;
			Variant::evaluate(vop,v1,v2,r,valid);
			if (!valid)
				return false;
			r_type.type=r.get_type();
			if (v1_use_value && v2_use_value)
				r_type.value=r;

			return true;

		}

	}

	return false;
}
Example #8
0
Vector<Vector2> Navigation2D::get_simple_path(const Vector2& p_start, const Vector2& p_end, bool p_optimize) {


	Polygon *begin_poly=NULL;
	Polygon *end_poly=NULL;
	Vector2 begin_point;
	Vector2 end_point;
	float begin_d=1e20;
	float end_d=1e20;

	//look for point inside triangle

	for (Map<int,NavMesh>::Element*E=navpoly_map.front();E;E=E->next()) {

		if (!E->get().linked)
			continue;
		for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {


			Polygon &p=F->get();
			if (begin_d || end_d) {
				for(int i=2;i<p.edges.size();i++) {

					if (begin_d>0) {

						if (Geometry::is_point_in_triangle(p_start,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) {

							begin_poly=&p;
							begin_point=p_start;
							begin_d=0;
							if (end_d==0)
								break;

						}
					}

					if (end_d>0) {

						if (Geometry::is_point_in_triangle(p_end,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) {

							end_poly=&p;
							end_point=p_end;
							end_d=0;
							if (begin_d==0)
								break;
						}
					}

				}
			}

			p.prev_edge=-1;
		}
	}

	//start or end not inside triangle.. look for closest segment :|
	if (begin_d || end_d) {
		for (Map<int,NavMesh>::Element*E=navpoly_map.front();E;E=E->next()) {

			if (!E->get().linked)
				continue;
			for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {

				Polygon &p=F->get();
				int es = p.edges.size();
				for(int i=0;i<es;i++) {

					Vector2 edge[2]={
						_get_vertex(p.edges[i].point),
						_get_vertex(p.edges[(i+1)%es].point)
					};


					if (begin_d>0) {
						Vector2 spoint=Geometry::get_closest_point_to_segment_2d(p_start,edge);
						float d = spoint.distance_to(p_start);
						if (d<begin_d) {
							begin_poly=&p;
							begin_point=spoint;
							begin_d=d;
						}
					}

					if (end_d>0) {
						Vector2 spoint=Geometry::get_closest_point_to_segment_2d(p_end,edge);
						float d = spoint.distance_to(p_end);
						if (d<end_d) {
							end_poly=&p;
							end_point=spoint;
							end_d=d;
						}
					}
				}
			}
		}
	}

	if (!begin_poly || !end_poly) {

		//print_line("No Path Path");
		return Vector<Vector2>(); //no path
	}

	if (begin_poly==end_poly) {

		Vector<Vector2> path;
		path.resize(2);
		path[0]=begin_point;
		path[1]=end_point;
		//print_line("Direct Path");
		return path;
	}


	bool found_route=false;

	List<Polygon*> open_list;

	begin_poly->entry=p_start;

	for(int i=0;i<begin_poly->edges.size();i++) {

		if (begin_poly->edges[i].C) {

			begin_poly->edges[i].C->prev_edge=begin_poly->edges[i].C_edge;
#ifdef USE_ENTRY_POINT
			Vector2 edge[2]={
				_get_vertex(begin_poly->edges[i].point),
				_get_vertex(begin_poly->edges[(i+1)%begin_poly->edges.size()].point)
			};

			Vector2 entry = Geometry::get_closest_point_to_segment_2d(begin_poly->entry,edge);
			begin_poly->edges[i].C->distance = begin_poly->entry.distance_to(entry);
			begin_poly->edges[i].C->entry=entry;
#else
			begin_poly->edges[i].C->distance=begin_poly->center.distance_to(begin_poly->edges[i].C->center);
#endif
			open_list.push_back(begin_poly->edges[i].C);

			if (begin_poly->edges[i].C==end_poly) {
				found_route=true;
			}
		}
	}


	while(!found_route) {

		if (open_list.size()==0) {
		//	print_line("NOU OPEN LIST");
			break;
		}
		//check open list

		List<Polygon*>::Element *least_cost_poly=NULL;
		float least_cost=1e30;

		//this could be faster (cache previous results)
		for (List<Polygon*>::Element *E=open_list.front();E;E=E->next()) {

			Polygon *p=E->get();


			float cost=p->distance;
			cost+=p->center.distance_to(end_point);

			if (cost<least_cost) {

				least_cost_poly=E;
				least_cost=cost;
			}
		}


		Polygon *p=least_cost_poly->get();
		//open the neighbours for search
		int es = p->edges.size();

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


			Polygon::Edge &e=p->edges[i];

			if (!e.C)
				continue;

#ifdef USE_ENTRY_POINT
			Vector2 edge[2]={
				_get_vertex(p->edges[i].point),
				_get_vertex(p->edges[(i+1)%es].point)
			};

			Vector2 edge_entry = Geometry::get_closest_point_to_segment_2d(p->entry,edge);
			float distance = p->entry.distance_to(edge_entry) + p->distance;

#else

			float distance = p->center.distance_to(e.C->center) + p->distance;

#endif


			if (e.C->prev_edge!=-1) {
				//oh this was visited already, can we win the cost?

				if (e.C->distance>distance) {

					e.C->prev_edge=e.C_edge;
					e.C->distance=distance;
#ifdef USE_ENTRY_POINT
					e.C->entry=edge_entry;
#endif
				}
			} else {
				//add to open neighbours

				e.C->prev_edge=e.C_edge;
				e.C->distance=distance;
#ifdef USE_ENTRY_POINT
				e.C->entry=edge_entry;
#endif

				open_list.push_back(e.C);

				if (e.C==end_poly) {
					//oh my reached end! stop algorithm
					found_route=true;
					break;

				}

			}
		}

		if (found_route)
			break;

		open_list.erase(least_cost_poly);
	}

	if (found_route) {

		Vector<Vector2> path;

		if (p_optimize) {
			//string pulling

			Polygon *apex_poly=end_poly;
			Vector2 apex_point=end_point;
			Vector2 portal_left=apex_point;
			Vector2 portal_right=apex_point;
			Polygon *left_poly=end_poly;
			Polygon *right_poly=end_poly;
			Polygon *p=end_poly;
			path.push_back(end_point);

			while(p) {

				Vector2 left;
				Vector2 right;

//#define CLOCK_TANGENT(m_a,m_b,m_c) ( ((m_a)-(m_c)).cross((m_a)-(m_b)) )
#define CLOCK_TANGENT(m_a,m_b,m_c) ((((m_a).x - (m_c).x) * ((m_b).y - (m_c).y) - ((m_b).x - (m_c).x) * ((m_a).y - (m_c).y)))

				if (p==begin_poly) {
					left=begin_point;
					right=begin_point;
				} else {
					int prev = p->prev_edge;
					int prev_n = (p->prev_edge+1)%p->edges.size();
					left = _get_vertex(p->edges[prev].point);
					right = _get_vertex(p->edges[prev_n].point);

					if (p->clockwise) {
						SWAP(left,right);
					}
					/*if (CLOCK_TANGENT(apex_point,left,(left+right)*0.5) < 0){
						SWAP(left,right);
					}*/
				}

				bool skip=false;

			/*	print_line("-----\nAPEX: "+(apex_point-end_point));
				print_line("LEFT:");
				print_line("\tPortal: "+(portal_left-end_point));
				print_line("\tPoint: "+(left-end_point));
				print_line("\tFree: "+itos(CLOCK_TANGENT(apex_point,portal_left,left) >= 0));
				print_line("RIGHT:");
				print_line("\tPortal: "+(portal_right-end_point));
				print_line("\tPoint: "+(right-end_point));
				print_line("\tFree: "+itos(CLOCK_TANGENT(apex_point,portal_right,right) <= 0));
*/

				if (CLOCK_TANGENT(apex_point,portal_left,left) >= 0){
					//process
					if (portal_left.distance_squared_to(apex_point)<CMP_EPSILON || CLOCK_TANGENT(apex_point,left,portal_right) > 0) {
						left_poly=p;
						portal_left=left;
					} else {

						//_clip_path(path,apex_poly,portal_right,right_poly);

						apex_point=portal_right;
						p=right_poly;
						left_poly=p;
						apex_poly=p;
						portal_left=apex_point;
						portal_right=apex_point;
						if (path[path.size()-1].distance_to(apex_point)>CMP_EPSILON)
							path.push_back(apex_point);
						skip=true;
						//print_line("addpoint left");
					}
				}

				if (!skip && CLOCK_TANGENT(apex_point,portal_right,right) <= 0){
					//process
					if (portal_right.distance_squared_to(apex_point)<CMP_EPSILON || CLOCK_TANGENT(apex_point,right,portal_left) < 0) {
						right_poly=p;
						portal_right=right;
					} else {

						//_clip_path(path,apex_poly,portal_left,left_poly);

						apex_point=portal_left;
						p=left_poly;
						right_poly=p;
						apex_poly=p;
						portal_right=apex_point;
						portal_left=apex_point;
						if (path[path.size()-1].distance_to(apex_point)>CMP_EPSILON)
							path.push_back(apex_point);
						//print_line("addpoint right");

					}
				}

				if (p!=begin_poly)
					p=p->edges[p->prev_edge].C;
				else
					p=NULL;

			}

			if (path[path.size()-1].distance_to(begin_point)>CMP_EPSILON)
				path.push_back(begin_point);

			path.invert();




		} else {
			//midpoints
			Polygon *p=end_poly;

			path.push_back(end_point);
			while(true) {
				int prev = p->prev_edge;
				int prev_n = (p->prev_edge+1)%p->edges.size();
				Vector2 point = (_get_vertex(p->edges[prev].point) + _get_vertex(p->edges[prev_n].point))*0.5;
				path.push_back(point);
				p = p->edges[prev].C;
				if (p==begin_poly)
					break;
			}

			path.push_back(begin_point);


			path.invert();;
		}

		return path;
	}


	return Vector<Vector2>();

}
Example #9
0
void LinkForward::fillMatrix()
{
  if(!hmm.isInLogSpace()) throw "HMM is not in log space";
  
  // Initialization:
  
  int nI=QI.size(), nD=QD.size(), nM=QM.size();
  int m=parent.getSeqLen(), n=child.getSeqLen();
  cachedEmitP.resize(numStates,m+1,n+1);
  cachedEmitP.setAllTo(NEGATIVE_INFINITY);
  F.resize(m+1,n+1,numStates);
  F.setAllTo(LOG_0); // ### redundant
  F(0,0,0)=LOG_1;
  for(STATE k=1 ; k<numStates ; ++k) F(0,0,k)=LOG_0;
  Array1D<double> logProbs(numStates);
  for(int j=1 ; j<=n ; ++j) {
    for(int ik=0 ; ik<nI ; ++ik) { // insertion states
      STATE k=QI[ik];
      for(STATE h=0 ; h<numStates ; ++h) {
	logProbs[h]=safeAdd(hmm.getTransP(h,k),getEmitP(k,m,j-1),
			    F(0,j-1,h));
      }
      F(0,j,k)=sumLogProbs<double>(logProbs);
    }
  }
  for(int i=1 ; i<=m ; +i) {
    for(int ik=0 ; ik<nD ; ++ik) { // deletion states
      STATE k=QD[ik];
      for(STATE h=0 ; h<numStates ; ++h) {
	logProbs[h]=safeAdd(hmm.getTransP(h,k),getEmitP(k,i-1,n),
			    F(i-1,0,h));
      }
      F(i,0,k)=sumLogProbs<double>(logProbs);
    }
  }

  // Recurrence:

  for(int i=m-1 ; i>=0 ; --i) {
    for(int j=n-1 ; j>=0 ; --j) {
      F(i,j,0)=LOG_0;
      for(STATE k=1 ; k<numStates ; ++k) {
	Vector<double> logProbs;
	const Array1D<STATE> &pred=hmm.getPredecessors(k);
	STATE *p=&pred[0];
	int numPred=pred.size();
	for(int s=0 ; s<numPred ; ++s) {
	  STATE h=*p;
	  double trans=hmm.getTransP(h,k);
	  switch(hmm.getStateType(h)) 
	    {
	    case PHMM_MATCH:
	      logProbs.push_back(safeAdd(trans,getEmitP(k,i-1,j-1),
					 F(i-1,j-1,h)));
	      break;
	    case PHMM_INSERT:
	      logProbs.push_back(safeAdd(trans,getEmitP(k,m,j-1),
					 F(i,j-1,h)));
	      break;
	    case PHMM_DELETE:
	      logProbs.push_back(safeAdd(trans,getEmitP(k,i-1,n),
					 F(i-1,j,h)));
	      break;
	    default: throw "error in LinkForward::fillMatrix (recurrence)";
	    }
	  ++p;
	}
	F(i,j,k)=sumLogProbs<double>(logProbs);
      }
    }
  }

  // Termination:
  logProbs[0]=LOG_0;
  for(STATE k=1 ; k<numStates ; ++k)
    logProbs[k]=F(m,n,k)+hmm.getTransP(k,0);
  likelihood=sumLogProbs<double>(logProbs);
}
bool CollisionPolygonEditor::forward_spatial_input_event(Camera* p_camera,const InputEvent& p_event) {


    Transform gt = node->get_global_transform();
    float depth = node->get_depth()*0.5;
    Vector3 n = gt.basis.get_axis(2).normalized();
    Plane p(gt.origin+n*depth,n);


    switch(p_event.type) {

    case InputEvent::MOUSE_BUTTON: {

        const InputEventMouseButton &mb=p_event.mouse_button;



        Vector2 gpoint=Point2(mb.x,mb.y);
        Vector3 ray_from = p_camera->project_ray_origin(gpoint);
        Vector3 ray_dir = p_camera->project_ray_normal(gpoint);

        Vector3 spoint;

        if (!p.intersects_ray(ray_from,ray_dir,&spoint))
            break;

        Vector2 cpoint(spoint.x,spoint.y);

        //cpoint=snap_point(cpoint); snap?

        Vector<Vector2> poly = node->get_polygon();

        //first check if a point is to be added (segment split)
        real_t grab_treshold=EDITOR_DEF("poly_editor/point_grab_radius",8);

        switch(mode) {


        case MODE_CREATE: {

            if (mb.button_index==BUTTON_LEFT && mb.pressed) {


                if (!wip_active) {

                    wip.clear();
                    wip.push_back( cpoint );
                    wip_active=true;
                    edited_point_pos=cpoint;
                    _polygon_draw();
                    edited_point=1;
                    return true;
                } else {


                    if (wip.size()>1 && p_camera->unproject_position(gt.xform(Vector3(wip[0].x,wip[0].y,depth))).distance_to(gpoint)<grab_treshold) {
                        //wip closed
                        _wip_close();

                        return true;
                    } else {

                        wip.push_back( cpoint );
                        edited_point=wip.size();
                        _polygon_draw();
                        return true;

                        //add wip point
                    }
                }
            } else if (mb.button_index==BUTTON_RIGHT && mb.pressed && wip_active) {
                _wip_close();
            }



        }
        break;

        case MODE_EDIT: {

            if (mb.button_index==BUTTON_LEFT) {
                if (mb.pressed) {

                    if (mb.mod.control) {


                        if (poly.size() < 3) {

                            undo_redo->create_action("Edit Poly");
                            undo_redo->add_undo_method(node,"set_polygon",poly);
                            poly.push_back(cpoint);
                            undo_redo->add_do_method(node,"set_polygon",poly);
                            undo_redo->add_do_method(this,"_polygon_draw");
                            undo_redo->add_undo_method(this,"_polygon_draw");
                            undo_redo->commit_action();
                            return true;
                        }

                        //search edges
                        int closest_idx=-1;
                        Vector2 closest_pos;
                        real_t closest_dist=1e10;
                        for(int i=0; i<poly.size(); i++) {

                            Vector2 points[2] = {
                                p_camera->unproject_position(gt.xform(Vector3(poly[i].x,poly[i].y,depth))),
                                p_camera->unproject_position(gt.xform(Vector3(poly[(i+1)%poly.size()].x,poly[(i+1)%poly.size()].y,depth)))
                            };

                            Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint,points);
                            if (cp.distance_squared_to(points[0])<CMP_EPSILON2 || cp.distance_squared_to(points[1])<CMP_EPSILON2)
                                continue; //not valid to reuse point

                            real_t d = cp.distance_to(gpoint);
                            if (d<closest_dist && d<grab_treshold) {
                                closest_dist=d;
                                closest_pos=cp;
                                closest_idx=i;
                            }


                        }

                        if (closest_idx>=0) {

                            pre_move_edit=poly;
                            poly.insert(closest_idx+1,cpoint);
                            edited_point=closest_idx+1;
                            edited_point_pos=cpoint;
                            node->set_polygon(poly);
                            _polygon_draw();
                            return true;
                        }
                    } else {

                        //look for points to move

                        int closest_idx=-1;
                        Vector2 closest_pos;
                        real_t closest_dist=1e10;
                        for(int i=0; i<poly.size(); i++) {

                            Vector2 cp = p_camera->unproject_position(gt.xform(Vector3(poly[i].x,poly[i].y,depth)));

                            real_t d = cp.distance_to(gpoint);
                            if (d<closest_dist && d<grab_treshold) {
                                closest_dist=d;
                                closest_pos=cp;
                                closest_idx=i;
                            }

                        }

                        if (closest_idx>=0) {

                            pre_move_edit=poly;
                            edited_point=closest_idx;
                            edited_point_pos=poly[closest_idx];
                            _polygon_draw();
                            return true;
                        }
                    }
                } else {

                    if (edited_point!=-1) {

                        //apply

                        ERR_FAIL_INDEX_V(edited_point,poly.size(),false);
                        poly[edited_point]=edited_point_pos;
                        undo_redo->create_action("Edit Poly");
                        undo_redo->add_do_method(node,"set_polygon",poly);
                        undo_redo->add_undo_method(node,"set_polygon",pre_move_edit);
                        undo_redo->add_do_method(this,"_polygon_draw");
                        undo_redo->add_undo_method(this,"_polygon_draw");
                        undo_redo->commit_action();

                        edited_point=-1;
                        return true;
                    }
                }
            }
            if (mb.button_index==BUTTON_RIGHT && mb.pressed && edited_point==-1) {



                int closest_idx=-1;
                Vector2 closest_pos;
                real_t closest_dist=1e10;
                for(int i=0; i<poly.size(); i++) {

                    Vector2 cp = p_camera->unproject_position(gt.xform(Vector3(poly[i].x,poly[i].y,depth)));

                    real_t d = cp.distance_to(gpoint);
                    if (d<closest_dist && d<grab_treshold) {
                        closest_dist=d;
                        closest_pos=cp;
                        closest_idx=i;
                    }

                }

                if (closest_idx>=0) {


                    undo_redo->create_action("Edit Poly (Remove Point)");
                    undo_redo->add_undo_method(node,"set_polygon",poly);
                    poly.remove(closest_idx);
                    undo_redo->add_do_method(node,"set_polygon",poly);
                    undo_redo->add_do_method(this,"_polygon_draw");
                    undo_redo->add_undo_method(this,"_polygon_draw");
                    undo_redo->commit_action();
                    return true;
                }

            }



        }
        break;
        }



    }
    break;
    case InputEvent::MOUSE_MOTION: {

        const InputEventMouseMotion &mm=p_event.mouse_motion;

        if (edited_point!=-1 && (wip_active || mm.button_mask&BUTTON_MASK_LEFT)) {

            Vector2 gpoint = Point2(mm.x,mm.y);

            Vector3 ray_from = p_camera->project_ray_origin(gpoint);
            Vector3 ray_dir = p_camera->project_ray_normal(gpoint);

            Vector3 spoint;

            if (!p.intersects_ray(ray_from,ray_dir,&spoint))
                break;

            Vector2 cpoint(spoint.x,spoint.y);

            //cpoint=snap_point(cpoint);
            edited_point_pos = cpoint;

            _polygon_draw();

        }

    }
    break;
    }

    return false;
}