Ejemplo n.º 1
0
void ResourceManager::AddMesh( sf::Uint32 id, std::string mesh_file ) {
	std::ifstream file( mesh_file.c_str() );

	if( !file.good() ) {
		LogConsole( "Failed to load Mesh resource " + string_cast( id ) + ", file not good." );
		return;
	}

	std::vector<sf::Vector3f> vertices;
	std::vector<sf::Vector3i> faces;

	std::string line;

	getline( file, line );

	char type;
	sf::Vector3f vertex;
	sf::Vector3i face;

	while( file.good() ) {
		std::stringstream line_stream( line );
		line_stream >> type;

		if( !line_stream.good() ) {
			LogConsole( "Failed to load Mesh resource " + string_cast( id ) + ", line stream not good." );
			return;
		}

		if( type == 'v' ) {
			line_stream >> vertex.x >> vertex.y >> vertex.z;

			vertices.push_back( vertex );
		} else if( type == 'f' ) {
Ejemplo n.º 2
0
Archivo: tools.cpp Proyecto: dedok/nkit
  std::string get_process_id()
  {
#if defined(NKIT_POSIX_PLATFORM)
    return "[" + string_cast((uint32_t)getpid()) + "]";
#elif defined(NKIT_WINNT)
  return "[" + string_cast((uint32_t)::GetCurrentProcessId()) + "]";
#else
#  error "static inline std::string get_process_id() does not supported"
#endif
  }
Ejemplo n.º 3
0
 void debug(char const *file, long line, const char *fmt = NULL, ...) {
     std::string s = "DEBUG: " + string_cast(file) + ":" + string_cast(line);
     if (!fmt) {
         printf("%s", s.c_str());
     }
     else {
         s = s + ": " + fmt;
         va_list args;
         va_start(args, fmt);
         vprintf(s.c_str(), args);
         va_end(args);
     }
     fflush(stdout);
 }
Ejemplo n.º 4
0
 void printf(std::string fmt, ...) const {
     fmt = string_cast(this->rank()) + ": " + fmt;
     va_list args;
     va_start(args, fmt);
     vfprintf(stdout, fmt.c_str(), args);
     va_end(args);
 }
void plugin_factory_collection::load_module(const filesystem::path& Path, const load_proxy_t LoadProxies)
{
	// K-3D modules now have the same extension on all platforms ...
	if(filesystem::extension(Path).lowercase().raw() != ".module")
		return;

	// If the module can be proxied for fast startup, do that and return ...
	if(LoadProxies == LOAD_PROXIES)
	{
		filesystem::path proxy_path = Path + ".proxy";
		if(filesystem::exists(proxy_path) && m_implementation->proxy_module(Path, proxy_path))
			return;
	}

	// OK, just load the module ...
	m_implementation->m_message_signal.emit(string_cast(boost::format(_("Loading plugin module %1%")) % Path.native_utf8_string().raw()));

	register_plugins_entry_point register_plugins = 0;
	os_load_module(Path, register_plugins);
	if(!register_plugins)
		return;

	// It's a K-3D module, all-right - give it a chance to register its plugins
	detail::plugin_registry registry(m_implementation->m_message_signal, m_implementation->m_factories);
	register_plugins(registry);
}
void plugin_factory_collection::load_modules(const filesystem::path& Path, const bool Recursive, const load_proxy_t LoadProxies)
{
	m_implementation->m_message_signal.emit(string_cast(boost::format(_("Searching for plugins in %1%")) % Path.native_utf8_string().raw()));

	// Create a sorted list of files in this directory ...
	std::vector<filesystem::path> files;
	for(k3d::filesystem::directory_iterator path(Path); path != k3d::filesystem::directory_iterator(); ++path)
		files.push_back(*path);
	std::sort(files.begin(), files.end());

	// Load modules
	for(std::vector<filesystem::path>::const_iterator file = files.begin(); file != files.end(); ++file)
	{
		if(!filesystem::is_directory(*file))
			load_module(*file, LoadProxies);
	}

	// Optionally descend recursively into subdirectories ...
	if(Recursive)
	{
		for(std::vector<filesystem::path>::const_iterator file = files.begin(); file != files.end(); ++file)
		{
			if(filesystem::is_directory(*file))
				load_modules(*file, Recursive, LoadProxies);
		}
	}
}
Ejemplo n.º 7
0
Object::Object( sf::Uint16 type, sf::String name, sf::Vector2f size, sf::Vector2f position,
								sf::Vector2f velocity, float rotation, float rotational_velecity ) :
	m_id( Game::GetGame()->GetObjectManager()->NewID() ),
	m_type( type ),
	m_name( name ),
	m_resource_id( 0 ),
	m_size( size ),
	m_position( position ),
	m_velocity( velocity ),
	m_rotation( rotation ),
	m_rotational_velocity( rotational_velecity ),
	m_delete_me( false ),
	m_dirty( true ),
	m_fresh( true ) {
	LogConsole( "Created object " + string_cast( m_id ) + " of type " + string_cast( m_type ) );
}
Ejemplo n.º 8
0
void Player::HandlePacket( PacketPtr packet ) {
	if( packet->getDataSize() < 4 ) {
		LogConsole("Player sent packet size < 4");
		return;
	}

	ObjectPtr agent( m_agent.lock() );
	if( !agent ) {
		LogConsole( "Player agent deleted, deleting player." );
		Delete();
		return;
	}

	sf::Uint16 type0;
	(*packet) >> type0;

	switch( type0 ) {
		case ClientToServer::CLIENT_COMMAND:
			agent->HandlePacket( packet );
			break;
		default:
			LogConsole( "Player sent packet with type0=" + string_cast( type0 ) );
			break;
	}
}
Ejemplo n.º 9
0
Archivo: tools.cpp Proyecto: dedok/nkit
 void rename(const std::string & from, const std::string & to)
 {
   if (::std::rename(from.c_str(), to.c_str()) == -1)
   {
     abort_with_core("RotateLogger rename file error: errno = "
         + string_cast(errno));
   }
 }
Ejemplo n.º 10
0
Player::~Player() {
	ObjectPtr agent( m_agent.lock() );
	if( agent ) {
		agent->Delete();
	}

	LogConsole( "Player " + string_cast( m_id ) + " destroyed" );
}
Ejemplo n.º 11
0
void ResourceManager::FillResourcePacket( sf::Uint32 id, PacketPtr packet ) const {
	std::map<sf::Uint32, const PacketPtr>::const_iterator iter( m_resources.find( id ) );

	if( iter == m_resources.end() ) {
		Die( "Could not find resource with ID: " + string_cast( id ) + "\n" );
	}

	packet->append( iter->second->getData(), iter->second->getDataSize() );
}
Ejemplo n.º 12
0
void ResourceManager::AddParticleSystem( sf::Uint32 id, ParticleSystem particle_system ) {
	if( m_resources.find( id ) != m_resources.end() ) {
		Die( "Resource " + string_cast( id ) + " already exists.\n" );
	}

	PacketPtr packet( std::make_shared<sf::Packet>() );

	(*packet) << static_cast<sf::Uint16>( ResourceType::PARTICLESYSTEM )
	          << id
	          << particle_system.texture_size
	          << particle_system.texture_sigma2
	          << particle_system.texture_exp;

	std::size_t emitters_size = particle_system.emitters.size();

	(*packet) << emitters_size;

	for( std::size_t index = 0; index < emitters_size; ++index ) {
		(*packet) << particle_system.emitters[ index ].rate;

		(*packet) << particle_system.emitters[ index ].spread;

		(*packet) << particle_system.emitters[ index ].radius_start;
		(*packet) << particle_system.emitters[ index ].radius_end;

		(*packet) << particle_system.emitters[ index ].prototype.lifetime;

		(*packet) << particle_system.emitters[ index ].prototype.velocity.x;
		(*packet) << particle_system.emitters[ index ].prototype.velocity.y;

		(*packet) << particle_system.emitters[ index ].prototype.acceleration.x;
		(*packet) << particle_system.emitters[ index ].prototype.acceleration.y;

		(*packet) << particle_system.emitters[ index ].prototype.size_start.x;
		(*packet) << particle_system.emitters[ index ].prototype.size_start.y;

		(*packet) << particle_system.emitters[ index ].prototype.size_end.x;
		(*packet) << particle_system.emitters[ index ].prototype.size_end.y;

		(*packet) << particle_system.emitters[ index ].prototype.color_start.r;
		(*packet) << particle_system.emitters[ index ].prototype.color_start.g;
		(*packet) << particle_system.emitters[ index ].prototype.color_start.b;
		(*packet) << particle_system.emitters[ index ].prototype.color_start.a;

		(*packet) << particle_system.emitters[ index ].prototype.color_end.r;
		(*packet) << particle_system.emitters[ index ].prototype.color_end.g;
		(*packet) << particle_system.emitters[ index ].prototype.color_end.b;
		(*packet) << particle_system.emitters[ index ].prototype.color_end.a;
	}

	m_resources.insert( std::pair<sf::Uint32, const PacketPtr>( id, packet ) );
}
Ejemplo n.º 13
0
igstk::TrackerTool::Pointer IgstkTool::buildInternalTool()
{
	igstk::TrackerTool::Pointer tool;

	igstk::PolarisTrackerTool::Pointer tempPolarisTool;
	igstk::AuroraTrackerTool::Pointer tempAuroraTool;

    igstk::Transform calibration = toIgstkTransform(mInternalStructure.mCalibration);
	switch (mInternalStructure.mTrackerType)
	{
	case tsNONE:
		break;
	case tsPOLARIS_SPECTRA:
	case tsPOLARIS_VICRA:
	case tsPOLARIS:
		tempPolarisTool = igstk::PolarisTrackerTool::New();
		tempPolarisTool->AddObserver(igstk::IGSTKEvent(), mToolObserver);
		if (!mInternalStructure.mWireless) //we only support wireless atm
			return tool = tempPolarisTool.GetPointer();
		tempPolarisTool->RequestSelectWirelessTrackerTool();
		tempPolarisTool->RequestSetSROMFileName(string_cast(mInternalStructure.mSROMFilename));
		tempPolarisTool->RequestConfigure();
        tempPolarisTool->SetCalibrationTransform(calibration);
		tool = tempPolarisTool;
		break;
	case tsAURORA:
		tempAuroraTool = igstk::AuroraTrackerTool::New();
		tempAuroraTool->AddObserver(igstk::IGSTKEvent(), mToolObserver);
		if (mInternalStructure.m5DOF)
		{
			tempAuroraTool->RequestSelect5DOFTrackerTool();
			tempAuroraTool->RequestSetPortNumber(mInternalStructure.mPortNumber);
			tempAuroraTool->RequestSetChannelNumber(mInternalStructure.mChannelNumber);
		}
		else
		{
			tempAuroraTool->RequestSelect6DOFTrackerTool();
			tempAuroraTool->RequestSetPortNumber(mInternalStructure.mPortNumber);
		}
		tempAuroraTool->RequestConfigure();
        tempAuroraTool->SetCalibrationTransform(calibration);
		tool = tempAuroraTool;
		break;
	case tsMICRON:
		//TODO: implement
		break;
	default:
		break;
	}
	return tool;
}
Ejemplo n.º 14
0
void Player::HandleSocketData() {
	while( !m_recv_buffer.empty() ) {
		PacketPtr packet = m_recv_buffer.front();

		if( !m_half_open ) {
			HandlePacket( packet );
		} else {
			LogConsole( "Client " + string_cast( m_id ) + " sent auth data" );

			Auth( packet );
		}

		m_recv_buffer.pop_front();
	}
}
Ejemplo n.º 15
0
void Player::SetAgent( sf::Uint16 id ) {
	m_tentative_agent_id = id;
	ObjectPtr object = Game::GetGame()->GetObjectManager()->GetObjectById( id );

	if( !object ) {
		return;
	}

	if( object->GetType() != ObjectType::SHIP ) {
		return;
	}

	ShipPtr agent = std::static_pointer_cast<Ship>( Game::GetGame()->GetObjectManager()->GetObjectById( id ) );
	agent->SetPlayer( true );
	LogConsole( "Set player ship to object: " + string_cast( id ) );
	m_tentative_agent_id = 0xffff;

	m_agent = agent;
}
Ejemplo n.º 16
0
Player::Player( ObjectPtr agent ) :
	m_id( Game::GetGame()->GetPlayerManager()->NewID() ),
	m_delete_me( false ),
	m_half_open( true ),
	m_agent(),
	m_inventory( std::make_shared<Inventory>() ) {

	LogConsole( "Player " + string_cast( m_id ) + " created" );

	// Set agent
	SetAgent( agent );

	ItemPtr some_item = std::make_shared<Item>( "Some Item", "Some Type" );
	ItemPtr another_item = std::make_shared<Item>( "Another Item", "Another Type" );

	m_inventory->AddItem( some_item, 3 );
	m_inventory->AddItem( another_item, 1 );
	m_inventory->RemoveItem( some_item, 1 );
}
Ejemplo n.º 17
0
/// Modify transformation
inode* modify_transformation(idocument& Document, inode& Object, iplugin_factory* Modifier)
{
	return_val_if_fail(Modifier, 0);

	// Get the upstream and downstream properties ...
	imatrix_sink* const downstream_sink = dynamic_cast<imatrix_sink*>(&Object);
	return_val_if_fail(downstream_sink, 0);

	iproperty& downstream_input = downstream_sink->matrix_sink_input();

	iproperty* const upstream_output = Document.pipeline().dependency(downstream_input);

	inode* modifier = 0;

	// This block is recorded for undo purposes ...
	{
		record_state_change_set changeset(Document, string_cast(boost::format(_("Add Modifier %1%")) % Modifier->name()), K3D_CHANGE_SET_CONTEXT);

		// Create our modifier object ...
		modifier = plugin::create<inode>(*Modifier, Document, unique_name(Document.nodes(), Modifier->name()));
		return_val_if_fail(modifier, 0);

		// Get its input and output properties ...
		imatrix_sink* const modifier_sink = dynamic_cast<imatrix_sink*>(modifier);
		return_val_if_fail(modifier_sink, 0);
		imatrix_source* const modifier_source = dynamic_cast<imatrix_source*>(modifier);
		return_val_if_fail(modifier_source, 0);

		// Insert the modifier into the DAG ...
		ipipeline::dependencies_t dependencies;
		if(upstream_output)
			dependencies.insert(std::make_pair(&modifier_sink->matrix_sink_input(), upstream_output));
		dependencies.insert(std::make_pair(&downstream_input, &modifier_source->matrix_source_output()));
		Document.pipeline().set_dependencies(dependencies);
	}

	return modifier;
}
Ejemplo n.º 18
0
void Game::Run() {
	m_frame_clock.restart();

	long counter = 0;
	float fps_micro_secs = 0.0f;

	while ( m_running && m_window->isOpen() ) {
		float micro_secs = static_cast<float>( m_frame_clock.getElapsedTime().asMicroseconds() );
		m_frame_clock.restart();

		Tick( micro_secs / 1000000.0f );

		counter++;

		fps_micro_secs += micro_secs;

		if( fps_micro_secs > 1000000.0f ) {
			fps_micro_secs = 0.0f;
			m_window->setTitle( "WYRM - " + string_cast( counter ) + " FPS" );
			counter = 0;
		}
	}
}
Ejemplo n.º 19
0
void IgstkTool::printInternalStructure()
{
	std::cout << "------------------------------------------------------------------" << std::endl;
	std::cout << "mIsProbe: " << mInternalStructure.mIsProbe << std::endl;
	std::cout << "mIsReference: " << mInternalStructure.mIsReference << std::endl;
	std::cout << "mIsPointer: " << mInternalStructure.mIsPointer << std::endl;
	std::cout << "mName: " << mInternalStructure.mName << std::endl;
	std::cout << "mUid: " << mInternalStructure.mUid << std::endl;
	std::cout << "mTrackerType: " << mInternalStructure.mTrackerType << std::endl;
	std::cout << "mSROMFilename: " << mInternalStructure.mSROMFilename << std::endl;
	std::cout << "mPortNumber: " << mInternalStructure.mPortNumber << std::endl;
	std::cout << "mChannelNumber: " << mInternalStructure.mChannelNumber << std::endl;
	std::cout << "mReferencePoints: " << string_cast(mInternalStructure.mReferencePoints.size()) << std::endl;
	std::cout << "mWireless: " << mInternalStructure.mWireless << std::endl;
	std::cout << "m5DOF: " << mInternalStructure.m5DOF << std::endl;
    std::cout << "mCalibration: " << mInternalStructure.mCalibration << std::endl;
    //mInternalStructure.mCalibration.Print(std::cout, itk::Indent());"
	std::cout << "mCalibrationFilename: " << mInternalStructure.mCalibrationFilename << std::endl;
	std::cout << "mGraphicsFileName: " << mInternalStructure.mGraphicsFileName << std::endl;
	std::cout << "mTransformSaveFileName: " << mInternalStructure.mTransformSaveFileName << std::endl;
	std::cout << "mLoggingFolderName: " << mInternalStructure.mLoggingFolderName << std::endl;
	std::cout << "------------------------------------------------------------------" << std::endl;
}
Ejemplo n.º 20
0
void ResourceManager::AddSphereTexture( sf::Uint32 id, int size, int octaves, float frequency, float persistence,
                                        float contrast, float brightness,
                                        GradientPoint* gradient, std::size_t num_gradient_points ) {
	if( m_resources.find( id ) != m_resources.end() ) {
		Die( "Resource " + string_cast( id ) + " already exists.\n" );
	}

	PacketPtr packet( std::make_shared<sf::Packet>() );

	(*packet) << static_cast<sf::Uint16>( ResourceType::SPHERE )
	          << id << size
	          << octaves << frequency << persistence << contrast << brightness << num_gradient_points;

	for( std::size_t index = 0; index < num_gradient_points; ++index ) {
		(*packet) << gradient[ index ].position;
		(*packet) << gradient[ index ].r;
		(*packet) << gradient[ index ].g;
		(*packet) << gradient[ index ].b;
		(*packet) << gradient[ index ].a;
	}

	m_resources.insert( std::pair<sf::Uint32, const PacketPtr>( id, packet ) );
}
Ejemplo n.º 21
0
std::map<std::string, std::string> getDisplayFriendlyInfo(MeshPtr mesh)
{
	std::map<std::string, std::string> retval;
	if(!mesh)
		return retval;

	//mesh
	retval["Filename"] = mesh->getFilename().toStdString();
	retval["Coordinate system"] = mesh->getCoordinateSystem().toString().toStdString();
	retval["Name"] = mesh->getName().toStdString();
	retval["Parent space"] = mesh->getParentSpace().toStdString();
	retval["Space"] = mesh->getSpace().toStdString();
	retval["Type"] = mesh->getType().toStdString();
	retval["Uid"] = mesh->getUid().toStdString();
	retval["rMd"] = string_cast(mesh->get_rMd());
	retval["Backface culling"] = string_cast(mesh->getBackfaceCulling());
	retval["Color"] = mesh->getColor().name().toStdString();
	retval["Frontface culling"] = string_cast(mesh->getFrontfaceCulling());
	retval["Is wireframe"] = string_cast(mesh->getIsWireframe());
	retval["Acquisition time"] = string_cast(mesh->getAcquisitionTime().toString(timestampSecondsFormatNice()));
	retval["Fiber bundle"] = string_cast(mesh->isFiberBundle());

	//vtkPolyData
	float actualMemorySizeKB = (float)mesh->getVtkPolyData()->GetActualMemorySize();
	retval["Actual memory size"] = string_cast(actualMemorySizeKB/(1024*1024))+" GB, "+string_cast(actualMemorySizeKB/1024)+" MB, "+string_cast(actualMemorySizeKB)+" kB";
	retval["Points"] = string_cast(mesh->getVtkPolyData()->GetNumberOfPoints());
	retval["Lines"] = string_cast(mesh->getVtkPolyData()->GetNumberOfLines());
	retval["Pieces"] = string_cast(mesh->getVtkPolyData()->GetNumberOfPieces());
	retval["Polys"] = string_cast(mesh->getVtkPolyData()->GetNumberOfPolys());
	retval["Strips"] = string_cast(mesh->getVtkPolyData()->GetNumberOfStrips());
	retval["Verts"] = string_cast(mesh->getVtkPolyData()->GetNumberOfVerts());

	return retval;
}
Ejemplo n.º 22
0
std::string variant::to_debug_string(std::vector<const game_logic::formula_callable*>* seen) const
{
	std::vector<const game_logic::formula_callable*> seen_stack;
	if(!seen) {
		seen = &seen_stack;
	}

	std::ostringstream s;
	switch(type_) {
	case TYPE_NULL:
		s << "(null)";
	case TYPE_INT:
		s << int_value_;
		break;
	case TYPE_DECIMAL:
		s << string_cast();
		break;
	case TYPE_LIST: {
		s << "[";
		for(size_t n = 0; n != num_elements(); ++n) {
			if(n != 0) {
				s << ", ";
			}

			s << operator[](n).to_debug_string(seen);
		}
		s << "]";
		break;
	}
	case TYPE_CALLABLE_LOADING: {
		char buf[64];
		sprintf(buf, "(loading %x)", callable_loading_);
		s << buf;
	}

	case TYPE_CALLABLE: {
		char buf[64];
		sprintf(buf, "(%p)", callable_);
		s << buf << "{";
		if(std::find(seen->begin(), seen->end(), callable_) == seen->end()) {
			seen->push_back(callable_);
			std::vector<game_logic::formula_input> v = callable_->inputs();
			bool first = true;
			for(size_t i=0; i<v.size(); ++i) {
				const game_logic::formula_input& input = v[i];
				if(!first) {
					s << ", ";
				}
				first = false;
				s << input.name << " ";
				if(input.access == game_logic::FORMULA_READ_WRITE) {
					s << "(read-write) ";
				} else if(input.access == game_logic::FORMULA_WRITE_ONLY) {
					s << "(writeonly) ";
				}

				s << "-> " << callable_->query_value(input.name).to_debug_string(seen);
			}
		} else {
			s << "...";
		}
		s << "}";
		break;
	}
	case TYPE_MAP: {
		s << "{";
		bool first_time = true;
		for(std::map<variant,variant>::const_iterator i=map_->elements.begin(); i != map_->elements.end(); ++i) {
			if(!first_time) {
				s << ",";
			}
			first_time = false;
			s << i->first.to_debug_string(seen);
			s << "->";
			s << i->second.to_debug_string(seen);
		}
		s << "}";
		break;
	}
	case TYPE_STRING: {
		s << "'" << string_->str << "'";
		break;
	}
	}

	return s.str();
}
Ejemplo n.º 23
0
// Replace:
//   array = { v1, v2, v3 };
// with
//   array[0] = v1;
//   array[1] = v2;
//   array[2] = v3;
std::string replace_array_assignations (const std::string code, std::set<std::string>& local_declarations)
{
	new_code_lines.clear();
	new_instanciations.clear();

	bool single_line_comment = false;
	bool multi_line_comment = false;
	bool preprocessor_directive = false;
	bool in_array_initialization = false;

	string_pos lvalue_end;
	string_pos current_code_line_start;
	string_pos array_start;

	unsigned int parenthesis_level = 0;

	char previous_character = ' ';

	std::map<std::string, std::string> replacements;
	std::map<std::string, std::string> replacement_lvalues;

	std::string new_code;
	for (std::string::size_type n = 0; n < code.size(); ++n)
	{
		char c = code[n];
		new_code += c;
		if (c == ' '
			|| c == '\n'
			|| c == '\t'
			|| c == '\r'
			|| single_line_comment
			|| multi_line_comment
			)
		{
			if (single_line_comment)
			{
				if (c == '\n' && previous_character != '\\')
				{
					single_line_comment = false;

					// new code line
					string_pos new_code_line_start = new_code.size();

					string_pos p = n;
					char next_c = code[p];
					while ((p < code.size()) && (next_c == '\n' || next_c == '\r'))
					{
						++p;
						++new_code_line_start;

						next_c = code[p];
					}

					new_code_line (new_code_line_start, new_code);
				}
			}

			if (multi_line_comment)
			{
				if (c == '/' && previous_character == '*')
					multi_line_comment = false;
			}

			if (preprocessor_directive)
			{
				if (c == '\n' && previous_character != '\\')
				{
					preprocessor_directive = false;

					// new code line
					string_pos new_code_line_start = new_code.size();
					current_code_line_start = new_code_line_start;

					string_pos p = n;
					char next_c = code[p];
					while ((p < code.size()) && (next_c == '\n' || next_c == '\r'))
					{
						++p;
						++new_code_line_start;

						next_c = code[p];
					}

					new_code_line (new_code_line_start, new_code);
				}
			}

			continue;
		}

		if (c == '/' && previous_character == '/')
		{
			single_line_comment = true;
		}
		else if (c == '*' && previous_character == '/')
		{
			multi_line_comment = true;
		}
		else if (c == '#')
		{
			preprocessor_directive = true;
		}
		else if (c == ';')
		{
			if (parenthesis_level == 0)
			{
				string_pos new_code_line_start = new_code.size();
				current_code_line_start = n + 1;

				string_pos p = n;
				char next_c = code[p];
				while (next_c == '\n' || next_c == '\r')
				{
					++p;
					++new_code_line_start;

					next_c = code[p];
				}

				new_code_line (new_code_line_start, new_code);
			}
		}
		else if (c == '=')
		{
			lvalue_end = n - 1;
		}
		else if (c == '(')
		{
			parenthesis_level++;
		}
		else if (c == ')')
		{
			parenthesis_level--;
		}
		else if (c == '{')
		{
			if (previous_character == '=')
			{
				// found array inialization
				in_array_initialization = true;
				array_start = n + 1;
			}
		}
		else if (c == '}')
		{
			if (in_array_initialization)
			{
				// found array initialization's end
				in_array_initialization = false;

				// store l-value
				std::string lvalue = std::string (code, current_code_line_start, lvalue_end - current_code_line_start + 1);
				lvalue = trim (lvalue);

				// put array in a string
				string_pos array_end = n - 1;
				std::string array = std::string (code, array_start, array_end - array_start + 1);

				string_pos replacement_start = current_code_line_start;
				string_pos replacement_size = array_end - replacement_start + 2;

				std::string replacement = std::string (code, replacement_start, replacement_size);

				// save for later replacement
				replacements[replacement] = array;
				replacement_lvalues[replacement] = lvalue;
			}
		}

		previous_character = c;
	}

	// build shader block
	std::string shader_block = "";
	for (std::vector<std::string>::iterator i = new_code_lines.begin(); i != new_code_lines.end(); ++i)
	{
		std::string line = *i;

		// quick'n'dirty replacements
		for (std::map<std::string, std::string>::iterator repl = replacements.begin(); repl != replacements.end(); ++repl)
		{
			std::string orig = repl->first;
			std::string array = repl->second;
			std::string lvalue = replacement_lvalues[orig];

			std::string::size_type repl_start = line.find (orig);
			if (repl_start != std::string::npos)
			{
				// split array
				std::vector<std::string> array_values = split_array (array);

				// build replacement
				std::string new_array = "\n";
				int array_index = 0;
				for (std::vector<std::string>::const_iterator val = array_values.begin(); val != array_values.end(); ++val)
				{
					if (array_index > 0)
					{
						new_array += ";\n";
					}

					new_array += "\t" + lvalue + "[" + string_cast (array_index++) + "] = " + *val;
				}

				// replace
				line.replace (repl_start, orig.size(), new_array);
			}
		}

		// save line
		shader_block += "\t" + line;
	}

	return shader_block;
}
Ejemplo n.º 24
0
/// Modify mesh
inode* modify_mesh(document_state& DocumentState, inode& Node, iplugin_factory* Modifier)
{
	return_val_if_fail(Modifier, 0);

	idocument& document = DocumentState.document();
	
	// Get the upstream and downstream properties ...
	imesh_sink* const downstream_sink = dynamic_cast<imesh_sink*>(&Node);
	return_val_if_fail(downstream_sink, 0);

	iproperty& downstream_input = downstream_sink->mesh_sink_input();

	iproperty* const upstream_output = document.pipeline().dependency(downstream_input);
	return_val_if_fail(upstream_output, 0);

	inode* modifier = 0;

	// This block is recorded for undo purposes ...
	{
		record_state_change_set changeset(document, string_cast(boost::format(_("Add Modifier %1%")) % Modifier->name()), K3D_CHANGE_SET_CONTEXT);

		// Create our modifier object ...
		modifier = plugin::create<inode>(*Modifier, document, unique_name(document.nodes(), Modifier->name()));
		return_val_if_fail(modifier, 0);

		// Get its input and output properties ...
		imesh_sink* const modifier_sink = dynamic_cast<imesh_sink*>(modifier);
		return_val_if_fail(modifier_sink, 0);
		imesh_source* const modifier_source = dynamic_cast<imesh_source*>(modifier);

		// Insert the modifier into the pipeline ...
		ipipeline::dependencies_t dependencies;
		dependencies.insert(std::make_pair(&modifier_sink->mesh_sink_input(), upstream_output));
		if(modifier_source)
			dependencies.insert(std::make_pair(&downstream_input, &modifier_source->mesh_source_output()));
		document.pipeline().set_dependencies(dependencies);

		// If the modifier is a mesh selection sink, set its selection state ...
		imesh_selection_sink* const modifier_mesh_selection_sink = dynamic_cast<imesh_selection_sink*>(modifier);
		imesh_selection_sink* const downstream_mesh_selection_sink = dynamic_cast<imesh_selection_sink*>(&Node);
		if(modifier_mesh_selection_sink && downstream_mesh_selection_sink)
		{
			if(selection::NODE == selection::state(DocumentState.document()).current_mode())
			{
				property::set_internal_value(
					modifier_mesh_selection_sink->mesh_selection_sink_input(),
					geometry::selection::create(1));
			}
			else
			{
				property::set_internal_value(
					modifier_mesh_selection_sink->mesh_selection_sink_input(),
					downstream_mesh_selection_sink->mesh_selection_sink_input().property_internal_value());
			}
	
			property::set_internal_value(
				downstream_mesh_selection_sink->mesh_selection_sink_input(),
				k3d::selection::set());
		}
	}
	
	// Give nodes a chance to initialize their property values based on their inputs, if any ...
	if(ireset_properties* const reset_properties = dynamic_cast<ireset_properties*>(modifier))
		reset_properties->reset_properties();

	return modifier;
}
Ejemplo n.º 25
0
void modify_selected_meshes(document_state& DocumentState, iplugin_factory* Modifier)
{
	return_if_fail(Modifier);
	idocument& document = DocumentState.document();
	if (Modifier->implements(typeid(imulti_mesh_sink)))
	{ // Mesh modifier taking multiple inputs
		uint_t count = 0;
		ipipeline::dependencies_t dependencies;
		const nodes_t selected_nodes = selection::state(DocumentState.document()).selected_nodes();
		// Create the node
		inode* multi_sink = pipeline::create_node(document, *Modifier);
		record_state_change_set changeset(document, string_cast(boost::format(_("Add Modifier %1%")) % Modifier->name()), K3D_CHANGE_SET_CONTEXT);
		nodes_t nodes_to_delete;
		for(nodes_t::const_iterator node = selected_nodes.begin(); node != selected_nodes.end(); ++node)
		{
			imesh_sink* const mesh_sink = dynamic_cast<imesh_sink*>(*node);
			if(!mesh_sink)
				continue;
			imatrix_sink* const matrix_sink = dynamic_cast<imatrix_sink*>(*node);

			iproperty* source_mesh = document.pipeline().dependency(mesh_sink->mesh_sink_input());
			if (!source_mesh)
				continue;
			
			if (matrix_sink) // Insert a transform node
			{
				iproperty* const source_transformation = document.pipeline().dependency(matrix_sink->matrix_sink_input());
				if (source_transformation)
				{
					inode* transform_points = plugin::create<inode>("TransformPoints", document, unique_name(document.nodes(), "TransformPoints"));
					return_if_fail(transform_points);
					imatrix_sink* transform_points_matrix_sink = dynamic_cast<imatrix_sink*>(transform_points);
					return_if_fail(transform_points_matrix_sink);
					imesh_sink* transform_points_mesh_sink = dynamic_cast<imesh_sink*>(transform_points);
					return_if_fail(transform_points_mesh_sink);
					dependencies.insert(std::make_pair(&transform_points_matrix_sink->matrix_sink_input(), source_transformation));
					dependencies.insert(std::make_pair(&transform_points_mesh_sink->mesh_sink_input(), source_mesh));
					imesh_source* transform_points_mesh_source = dynamic_cast<imesh_source*>(transform_points);
					return_if_fail(transform_points_mesh_source);
					source_mesh = &transform_points_mesh_source->mesh_source_output();
					imesh_selection_sink* selection_sink = dynamic_cast<imesh_selection_sink*>(transform_points);
					return_if_fail(selection_sink);
					property::set_internal_value(selection_sink->mesh_selection_sink_input(), k3d::geometry::selection::create(1.0));
				}
			}
			++count;
			// Create a new user property
			std::stringstream name, label;
			name << "input_mesh" << count;
			label << "Input Mesh " << count;
			iproperty* sink = property::get(*multi_sink, name.str());
			if (!sink)
				sink = property::create<mesh*>(*multi_sink, name.str(), label.str(), "", static_cast<mesh*>(0));
			// Store the connection
			dependencies.insert(std::make_pair(sink, source_mesh));
			// Delete the input node
			nodes_to_delete.push_back(*node);
		}
		document.pipeline().set_dependencies(dependencies);
		delete_nodes(document, nodes_to_delete);
		// Give nodes a chance to initialize their property values based on their inputs, if any ...
		if(ireset_properties* const reset_properties = dynamic_cast<ireset_properties*>(multi_sink))
			reset_properties->reset_properties();

		panel::mediator(DocumentState.document()).set_focus(*multi_sink);
	}
	else
	{ // Normal mesh modifier
		nodes_t new_modifiers;
	
		const nodes_t selected_nodes = selection::state(DocumentState.document()).selected_nodes();
		for(nodes_t::const_iterator node = selected_nodes.begin(); node != selected_nodes.end(); ++node)
		{
			new_modifiers.push_back(modify_mesh(DocumentState, **node, Modifier));
			assert_warning(new_modifiers.back());
		}
	
		// Show the new modifier properties if only one was processed
		if(selected_nodes.size() == 1)
		{
			panel::mediator(DocumentState.document()).set_focus(*new_modifiers.front());
		}
		else // otherwise connect all parameter properties to the first node and show that one
		{
			iproperty_collection* first_property_collection = dynamic_cast<iproperty_collection*>(new_modifiers.front());
			if (first_property_collection)
			{
				// Get the in-and output property names, to exclude them from the connections
				imesh_sink* const modifier_sink = dynamic_cast<imesh_sink*>(new_modifiers.front());
				return_if_fail(modifier_sink);
				imesh_source* const modifier_source = dynamic_cast<imesh_source*>(new_modifiers.front());
				return_if_fail(modifier_source);
				const std::string sink_name = modifier_sink->mesh_sink_input().property_name();
				const std::string source_name = modifier_source->mesh_source_output().property_name();
				
				ipipeline::dependencies_t dependencies;
				const iproperty_collection::properties_t& first_properties = first_property_collection->properties();
				nodes_t::iterator modifier = new_modifiers.begin();
				++modifier;
				for (modifier; modifier != new_modifiers.end(); ++modifier)
				{
					iproperty_collection* property_collection = dynamic_cast<iproperty_collection*>(*modifier);
					return_if_fail(property_collection);
					const iproperty_collection::properties_t& properties = property_collection->properties();
					iproperty_collection::properties_t::const_iterator property = properties.begin();
					for (iproperty_collection::properties_t::const_iterator first_property = first_properties.begin(); first_property != first_properties.end(); ++first_property)
					{
						return_if_fail(property != properties.end());
						return_if_fail((*property)->property_name() == (*first_property)->property_name());
						if ((*property)->property_name() == sink_name || (*property)->property_name() == source_name || (*property)->property_name() == "name")
						{
							++property;
							continue;
						}
						dependencies.insert(std::make_pair(*property, *first_property));
						++property;
					}
				}
				document.pipeline().set_dependencies(dependencies);
				panel::mediator(DocumentState.document()).set_focus(*new_modifiers.front());
			}
		}
	}
}
Ejemplo n.º 26
0
Archivo: tools.cpp Proyecto: dedok/nkit
 std::string string_cast(unsigned long i)
 {
   return string_cast(static_cast<size_t>(i));
 }
Ejemplo n.º 27
0
Object::~Object() {
	LogConsole( "Destroyed object " + string_cast( m_id ) + " of type " + string_cast( m_type ) );
}