void DisplayFilterEdit::bookmarkClicked()
{
    emit addBookmark(text());
}
bool InspectorIH::handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& /*aa*/ )
{
    const osgSDL::SDLEventAdapter* p_eventAdapter = dynamic_cast< const osgSDL::SDLEventAdapter* >( &ea );
    assert( p_eventAdapter && "invalid event adapter received" );

    unsigned int     eventType    = p_eventAdapter->getEventType();
    int              key          = p_eventAdapter->getSDLKey();
    const SDL_Event& sdlevent     = p_eventAdapter->getSDLEvent();

    if ( eventType == osgGA::GUIEventAdapter::FRAME )
        return false;

    // terminate application on Escape
    if ( key == SDLK_ESCAPE )
        yaf3d::Application::get()->stop();

    // toggle info dialog rendering
    if ( ( key == SDLK_SPACE ) && ( eventType == osgGA::GUIEventAdapter::KEYDOWN ) )
    {
        _infoEnabled = !_infoEnabled;
        getUserObject()->enableInfoWindow( _infoEnabled );
    }

    // enable / disable picking mode
    if ( ( key == SDLK_RCTRL ) || ( key == SDLK_LCTRL ) )
    {
        if ( eventType == osgGA::GUIEventAdapter::KEYDOWN )
            _pickingEnabled = true;
        else if ( eventType == osgGA::GUIEventAdapter::KEYUP )
            _pickingEnabled = false;
    }

    // pick an object
    if ( _pickingEnabled )
    {
        if ( sdlevent.button.button == SDL_BUTTON_LEFT && eventType == osgGA::GUIEventAdapter::PUSH )
        {
            float x = sdlevent.motion.x, y = sdlevent.motion.y;
            x = 2.0f * ( x * _iscreenWidth ) - 1.0f;
            y = 2.0f * ( y * _iscreenHeight ) - 1.0f;

            // picked something?
            if ( pick( x, -y ) )
            {

                InspectorIH::PickResults* res = getPickResults();

                osgUtil::Hit*   p_hit      = res->_p_hit;
                osg::Drawable*  p_drawable = res->_p_drawable;

                // evaluate the node path of picked drawable and extract drawable's node name and location ( in world space )
                osg::NodePath& nodepath = p_hit->getNodePath();
                std::string nodename;
                if ( nodepath.size() )
                {
                    osg::MatrixTransform* p_mtNode = NULL;
                    osg::NodePath::iterator p_nbeg = nodepath.end(), p_nend = nodepath.begin();
                    p_nbeg--;
                    for ( ; p_nbeg != p_nend; --p_nbeg )
                    {
                        osg::MatrixTransform* p_mt  = dynamic_cast< osg::MatrixTransform* >( *p_nbeg );
                        osg::Group*           p_grp = dynamic_cast< osg::Group* >( *p_nbeg );

                        if ( !nodename.length() )
                        {
                            if ( p_mt )
                            {
                                nodename = p_mt->getName();
                                if ( !p_mtNode ) // we need only the first embedding transform node
                                    p_mtNode = p_mt;
                            }
                            else if ( p_grp )
                            {
                                nodename = p_grp->getName();
                            }
                        }
                        else
                            break;
                    }

                    // update the bbox and get its dimensions
                    const osg::Matrix* p_mat = p_hit->getMatrix();
                    osg::Vec3f pos = p_mat->getTrans();
                    osg::Vec3f dims( updateBBox( p_drawable, *p_mat, p_mtNode ? true : false ) );

                    // get primitive count of selected drawable
                    const osg::Geometry*    p_geom = p_drawable->asGeometry();
                    unsigned int            prims  = p_geom->getNumPrimitiveSets();

                    // format and set the output text
                    std::ostringstream str;
                    str << "name       " << nodename << std::endl;
                    str << "position   " << pos.x() << " " << pos.y() << " " << pos.z() << std::endl;
                    str << "primitives " << prims << std::endl;
                    str << "dimensions " << dims.x() << " " << dims.y() << " " << dims.z() << std::endl;
                    CEGUI::String text( str.str() );
                    getUserObject()->setPickerOutputText( text );
                }
            }
        }
    }

    // don't check for movement keys when locked
    if ( _lockMovement )
        return false;

    EnCamera*   p_camera = getUserObject()->_p_cameraEntity;
    float&      speed    = getUserObject()->_speed;
    float&      dt       = getUserObject()->_deltaTime;
    osg::Vec3f  pos;

    if ( eventType == osgGA::GUIEventAdapter::KEYDOWN )
    {
        if ( key == SDLK_w )
            _moveForward = true;
        else if ( key == SDLK_s )
            _moveBackward = true;
        else if ( key == SDLK_a )
            _moveLeft = true;
        else if ( key == SDLK_d )
            _moveRight = true;
    }
    else if ( eventType == osgGA::GUIEventAdapter::KEYUP )
    {
        if ( key == SDLK_w )
            _moveForward = false;
        else if ( key == SDLK_s )
            _moveBackward = false;
        else if ( key == SDLK_a )
            _moveLeft = false;
        else if ( key == SDLK_d )
            _moveRight = false;
    }

    if ( _moveForward )
        pos._v[ 1 ] += speed * dt;
    else if ( _moveBackward )
        pos._v[ 1 ] -= speed * dt;

    if ( _moveLeft )
        pos._v[ 0 ] -= speed * dt;
    else if ( _moveRight )
        pos._v[ 0 ] += speed * dt;

    // enable the camera rotation on dragging right mouse button
    if ( sdlevent.button.button == SDL_BUTTON_RIGHT )
    {
        if ( eventType == osgGA::GUIEventAdapter::PUSH )
            _rotationEnabled = true;
        else if ( eventType == osgGA::GUIEventAdapter::RELEASE )
            _rotationEnabled = false;
    }

    // adjust pitch and yaw
    if ( ( eventType == osgGA::GUIEventAdapter::DRAG ) && _rotationEnabled )
    {
        // skip events which come in when we warp the mouse pointer to middle of app window ( see below )
        if ( (  sdlevent.motion.x == _screenMiddleX ) && ( sdlevent.motion.y == _screenMiddleY ) )
            return false;

        static float lastxrel = 0;
        static float lastyrel = 0;
        float xrel = float( sdlevent.motion.xrel ) * dt;
        float yrel = float( sdlevent.motion.yrel ) * dt;

        // smooth the view change avoiding hart camera rotations
        _yaw   += ( xrel + lastxrel ) * 0.1f;
        _pitch += ( yrel + lastyrel ) * 0.1f;
        lastxrel = xrel;
        lastyrel = yrel;

        // set new camera orientation
        p_camera->setLocalPitchYaw( -_pitch, -_yaw );

        // reset mouse position in order to avoid leaving the app window
        yaf3d::Application::get()->getViewer()->requestWarpPointer( _screenMiddleX, _screenMiddleY );
    }

    // update camera position
    if ( _moveForward || _moveBackward || _moveLeft || _moveRight )
    {
        pos = p_camera->getLocalRotation() * pos;
        p_camera->setCameraPosition( pos + p_camera->getCameraPosition() );
    }

    return false;
}
void TiXmlElement::StreamIn (std::istream * in, TIXML_STRING * tag)
{
	// We're called with some amount of pre-parsing. That is, some of "this"
	// element is in "tag". Go ahead and stream to the closing ">"
	while( in->good() )
	{
		int c = in->get();
		if ( c <= 0 )
		{
			TiXmlDocument* document = GetDocument();
			if ( document )
				document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
			return;
		}
		(*tag) += (char) c ;
		
		if ( c == '>' )
			break;
	}

	if ( tag->length() < 3 ) return;

	// Okay...if we are a "/>" tag, then we're done. We've read a complete tag.
	// If not, identify and stream.

	if (    tag->at( tag->length() - 1 ) == '>' 
		 && tag->at( tag->length() - 2 ) == '/' )
	{
		// All good!
		return;
	}
	else if ( tag->at( tag->length() - 1 ) == '>' )
	{
		// There is more. Could be:
		//		text
		//		cdata text (which looks like another node)
		//		closing tag
		//		another node.
		for ( ;; )
		{
			StreamWhiteSpace( in, tag );

			// Do we have text?
			if ( in->good() && in->peek() != '<' ) 
			{
				// Yep, text.
				TiXmlText text( "" );
				text.StreamIn( in, tag );

				// What follows text is a closing tag or another node.
				// Go around again and figure it out.
				continue;
			}

			// We now have either a closing tag...or another node.
			// We should be at a "<", regardless.
			if ( !in->good() ) return;
			assert( in->peek() == '<' );
			int tagIndex = (int) tag->length();

			bool closingTag = false;
			bool firstCharFound = false;

			for( ;; )
			{
				if ( !in->good() )
					return;

				int c = in->peek();
				if ( c <= 0 )
				{
					TiXmlDocument* document = GetDocument();
					if ( document )
						document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
					return;
				}
				
				if ( c == '>' )
					break;

				*tag += (char) c;
				in->get();

				// Early out if we find the CDATA id.
				if ( c == '[' && tag->size() >= 9 )
				{
					size_t len = tag->size();
					const char* start = tag->c_str() + len - 9;
					if ( strcmp( start, "<![CDATA[" ) == 0 ) {
						assert( !closingTag );
						break;
					}
				}

				if ( !firstCharFound && c != '<' && !IsWhiteSpace( c ) )
				{
					firstCharFound = true;
					if ( c == '/' )
						closingTag = true;
				}
			}
			// If it was a closing tag, then read in the closing '>' to clean up the input stream.
			// If it was not, the streaming will be done by the tag.
			if ( closingTag )
			{
				if ( !in->good() )
					return;

				int c = in->get();
				if ( c <= 0 )
				{
					TiXmlDocument* document = GetDocument();
					if ( document )
						document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
					return;
				}
				assert( c == '>' );
				*tag += (char) c;

				// We are done, once we've found our closing tag.
				return;
			}
			else
			{
				// If not a closing tag, id it, and stream.
				const char* tagloc = tag->c_str() + tagIndex;
				TiXmlNode* node = Identify( tagloc, TIXML_DEFAULT_ENCODING );
				if ( !node )
					return;
				node->StreamIn( in, tag );
				delete node;
				node = 0;

				// No return: go around from the beginning: text, closing tag, or node.
			}
		}
	}
}
void
PlayableItemWidget::paintEvent( QPaintEvent* event )
{   
    static QPixmap m_radio_left_hover = QPixmap( ":/meta_radio_LEFT_HOVER.png" );
    static QPixmap m_radio_left_press = QPixmap( ":/meta_radio_LEFT_PRESS.png" );
    static QPixmap m_radio_left_rest = QPixmap( ":/meta_radio_LEFT_REST.png" );

    static QPixmap m_radio_middle_hover = QPixmap( ":/meta_radio_MIDDLE_HOVER.png" );
    static QPixmap m_radio_middle_press = QPixmap( ":/meta_radio_MIDDLE_PRESS.png" );
    static QPixmap m_radio_middle_rest = QPixmap( ":/meta_radio_MIDDLE_REST.png" );

    static QPixmap m_radio_right_hover = QPixmap( ":/meta_radio_RIGHT_HOVER.png" );
    static QPixmap m_radio_right_press = QPixmap( ":/meta_radio_RIGHT_PRESS.png" );
    static QPixmap m_radio_right_rest = QPixmap( ":/meta_radio_RIGHT_REST.png" );

    static QPixmap m_radio_small_hover = QPixmap( ":/radio_play_small_HOVER.png" );
    static QPixmap m_radio_small_press = QPixmap( ":/radio_play_small_PRESS.png" );
    static QPixmap m_radio_small_rest = QPixmap( ":/radio_play_small_REST.png" );

    if ( m_style == DescriptionNone )
    {
        QPushButton::paintEvent( event );
    }
    else if ( m_style == DescriptionElide )
    {
        QPainter p(this);

        QTextOption to;
        to.setAlignment( Qt::AlignLeft | Qt::AlignVCenter );

        QRect textRect = contentsRect().adjusted( 30, 0, 0, 0 );
        p.drawText( textRect, fontMetrics().elidedText( text(), Qt::ElideRight, textRect.width() ), to );

        if ( isDown() )
            p.drawPixmap( rect().topLeft(), m_radio_small_press );
        else if ( m_hovered )
            p.drawPixmap( rect().topLeft(), m_radio_small_hover );
        else
            p.drawPixmap( rect().topLeft(), m_radio_small_rest );
    }
    else if ( m_style == DescriptionBottom )
    {
        QPushButton::paintEvent( event );

        QPainter p( this );

        p.setPen( QColor( 0x898989 ) );

        QFont font = p.font();
        font.setPixelSize( 12 );
        p.setFont( font );

        QTextOption to;
        to.setAlignment( Qt::AlignBottom );

        QFontMetrics fm( font );

        QRect rect = contentsRect();
        rect.adjust( 54, 0, 0, -14 );
        p.drawText( rect, fm.elidedText( m_description, Qt::ElideRight, rect.width() ), to );
    }
    else if ( m_style == ThreePart )
    {
        QPainter p( this );

        QRect middleRect = QRect( m_radio_left_rest.width(), 0, rect().width() - m_radio_left_rest.width() - m_radio_right_rest.width(), 49 );

        if ( isDown() )
        {
            p.drawPixmap( rect().topLeft(), m_radio_left_press );
            p.drawPixmap( middleRect, m_radio_middle_press );
            p.drawPixmap( rect().topLeft() + QPoint( rect().width() - m_radio_right_press.width(), 0 ), m_radio_right_press );
        }
        else if ( m_hovered )
        {
            p.drawPixmap( rect().topLeft(), m_radio_left_hover );
            p.drawPixmap( middleRect, m_radio_middle_hover );
            p.drawPixmap( rect().topLeft() + QPoint( rect().width() - m_radio_right_hover.width(), 0 ), m_radio_right_hover );
        }
        else
        {
            p.drawPixmap( rect().topLeft(), m_radio_left_rest );
            p.drawPixmap( middleRect, m_radio_middle_rest );
            p.drawPixmap( rect().topLeft() + QPoint( rect().width() - m_radio_right_rest.width(), 0 ), m_radio_right_rest );
        }

        QFontMetrics fmText( font() );
        QRect textRect = rect().adjusted( 40, 8, -20, 0 );
        p.drawText( textRect, fmText.elidedText( text(), Qt::ElideRight, textRect.width() ) );

        p.setPen( QColor( 0x898989 ) );

        QFont font = p.font();
        font.setPixelSize( 10 );
        p.setFont( font );

        QFontMetrics fmDesc( font );
        QRect descRect = rect().adjusted( 40, 28, -20, 0 );
        p.drawText( descRect, fmDesc.elidedText( m_description, Qt::ElideRight, descRect.width() ) );
    }
}
Exemple #5
0
void manageCell(void)
{
	char i, j, a, combat;
	char *ptr;
	//printf("ca = %d\n", ca);
	if (ca==7 || ca==8 || ca==51) {
		// personnage
		//printf("Voila un personnage, dialoguer (O/N) ?\n");
        //a = get();
        //if (a == 'o' || a == 'O') { 
			text();
			io_needed = 0;
			saveCharacters();
			restorePageZero();
			SwitchToCommand("DIALOG");
		//} else {
		//	puts("\n");
		//}
	} else if (ca==99) {
		printf("        Retour au village (O/N)?\n");
        a = get();
        if (a == 'o' || a == 'O') { 
        	text();
        	io_needed = 1;
        	// re-init de la position et orientation pour retour laby
        	x = y = s = 2;
			saveCharacters();
			restorePageZero();
        	SwitchToCommand("VILLE");
		} else {
			puts("\n");
		}
	} else if (ca >=30 && ca <= 50) {
		// combats_coffres[ville-1]
		// si le combat n'a pas été déjà fini
		unsigned char nb = ca - 30 + 8; // les 8 premiers bits stockent les coffres
		if(!TestBit(combats_coffres[ville-1], nb)) {
			printf("       Combat !", ca);
			wait(300);
			//printf("Combat %d non fini!\n", nb);
			//printf("debug : C pour combat, autre evite.\n");
			//a = get();
			//if (a == 'c' || a == 'C') {
				DiscLoad("STARK.BIN");
				puts("    < ESPACE >");
				a = get();
				if (a == 's' || a == 'S') return; // skip
				text();
				io_needed = 0;
				saveCharacters();
				restorePageZero();
				SwitchToCommand("COMBAT");
			//}
		}
	// coffres
	} else if (ca>=21 && ca<=28) {
		// si le coffre n'a pas été déjà ouvert
		unsigned char nb = ca - 21;
		if(!TestBit(combats_coffres[ville-1], nb)) {
			printf("      Vous trouvez un coffre !", ca);
			wait(300);
			//printf("Coffre %d non fini!\n", nb);
			//printf("debug : C pour camp, autre evite.\n");
			//a = get();
			//if (a == 'c' || a == 'C') {
				text();
				io_needed = 1;
				saveCharacters();
				restorePageZero();
				SwitchToCommand("CAMP");
			//}
		}
	} else if (ca==52) {
		DiscLoad("ZWALL2.BIN");
		/* // A ADAPTER
		3101 IFPM=0THENPRINT"ET LA POTION ?":ZAP:WAIT50:GOTO3104
		3102 IF WALL=1THENPRINT"VERS LE NORD DU MUR":GOTO3110
		3104 PRINT"PORTE DU NORD CLOSE":WAITTI*10:GOTO3140
		3110 GETA$:IFA$=""THEN3110
		3120 GOSUB 30500:ZAP:TEXT:PRINT@10,10;"ZE END":END
		3130 FORI=1TO5:ZAP:WAIT30:NEXT:SHOOT
		3140 X=XO:Y=YO
		3150 RETURN
		*/
		if(pm==0) { // potion
			printf("      ET LA POTION ?\n");
			zap();
			wait(400);
		} else if(TestBit(&dedans, 7)) { // wall
			printf("      VERS LE NORD DU MUR\n");
			wait(250);
			text();
			io_needed = 0;
			saveCharacters();
			restorePageZero();
			SwitchToCommand("DIALOG");
		} else {
			printf("     PORTE DU NORD CLOSE\n");
			wait(400);
		}
	} else {
		// combats aléatoires ?
#ifdef RANDOM
		combat = (nb_combat < 20) ? rand()%10 == 1 : rand()%15 == 1;
		if(combat) {
			nb_combat++;
			printf("combat %d\n", ca);
			printf("debug : C pour combat, autre evite (nb combat : %d).\n", nb_combat);
			a = get();
			if (a == 'c' || a == 'C') {
				text();
				io_needed = 0;
				saveCharacters();
				restorePageZero();
				SwitchToCommand("COMBAT");
			}
		}
#endif
	}
	//prep();
	//drawLaby();
}
void MainWindow::generateImage(const QString &path)
{
    try {
        QFile imageFile(path);
        if (!imageFile.open(QIODevice::WriteOnly)) {
            throw tr("<p>Could not write the image file</p><p>The error message was: %1</p>").arg(imageFile.errorString());
        }
        QDataStream ds(&imageFile);
        // First calculate everything.
        struct DirectoryEntry {
            QString filePath; // The path of the file.
            quint32 startBlock; // The start block, relative to the directory size.
            quint32 fileSize; // The size of the file.
            quint8 fileNameSize; // The size of the file name.
            QByteArray fileName; // The file name in ascii format.
        };
        QRegularExpression reValidFileName("^[-a-z0-9_]{1,16}$", QRegularExpression::CaseInsensitiveOption);
        QSet<QString> identifiers;
        QList<DirectoryEntry> directoryEntries;
        quint32 currentStartBlock = 0;
        for (int i = 0; i < ui->fileList->topLevelItemCount(); ++i) {
            // Gather all available information and check if everything is in range.
            const auto item = ui->fileList->topLevelItem(i);
            const QString identifier = item->text(0);
            if (identifiers.contains(identifier)) {
                throw tr("The identifier \"%1\" exists multiple times.").arg(identifier);
            }
            const QString filePath = item->data(0, DataPath).toString();
            QFileInfo fileInfo(filePath);
            if (!fileInfo.exists()) {
                throw tr("Could not find file \"%1\" with path \"%2\".").arg(identifier).arg(filePath);
            }
            if (!fileInfo.isReadable()) {
                throw tr("File \"%1\" with path \"%2\" is not readable.").arg(identifier).arg(filePath);
            }
            const qint64 fileSize = fileInfo.size();
            if (fileSize > Q_INT64_C(0xffffffff)) {
                throw tr("The file size of file \"%1\" with path \"%2\" exceeds the maximum size of 4.2GB.").arg(identifier).arg(filePath);
            }
            if (fileSize == 0) {
                throw tr("The file size of file \"%1\" with path \"%2\" is zero. This is not supported.").arg(identifier).arg(filePath);
            }
            if (!reValidFileName.match(identifier).hasMatch()) {
                throw tr("The identifier \"%1\" is not valid. Only characters a-z, 0-9, _ and - are allowed. The length of the identifier must be between 1 and 16 characters.").arg(identifier);
            }
            // Create the directory entry.
            DirectoryEntry entry;
            entry.filePath = filePath;
            entry.startBlock = currentStartBlock;
            entry.fileSize = static_cast<quint32>(fileSize);
            entry.fileName = identifier.toUtf8();
            entry.fileNameSize = static_cast<quint8>(entry.fileName.size());
            identifiers.insert(identifier);
            directoryEntries.append(entry);
            const quint32 numberOfBlocks = static_cast<quint32>(((fileSize-Q_INT64_C(1))/static_cast<qint64>(cSDBlockSize)))+1;
            currentStartBlock += numberOfBlocks;
        }
        // Calculate the directory size.
        quint32 directorySize = (4 + 4); // 4 bytes magic + 4 bytes end mark.
        for (auto entry : directoryEntries) {
            directorySize += (9 + entry.fileNameSize);
        }
        const quint32 firstDataBlock = ((directorySize-1)/512u)+1u;
        // Write the directory.
        if (ds.writeRawData("HCDI", 4) != 4) {
            throw tr("Could not write the magic to the image file.");
        }
        ds.setByteOrder(QDataStream::LittleEndian);
        for (auto entry : directoryEntries) {
            if (ui->nonHcCards->isChecked()) {
                ds << static_cast<quint32>((entry.startBlock + firstDataBlock) * 512);
            } else {
                ds << static_cast<quint32>(entry.startBlock + firstDataBlock);
            }
            ds << static_cast<quint32>(entry.fileSize);
            ds << static_cast<quint8>(entry.fileNameSize);
            if (ds.writeRawData(entry.fileName.constData(), entry.fileNameSize) != entry.fileNameSize) {
                throw tr("There was a problem writing to the image file.");
            }
        }
        // Write the end mark.
        ds << static_cast<quint32>(0);
        // Fill bytes to the next full block size.
        while ((imageFile.pos() & cSDBlockSizeMask) != 0) {
            ds << static_cast<quint8>(0);
        }
        // Now copy all files
        char buffer[cSDBlockSize];
        for (auto entry : directoryEntries) {
            QFile entryFile(entry.filePath);
            if (!entryFile.open(QIODevice::ReadOnly)) {
                throw tr("Could not open the file \"%1\" with path \"%2\". The error message was: %3").arg(QString::fromLatin1(entry.fileName)).arg(entry.filePath).arg(entryFile.errorString());
            }
            while (!entryFile.atEnd()) {
                const qint64 readBytes = entryFile.read(buffer, cSDBlockSize);
                if (readBytes > 0) {
                    qint64 writeIndex = 0;
                    qint64 writtenBytes = 0;
                    while (writeIndex < readBytes) {
                        writtenBytes = imageFile.write(buffer + writeIndex, readBytes - writeIndex);
                        if (writtenBytes < 0) {
                            throw tr("There was a problem writing data to the image.");
                        }
                        writeIndex += writtenBytes;
                    }
                    // Fill bytes to the next full block size.
                    while ((imageFile.pos() & cSDBlockSizeMask) != 0) {
                        ds << static_cast<quint8>(0);
                    }
                }
            }
            entryFile.close();
        }
        imageFile.close();
        // Successfully wrote the image file.
    } catch (const QString &message) {
        QMessageBox m(this);
        m.setIcon(QMessageBox::Critical);
        m.setText(message);
        m.exec();
    }
}
Exemple #7
0
void MainWindow::saveFile()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("XML Files (*.xml)"));

    if(fileName != "")
    {
        TiXmlDocument doc;
        // Declaration
        TiXmlDeclaration declaration(std::string("1.0"), std::string(), std::string() );
        // InsertEndChild method uses deep copy
        doc.InsertEndChild( declaration );
        TiXmlElement project("project");
        TiXmlElement node("name");
        // Use TiXmlText to insert text body to an element
        // Covert QString back to std::string
        TiXmlText text(projectName.toStdString());
        node.InsertEndChild(text);
        project.InsertEndChild(node);

        // And all the HEES components
        QList<QGraphicsItem*> itemList = scene->items();
        for(int i=0;i<itemList.size();i++)
        {
            HEESGraphicsItem * item = dynamic_cast<HEESGraphicsItem *>(itemList[i]);
            if( item )
            {
                TiXmlElement comp("comp");
                switch(item->myType())
                {
                case SOURCE:
                    comp.SetAttribute("type","source");
                    break;
                case LOAD:
                    comp.SetAttribute("type","load");
                    break;
                case BANK:
                    comp.SetAttribute("type","bank");
                    break;
                case CTI:
                    comp.SetAttribute("type","cti");
                    break;
                case CONVERTER:
                    comp.SetAttribute("type","converter");
                    break;
                case MANAGER:
                    comp.SetAttribute("type","manager");
                    break;
                }

                comp.SetAttribute("x_pos", item->x());
                comp.SetAttribute("y_pos", item->y());

                TiXmlElement nameNode("name");
                text.SetValue(item->name.toStdString());
                nameNode.InsertEndChild(text);
                comp.InsertEndChild(nameNode);

                if(item->myType() == CONVERTER)
                {
                    TiXmlElement portANode("port_a");
                    text.SetValue(item->getPortAName().toStdString());
                    portANode.InsertEndChild(text);
                    comp.InsertEndChild(portANode);

                    TiXmlElement portBNode("port_b");
                    text.SetValue(item->getPortBName().toStdString());
                    portBNode.InsertEndChild(text);
                    comp.InsertEndChild(portBNode);
                }

                TiXmlElement derivedNode("derived");
                if(item->myType() != CTI)
                {
                    derivedNode.SetAttribute("type",item->derivedType.toStdString());
                }

                DerivedAttributes * attributes = item->myAttributes();
                for(int j=0; j<attributes->rowCount()-1; j++)
                {
                    TiXmlElement attributeNode(attributes->nameAt(j).toStdString());
                    text.SetValue(attributes->valueAt(j).toStdString());
                    attributeNode.InsertEndChild(text);
                    derivedNode.InsertEndChild(attributeNode);
                }

                comp.InsertEndChild(derivedNode);
                project.InsertEndChild(comp);
            }
        }

        // Add all the sensors
        for(int i=0;i<itemList.size();i++)
        {
            HEESGraphicsItem * item = dynamic_cast<HEESGraphicsItem *>(itemList[i]);
            if( item )
            {
                SensorList * sensorList = item->mySensors();
                for(int j=0; j<sensorList->size(); j++)
                {
                    TiXmlElement sensorNode("sensor");
                    sensorNode.SetAttribute("target", item->name.toStdString());
                    sensorNode.SetAttribute("property", sensorList->sensorAt(j).toStdString());
                    project.InsertEndChild(sensorNode);
                }
            }
        }

        // Add all the commands
        for(int i=0;i<commands.size();i++)
        {
            TiXmlElement cmdNode("cmd");
            Command * cmd = commands.commandAt(i);
            cmdNode.SetAttribute("time", cmd->time);
            cmdNode.SetAttribute("type", cmd->type.toStdString());
            if( !cmd->targetName.isEmpty() )
                cmdNode.SetAttribute("target", cmd->targetName.toStdString());
            if( !cmd->propertyName.isEmpty() )
            {
                TiXmlElement propertyNode(cmd->propertyName.toStdString());
                text.SetValue(cmd->propertyValue.toStdString());
                propertyNode.InsertEndChild(text);
                cmdNode.InsertEndChild(propertyNode);
            }
            project.InsertEndChild(cmdNode);
        }

        doc.InsertEndChild(project);

        if(!doc.SaveFile(fileName.toStdString()))
        {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
        }
    }
}
Exemple #8
0
string Timevault::text(void)
{
    return text(false);
}
Exemple #9
0
Timevault::~Timevault()
{
    cout << text() << endl;
}
 CAmount value(bool *valid_out=0) const
 {
     return parse(text(), valid_out);
 }
Exemple #11
0
/// Process queued scripts
void Map::ScriptsProcess()
{ 
    if (m_scriptSchedule.empty())
        return;

    ///- Process overdue queued scripts
    ScriptScheduleMap::iterator iter = m_scriptSchedule.begin();
    // ok as multimap is a *sorted* associative container
    while (!m_scriptSchedule.empty() && (iter->first <= sWorld->GetGameTime()))
    {
        ScriptAction const& step = iter->second;

        Object* source = NULL;
        if (step.sourceGUID)
        {
            switch (GUID_HIPART(step.sourceGUID))
            {
                case HIGHGUID_ITEM: // as well as HIGHGUID_CONTAINER
                    if (Player* player = GetPlayer(step.ownerGUID))
                        source = player->GetItemByGuid(step.sourceGUID);
                    break;
                case HIGHGUID_UNIT:
                case HIGHGUID_VEHICLE:
                    source = GetCreature(step.sourceGUID);
                    break;
                case HIGHGUID_PET:
                    source = GetPet(step.sourceGUID);
                    break;
                case HIGHGUID_PLAYER:
                    source = GetPlayer(step.sourceGUID);
                    break;
                case HIGHGUID_TRANSPORT:
                case HIGHGUID_GAMEOBJECT:
                    source = GetGameObject(step.sourceGUID);
                    break;
                case HIGHGUID_CORPSE:
                    source = GetCorpse(step.sourceGUID);
                    break;
                case HIGHGUID_MO_TRANSPORT:
                {
                    GameObject* go = GetGameObject(step.sourceGUID);
                    source = go ? go->ToTransport() : NULL;
                    break;
                }
                default:
                    sLog->outError("%s source with unsupported high guid (GUID: " UI64FMTD ", high guid: %u).",
                        step.script->GetDebugInfo().c_str(), step.sourceGUID, GUID_HIPART(step.sourceGUID));
                    break;
            }
        }

        WorldObject* target = NULL;
        if (step.targetGUID)
        {
            switch (GUID_HIPART(step.targetGUID))
            {
                case HIGHGUID_UNIT:
                case HIGHGUID_VEHICLE:
                    target = GetCreature(step.targetGUID);
                    break;
                case HIGHGUID_PET:
                    target = GetPet(step.targetGUID);
                    break;
                case HIGHGUID_PLAYER:                       // empty GUID case also
                    target = GetPlayer(step.targetGUID);
                    break;
                case HIGHGUID_TRANSPORT:
                case HIGHGUID_GAMEOBJECT:
                    target = GetGameObject(step.targetGUID);
                    break;
                case HIGHGUID_CORPSE:
                    target = GetCorpse(step.targetGUID);
                    break;
                case HIGHGUID_MO_TRANSPORT:
                {
                    GameObject* go = GetGameObject(step.targetGUID);
                    target = go ? go->ToTransport() : NULL;
                    break;
                }
                default:
                    sLog->outError("%s target with unsupported high guid (GUID: " UI64FMTD ", high guid: %u).",
                        step.script->GetDebugInfo().c_str(), step.targetGUID, GUID_HIPART(step.targetGUID));
                    break;
            }
        }

        switch (step.script->command)
        {
            case SCRIPT_COMMAND_TALK:
                if (step.script->Talk.ChatType > CHAT_TYPE_WHISPER && step.script->Talk.ChatType != CHAT_MSG_RAID_BOSS_WHISPER)
                {
                    sLog->outError("%s invalid chat type (%u) specified, skipping.", step.script->GetDebugInfo().c_str(), step.script->Talk.ChatType);
                    break;
                }
                if (step.script->Talk.Flags & SF_TALK_USE_PLAYER)
                {
                    if (Player* player = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                    {
                        LocaleConstant loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
                        std::string text(sObjectMgr->GetTrinityString(step.script->Talk.TextID, loc_idx));

                        switch (step.script->Talk.ChatType)
                        {
                            case CHAT_TYPE_SAY:
                                player->Say(text, LANG_UNIVERSAL);
                                break;
                            case CHAT_TYPE_YELL:
                                player->Yell(text, LANG_UNIVERSAL);
                                break;
                            case CHAT_TYPE_TEXT_EMOTE:
                            case CHAT_TYPE_BOSS_EMOTE:
                                player->TextEmote(text);
                                break;
                            case CHAT_TYPE_WHISPER:
                            case CHAT_MSG_RAID_BOSS_WHISPER:
                            {
                                uint64 targetGUID = target ? target->GetGUID() : 0;
                                if (!targetGUID || !IS_PLAYER_GUID(targetGUID))
                                    sLog->outError("%s attempt to whisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str());
                                else
                                    player->Whisper(text, LANG_UNIVERSAL, targetGUID);
                                break;
                            }
                            default:
                                break;                              // must be already checked at load
                        }
                    }
                }
                else
                {
                    // Source or target must be Creature.
                    if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                    {
                        uint64 targetGUID = target ? target->GetGUID() : 0;
                        switch (step.script->Talk.ChatType)
                        {
                            case CHAT_TYPE_SAY:
                                cSource->MonsterSay(step.script->Talk.TextID, LANG_UNIVERSAL, target);
                                break;
                            case CHAT_TYPE_YELL:
                                cSource->MonsterYell(step.script->Talk.TextID, LANG_UNIVERSAL, target);
                                break;
                            case CHAT_TYPE_TEXT_EMOTE:
                                cSource->MonsterTextEmote(step.script->Talk.TextID, target);
                                break;
                            case CHAT_TYPE_BOSS_EMOTE:
                                cSource->MonsterTextEmote(step.script->Talk.TextID, target, true);
                                break;
                            case CHAT_TYPE_WHISPER:
                                if (!targetGUID || !IS_PLAYER_GUID(targetGUID))
                                    sLog->outError("%s attempt to whisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str());
                                else
                                    cSource->MonsterWhisper(step.script->Talk.TextID, target->ToPlayer());
                                break;
                            case CHAT_MSG_RAID_BOSS_WHISPER:
                                if (!targetGUID || !IS_PLAYER_GUID(targetGUID))
                                    sLog->outError("%s attempt to raidbosswhisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str());
                                else
                                    cSource->MonsterWhisper(step.script->Talk.TextID, target->ToPlayer(), true);
                                break;
                            default:
                                break;                              // must be already checked at load
                        }
                    }
                }
                break;

            case SCRIPT_COMMAND_EMOTE:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    if (step.script->Emote.Flags & SF_EMOTE_USE_STATE)
                        cSource->SetUInt32Value(UNIT_NPC_EMOTESTATE, step.script->Emote.EmoteID);
                    else
                        cSource->HandleEmoteCommand(step.script->Emote.EmoteID);
                }
                break;

            case SCRIPT_COMMAND_FIELD_SET:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    // Validate field number.
                    if (step.script->FieldSet.FieldID <= OBJECT_FIELD_ENTRY || step.script->FieldSet.FieldID >= cSource->GetValuesCount())
                        sLog->outError("%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.",
                            step.script->GetDebugInfo().c_str(), step.script->FieldSet.FieldID,
                            cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow());
                    else
                        cSource->SetUInt32Value(step.script->FieldSet.FieldID, step.script->FieldSet.FieldValue);
                }
                break;

            case SCRIPT_COMMAND_MOVE_TO:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    Unit * unit = (Unit*)cSource;
                    if (step.script->MoveTo.TravelTime != 0)
                    {
                        float speed = unit->GetDistance(step.script->MoveTo.DestX, step.script->MoveTo.DestY, step.script->MoveTo.DestZ) / ((float)step.script->MoveTo.TravelTime * 0.001f);
                        unit->MonsterMoveWithSpeed(step.script->MoveTo.DestX, step.script->MoveTo.DestY, step.script->MoveTo.DestZ, speed);
                    }
                    else
                        unit->NearTeleportTo(step.script->MoveTo.DestX, step.script->MoveTo.DestY, step.script->MoveTo.DestZ, unit->GetOrientation());
                }
                break;

            case SCRIPT_COMMAND_FLAG_SET:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    // Validate field number.
                    if (step.script->FlagToggle.FieldID <= OBJECT_FIELD_ENTRY || step.script->FlagToggle.FieldID >= cSource->GetValuesCount())
                        sLog->outError("%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.",
                            step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID,
                            cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow());
                    else
                        cSource->SetFlag(step.script->FlagToggle.FieldID, step.script->FlagToggle.FieldValue);
                }
                break;

            case SCRIPT_COMMAND_FLAG_REMOVE:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    // Validate field number.
                    if (step.script->FlagToggle.FieldID <= OBJECT_FIELD_ENTRY || step.script->FlagToggle.FieldID >= cSource->GetValuesCount())
                        sLog->outError("%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.",
                            step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID,
                            cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow());
                    else
                        cSource->RemoveFlag(step.script->FlagToggle.FieldID, step.script->FlagToggle.FieldValue);
                }
                break;

            case SCRIPT_COMMAND_TELEPORT_TO:
                if (step.script->TeleportTo.Flags & SF_TELEPORT_USE_CREATURE)
                {
                    // Source or target must be Creature.
                    if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script, true))
                        cSource->NearTeleportTo(step.script->TeleportTo.DestX, step.script->TeleportTo.DestY, step.script->TeleportTo.DestZ, step.script->TeleportTo.Orientation);
                }
                else
                {
                    // Source or target must be Player.
                    if (Player* player = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                        player->TeleportTo(step.script->TeleportTo.MapID, step.script->TeleportTo.DestX, step.script->TeleportTo.DestY, step.script->TeleportTo.DestZ, step.script->TeleportTo.Orientation);
                }
                break;

            case SCRIPT_COMMAND_QUEST_EXPLORED:
            {
                if (!source)
                {
                    sLog->outError("%s source object is NULL.", step.script->GetDebugInfo().c_str());
                    break;
                }
                if (!target)
                {
                    sLog->outError("%s target object is NULL.", step.script->GetDebugInfo().c_str());
                    break;
                }

                // when script called for item spell casting then target == (unit or GO) and source is player
                WorldObject* worldObject;
                Player* player = target->ToPlayer();
                if (player)
                {
                    if (source->GetTypeId() != TYPEID_UNIT && source->GetTypeId() != TYPEID_GAMEOBJECT && source->GetTypeId() != TYPEID_PLAYER)
                    {
                        sLog->outError("%s source is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.",
                            step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow());
                        break;
                    }
                    worldObject = dynamic_cast<WorldObject*>(source);
                }
                else
                {
                    player = source->ToPlayer();
                    if (player)
                    {
                        if (target->GetTypeId() != TYPEID_UNIT && target->GetTypeId() != TYPEID_GAMEOBJECT && target->GetTypeId() != TYPEID_PLAYER)
                        {
                            sLog->outError("%s target is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.",
                                step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow());
                            break;
                        }
                        worldObject = dynamic_cast<WorldObject*>(target);
                    }
                    else
                    {
                        sLog->outError("%s neither source nor target is player (source: TypeId: %u, Entry: %u, GUID: %u; target: TypeId: %u, Entry: %u, GUID: %u), skipping.",
                            step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow(),
                            target->GetTypeId(), target->GetEntry(), target->GetGUIDLow());
                        break;
                    }
                }

                // quest id and flags checked at script loading
                if ((worldObject->GetTypeId() != TYPEID_UNIT || ((Unit*)worldObject)->IsAlive()) &&
                    (step.script->QuestExplored.Distance == 0 || worldObject->IsWithinDistInMap(player, float(step.script->QuestExplored.Distance))))
                    player->AreaExploredOrEventHappens(step.script->QuestExplored.QuestID);
                else
                    player->FailQuest(step.script->QuestExplored.QuestID);

                break;
            }

            case SCRIPT_COMMAND_KILL_CREDIT:
                // Source or target must be Player.
                if (Player* player = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                {
                    if (step.script->KillCredit.Flags & SF_KILLCREDIT_REWARD_GROUP)
                        player->RewardPlayerAndGroupAtEvent(step.script->KillCredit.CreatureEntry, player);
                    else
                        player->KilledMonsterCredit(step.script->KillCredit.CreatureEntry, 0);
                }
                break;

            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
                if (!step.script->RespawnGameobject.GOGuid)
                {
                    sLog->outError("%s gameobject guid (datalong) is not specified.", step.script->GetDebugInfo().c_str());
                    break;
                }

                // Source or target must be WorldObject.
                if (WorldObject* pSummoner = _GetScriptWorldObject(source, true, step.script))
                {
                    GameObject* pGO = _FindGameObject(pSummoner, step.script->RespawnGameobject.GOGuid);
                    if (!pGO)
                    {
                        sLog->outError("%s gameobject was not found (guid: %u).", step.script->GetDebugInfo().c_str(), step.script->RespawnGameobject.GOGuid);
                        break;
                    }

                    if (pGO->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE ||
                        pGO->GetGoType() == GAMEOBJECT_TYPE_DOOR        ||
                        pGO->GetGoType() == GAMEOBJECT_TYPE_BUTTON      ||
                        pGO->GetGoType() == GAMEOBJECT_TYPE_TRAP)
                    {
                        sLog->outError("%s can not be used with gameobject of type %u (guid: %u).",
                            step.script->GetDebugInfo().c_str(), uint32(pGO->GetGoType()), step.script->RespawnGameobject.GOGuid);
                        break;
                    }

                    // Check that GO is not spawned
                    if (!pGO->isSpawned())
                    {
                        int32 nTimeToDespawn = std::max(5, int32(step.script->RespawnGameobject.DespawnDelay));
                        pGO->SetLootState(GO_READY);
                        pGO->SetRespawnTime(nTimeToDespawn);

                        pGO->GetMap()->AddToMap(pGO);
                    }
                }
                break;

            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
            {
                // Source must be WorldObject.
                if (WorldObject* pSummoner = _GetScriptWorldObject(source, true, step.script))
                {
                    if (!step.script->TempSummonCreature.CreatureEntry)
                        sLog->outError("%s creature entry (datalong) is not specified.", step.script->GetDebugInfo().c_str());
                    else
                    {
						uint32 entry = step.script->TempSummonCreature.CreatureEntry;

                        float x = step.script->TempSummonCreature.PosX;
                        float y = step.script->TempSummonCreature.PosY;
                        float z = step.script->TempSummonCreature.PosZ;
                        float o = step.script->TempSummonCreature.Orientation;

						if (step.script->TempSummonCreature.CheckIfExists)
							if (Unit* trigger = pSummoner->SummonTrigger(x, y, z, o, 1))
								if (trigger->FindNearestCreature(entry, 60.0f))
									break;

                        if (!pSummoner->SummonCreature(entry, x, y, z, o, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, step.script->TempSummonCreature.DespawnDelay))
                            sLog->outError("%s creature was not spawned (entry: %u).", step.script->GetDebugInfo().c_str(), step.script->TempSummonCreature.CreatureEntry);
                    }
                }
                break;
            }

            case SCRIPT_COMMAND_OPEN_DOOR:
            case SCRIPT_COMMAND_CLOSE_DOOR:
                _ScriptProcessDoor(source, target, step.script);
                break;

            case SCRIPT_COMMAND_ACTIVATE_OBJECT:
                // Source must be Unit.
                if (Unit* unit = _GetScriptUnit(source, true, step.script))
                {
                    // Target must be GameObject.
                    if (!target)
                    {
                        sLog->outError("%s target object is NULL.", step.script->GetDebugInfo().c_str());
                        break;
                    }

                    if (target->GetTypeId() != TYPEID_GAMEOBJECT)
                    {
                        sLog->outError("%s target object is not gameobject (TypeId: %u, Entry: %u, GUID: %u), skipping.",
                            step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow());
                        break;
                    }

                    if (GameObject* pGO = target->ToGameObject())
                        pGO->Use(unit);
                }
                break;

            case SCRIPT_COMMAND_REMOVE_AURA:
            {
                // Source (datalong2 != 0) or target (datalong2 == 0) must be Unit.
                bool bReverse = step.script->RemoveAura.Flags & SF_REMOVEAURA_REVERSE;
                if (Unit* unit = _GetScriptUnit(bReverse ? source : target, bReverse, step.script))
                    unit->RemoveAurasDueToSpell(step.script->RemoveAura.SpellID);
                break;
            }

            case SCRIPT_COMMAND_CAST_SPELL:
            {
                // TODO: Allow gameobjects to be targets and casters
                if (!source && !target)
                {
                    sLog->outError("%s source and target objects are NULL.", step.script->GetDebugInfo().c_str());
                    break;
                }

                Unit* uSource = NULL;
                Unit* uTarget = NULL;
                // source/target cast spell at target/source (script->datalong2: 0: s->t 1: s->s 2: t->t 3: t->s
                switch (step.script->CastSpell.Flags)
                {
                    case SF_CASTSPELL_SOURCE_TO_TARGET: // source -> target
                        uSource = source ? source->ToUnit() : NULL;
                        uTarget = target ? target->ToUnit() : NULL;
                        break;
                    case SF_CASTSPELL_SOURCE_TO_SOURCE: // source -> source
                        uSource = source ? source->ToUnit() : NULL;
                        uTarget = uSource;
                        break;
                    case SF_CASTSPELL_TARGET_TO_TARGET: // target -> target
                        uSource = target ? target->ToUnit() : NULL;
                        uTarget = uSource;
                        break;
                    case SF_CASTSPELL_TARGET_TO_SOURCE: // target -> source
                        uSource = target ? target->ToUnit() : NULL;
                        uTarget = source ? source->ToUnit() : NULL;
                        break;
                    case SF_CASTSPELL_SEARCH_CREATURE: // source -> creature with entry
                        uSource = source ? source->ToUnit() : NULL;
                        uTarget = uSource ? GetClosestCreatureWithEntry(uSource, abs(step.script->CastSpell.CreatureEntry), step.script->CastSpell.SearchRadius) : NULL;
                        break;
                }

                if (!uSource || !uSource->isType(TYPEMASK_UNIT))
                {
                    sLog->outError("%s no source unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID);
                    break;
                }

                if (!uTarget || !uTarget->isType(TYPEMASK_UNIT))
                {
                    sLog->outError("%s no target unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID);
                    break;
                }

                bool triggered = (step.script->CastSpell.Flags != 4) ?
                    step.script->CastSpell.CreatureEntry & SF_CASTSPELL_TRIGGERED :
                    step.script->CastSpell.CreatureEntry < 0;
                uSource->CastSpell(uTarget, step.script->CastSpell.SpellID, triggered);
                break;
            }

            case SCRIPT_COMMAND_PLAY_SOUND:
                // Source must be WorldObject.
                if (WorldObject* object = _GetScriptWorldObject(source, true, step.script))
                {
                    // PlaySound.Flags bitmask: 0/1=anyone/target
                    Player* player = NULL;
                    if (step.script->PlaySound.Flags & SF_PLAYSOUND_TARGET_PLAYER)
                    {
                        // Target must be Player.
                        player = _GetScriptPlayer(target, false, step.script);
                        if (!target)
                            break;
                    }

                    // PlaySound.Flags bitmask: 0/2=without/with distance dependent
                    if (step.script->PlaySound.Flags & SF_PLAYSOUND_DISTANCE_SOUND)
                        object->PlayDistanceSound(step.script->PlaySound.SoundID, player);
                    else
                        object->PlayDirectSound(step.script->PlaySound.SoundID, player);
                }
                break;

            case SCRIPT_COMMAND_CREATE_ITEM:
                // Target or source must be Player.
                if (Player* pReceiver = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                {
                    ItemPosCountVec dest;
                    InventoryResult msg = pReceiver->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, step.script->CreateItem.ItemEntry, step.script->CreateItem.Amount);
                    if (msg == EQUIP_ERR_OK)
                    {
                        if (Item* item = pReceiver->StoreNewItem(dest, step.script->CreateItem.ItemEntry, true))
                            pReceiver->SendNewItem(item, step.script->CreateItem.Amount, false, true);
                    }
                    else
                        pReceiver->SendEquipError(msg, NULL, NULL, step.script->CreateItem.ItemEntry);
                }
                break;

            case SCRIPT_COMMAND_DESPAWN_SELF:
                // Target or source must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script, true))
                    cSource->DespawnOrUnsummon(step.script->DespawnSelf.DespawnDelay);
                break;

            case SCRIPT_COMMAND_LOAD_PATH:
                // Source must be Unit.
                if (Unit* unit = _GetScriptUnit(source, true, step.script))
                {
                    if (!sWaypointMgr->GetPath(step.script->LoadPath.PathID))
                        sLog->outError("%s source object has an invalid path (%u), skipping.", step.script->GetDebugInfo().c_str(), step.script->LoadPath.PathID);
                    else
                        unit->GetMotionMaster()->MovePath(step.script->LoadPath.PathID, step.script->LoadPath.IsRepeatable);
                }
                break;

            case SCRIPT_COMMAND_CALLSCRIPT_TO_UNIT:
            {
                if (!step.script->CallScript.CreatureEntry)
                {
                    sLog->outError("%s creature entry is not specified, skipping.", step.script->GetDebugInfo().c_str());
                    break;
                }
                if (!step.script->CallScript.ScriptID)
                {
                    sLog->outError("%s script id is not specified, skipping.", step.script->GetDebugInfo().c_str());
                    break;
                }

                Creature* cTarget = NULL;
                WorldObject* wSource = dynamic_cast <WorldObject*> (source);
                if (wSource) //using grid searcher
                {
                    CellCoord p(Trinity::ComputeCellCoord(wSource->GetPositionX(), wSource->GetPositionY()));
                    Cell cell(p);

                    Trinity::CreatureWithDbGUIDCheck target_check(wSource, step.script->CallScript.CreatureEntry);
                    Trinity::CreatureSearcher<Trinity::CreatureWithDbGUIDCheck> checker(wSource, cTarget, target_check);

                    TypeContainerVisitor<Trinity::CreatureSearcher <Trinity::CreatureWithDbGUIDCheck>, GridTypeMapContainer > unit_checker(checker);
                    cell.Visit(p, unit_checker, *wSource->GetMap(), *wSource, wSource->GetGridActivationRange());
                }
                else //check hashmap holders
                {
                    if (CreatureData const* data = sObjectMgr->GetCreatureData(step.script->CallScript.CreatureEntry))
                        cTarget = ObjectAccessor::GetObjectInWorld<Creature>(data->mapid, data->posX, data->posY, MAKE_NEW_GUID(step.script->CallScript.CreatureEntry, data->id, HIGHGUID_UNIT), cTarget);
                }

                if (!cTarget)
                {
                    sLog->outError("%s target was not found (entry: %u)", step.script->GetDebugInfo().c_str(), step.script->CallScript.CreatureEntry);
                    break;
                }

                //Lets choose our ScriptMap map
                ScriptMapMap* datamap = GetScriptsMapByType(ScriptsType(step.script->CallScript.ScriptType));
                //if no scriptmap present...
                if (!datamap)
                {
                    sLog->outError("%s unknown scriptmap (%u) specified, skipping.", step.script->GetDebugInfo().c_str(), step.script->CallScript.ScriptType);
                    break;
                }

                // Insert script into schedule but do not start it
                ScriptsStart(*datamap, step.script->CallScript.ScriptID, cTarget, NULL);
                break;
            }

            case SCRIPT_COMMAND_KILL:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    if (cSource->isDead())
                        sLog->outError("%s creature is already dead (Entry: %u, GUID: %u)",
                            step.script->GetDebugInfo().c_str(), cSource->GetEntry(), cSource->GetGUIDLow());
                    else
                    {
                        cSource->setDeathState(JUST_DIED);
                        if (step.script->Kill.RemoveCorpse == 1)
                            cSource->RemoveCorpse();
                    }
                }
                break;

            case SCRIPT_COMMAND_ORIENTATION:
                // Source must be Unit.
                if (Unit* sourceUnit = _GetScriptUnit(source, true, step.script))
                {
                    if (step.script->Orientation.Flags & SF_ORIENTATION_FACE_TARGET)
                    {
                        // Target must be Unit.
                        Unit* targetUnit = _GetScriptUnit(target, false, step.script);
                        if (!targetUnit)
                            break;

                        sourceUnit->SetFacingToObject(targetUnit);
                    }
                    else
                        sourceUnit->SetFacingTo(step.script->Orientation.Orientation);
                }
                break;

            case SCRIPT_COMMAND_EQUIP:
                // Source must be Creature.
                if (Creature* cSource = _GetScriptCreature(source, true, step.script))
                    cSource->LoadEquipment(step.script->Equip.EquipmentID);
                break;

            case SCRIPT_COMMAND_MODEL:
                // Source must be Creature.
                if (Creature* cSource = _GetScriptCreature(source, true, step.script))
                    cSource->SetDisplayId(step.script->Model.ModelID);
                break;

            case SCRIPT_COMMAND_CLOSE_GOSSIP:
                // Source must be Player.
                if (Player* player = _GetScriptPlayer(source, true, step.script))
                    player->PlayerTalkClass->SendCloseGossip();
                break;

            case SCRIPT_COMMAND_PLAYMOVIE:
                // Source must be Player.
                if (Player* player = _GetScriptPlayer(source, true, step.script))
                    player->SendMovieStart(step.script->PlayMovie.MovieID);
                break;

            default:
                sLog->outError("Unknown script command %s.", step.script->GetDebugInfo().c_str());
                break;
        }

        m_scriptSchedule.erase(iter);
        iter = m_scriptSchedule.begin();
        sScriptMgr->DecreaseScheduledScriptCount();
    }
}
bool wxRadioBox::Create(wxWindow *parent, wxWindowID id, const wxString& title,
                        const wxPoint& pos, const wxSize& size,
                        int n, const wxString choices[],
                        int majorDim, long style,
                        const wxValidator& val, const wxString& name)
{
    if( !CreateControl( parent, id, pos, size, style, val, name ) )
        return false;
    PreCreation();

    m_noItems = (unsigned int)n;
    m_noRowsOrCols = majorDim;

    SetMajorDim(majorDim == 0 ? n : majorDim, style);

    Widget parentWidget = (Widget) parent->GetClientWidget();
    Display* dpy = XtDisplay(parentWidget);

    m_mainWidget = XtVaCreateWidget ("radioboxframe",
                                     xmFrameWidgetClass, parentWidget,
                                     XmNresizeHeight, True,
                                     XmNresizeWidth, True,
                                     NULL);

    wxString label1(GetLabelText(title));

    if (!label1.empty())
    {
        wxXmString text(label1);
        m_labelWidget = (WXWidget)
                        XtVaCreateManagedWidget( label1.mb_str(),
#if wxUSE_GADGETS
                                style & wxCOLOURED ? xmLabelWidgetClass
                                : xmLabelGadgetClass,
                                (Widget)m_mainWidget,
#else
                                xmLabelWidgetClass, (Widget)m_mainWidget,
#endif
                                wxFont::GetFontTag(), m_font.GetFontTypeC(dpy),
                                XmNlabelString, text(),
// XmNframeChildType is not in Motif 1.2, nor in Lesstif,
// if it was compiled with 1.2 compatibility
// TODO: check this still looks OK for Motif 1.2.
#if (XmVersion > 1200)
                                XmNframeChildType, XmFRAME_TITLE_CHILD,
#else
                                XmNchildType, XmFRAME_TITLE_CHILD,
#endif
                                XmNchildVerticalAlignment, XmALIGNMENT_CENTER,
                                NULL);
    }

    Arg args[3];

    XtSetArg (args[0], XmNorientation, ((style & wxHORIZONTAL) == wxHORIZONTAL ?
                                        XmHORIZONTAL : XmVERTICAL));
    XtSetArg (args[1], XmNnumColumns, GetMajorDim());
    XtSetArg (args[2], XmNadjustLast, False);

    Widget radioBoxWidget =
        XmCreateRadioBox ((Widget)m_mainWidget, wxMOTIF_STR("radioBoxWidget"), args, 3);

    m_radioButtons.reserve(n);
    m_radioButtonLabels.reserve(n);

    int i;
    for (i = 0; i < n; i++)
    {
        wxString str(GetLabelText(choices[i]));
        m_radioButtonLabels.push_back(str);
        Widget radioItem =  XtVaCreateManagedWidget (
                                str.mb_str(),
#if wxUSE_GADGETS
                                xmToggleButtonGadgetClass, radioBoxWidget,
#else
                                xmToggleButtonWidgetClass, radioBoxWidget,
#endif
                                wxFont::GetFontTag(), m_font.GetFontTypeC(dpy),
                                NULL);
        m_radioButtons.push_back((WXWidget)radioItem);
        XtAddCallback (radioItem, XmNvalueChangedCallback,
                       (XtCallbackProc) wxRadioBoxCallback,
                       (XtPointer) this);
    }

    SetSelection (0);

    XtRealizeWidget((Widget)m_mainWidget);
    XtManageChild (radioBoxWidget);
    XtManageChild ((Widget)m_mainWidget);

    PostCreation();
    AttachWidget (parent, m_mainWidget, NULL, pos.x, pos.y, size.x, size.y);

    return true;
}
const text parsedMessageAttachment::getDescription() const
{
	return text();
}
Exemple #14
0
INT_PTR CALLBACK dialogProc (HWND hwnd, 
                          UINT message, 
                          WPARAM wParam, 
                          LPARAM lParam) {

    switch (message) {

		case WM_INITDIALOG: {

			enumSerialPorts(hwnd, IDC_COMBO1);

			TCHAR portName[32];
			_sntprintf_s(portName,_countof(portName),_TRUNCATE,_T("COM%d"), settings.getComPort());
			int const portIdx = SendDlgItemMessage(hwnd, IDC_COMBO1, CB_FINDSTRINGEXACT, -1, reinterpret_cast<LPARAM>(portName));
			SendDlgItemMessage(hwnd, IDC_COMBO1, CB_SETCURSEL, portIdx, 0);

			ShowWindow(hwnd, SW_SHOW);

			return TRUE;
		}

		case WM_COMMAND: {

			switch(LOWORD(wParam)) {

				case IDOK: {

					int const curSel = SendDlgItemMessage(hwnd, IDC_COMBO1, CB_GETCURSEL, 0, 0);
					if (curSel != CB_ERR)
					{
						int const textLen = SendDlgItemMessage(hwnd, IDC_COMBO1, CB_GETLBTEXTLEN, curSel, 0);
						std::vector<TCHAR> text(textLen + 1);
						SendDlgItemMessage(hwnd, IDC_COMBO1, CB_GETLBTEXT, curSel, reinterpret_cast<LPARAM>(&text[0]));
						if (text.size() > 3) // should start with "COM"
						{
							settings.setComPort(_tstoi(&text[3]));
							settings.saveSettings();
						}
					}

					DestroyWindow (hwnd);
					return TRUE;
				}

				case IDCANCEL: {
					//
					//ignore changes
					//
					DestroyWindow (hwnd);
					return TRUE;
				}

			}

			return FALSE;

		}
		case WM_DESTROY:
			PostQuitMessage(0);
			return TRUE;
		case WM_CLOSE:
			DestroyWindow (hwnd);
			return TRUE;
	}

    return FALSE;

}
bool JasparTreeItem::operator<(const QTreeWidgetItem & other) const {
    int col = treeWidget()->sortColumn();
    const JasparTreeItem& ei = static_cast<const JasparTreeItem&>(other);
    return text(col) < ei.text(col);
}
Exemple #16
0
void CrewUI::helmsUI()
{
    sf::RenderTarget* window = getRenderTarget();
    sf::Vector2f mouse = InputHandler::getMousePos();
    if (InputHandler::mouseIsPressed(sf::Mouse::Left))
    {
        sf::Vector2f diff = mouse - sf::Vector2f(800, 450);
        if (sf::length(diff) < 400)
            mySpaceship->commandTargetRotation(sf::vector2ToAngle(diff));
    }
    
    //Radar
    float radarDistance = 5000;
    drawRaderBackground(mySpaceship->getPosition(), sf::Vector2f(800, 450), 400, 400.0f / radarDistance);
    foreach(SpaceObject, obj, spaceObjectList)
    {
        if (obj != mySpaceship && sf::length(obj->getPosition() - mySpaceship->getPosition()) < radarDistance)
            obj->drawRadar(*window, sf::Vector2f(800, 450) + (obj->getPosition() - mySpaceship->getPosition()) / radarDistance * 400.0f, 400.0f / radarDistance, false);
    }

    P<SpaceObject> target = mySpaceship->getTarget();
    if (target)
    {
        sf::Sprite objectSprite;
        textureManager.setTexture(objectSprite, "redicule.png");
        objectSprite.setPosition(sf::Vector2f(800, 450) + (target->getPosition() - mySpaceship->getPosition()) / radarDistance * 400.0f);
        window->draw(objectSprite);
    }
    mySpaceship->drawRadar(*window, sf::Vector2f(800, 450), 400.0f / radarDistance, false);
    drawHeadingCircle(sf::Vector2f(800, 450), 400);
    //!Radar

    text(sf::FloatRect(10, 100, 200, 20), "Energy: " + string(int(mySpaceship->energy_level)), AlignLeft, 20);
    
    float res = vslider(sf::FloatRect(20, 500, 50, 300), mySpaceship->impulseRequest, 1.0, -1.0);
    if (res > -0.15 && res < 0.15)
        res = 0.0;
    if (res != mySpaceship->impulseRequest)
        mySpaceship->commandImpulse(res);
    text(sf::FloatRect(20, 800, 50, 20), string(int(mySpaceship->impulseRequest * 100)) + "%", AlignLeft, 20);
    text(sf::FloatRect(20, 820, 50, 20), string(int(mySpaceship->currentImpulse * 100)) + "%", AlignLeft, 20);

    float x = 100;
    if (mySpaceship->hasWarpdrive)
    {
        res = vslider(sf::FloatRect(x, 500, 50, 300), mySpaceship->warpRequest, 4.0, 0.0);
        if (res != mySpaceship->warpRequest)
            mySpaceship->commandWarp(res);
        text(sf::FloatRect(100, 800, 50, 20), string(int(mySpaceship->warpRequest)), AlignLeft, 20);
        text(sf::FloatRect(100, 820, 50, 20), string(int(mySpaceship->currentWarp * 100)) + "%", AlignLeft, 20);
        x += 80;
    }
    if (mySpaceship->hasJumpdrive)
    {
        jumpDistance = vslider(sf::FloatRect(x, 500, 50, 300), jumpDistance, 40.0, 1.0, 1.0);
        jumpDistance = roundf(jumpDistance * 10.0f) / 10.0f;
        text(sf::FloatRect(x, 800, 50, 20), string(jumpDistance, 1) + "km", AlignLeft, 20);
        if (mySpaceship->jumpDelay > 0.0)
        {
            text(sf::FloatRect(x, 820, 50, 20), string(int(ceilf(mySpaceship->jumpDelay))), AlignLeft, 20);
        }else{
            if (button(sf::FloatRect(x - 10, 820, 70, 30), "Jump", 20))
            {
                mySpaceship->commandJump(jumpDistance);
            }
        }
        x += 80;
    }

    switch(mySpaceship->docking_state)
    {
    case DS_NotDocking:
        {
            PVector<Collisionable> obj_list = CollisionManager::queryArea(mySpaceship->getPosition() - sf::Vector2f(1000, 1000), mySpaceship->getPosition() + sf::Vector2f(1000, 1000));
            P<SpaceStation> station;
            foreach(Collisionable, obj, obj_list)
            {
                station = obj;
                if (station && sf::length(station->getPosition() - mySpaceship->getPosition()) < 1000.0)
                {
                    break;
                }
            }
            
            if (station)
            {
                if (button(sf::FloatRect(x, 800, 280, 50), "Request Dock", 30))
                    mySpaceship->commandDock(station);
            }else{
                disabledButton(sf::FloatRect(x, 800, 280, 50), "Request Dock", 30);
            }
        }
        break;
    case DS_Docking:
        disabledButton(sf::FloatRect(x, 800, 280, 50), "Docking...", 30);
        break;
    case DS_Docked:
        if (button(sf::FloatRect(x, 800, 280, 50), "Undock", 30))
            mySpaceship->commandUndock();
        break;
    }
Exemple #17
0
int
main(int argc, char **argv)
{
	int i;

	/* revoke privs */
	setgid(getgid());

	acnt = 1;
	signal(SIGINT, getout);
	if (tcgetattr(0, &tty) == -1)			/* get old tty mode */
		errexit("teachgammon(tcgetattr)");
	old = tty.c_lflag;
	raw = ((noech = old & ~ECHO) & ~ICANON);	/* set up modes */
	ospeed = cfgetospeed(&tty);			/* for termlib */
	tflag = getcaps(getenv("TERM"));
	getarg(argc, argv);
	if (tflag) {
		noech &= ~(ICRNL | OXTABS);
		raw &= ~(ICRNL | OXTABS);
		clear();
	}
	text(hello);
	text(list);
	i = text(contin);
	if (i == 0)
		i = 2;
	init();
	while (i)
		switch (i) {
		case 1:
			leave();

		case 2:
			if ((i = text(intro1)) != 0)
				break;
			wrboard();
			if ((i = text(intro2)) != 0)
				break;

		case 3:
			if ((i = text(moves)) != 0)
				break;

		case 4:
			if ((i = text(remove)) != 0)
				break;

		case 5:
			if ((i = text(hits)) != 0)
				break;

		case 6:
			if ((i = text(endgame)) != 0)
				break;

		case 7:
			if ((i = text(doubl)) != 0)
				break;

		case 8:
			if ((i = text(stragy)) != 0)
				break;

		case 9:
			if ((i = text(prog)) != 0)
				break;

		case 10:
			if ((i = text(lastch)) != 0)
				break;
		}
	tutor();
	/* NOTREACHED */
	return (0);
}
void Matrix::print(QPrinter *printer)
{
	if (!printer)
		return;

	QPainter p;
	if ( !p.begin(printer))
		return; // paint on printer

	int dpiy = printer->logicalDpiY();
	const int margin = (int) ( (1/2.54)*dpiy ); // 1 cm margins

	if (d_view_type == ImageView){
		p.drawImage (printer->pageRect(), d_matrix_model->renderImage());
		return;
	}

	QHeaderView *vHeader = d_table_view->verticalHeader();

	int rows = numRows();
	int cols = numCols();
	int height = margin;
	int i, vertHeaderWidth = vHeader->width();
	int right = margin + vertHeaderWidth;

	// print header
	p.setFont(QFont());
	QString header_label = d_matrix_model->headerData(0, Qt::Horizontal).toString();
	QRect br = p.boundingRect(br, Qt::AlignCenter, header_label);
	p.drawLine(right, height, right, height+br.height());
	QRect tr(br);

	for(i=0; i<cols; i++){
		int w = d_table_view->columnWidth(i);
		tr.setTopLeft(QPoint(right,height));
		tr.setWidth(w);
		tr.setHeight(br.height());
		header_label = d_matrix_model->headerData(i, Qt::Horizontal).toString();
		p.drawText(tr, Qt::AlignCenter, header_label,-1);
		right += w;
		p.drawLine(right, height, right, height+tr.height());

		if (right >= printer->width()-2*margin )
			break;
	}

	p.drawLine(margin + vertHeaderWidth, height, right-1, height);//first horizontal line
	height += tr.height();
	p.drawLine(margin, height, right-1, height);

	// print table values
	for(i=0;i<rows;i++){
		right = margin;
		QString cell_text = d_matrix_model->headerData(i, Qt::Horizontal).toString()+"\t";
		tr = p.boundingRect(tr, Qt::AlignCenter, cell_text);
		p.drawLine(right, height, right, height+tr.height());

		br.setTopLeft(QPoint(right,height));
		br.setWidth(vertHeaderWidth);
		br.setHeight(tr.height());
		p.drawText(br,Qt::AlignCenter,cell_text,-1);
		right += vertHeaderWidth;
		p.drawLine(right, height, right, height+tr.height());

		for(int j=0; j<cols; j++){
			int w = d_table_view->columnWidth (j);
			cell_text = text(i,j)+"\t";
			tr = p.boundingRect(tr,Qt::AlignCenter,cell_text);
			br.setTopLeft(QPoint(right,height));
			br.setWidth(w);
			br.setHeight(tr.height());
			p.drawText(br, Qt::AlignCenter, cell_text, -1);
			right += w;
			p.drawLine(right, height, right, height+tr.height());

			if (right >= printer->width()-2*margin )
				break;
		}
		height += br.height();
		p.drawLine(margin, height, right-1, height);

		if (height >= printer->height()-margin ){
			printer->newPage();
			height = margin;
			p.drawLine(margin, height, right, height);
		}
	}
	p.end();
}
Exemple #19
0
	void Map::ParseFile(const string &fileName) 
	{
		file_name = fileName;

		int lastSlash = fileName.find_last_of("/");

		// Get the directory of the file using substring.
		if (lastSlash > 0) 
		{
			file_path = fileName.substr(0, lastSlash + 1);
		} 
		else 
		{
			file_path = "";
		}

		char* fileText;
		int fileSize;

		// Open the file for reading.
#ifdef USE_SDL2_LOAD
		SDL_RWops * file = SDL_RWFromFile (fileName.c_str(), "rb");
#else
		FILE *file = fopen(fileName.c_str(), "rb");
#endif

		// Check if the file could not be opened.
		if (!file) 
		{
			has_error = true;
			error_code = TMX_COULDNT_OPEN;
			error_text = "Could not open the file.";
			return;
		}
	
		// Find out the file size.	
#ifdef USE_SDL2_LOAD
		fileSize = file->size(file);
#else
		fseek(file, 0, SEEK_END);
		fileSize = ftell(file);
		fseek(file, 0, SEEK_SET);
#endif
		
		// Check if the file size is valid.
		if (fileSize <= 0)
		{
			has_error = true;
			error_code = TMX_INVALID_FILE_SIZE;
			error_text = "The size of the file is invalid.";
			return;
		}

		// Allocate memory for the file and read it into the memory.
		fileText = new char[fileSize + 1];
		fileText[fileSize] = 0;
#ifdef USE_SDL2_LOAD
		file->read(file, fileText, 1, fileSize);
#else
		fread(fileText, 1, fileSize, file);
#endif

#ifdef USE_SDL2_LOAD
		file->close(file);
#else
		fclose(file);
#endif

		// Copy the contents into a C++ string and delete it from memory.
		std::string text(fileText, fileText+fileSize);
		delete [] fileText;

		ParseText(text);		
	}
Exemple #20
0
int main()
{
	enum Direction { Right, Left, Down, Up };

	sf::Vector2i blockDimensions(10, 10);

	sf::Vector2i source(1, Down);

	float frameCounter = 0, switchFrame = 100, frameSpeed = 500;

	srand(time(0));

	sf::RenderWindow window; 
	//2D Array Vector
	sf::Vector2u windowSize(800, 600);
	//Create the window
	window.create(sf::VideoMode(windowSize.x, windowSize.y), "RPG", sf::Style::Default);

	//Actual time
	sf::Clock clock;
	sf::Time time = sf::seconds(2);

	bool updateFrame = true;

	std::string message = "Hello my name is Max";
	std::string display = "";

	int index = 0;

	//Stops key repeat when holding down
	//window.setKeyRepeatEnabled(false);
	
	//Load in a font type
	sf::Font font;
	if (!font.loadFromFile("modern.fon"))
		std::cout << "Can't find font file" << std::endl;

	//Make a string, load into text, and do things with text
	sf::String sentence;
	sf::Text text(sentence, font, 40);
	text.setColor(sf::Color(44, 127, 255));
	text.setStyle(sf::Text::Bold | sf::Text::Underlined);

	//Images and Sprites
	sf::Texture playerTexture;
	//Loads in spritemap
	if (!playerTexture.loadFromFile("Monsters4.png"))
		std::cout << "Error: Could not load Player Image" << std::endl;

	sf::Sprite playerSprite;
	playerSprite.setTexture(playerTexture);
	playerSprite.setPosition(0, 0);

	//Checks controller connection before the game loop starts
	if (sf::Joystick::isConnected(0))
		std::cout << "Joystick 1 is connected" << std::endl;
	else
		std::cout << "Joystick 1 is disconnected" << std::endl;

	//Gets number of buttons on controller
	int buttonCount = sf::Joystick::getButtonCount(0);
	std::cout << "Number of controller buttons: " << buttonCount << std::endl;

	//Check if controller has axis
	bool hasAxis = sf::Joystick::hasAxis(0, sf::Joystick::Z);

	//Update loop
	while (window.isOpen())
	{
		//Make an event
		sf::Event evt;
		//Loop checking for any event
		while (window.pollEvent(evt))
		{
			//Event Finders
			switch (evt.type)
			{
				case sf::Event::Closed:
					window.close();
					break;
				//Various Mouse Events
				case sf::Event::MouseEntered:
					//std::cout << "Mouse in screen bounds" << std::endl;
					break;
				case sf::Event::MouseLeft:
					//std::cout << "Mouse not in screen bound" << std::endl;
					break;
				case sf::Event::MouseMoved:
					//std::cout << "X: " << evt.mouseMove.x << "Y: " << evt.mouseMove.y << std::endl;
					break;
				case sf::Event::MouseButtonPressed:
					if (evt.mouseButton.button == sf::Mouse::Left)
					//	std::cout << "Left Button Pressed at: X:" << evt.mouseButton.x << "Y: " << evt.mouseButton.y << std::endl;
					break;
				case sf::Event::MouseWheelMoved:
					//std::cout << "Delta: "/*Positive: Down, Negative: Up. Higher number = harder scrolling*/ << evt.mouseWheel.delta << std::endl;
					break;

				//Keyboard Events
				case sf::Event::KeyPressed:
					/*if (evt.key.code == sf::Keyboard::Return)
						window.close();
					else if (evt.key.code == sf::Keyboard::Up)
						source.y = Up;
					else if (evt.key.code == sf::Keyboard::Down)
					{
						source.y = Down;
						source.x++;
						if (source.x * 32 >= playerTexture.getSize().x)
							source.x = 0;
					}
						
					else if (evt.key.code == sf::Keyboard::Right)
						source.y = Right;
					else if (evt.key.code == sf::Keyboard::Left)
						source.y = Left;
					break;*/


				//Text Events (Letters Keyboard)
				case sf::Event::TextEntered:
					//Only regular characters
					if (evt.text.unicode != 8)
					{
						if (evt.text.unicode >= 33 && evt.text.unicode <= 126)
							display += (char)evt.text.unicode;
					}
					else if (evt.text.unicode == 8)
						display = display.substr(0, display.length() - 1);

					//CMD Code for clear -- clear for Linux/Mac
					system("cls");
					//std::cout << display;
					break;

				//Controller Events -- May change based on drivers
				case sf::Event::JoystickConnected:
					//Shows which joystick is connected
					//std::cout << "Joystick" << evt.joystickConnect.joystickId + 1 << "is connected" << std::endl;
					break;
				case sf::Event::JoystickDisconnected:
					//Shows which joystick is disconnected
					//std::cout << "Joystick" << evt.joystickConnect.joystickId + 1 << "is disconnected" << std::endl;
					break;
				//Use this one to change controller button mapping
				case sf::Event::JoystickButtonPressed:
					//std::cout << "Button: " << evt.joystickButton.button << std::endl;
					break;
				//Check position if controller
				case sf::Event::JoystickMoved:
					if (evt.joystickMove.axis == sf::Joystick::X)
					//	std::cout << "Position : " << evt.joystickMove.position << std::endl;
					break;


				//Window Events
				case sf::Event::GainedFocus:
					//std::cout << "Window now active" << std::endl;
					break;
				case sf::Event::LostFocus:
					//std::cout << "Window not active" << std::endl;
					break;
				case sf::Event::Resized:
					//std::cout << "Width: " << evt.size.width << "Height: " << evt.size.height << std::endl;
					break;
					
			}
		}
		
		//Live keyboard input -- Can hold down keys
		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
		{
			source.y = Up;
			playerSprite.move(0, -0.1);
		}
		else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
		{
			source.y = Down;
			playerSprite.move(0, 0.1);
		}
		else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
		{
			source.y = Right;
			playerSprite.move(0.1, 0);
		}
		else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
		{
			source.y = Left;
			playerSprite.move(-0.1, 0);
		}

		sf::Vector2f moveSpeed(sf::Joystick::getAxisPosition(0, sf::Joystick::X), sf::Joystick::getAxisPosition(0, sf::Joystick::Y));

		if (moveSpeed.x > 0)
			source.y = Right;
		else if (moveSpeed.x < 0)
			source.y = Left;
		else if (moveSpeed.y < 0)
			source.y = Up;
		else if (moveSpeed.y > 0)
			source.y = Down;

		playerSprite.move(moveSpeed.x * clock.getElapsedTime().asSeconds(), moveSpeed.y * clock.getElapsedTime().asSeconds());
		

		//Gets actual position in window. Without parameter, mouse position for the monitor
		sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
		//Sets a fixed position for mouse in window
		//sf::Mouse::setPosition(sf::Vector2i(100, 100), window);

		std::cout << "X: " << mousePosition.x << "Y: " << mousePosition.y << std::endl;

		//Live mouse input
		if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
			updateFrame = true;
		else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
			updateFrame = false;

		//Same as above for controller
		if (sf::Joystick::isButtonPressed(0, 1))
			updateFrame = true;
		else if (sf::Joystick::isButtonPressed(0, 2))
			updateFrame = false;

		//Starts sprite animation
		if (updateFrame)
			frameCounter += frameSpeed * clock.restart().asSeconds();
		else
			frameCounter = 0;
		
		//Change speed of animation
		if (frameCounter >= switchFrame)
		{
			frameCounter = 0;
			source.x++;
			if (source.x * 32 >= playerTexture.getSize().x)
				source.x = 0;
		}

		//Vertex Arrays are geometry objects
		/*for (int i = 0; i < windowSize.x / blockDimensions.x; i++)
		{
			for (int j = 0; j < windowSize.y / blockDimensions.y; j++)
			{
				sf::VertexArray vArray(sf::PrimitiveType::LinesStrip, 4);
				vArray[0].position = sf::Vector2f(i * blockDimensions.x, j * blockDimensions.y);
				vArray[1].position = sf::Vector2f(i * blockDimensions.x + blockDimensions.x, j * blockDimensions.y + blockDimensions.y);
				vArray[2].position = sf::Vector2f(i * blockDimensions.x + blockDimensions.x, j * blockDimensions.y + blockDimensions.y);
				vArray[3].position = sf::Vector2f(i * blockDimensions.x, j * blockDimensions.y + blockDimensions.y);

				for (int k = 0; k < 4; k++)
				{
					int red = rand() % 255;
					int green = rand() % 255;
					int blue = rand() % 255;

					vArray[k].color = sf::Color(red, green, blue);
				}
				window.draw(vArray);
			}
		}*/

		sf::RectangleShape rect(sf::Vector2f(100, 100)); 
		rect.setFillColor(sf::Color(255, 0, 0, 255));
		rect.setOutlineColor(sf::Color::Blue); 
		rect.setOutlineThickness(2.0f);
		rect.setPosition(sf::Vector2f(20, 20));
		rect.setTexture(&playerTexture);

		//Wait for an event to happen
		/*if (window.waitEvent(evt))
		{
			std::cout << "Event" << std::endl;
		}*/

		//Actual time
		time = clock.getElapsedTime(); //Can be one line
		clock.restart(); //Send up ^^^^^^
		

		

		playerSprite.setTextureRect(sf::IntRect(source.x * 32, source.y * 32, 32, 32));
		window.clear();
		//Draw to screen
		window.draw(playerSprite);
		window.draw(rect);
		//Update window
		window.display();
		
	}
}
Exemple #21
0
void FindTextContent::focusOutEvent(QFocusEvent *event)
{
  if (text().isEmpty())
    findLabel_->setVisible(true);
  QLineEdit::focusOutEvent(event);
}
bool QCompletionEdit::eventFilter( QObject *o, QEvent *e )
{
    if ( o == popup || o == listbox || o == listbox->viewport() ) {
	if ( e->type() == QEvent::KeyPress ) {
	    QKeyEvent *ke = (QKeyEvent*)e;
	    if ( ke->key() == Key_Enter || ke->key() == Key_Return || ke->key() == Key_Tab ) {
		if ( ke->key() == Key_Tab && listbox->count() > 1 &&
		     listbox->currentItem() < (int)listbox->count() - 1 ) {
		    listbox->setCurrentItem( listbox->currentItem() + 1 );
		    return true;
		}
		popup->close();
		setFocus();
		blockSignals( true );
		setText( listbox->currentText() );
		blockSignals( false );
		emit chosen( text() );
		return true;
	    } else if ( ke->key() == Key_Left || ke->key() == Key_Right ||
			ke->key() == Key_Up || ke->key() == Key_Down ||
			ke->key() == Key_Home || ke->key() == Key_End ||
			ke->key() == Key_Prior || ke->key() == Key_Next ) {
		return false;
	    } else if ( ke->key() == Key_Escape ) {
		popup->close();
		setFocus();
	    } else if ( ke->key() != Key_Shift && ke->key() != Key_Control &&
			ke->key() != Key_Alt ) {
		updateListBox();
		if ( listbox->count() == 0 || text().length() == 0 ) {
		    popup->close();
		    setFocus();
		}
		QApplication::sendEvent( this, e );
		return true;
	    }
	} else if ( e->type() == QEvent::MouseButtonDblClick ) {
	    popup->close();
	    setFocus();
	    blockSignals( true );
	    setText( listbox->currentText() );
	    blockSignals( false );
	    emit chosen( text() );
	    return true;
	}
    } else if ( o == this ) {
	if ( e->type() == QEvent::KeyPress ) {
	    QKeyEvent *ke = (QKeyEvent*)e;
	    if ( ke->key() == Key_Up ||
		 ke->key() == Key_Down ||
		 ke->key() == Key_Prior ||
		 ke->key() == Key_Next ||
		 ke->key() == Key_Return ||
		 ke->key() == Key_Enter ||
		 ke->key() == Key_Tab ||
		 ke->key() ==  Key_Escape ) {
		QApplication::sendEvent( listbox, e );
		return true;
	    }
	}
    }
    return QLineEdit::eventFilter( o, e );
}
Exemple #23
0
void main()
{		
		char j, a;
		unsigned int *seed;
		backupPageZero();
        GenerateTables();
		DiscLoad("FONT.BIN");
        // testing
        
        //sedoric("!LOAD(\"TEAM.BIN\")");
       	//cls();
       	
       	#ifdef debug 
        printf("char : %d, short %d, int %d, long %d, float %d\n",
        	sizeof(char), sizeof(short), sizeof(int), sizeof(long), sizeof(float));
        	
       
        printf("taper sur une touche pour continuer\n");
        a = (char)getchar();
        #endif
        io_needed = 1;
        loadCharacters();
        
        #ifdef debug
        printf("taper sur une touche pour continuer\n");
        a = (char)getchar();
        #endif
        loadLaby();
        if (ca==0) {
        	if (c[x+y*XMAX] != 0) {
        		unsigned char nb = 255;
        		// un coffre ou un combat a été fini
        		char cas = c[x+y*XMAX];
        		if (cas>=21 && cas<=28) nb = cas - 21;
        		else if (cas >=30 && cas <= 50) nb = cas - 30 + 8; // les 8 premiers bits stockent les coffres
				if (nb < 40) {
					SetBit(combats_coffres[ville-1], nb);
					//printf("Coffre ou Combat %d fini!\n", nb);
					c[x+y*XMAX] = 0;
				}
        	}
        }
        
        #ifdef debug
        for (a=0; a<8; a++)
        	for (j=0; j<40; j++)
				if(TestBit(combats_coffres[a], j))
					printf("Bit %d is set\n", j);
        
        // testing
        // SetBit(combats_coffres[ville-1], 0);
        #endif
        
        printf("Taper sur une touche pour continuer\n");
        get();
		
		seed = (unsigned int *) 630; // timer
		srand(*seed);
		#ifdef debug
		printf("timer vaut %d\n", *seed);
		printf("alea vaut %d\n", rand());
				
		printf("taper sur une touche pour continuer\n");
        a = (char)getchar();
		#endif
		
        // Sedoric(command2);
      
		// 330 CASE=C(X,Y)
		prep();
		drawLaby();

		ca = c[x+y*XMAX];
		// manageCell();
		// 320 GOSUB 500:GOSUB 1000
		
		
		
		while(1) {
						
			// 380 GET A$
			//a = (char)getchar();
			//printf("x=%d, y=%d, s=%d ca=%d\n", x,y,s,ca);
			a = get();
			
			switch(a) {
				//#ifdef debug
				case 'F': // pour debug
				case 'f':
					// 390 IF A$="F" THEN END
					a = 'F';
					text();
					io_needed = 1;
					saveCharacters();
					restorePageZero();
					printf("sauvegarde ok\n");
					SwitchToCommand("!DIR"); // évite une erreur bizarre
					return;
					break;
				//#endif
				case ' ':
					// 400 IF A$=" "AND F(1)>1 AND F(1)<7 THEN GOSUB 3000:GOTO 330
					if(f[0]>1&&f[0]<7) {
						#ifdef debug
						for (j=0;j<4;j++) {	
							printf("cle(%d,%d) = %d ", 3, j, cles[3][j]);
						}
						#endif
						// 3000 REM ClÈ
						// 3010 IF F(1)=2 THEN 3030
						// 3020 IF CLEF(VIL,(F(1)-2))=0 THEN ZAP:PRINT TX$(4):GOTO 3050
						// 3030 F(1)=0:GOSUB 600:PING
						// 3050 RETURN
						if (f[0] == 2) {
							f[0]=0;
							forward();
							ping();
							// on avance deux fois
							prep();
							printf("On passe la porte\n");
							wait(180);
							drawLaby();
							forward();
						} else {
							////// MODIF Maximus *******
							if(cles[ville-1][f[0]-3]==0) {
								zap();
								printf("Ou est la cl{ ?\n");
							} else {
								#ifdef debug
								printf("Porte %d cle(%d,%d) %d  ", 
									f[0], ville-1, (f[0]-3), cles[ville-1][f[0]-3]);
								a = (char)getchar();
								#endif
								InvertBit(&dedans,f[0]-3);
								f[0]=0;
								forward();
								ping();
								// on avance deux fois
								prep();
								printf("On passe la porte\n");
								wait(180);
								drawLaby();
								forward();
								
							}
						}
					}
					break;
				case 'I':
				case 'i':
				case 'Z':
				case 'z':
					// 410 IF A$="I" OR A$="i" THEN GOSUB 600:GOTO 330
					forward();
					break;
				case 'J':
				case 'j':
				case 'Q':
				case 'q':
					// 420 IF A$="J" OR A$="j" THEN S=S-1:IF S=0 THEN S=4
					s--;
					if(s<0) s=3;
					prep(); drawLaby();
					break;
				case 'L':
				case 'l':
				case 'D':
				case 'd':
					// 430 IF A$="L" OR A$="l" THEN S=S+1:IF S=5 THEN S=1
					s++;
					if(s>3) s=0;
					prep(); drawLaby();
					break;
				case 'C':
				case 'c':
					// 435 IF A$="C" THEN GOTO 21000
					text();
					io_needed = 1;
					saveCharacters();
					restorePageZero();
					SwitchToCommand("CAMP");
					break;
				//#ifdef debug
				case 'A':
				case 'a':
					printf("alea vaut %d\n", rand());
					break;
				case 'K':
				case 'k':					
					for (j=0;j<4;j++) {	
						cles[ville-1][j] = !cles[ville-1][j];
					}
					break;
				case 'V':
				case 'v':
					text();
					io_needed = 1;
					saveCharacters();
					restorePageZero();
					SwitchToCommand("VILLE");
					break;
				//#endif
				default:
					puts("I:avance, J:droite, L:gauche\nESPACE: ouvrir porte");
					wait(200);
			}
			// 450 GOTO 300
		}
}
Exemple #24
0
 QString repository() const
 {
     return text(0);
 }
void TableStatistics::update(Table *t, const QString& colName)
{
  if (t != d_base) return;
  
  int j;
  if (d_type == row)
    for (unsigned r=0; r < d_targets.size(); r++)
    {
      int cols=d_base->tableCols();
      int i = d_targets[r];
      int m = 0;
      for (j = 0; j < cols; j++)
		if (!d_base->text(i, j).isEmpty() && d_base->columnType(j) == Numeric)
			m++;

	  if (!m)
		{//clear row statistics
		for (j = 1; j<9; j++)
			setText(r, j, QString::null);
		}

      if (m > 0)
      {
	double *dat = new double[m];
	gsl_vector *y = gsl_vector_alloc (m);
	int aux = 0;
	for (j = 0; j<cols; j++)
	{
	  QString text = d_base->text(i,j);
	  if (!text.isEmpty() && d_base->columnType(j) == Numeric)
	  {					
	    double val = text.toDouble();
	    gsl_vector_set (y, aux, val);
	    dat[aux] = val;
	    aux++;
	  }
	}
	double mean = gsl_stats_mean (dat, 1, m);
	double min, max;
	gsl_vector_minmax (y, &min, &max);

	setText(r, 1, QString::number(d_base->tableCols()));
	setText(r, 2, QString::number(mean));
	setText(r, 3, QString::number(gsl_stats_sd(dat, 1, m)));
	setText(r, 4, QString::number(gsl_stats_variance(dat, 1, m)));
	setText(r, 5, QString::number(mean*m));
	setText(r, 6, QString::number(max));
	setText(r, 7, QString::number(min));
	setText(r, 8, QString::number(m));

	gsl_vector_free (y);
	delete[] dat;
      }
    }
  else if (d_type == column)
    for (unsigned c=0; c < d_targets.size(); c++)
      if (colName == QString(d_base->name())+"_"+text(c, 0))
      {
	int i = d_base->colIndex(colName);
	if (d_base->columnType(i) != Numeric) return;

	int rows = d_base->tableRows();
	int start = -1, m = 0;
	for (j=0; j<rows; j++)
	  if (!d_base->text(j,i).isEmpty())
	  {
	    m++;
	    if (start<0) start=j;
	  }

	  if (!m)
		{//clear col statistics
		for (j = 1; j<11; j++)
			setText(c, j, QString::null);
		return;
		}

	if (start<0) return;

	double *dat = new double[m];
	gsl_vector *y = gsl_vector_alloc (m);

	int aux = 0, min_index = start, max_index = start;
	double val = d_base->text(start, i).toDouble();
	gsl_vector_set (y, 0, val);
	dat[0] = val;
	double min = val, max = val;
	for (j = start + 1; j<rows; j++)
	{
	  if (!d_base->text(j, i).isEmpty())
	  {
	    aux++;
	    val = d_base->text(j, i).toDouble();
	    gsl_vector_set (y, aux, val);
	    dat[aux] = val;
	    if (val < min)
	    {
	      min = val;
	      min_index = j;
	    }
	    if (val > max)
	    {
	      max = val;
	      max_index = j;
	    }
	  }
	}
	double mean=gsl_stats_mean (dat, 1, m);

	setText(c, 1, "[1:"+QString::number(rows)+"]");
	setText(c, 2, QString::number(mean));
	setText(c, 3, QString::number(gsl_stats_sd(dat, 1, m)));
	setText(c, 4, QString::number(gsl_stats_variance(dat, 1, m)));
	setText(c, 5, QString::number(mean*m));
	setText(c, 6, QString::number(max_index + 1));
	setText(c, 7, QString::number(max));
	setText(c, 8, QString::number(min_index + 1));
	setText(c, 9, QString::number(min));
	setText(c, 10, QString::number(m));

	gsl_vector_free (y);
	delete[] dat;
      }

for (int i=0; i<worksheet->numCols(); i++)
	emit modifiedData(this, Table::colName(i));
}
Exemple #26
0
 int compression() const
 {
     bool ok;
     int n = text(2).toInt(&ok);
     return ok ? n : -1;
 }
Exemple #27
0
 void clickedAction(){
   dlg.edit->setText( text() );
   dlg.edit->setSelectionBounds( dlg.edit->text().size(),
                                 dlg.edit->text().size()+1 );
   }
Exemple #28
0
void ProxyAction::changeContexts(QList<int> contexts)
{
    LOG_TRACE("Context update request on proxy action", text());

    if (m_contextActions.isEmpty())
    {
        LOG_TRACE("No backend actions stored here.");
        return;
    }

    m_contexts = contexts;

    QAction *oldAction = m_activeAction;
    m_activeAction = 0;

    for (int n = 0; n < m_contexts.size(); n++)
    {
        QAction *a = m_contextActions.value(m_contexts.at(n), 0);
        if (a)
        {
            m_activeAction = a;
            m_activeAction->setObjectName(a->text());

            LOG_TRACE(QString("Backend action found: %1, shortcut: %2, proxy shortcut: %3")
                      .arg(m_activeAction->text())
                      .arg(m_activeAction->shortcut().toString())
                      .arg(m_action->shortcut().toString()));
            break;
        }
    }

    if (m_activeAction == oldAction && m_initialized)
    {
        updateFrontend();

        LOG_TRACE("New backend action is the same as the active action; nothing to be done.");
        return;
    }

    if (oldAction)
    {
        LOG_TRACE(QString("Disconnecting multi-context action from previous backend action in parent: %1")
                  .arg(oldAction->parent() ? oldAction->parent()->objectName() : "Unspecified parent"));

        disconnect(oldAction, SIGNAL(changed()), this, SLOT(updateFrontend()));
        disconnect(m_action, SIGNAL(triggered(bool)), oldAction, SIGNAL(triggered(bool)));
        disconnect(m_action, SIGNAL(toggled(bool)), oldAction, SLOT(setChecked(bool)));
    }

    if (m_activeAction)
    {
        LOG_TRACE(QString("Connecting base action: %1, shortcut: %2, parent: %3")
                  .arg(m_activeAction->text())
                  .arg(m_action->shortcut().toString())
                  .arg(m_activeAction->parent() ? m_activeAction->parent()->objectName() : "Unspecified parent"));

        connect(m_activeAction, SIGNAL(changed()), SLOT(updateFrontend()));
        connect(m_action, SIGNAL(triggered(bool)), m_activeAction, SIGNAL(triggered(bool)));
        connect(m_action, SIGNAL(toggled(bool)), m_activeAction, SLOT(setChecked(bool)));

        updateFrontend();

        m_initialized = true;

        return;
    }
    else
    {
        LOG_TRACE("New backend action could not be found; action will be disabled in this context.");
    }

    m_action->setEnabled(false);
}
Exemple #29
0
std::unique_ptr<RenderQueue> BREW::CreateFrameDrawable( std::shared_ptr<const Frame> frame ) const {
	auto padding = GetProperty<float>( "Padding", frame );
	auto border_color = GetProperty<sf::Color>( "BorderColor", frame );
	auto color = GetProperty<sf::Color>( "Color", frame );
	auto border_width = GetProperty<float>( "BorderWidth", frame );
	const auto& font_name = GetProperty<std::string>( "FontName", frame );
	auto font_size = GetProperty<unsigned int>( "FontSize", frame );
	const auto& font = GetResourceManager().GetFont( font_name );
	auto label_padding = GetProperty<float>( "LabelPadding", frame );
	auto line_height = GetFontLineHeight( *font, font_size );

	std::unique_ptr<RenderQueue> queue( new RenderQueue );

	// Right
	queue->Add(
		Renderer::Get().CreateLine(
			sf::Vector2f( frame->GetAllocation().width - border_width / 2.f, line_height / 2.f + border_width / 2.f ),
			sf::Vector2f( frame->GetAllocation().width - border_width / 2.f, frame->GetAllocation().height - border_width ),
			border_color,
			border_width
		)
	);

	// Bottom
	queue->Add(
		Renderer::Get().CreateLine(
			sf::Vector2f( frame->GetAllocation().width - border_width / 2.f, frame->GetAllocation().height - border_width ),
			sf::Vector2f( border_width / 2.f, frame->GetAllocation().height - border_width ),
			border_color,
			border_width
		)
	);

	// Left
	queue->Add(
		Renderer::Get().CreateLine(
			sf::Vector2f( border_width / 2.f, frame->GetAllocation().height - border_width ),
			sf::Vector2f( border_width / 2.f, line_height / 2.f + border_width / 2.f ),
			border_color,
			border_width
		)
	);

	auto label_start_x = 0.f;
	auto label_end_x = 0.f;

	auto alignment = frame->GetAlignment().x;

	if( frame->GetLabel().getSize() > 0 ) {
		auto metrics = GetTextStringMetrics( frame->GetLabel(), *font, font_size );
		metrics.x += 2.f * label_padding;

		label_start_x = padding + ( alignment * ( frame->GetAllocation().width - 2.f * padding - metrics.x ) );
		label_end_x = label_start_x + metrics.x;

		sf::Text text( frame->GetLabel(), *font, font_size );
		text.setPosition( label_start_x + label_padding, border_width / 2.f );
		text.setFillColor( color );
		queue->Add( Renderer::Get().CreateText( text ) );
	}

	// Top Left
	queue->Add(
		Renderer::Get().CreateLine(
			sf::Vector2f( border_width / 2.f, line_height / 2.f + border_width / 2.f ),
			sf::Vector2f( label_start_x - .5f * border_width, line_height / 2.f + border_width / 2.f ),
			border_color,
			border_width
		)
	);

	// Top Right
	queue->Add(
		Renderer::Get().CreateLine(
			sf::Vector2f( label_end_x + .5f * border_width, line_height / 2.f + border_width / 2.f ),
			sf::Vector2f( frame->GetAllocation().width - border_width / 2.f, line_height / 2.f + border_width / 2.f ),
			border_color,
			border_width
		)
	);

	return queue;
}
Exemple #30
0
// -------------------------------------------------------------------------------
QString Editor::getText( void )
// -------------------------------------------------------------------------------
{
  return text();
}