Пример #1
0
int main(int argc, char** argv) {

	printf("\nStarting Unit Test 4 (drawCard)\n");

	int *tempKC = kingdomCards(council_room, feast, mine, great_hall, cutpurse,
		treasure_map, outpost, smithy, gardens, embargo);
	G = newGame();

	initializeGame(4, tempKC, 4, G);

	printf("\n**********************Before Draw**************************\n");
	displayState(4);	
	int *tempDeck = malloc(MAX_DECK * sizeof(int));
	memcpy(tempDeck, G->deck[0], MAX_DECK);
	int tmpDeckCount = G->deckCount[0];
	int c;
	c = G->deck[0][tmpDeckCount - 1];

	drawCard(0, G);
	printf("\n**********************After Draw**************************\n");
	displayState(4);
	printf("\n************************************************\n");
	printf("\nTop of deck:  ");
	printCardName(c);
	printf("\nNew Card in Hand:  ");
	printCardName(G->deck[0][G->deckCount[0]]);

	printf("\n\n*********************************************************\n");
	printf("Successfully finished Unit Test 4\n");
	printf("*********************************************************\n\n");
	return 0;
}
Пример #2
0
void HTMLPlugInElement::swapRendererTimerFired(Timer<HTMLPlugInElement>*)
{
    ASSERT(displayState() == PreparingPluginReplacement || displayState() == DisplayingSnapshot);
    if (userAgentShadowRoot())
        return;
    
    // Create a shadow root, which will trigger the code to add a snapshot container
    // and reattach, thus making a new Renderer.
    ensureUserAgentShadowRoot();
}
Пример #3
0
int main(int argc, char** argv) {
	printf("\nStarting Card Test 4 (gardens)\n");

	tempKC = kingdomCards(council_room, feast, mine, great_hall, cutpurse,
		treasure_map, outpost, smithy, gardens, embargo);
	G = newGame();
	initializeGame(2, tempKC, 4, G);
	int turn1 = G->whoseTurn;
	int turn2 = turn1 + 1;

	//Assign first hand draw (deck must be identifiable)
	G->hand[turn1][0] = estate;
	G->hand[turn1][1] = baron;
	G->hand[turn1][2] = copper;
	G->hand[turn1][3] = gardens;
	G->hand[turn1][4] = copper;

	//Each Deck position should be different (identification)
	G->deck[turn1][0] = estate;
	G->deck[turn1][1] = silver;
	G->deck[turn1][2] = gold;
	G->deck[turn1][3] = village;
	G->deck[turn1][4] = minion;

	//Set 2nd player to keep deck identifiable
	G->deck[turn2][0] = estate;
	G->deck[turn2][1] = estate;
	G->deck[turn2][2] = copper;
	G->deck[turn2][3] = copper;
	G->deck[turn2][4] = copper;
	G->deck[turn2][5] = tribute;
	G->deck[turn2][6] = salvager;
	G->deck[turn2][7] = adventurer;
	G->deck[turn2][8] = baron;
	G->deck[turn2][9] = remodel;

	printf("\n*********Before card effect***********\n");
	displayState(2);
	int result = cardEffect(gardens, 0, 0, 0, G, 0, 0);
	printf("\n*********After card effect***********\n");
	displayState(2);
	printf("cardEffect returns:  %i\n", result);

	printf("\n*********************************************************\n");
	printf("*********Successfully finished Card Test 4***********\n");
	printf("*********************************************************\n\n");
	return 0;
}
Пример #4
0
void HTMLPlugInImageElement::restartSnapshottedPlugIn()
{
    if (displayState() != RestartingWithPendingMouseClick)
        setDisplayState(Restarting);

    reattach();
}
Пример #5
0
void CommandDir::listDir(const MyString& path, VirtualDiskNode* vfs, bool only_dir /*= false*/)
{
    DirHandler dir_handler = vfs->openDir(path);
    int file_count = 0;
    int file_size = 0;
    int dir_count = 0;
    for (DirIterator iter = dir_handler.getIterator(); !iter.isDone(); iter.next())
    {
        state s = iter.getItem();
        if (s.type == FILE_TYPE && only_dir)
            continue;
        displayState(s, only_dir);

        if (s.type == FILE_TYPE && !only_dir)
        {
            ++file_count;
            file_size += s.size;
        }
        else if (s.type == DIR_TYPE)
        {
            ++dir_count;
            //         三个空格   六个空格
        }
    }
    _tprintf(_T("%15d 个文件%14d 字节\n"), file_count, file_size);
    _tprintf(_T("%15d 个目录\n"), dir_count);
}
Пример #6
0
void HTMLPlugInElement::defaultEventHandler(Event* event)
{
    // Firefox seems to use a fake event listener to dispatch events to plug-in
    // (tested with mouse events only). This is observable via different order
    // of events - in Firefox, event listeners specified in HTML attributes
    // fires first, then an event gets dispatched to plug-in, and only then
    // other event listeners fire. Hopefully, this difference does not matter in
    // practice.

    // FIXME: Mouse down and scroll events are passed down to plug-in via custom
    // code in EventHandler; these code paths should be united.

    RenderObject* r = renderer();
    if (!r || !r->isWidget())
        return;
    if (r->isEmbeddedObject()) {
        if (toRenderEmbeddedObject(r)->showsUnavailablePluginIndicator())
            return;
        if (displayState() < Playing)
            return;
    }
    RefPtr<Widget> widget = toRenderWidget(r)->widget();
    if (!widget)
        return;
    widget->handleEvent(event);
    if (event->defaultHandled())
        return;
    HTMLFrameOwnerElement::defaultEventHandler(event);
}
Пример #7
0
/*public*/ LightIcon::LightIcon(Editor* editor, QObject *parent) : PositionableIcon(new NamedIcon("resources/icons/smallschematics/tracksegments/os-lefthand-east-closed.gif",  "resources/icons/smallschematics/tracksegments/os-lefthand-east-closed.gif"), editor, (Positionable*)this)
{
    // super ctor call to make sure this is an icon label
    //super(new NamedIcon("resources/icons/smallschematics/tracksegments/os-lefthand-east-closed.gif",
//                        "resources/icons/smallschematics/tracksegments/os-lefthand-east-closed.gif"), editor);
 log = new Logger("LightIcon");
 log->setDebugEnabled(true);
 _control = true;
 light = NULL;
 _bVisible = true;
 _icon = true;

 setPopupUtility(NULL);
 offLName = "resources/icons/smallschematics/tracksegments/os-lefthand-east-closed.gif";
 off = new NamedIcon(offLName, offLName);
 onLName = "resources/icons/smallschematics/tracksegments/os-lefthand-east-thrown.gif";
 on = new NamedIcon(onLName, onLName);
 inconsistentLName = "resources/icons/smallschematics/tracksegments/os-lefthand-east-error.gif";
 inconsistent = new NamedIcon(inconsistentLName, inconsistentLName);
 unknownLName = "resources/icons/smallschematics/tracksegments/os-lefthand-east-unknown.gif";
 unknown = new NamedIcon(unknownLName, unknownLName);
 _namedIcon = unknown;
 _editor = editor;
 _icon = true;
 displayState(lightState());
}
Пример #8
0
void HTMLPlugInElement::setDisplayState(DisplayState state)
{
    m_displayState = state;
    
    if ((state == DisplayingSnapshot || displayState() == PreparingPluginReplacement) && !m_swapRendererTimer.isActive())
        m_swapRendererTimer.startOneShot(0);
}
Пример #9
0
RenderObject* HTMLPlugInImageElement::createRenderer(RenderArena* arena, RenderStyle* style)
{
    // Once a PlugIn Element creates its renderer, it needs to be told when the Document goes
    // inactive or reactivates so it can clear the renderer before going into the page cache.
    if (!m_needsDocumentActivationCallbacks) {
        m_needsDocumentActivationCallbacks = true;
        document()->registerForPageCacheSuspensionCallbacks(this);
    }

    if (displayState() == DisplayingSnapshot) {
        RenderSnapshottedPlugIn* renderSnapshottedPlugIn = new (arena) RenderSnapshottedPlugIn(this);
        renderSnapshottedPlugIn->updateSnapshot(m_snapshotImage);
        return renderSnapshottedPlugIn;
    }

    // Fallback content breaks the DOM->Renderer class relationship of this
    // class and all superclasses because createObject won't necessarily
    // return a RenderEmbeddedObject, RenderPart or even RenderWidget.
    if (useFallbackContent())
        return RenderObject::createObject(this, style);

    if (isImageType()) {
        RenderImage* image = new (arena) RenderImage(this);
        image->setImageResource(RenderImageResource::create());
        return image;
    }

    return new (arena) RenderEmbeddedObject(this);
}
Пример #10
0
void clientDoTurn() {
    char moves[MAX_STARTING_HEALTH];
    char pos_moves[] = "^<>v()S-";
    displayState();
    printf ("Make a move: ");
    scanf ("%s", moves);
    makeMoves(moves);
}
Пример #11
0
int main(void) {
  Display *disp;
  int opcode;
  unsigned int state;
  int maj = XkbMajorVersion;
  int min = XkbMinorVersion;
  XkbEvent ev;

  /* Open Display */
  if ( !(disp = XOpenDisplay(NULL))) {
    fprintf(stderr, "Can't open display: CHECK DISPLAY VARIABLE\n");
    exit(1);
  }

  if (!XkbLibraryVersion(&maj, &min)) {
    fprintf(stderr, "Couldn't get Xkb library version\n");
    exit(1);
  }
  
  if (!XkbQueryExtension(disp, &opcode, &xkb_event_base, &xkb_error_base, &maj, &min)) {
    fprintf(stderr, "XkbQueryExtension error\n");
    exit(1);
  }

  if (!XkbSelectEvents(disp, XkbUseCoreKbd, XkbIndicatorStateNotifyMask, 
                       XkbIndicatorStateNotifyMask)) {
    fprintf(stderr, "XkbSelectEvents\n");
    exit(1);
  }

  XkbGetIndicatorState(disp, XkbUseCoreKbd, &state);
  displayState(state);
  
  /*
  win = XCreateSimpleWindow(disp, DefaultRootWindow(display), 0, 0, 200, 300, 5, white,
                            black);
  */

  while (1) {
    XNextEvent(disp, &ev.core);
    if (ev.type == xkb_event_base && ev.any.xkb_type == XkbIndicatorStateNotify) {
      displayState(ev.indicators.state);
    }
  }
  return 0;
}
Пример #12
0
void HTMLPlugInImageElement::simulatedMouseClickTimerFired(DeferrableOneShotTimer<HTMLPlugInImageElement>*)
{
    ASSERT(displayState() == PlayingWithPendingMouseClick);
    ASSERT(m_pendingClickEventFromSnapshot);

    dispatchSimulatedClick(m_pendingClickEventFromSnapshot.get(), SendMouseOverUpDownEvents, DoNotShowPressedLook);

    setDisplayState(Playing);
    m_pendingClickEventFromSnapshot = nullptr;
}
Пример #13
0
void HTMLPlugInElement::didAddUserAgentShadowRoot(ShadowRoot* root)
{
    if (!m_pluginReplacement || !document().page() || displayState() != PreparingPluginReplacement)
        return;
    
    root->setResetStyleInheritance(true);
    if (m_pluginReplacement->installReplacement(root)) {
        setDisplayState(DisplayingPluginReplacement);
        setNeedsStyleRecalc(ReconstructRenderTree);
    }
}
Пример #14
0
void testNoDiscard()
{
	G = newGame();
	initializeGame(2, tempKC, 4, G);
	int turn1 = G->whoseTurn;
	int turn2 = turn1 + 1;

	//Assign first hand draw (deck must be identifiable)
	G->hand[turn1][0] = estate;
	G->hand[turn1][1] = baron;
	G->hand[turn1][2] = copper;
	G->hand[turn1][3] = copper;
	G->hand[turn1][4] = copper;

	//Each Deck position should be different (identification)
	G->deck[turn1][0] = estate;
	G->deck[turn1][1] = silver;
	G->deck[turn1][2] = gold;
	G->deck[turn1][3] = village;
	G->deck[turn1][4] = minion;

	//Set 2nd player to keep deck identifiable
	G->deck[turn2][0] = estate;
	G->deck[turn2][1] = estate;
	G->deck[turn2][2] = copper;
	G->deck[turn2][3] = copper;
	G->deck[turn2][4] = copper;
	G->deck[turn2][5] = tribute;
	G->deck[turn2][6] = salvager;
	G->deck[turn2][7] = adventurer;
	G->deck[turn2][8] = baron;
	G->deck[turn2][9] = remodel;

	printf("\n*********Before card effect (No Discard)***********\n");
	displayState(G);
	cardEffect(baron, 0, 0, 0, G, 0, 0);
	printf("\n*********After card effect(No Discard)***********\n");
	displayState(G);
	return;
}
Пример #15
0
void HTMLPlugInImageElement::checkSnapshotStatus()
{
    if (!renderer()->isSnapshottedPlugIn()) {
        if (displayState() == Playing)
            checkSizeChangeForSnapshotting();
        return;
    }

    ShadowRoot* root = userAgentShadowRoot();
    if (!root)
        return;

    Element* shadowContainer = toElement(root->firstChild());
    shadowContainer->setAttribute(classAttr, classNameForShadowRoot(this));
}
Пример #16
0
void HTMLPlugInElement::defaultEventHandler(Event* event)
{
    // Firefox seems to use a fake event listener to dispatch events to plug-in (tested with mouse events only).
    // This is observable via different order of events - in Firefox, event listeners specified in HTML attributes fires first, then an event
    // gets dispatched to plug-in, and only then other event listeners fire. Hopefully, this difference does not matter in practice.

    // FIXME: Mouse down and scroll events are passed down to plug-in via custom code in EventHandler; these code paths should be united.

    auto renderer = this->renderer();
    if (!renderer || !renderer->isWidget())
        return;

    if (renderer->isEmbeddedObject()) {
        if (toRenderEmbeddedObject(renderer)->isPluginUnavailable()) {
            toRenderEmbeddedObject(renderer)->handleUnavailablePluginIndicatorEvent(event);
            return;
        }

        if (toRenderEmbeddedObject(renderer)->isSnapshottedPlugIn() && displayState() < Restarting) {
            toRenderSnapshottedPlugIn(renderer)->handleEvent(event);
            HTMLFrameOwnerElement::defaultEventHandler(event);
            return;
        }

        if (displayState() < Playing)
            return;
    }

    RefPtr<Widget> widget = toRenderWidget(renderer)->widget();
    if (!widget)
        return;
    widget->handleEvent(event);
    if (event->defaultHandled())
        return;
    HTMLFrameOwnerElement::defaultEventHandler(event);
}
Пример #17
0
void HTMLPlugInImageElement::updateSnapshot(PassRefPtr<Image> image)
{
    if (displayState() > DisplayingSnapshot)
        return;

    m_snapshotImage = image;

    if (renderer()->isSnapshottedPlugIn()) {
        toRenderSnapshottedPlugIn(renderer())->updateSnapshot(image);
        return;
    }

    if (renderer()->isEmbeddedObject())
        renderer()->repaint();
}
Пример #18
0
void CommandDir::exec(VirtualDiskNode* vfs)
{
    if (!vfs)
    {
        assert(0);
        return;
    }
    
    if (m_pathes.isEmpty())
    {
        m_pathes.append(vfs->pwd());
    }

    for (int i = 0; i < m_pathes.size(); ++i)
    {
        MyString path = m_pathes[i];
        if (!isNormalizedPath(path))
        {
            path = vfs->pathNormalize(path);
        }
        path = path.toLower();
        if (!vfs->isExist(path))
        {
            throw CommandException(_T("系统找不到指定路径\n"));
        }
        if (vfs->isFile(path))
        {
            FileHandler file_handler = vfs->openFile(path);
            state s = file_handler.stat();
            displayState(s, false);
            _tprintf(_T("%15d 个文件%14d 字节\n"), 1, s.size);
            _tprintf(_T("%15d 个目录\n"), 0);
        }
        if (vfs->isDir(path))
        {
            if (m_recursive)
            {
                listDirRecursive(path, vfs, m_only_dir);
            }
            else
            {
                listDir(path, vfs, m_only_dir);
            }
        }
    }
    return;
}
Пример #19
0
void TcpClient::doConnect(QString host, quint16 port)
{

    //MainWindow *ui = new MainWindow;
    //MainWindow *ui = new MainWindow();

    socket = new QTcpSocket(this);

    //connect(socket, SIGNAL(connected()), ui, SLOT(connectedToServer()));
    connect(socket, SIGNAL(connected()), this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten(qint64)));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
    connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(displayState(QAbstractSocket::SocketState)));


    if(validateIpAddress(host))
    {

        qDebug() << "Connecting to " + host + ":" + QString::number(port);

        // this is not blocking call
        socket->connectToHost(host, port);


        // we need to wait...
        if(!socket->waitForConnected(5000))
        {
            qDebug() << "Error: " << socket->errorString();
        }

    }
    else
    {

        QMessageBox::warning(NULL, "Error", "This IP address is invalid.");
        qDebug() << "Invalid ip address: " + host;

    }

}
Пример #20
0
int main(void)
{
     cgi_init();

     mysqlpp::Connection c(false);
     if (!c.connect("okzoniom", "localhost", "okzoniom", getDBIdent().c_str())) {
          cgi_redirect("./error.okz?state=err_db");
          return 0;
     } else {
          //Set UTF8
          mysqlpp::Query q = c.query("SET NAMES utf8");
          q.exec();
     }
     initializeFaction(c);

     cgi_session_save_path("sessions/");
     cgi_session_start();

     cgi_process_form();



     cgi_init_headers();
     __tr("your_army");
     header("your_army");
     menu();
     sidebar();

     if (cgi_session_var("login") == NULL) {
          std::cout << "<div class=\"err\">" << __tr("profil_mustlogin") << "</div>";
     } else {
          displayState();
          show(cgi_session_var("login"), c);
     }

     footer();
     return 0;
}
Пример #21
0
int main(int argc, char **argv)
{
#pragma region InitialNite And Ni
	// Initial NiTE
	if (NiTE::initialize() != STATUS_OK)
	{
		cerr << "NiTE initial error" << endl;
		system("PAUSE");
		return -1;
	}

	if (openni::OpenNI::initialize() != openni::STATUS_OK){
		cerr << "NiTE initial error" << endl;
		system("PAUSE");
		return -1;
	}
#pragma endregion


#pragma region GetAllDevice
	openni::Array<openni::DeviceInfo> deviceInfoList;
	openni::OpenNI::enumerateDevices(&deviceInfoList);
	cout << endl;
	cout << "Device numbers: " << deviceInfoList.getSize() << endl;

	vector<CDevice> vDevices;
	for (int i = 0; i < deviceInfoList.getSize(); ++i)
	{
		cout << "Device " << i << "\n";
		const openni::DeviceInfo& rDevInfo = deviceInfoList[i];

		cout << " " << rDevInfo.getName() << " by " << rDevInfo.getVendor() << "\n";
		cout << " PID: " << rDevInfo.getUsbProductId() << "\n";
		cout << " VID: " << rDevInfo.getUsbVendorId() << "\n";
		cout << " URI: " << rDevInfo.getUri() << endl;

		// initialize
		CDevice mDevWin(i, deviceInfoList[i].getUri());
		vDevices.push_back(mDevWin);
	}
#pragma endregion


	// start
	while (true)
	{
		for (vector<CDevice>::iterator itdev = vDevices.begin(); itdev != vDevices.end(); ++itdev){
			// get user frame
			UserTrackerFrameRef	mUserFrame;
			if (itdev->pUserTracker->readFrame(&mUserFrame) == nite::STATUS_OK)
			{
				// get depth data and convert to OpenCV format
				openni::VideoFrameRef vfDepthFrame = mUserFrame.getDepthFrame();
				const cv::Mat mImageDepth(vfDepthFrame.getHeight(), vfDepthFrame.getWidth(), CV_16UC1, const_cast<void*>(vfDepthFrame.getData()));
				// re-map depth data [0,Max] to [0,255]
				cv::Mat mScaledDepth;
				mImageDepth.convertTo(mScaledDepth, CV_8U, 255.0 / 10000);

				// convert gray-scale to color
				cv::Mat mImageBGR;
				cv::cvtColor(mScaledDepth, mImageBGR, CV_GRAY2BGR);

				// get users data
				const nite::Array<UserData>& aUsers = mUserFrame.getUsers();
				for (int i = 0; i < aUsers.getSize(); ++i)
				{
					const UserData& rUser = aUsers[i];

					// check user status
					if (rUser.isNew())
					{
						cout << "New User [" << rUser.getId() << "] found." << endl;
						//  start tracking for new user
						itdev->pUserTracker->setSkeletonSmoothingFactor(0.65); //平滑控制。
						itdev->pUserTracker->startSkeletonTracking(rUser.getId());
					}
					else if (rUser.isLost())
					{
						cout << "User [" << rUser.getId() << "] lost." << endl;
					}

					if (rUser.isVisible())
					{
						// get user skeleton
						const Skeleton& rSkeleton = rUser.getSkeleton();
						if (rSkeleton.getState() == SKELETON_TRACKED)
						{
#pragma region DrawSkeletonLineAndCircle
							// build joints array
							nite::SkeletonJoint aJoints[15];
							aJoints[0] = rSkeleton.getJoint(JOINT_HEAD);
							aJoints[1] = rSkeleton.getJoint(JOINT_NECK);
							aJoints[2] = rSkeleton.getJoint(JOINT_LEFT_SHOULDER);
							aJoints[3] = rSkeleton.getJoint(JOINT_RIGHT_SHOULDER);
							aJoints[4] = rSkeleton.getJoint(JOINT_LEFT_ELBOW);
							aJoints[5] = rSkeleton.getJoint(JOINT_RIGHT_ELBOW);
							aJoints[6] = rSkeleton.getJoint(JOINT_LEFT_HAND);
							aJoints[7] = rSkeleton.getJoint(JOINT_RIGHT_HAND);
							aJoints[8] = rSkeleton.getJoint(JOINT_TORSO);
							aJoints[9] = rSkeleton.getJoint(JOINT_LEFT_HIP);
							aJoints[10] = rSkeleton.getJoint(JOINT_RIGHT_HIP);
							aJoints[11] = rSkeleton.getJoint(JOINT_LEFT_KNEE);
							aJoints[12] = rSkeleton.getJoint(JOINT_RIGHT_KNEE);
							aJoints[13] = rSkeleton.getJoint(JOINT_LEFT_FOOT);
							aJoints[14] = rSkeleton.getJoint(JOINT_RIGHT_FOOT);

							// convert joint position to image
							cv::Point2f aPoint[15];
							for (int s = 0; s < 15; ++s)
							{
								const Point3f& rPos = aJoints[s].getPosition();
								itdev->pUserTracker->convertJointCoordinatesToDepth(rPos.x, rPos.y, rPos.z, &(aPoint[s].x), &(aPoint[s].y));
							}

							// draw line
							cv::line(mImageBGR, aPoint[0], aPoint[1], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[1], aPoint[2], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[1], aPoint[3], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[2], aPoint[4], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[3], aPoint[5], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[4], aPoint[6], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[5], aPoint[7], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[1], aPoint[8], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[8], aPoint[9], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[8], aPoint[10], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[9], aPoint[11], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[10], aPoint[12], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[11], aPoint[13], cv::Scalar(255, 0, 0), 3);
							cv::line(mImageBGR, aPoint[12], aPoint[14], cv::Scalar(255, 0, 0), 3);

							// draw joint
							for (int s = 0; s < 15; ++s)
							{
								if (aJoints[s].getPositionConfidence() > 0.5)
									cv::circle(mImageBGR, aPoint[s], 3, cv::Scalar(0, 0, 255), 2);
								else
									cv::circle(mImageBGR, aPoint[s], 3, cv::Scalar(0, 255, 0), 2);
							}

							cv::putText(mImageBGR, "USER" + to_string(rUser.getId()), aPoint[0], cv::FONT_HERSHEY_DUPLEX, 0.5, cv::Scalar(255, 255, 255));

#pragma endregion

							//獲取初始值
							if (itdev->detectFlag == 0)//第一次偵測
							{
#pragma region 初始化Algorithm
								itdev->DSTimes++;
								if (itdev->DSTimes == 1)
								{
									itdev->fheadf.x = aJoints[0].getPosition().x;//站立時的頭的位置;
									itdev->fheadf.y = aJoints[0].getPosition().y;
									itdev->fheadf.z = aJoints[0].getPosition().z;

									itdev->ftorsof.x = aJoints[8].getPosition().x;//站立時的質心位置;
									itdev->ftorsof.y = aJoints[8].getPosition().y;
									itdev->ftorsof.z = aJoints[8].getPosition().z;

									itdev->lefthand.x = aJoints[6].getPosition().x;
									itdev->lefthand.y = aJoints[6].getPosition().y;
									itdev->lefthand.z = aJoints[6].getPosition().z;

									itdev->righthand.x = aJoints[7].getPosition().x;
									itdev->righthand.y = aJoints[7].getPosition().y;
									itdev->righthand.z = aJoints[7].getPosition().z;
									//左右手距離*0.55。 為什麼要乘0.55?
									itdev->armLen = sqrt((itdev->lefthand.x - itdev->righthand.x)*(itdev->lefthand.x - itdev->righthand.x) +
										(itdev->lefthand.y - itdev->righthand.y)*(itdev->lefthand.y - itdev->righthand.y) +
										(itdev->lefthand.z - itdev->righthand.z)*(itdev->lefthand.z - itdev->righthand.z))*0.55;
								}
								else if (itdev->DSTimes > 1 && itdev->DSTimes <= 200)	//偵測次數於200次以內
								{
									itdev->fheadf.x = itdev->fheadf.x + aJoints[0].getPosition().x;//站立時的頭的位置(累加);
									itdev->fheadf.y = itdev->fheadf.y + aJoints[0].getPosition().y;
									itdev->fheadf.z = itdev->fheadf.z + aJoints[0].getPosition().z;

									itdev->ftorsof.x = itdev->ftorsof.x + aJoints[8].getPosition().x;//站立時的質心位置(累加);
									itdev->ftorsof.y = itdev->ftorsof.y + aJoints[8].getPosition().y;
									itdev->ftorsof.z = itdev->ftorsof.z + aJoints[8].getPosition().z;

									itdev->lefthand.x = aJoints[6].getPosition().x;
									itdev->lefthand.y = aJoints[6].getPosition().y;
									itdev->lefthand.z = aJoints[6].getPosition().z;

									itdev->righthand.x = aJoints[7].getPosition().x;
									itdev->righthand.y = aJoints[7].getPosition().y;
									itdev->righthand.z = aJoints[7].getPosition().z;
									//?????
									int cc = sqrt((itdev->lefthand.x - itdev->righthand.x)*(itdev->lefthand.x - itdev->righthand.x) +
										(itdev->lefthand.y - itdev->righthand.y)*(itdev->lefthand.y - itdev->righthand.y) +
										(itdev->lefthand.z - itdev->righthand.z)*(itdev->lefthand.z - itdev->righthand.z))*0.55;

									//	cout << "測試下身長:" << cc << endl;
									itdev->armLen = itdev->armLen + cc;
								}
								if (itdev->DSTimes >= 200)//計算頭、身初始值、跌倒閥值
								{
									itdev->detectFlag = 1;
									itdev->fhead_Ini.x = itdev->fheadf.x / itdev->DSTimes;
									itdev->fhead_Ini.y = itdev->fheadf.y / itdev->DSTimes;
									itdev->fhead_Ini.z = itdev->fheadf.z / itdev->DSTimes;

									itdev->ftorso_Ini.x = itdev->ftorsof.x / itdev->DSTimes;
									itdev->ftorso_Ini.y = itdev->ftorsof.y / itdev->DSTimes;
									itdev->ftorso_Ini.z = itdev->ftorsof.z / itdev->DSTimes;

									itdev->fallDownThreshold = ((int)((itdev->armLen / itdev->DSTimes) / 100) * 100);

									cout << "跌倒的閾值:" << itdev->fallDownThreshold << endl;

									//計算頭 身當前的值
									itdev->fhead.x = aJoints[JOINT_HEAD].getPosition().x;
									itdev->fhead.y = aJoints[JOINT_HEAD].getPosition().y;
									itdev->fhead.z = aJoints[JOINT_HEAD].getPosition().z;
									itdev->fhead_Pre = itdev->fhead;

									itdev->ftorso.x = aJoints[JOINT_TORSO].getPosition().x;
									itdev->ftorso.y = aJoints[JOINT_TORSO].getPosition().y;
									itdev->ftorso.z = aJoints[JOINT_TORSO].getPosition().z;
									itdev->ftorso_Pre = itdev->ftorso;

									cout << "第" << itdev->DSTimes << "次" << "的頭部h:" << itdev->fhead.y << endl;
								}
#pragma endregion
							}
							else
							{
								if (itdev->cishu == 8)
								{
									itdev->cishu = 0;
#pragma region MainAlgorithm 
									itdev->fhead.x = aJoints[0].getPosition().x;
									itdev->fhead.y = aJoints[0].getPosition().y;
									itdev->fhead.z = aJoints[0].getPosition().z;

									itdev->ftorso.x = aJoints[8].getPosition().x;
									itdev->ftorso.y = aJoints[8].getPosition().y;
									itdev->ftorso.z = aJoints[8].getPosition().z;

									itdev->neck.x = aJoints[1].getPosition().x;
									itdev->neck.y = aJoints[1].getPosition().y;
									itdev->neck.z = aJoints[1].getPosition().z;

									itdev->event_Now = eventDetect(itdev->fhead_Pre, itdev->ftorso_Pre, itdev->fhead, itdev->ftorso, itdev->fhead_Ini, itdev->ftorso_Ini, itdev->neck, itdev->fallDownThreshold);//(前一幀,後一幀,初始幀)


#pragma region 統計時間,依時間檢查動作是否正確,發生錯誤僅作顯示,對程式邏輯沒有影響
									//統計時間
									if (itdev->event_Now == INCIDENT_SIT_DOWN)
										itdev->zuo = clock();
									if (itdev->event_Now == INCIDENT_FALLDOWN)
										itdev->die = clock();
									if (itdev->event_Now == INCIDENT_SIT_UP)
										itdev->zql = clock();
									if (itdev->event_Now == INCIDENT_STANDUP)
										itdev->zanql = clock();

									//僅顯示出可能的錯誤資訊、沒有實際影響
									if (itdev->event_Now == INCIDENT_FALLDOWN && difftime(itdev->zuo, itdev->firsttime) > 0 && difftime(itdev->zuo_Pre, itdev->zuo) != 0)
									{
										automendG(itdev->event_Now, difftime(itdev->die, itdev->zuo));//若"跌倒"與"坐下"事件大於10秒 則顯示警告
										itdev->zuo_Pre = itdev->zuo;
									}

									if (itdev->event_Now == INCIDENT_STANDUP && difftime(itdev->zql, itdev->firsttime) > 0 && difftime(itdev->zql_Pre, itdev->zql) != 0)
									{
										automendG(itdev->event_Now, difftime(itdev->zanql, itdev->zql));////若"站起來"與"坐起來"事件大於10秒 則顯示警告
										itdev->zql_Pre = itdev->zql;
									}
#pragma endregion


#pragma region 用於調試的,直接顯示出事件偵測結果,對程式邏輯沒有影響。
									if (itdev->event_Pre != itdev->event_Now)
									{
										if (itdev->event_Now == INCIDENT_NONE)
											cout << "沒偵測到事件發生!" << endl;
										if (itdev->event_Now == INCIDENT_STOP)
											cout << "發生的事件: " << "停止" << endl;
										if (itdev->event_Now == INCIDENT_WALK)
											cout << "發生的事件: " << "走" << endl;
										if (itdev->event_Now == INCIDENT_SIT_UP)
											cout << "發生的事件: " << "坐起來" << endl;
										if (itdev->event_Now == INCIDENT_STANDUP)
											cout << "發生的事件: " << "站起來" << endl;
										if (itdev->event_Now == INCIDENT_FALLDOWN)
											cout << "發生的事件: " << "跌倒" << endl;
										if (itdev->event_Now == INCIDENT_SIT_DOWN)
											cout << "發生的事件: " << "坐下" << endl;
										if (itdev->event_Now == INCIDENT_LAYDOWN)
											cout << "發生的事件: " << "躺下" << endl;
									}
									itdev->event_Pre = itdev->event_Now;
#pragma endregion


									if (itdev->weizhi == 0)
									{
										itdev->nextState = firststate(itdev->event_Now);
										if (itdev->nextState != 0)
											itdev->weizhi = 1;
										displayState(itdev->nextState, itdev->nowState,itdev->deviceID);
										itdev->nowState = itdev->nextState;
									}
									else if (itdev->weizhi == 1)
									{
										if (itdev->event_Now != 0)
										{
											if (unnormalzhenc(itdev->event_Now, itdev->nowState) == 1);
											{
												itdev->weizhi = 0;
											}
											itdev->nextState = stateTransfer(itdev->event_Now, itdev->nowState);
										}
										displayState(itdev->nextState, itdev->nowState, itdev->deviceID);
										itdev->nowState = itdev->nextState;
									}
									itdev->fhead_Pre = itdev->fhead;
									itdev->ftorso_Pre = itdev->ftorso;
#pragma endregion
								}
								itdev->cishu++;
							}
						}
					}
				}

				// show image
				cv::imshow(itdev->sWindow.c_str(), mImageBGR);
				mUserFrame.release();
			}
			else
			{
				cerr << "Can't get user frame" << endl;
			}
		}
		// check keyboard
		if (cv::waitKey(1) == 'q')
			break;
	}

	// stop
	for (vector<CDevice>::iterator itDev = vDevices.begin(); itDev != vDevices.end(); ++itDev){
		itDev->pUserTracker->destroy();
		delete itDev->pUserTracker;
		itDev->pDevice->close();
		delete itDev->pDevice;
	}

	cv::destroyAllWindows();
	NiTE::shutdown();
	openni::OpenNI::shutdown();
	system("PAUSE");

	return 0;
}
Пример #22
0
void HTMLPlugInImageElement::subframeLoaderWillCreatePlugIn(const KURL& url)
{
    LOG(Plugins, "%p Plug-in URL: %s", this, m_url.utf8().data());
    LOG(Plugins, "   Loaded URL: %s", url.string().utf8().data());

    m_loadedUrl = url;

    if (!document()->page()
        || !document()->page()->settings()->plugInSnapshottingEnabled())
        return;

    if (displayState() == Restarting) {
        setDisplayState(Playing);
        LOG(Plugins, "%p Plug-in is explicitly restarting", this);
        return;
    }

    if (displayState() == RestartingWithPendingMouseClick) {
        LOG(Plugins, "%p Plug-in is explicitly restarting but also waiting for a click", this);
        return;
    }

    bool inMainFrame = document()->frame() == document()->page()->mainFrame();

    if (document()->isPluginDocument() && inMainFrame) {
        LOG(Plugins, "%p Plug-in document in main frame", this);
        return;
    }

    if (ScriptController::processingUserGesture()) {
        LOG(Plugins, "%p Script is currently processing user gesture, set to play", this);
        return;
    }

    if (m_createdDuringUserGesture) {
        LOG(Plugins, "%p Plug-in was created when processing user gesture, set to play", this);
        return;
    }

    double lastKnownUserGestureTimestamp = document()->lastHandledUserGestureTimestamp();
    if (!inMainFrame && document()->page()->mainFrame() && document()->page()->mainFrame()->document())
        lastKnownUserGestureTimestamp = std::max(lastKnownUserGestureTimestamp, document()->page()->mainFrame()->document()->lastHandledUserGestureTimestamp());
    if (currentTime() - lastKnownUserGestureTimestamp < autostartSoonAfterUserGestureThreshold) {
        LOG(Plugins, "%p Plug-in was created shortly after a user gesture, set to play", this);
        return;
    }

    RenderBox* renderEmbeddedObject = toRenderBox(renderer());
    Length styleWidth = renderEmbeddedObject->style()->width();
    Length styleHeight = renderEmbeddedObject->style()->height();
    LayoutRect contentBoxRect = renderEmbeddedObject->contentBoxRect();
    int contentWidth = contentBoxRect.width();
    int contentHeight = contentBoxRect.height();
    int contentArea = contentWidth * contentHeight;
    IntSize visibleViewSize = document()->frame()->view()->visibleSize();
    int visibleArea = visibleViewSize.width() * visibleViewSize.height();

    if (inMainFrame && styleWidth.isPercent() && (styleWidth.percent() == 100)
        && styleHeight.isPercent() && (styleHeight.percent() == 100)
        && (static_cast<float>(contentArea) / visibleArea > sizingFullPageAreaRatioThreshold)) {
        LOG(Plugins, "%p Plug-in is top level full page, set to play", this);
        return;
    }

    if (contentWidth <= sizingTinyDimensionThreshold || contentHeight <= sizingTinyDimensionThreshold) {
        LOG(Plugins, "%p Plug-in is very small %dx%d, set to play", this, contentWidth, contentHeight);
        return;
    }

    if (!document()->page()->plugInClient()) {
        setDisplayState(WaitingForSnapshot);
        return;
    }

    if (document()->page()->plugInClient()->shouldAutoStartFromOrigin(document()->page()->mainFrame()->document()->baseURL().host(), url.host(), loadedMimeType())) {
        LOG(Plugins, "%p Plug-in from (%s, %s) is marked to auto-start, set to play", this, document()->page()->mainFrame()->document()->baseURL().host().utf8().data(), url.host().utf8().data());
        return;
    }

    LOG(Plugins, "%p Plug-in from (%s, %s) is not auto-start, sized at %dx%d, set to wait for snapshot", this, document()->page()->mainFrame()->document()->baseURL().host().utf8().data(), url.host().utf8().data(), contentWidth, contentHeight);
    setDisplayState(WaitingForSnapshot);
}
void App::process()
{
    if (sources.empty())
    {
        std::cout << "Using default frames source...\n";
        sources.push_back(new VideoSource("data/bgfg/haut-640x480.avi"));
    }

    cv::Mat frame;
    cv::gpu::GpuMat d_frame;
    IplImage ipl_frame;

    cv::Mat fgmask;
    cv::gpu::GpuMat d_fgmask;
    cv::Mat buf;

    cv::Mat outImg;
    cv::Mat foreground;

    while (!exited)
    {
        int64 total_time = cv::getTickCount();

        sources[curSource]->next(frame);
        d_frame.upload(frame);
        ipl_frame = frame;
        frame.copyTo(outImg);

        double total_fps = 0.0;
        double proc_fps = 0.0;

        try
        {
            int64 proc_time = cv::getTickCount();

            switch (method) {
            case MOG:
                {
                    if (useGpu)
                    {
                        if (reinitialize)
                            mog_gpu.initialize(d_frame.size(), d_frame.type());
                        mog_gpu(d_frame, d_fgmask, 0.01f);
                    }
                    else
                    {
                        if (reinitialize)
                            mog_cpu.initialize(frame.size(), frame.type());
                        mog_cpu(frame, fgmask, 0.01);
                    }
                    break;
                }
            //case MOG2:
            //    {
            //        if (useGpu)
            //        {
            //            if (reinitialize)
            //                mog2_gpu.initialize(d_frame.size(), d_frame.type());
            //            mog2_gpu(d_frame, d_fgmask);
            //        }
            //        else
            //        {
            //            if (reinitialize)
            //            {
            //                mog2_cpu.set("detectShadows", false);
            //                mog2_cpu.initialize(frame.size(), frame.type());
            //            }
            //            mog2_cpu(frame, fgmask);
            //        }
            //        break;
            //    }
            case FGD:
                {
                    if (useGpu)
                    {
                        if (reinitialize)
                            fgd_gpu.create(d_frame);
                        fgd_gpu.update(d_frame);
                        fgd_gpu.foreground.copyTo(d_fgmask);
                    }
                    else
                    {
                        if (reinitialize)
                            fgd_cpu = cvCreateFGDStatModel(&ipl_frame);
                        cvUpdateBGStatModel(&ipl_frame, fgd_cpu);
                        cv::Mat(fgd_cpu->foreground).copyTo(fgmask);
                    }
                    break;
                }
            //case GMG:
            //    {
            //        if (useGpu)
            //        {
            //            if (reinitialize)
            //                gmg_gpu.initialize(d_frame.size());
            //            gmg_gpu(d_frame, d_fgmask);
            //        }
            //        else
            //        {
            //            if (reinitialize)
            //                gmg_cpu.initialize(frame.size(), 0, 255);
            //            gmg_cpu(frame, fgmask);
            //        }
            //        break;
            //    }
            case VIBE:
                {
                    if (useGpu)
                    {
                        if (reinitialize)
                            vibe_gpu.initialize(d_frame);
                        vibe_gpu(d_frame, d_fgmask);
                    }
                    break;
                }
            }

            proc_fps = cv::getTickFrequency() / (cv::getTickCount() - proc_time);

            if (useGpu)
                d_fgmask.download(fgmask);

            cv::filterSpeckles(fgmask, 0, 100, 1, buf);

            cv::add(outImg, cv::Scalar(100, 100, 0), outImg, fgmask);

            foreground.create(frame.size(), frame.type());
            foreground.setTo(0);
            frame.copyTo(foreground, fgmask);

            total_fps = cv::getTickFrequency() / (cv::getTickCount() - total_time);

            reinitialize = false;
        }
        catch (const cv::Exception&)
        {
            std::string msg = "Can't allocate memory";

            int fontFace = cv::FONT_HERSHEY_DUPLEX;
            int fontThickness = 2;
            double fontScale = 0.8;

            cv::Size fontSize = cv::getTextSize("T[]", fontFace, fontScale, fontThickness, 0);

            cv::Point org(outImg.cols / 2, outImg.rows / 2);
            org.x -= fontSize.width;
            org.y -= fontSize.height / 2;

            cv::putText(outImg, msg, org, fontFace, fontScale, cv::Scalar(0,0,0,255), 5 * fontThickness / 2, 16);
            cv::putText(outImg, msg, org, fontFace, fontScale, CV_RGB(255, 0, 0), fontThickness, 16);
        }

        displayState(outImg, proc_fps, total_fps);

        cv::imshow("Background Subtraction Demo", outImg);
        cv::imshow("Foreground", foreground);

        processKey(cv::waitKey(30) & 0xff);
    }
}
Пример #24
0
void HTMLPlugInImageElement::subframeLoaderWillCreatePlugIn(const KURL& url)
{
    if (!document()->page()
        || !document()->page()->settings()->plugInSnapshottingEnabled())
        return;

    bool inMainFrame = document()->frame() == document()->page()->mainFrame();

    if (document()->isPluginDocument() && inMainFrame) {
        LOG(Plugins, "%p Plug-in document in main frame", this);
        return;
    }

    if (ScriptController::processingUserGesture()) {
        LOG(Plugins, "%p Script is processing user gesture, set to play", this);
        return;
    }

    if (m_createdDuringUserGesture) {
        LOG(Plugins, "%p Plug-in was created when processing user gesture, set to play", this);
        return;
    }

    double lastKnownUserGestureTimestamp = document()->lastHandledUserGestureTimestamp();
    if (!inMainFrame && document()->page()->mainFrame() && document()->page()->mainFrame()->document())
        lastKnownUserGestureTimestamp = std::max(lastKnownUserGestureTimestamp, document()->page()->mainFrame()->document()->lastHandledUserGestureTimestamp());
    if (currentTime() - lastKnownUserGestureTimestamp < autostartSoonAfterUserGestureThreshold) {
        LOG(Plugins, "%p Plug-in was created shortly after a user gesture, set to play", this);
        return;
    }

    RenderBox* renderEmbeddedObject = toRenderBox(renderer());
    Length styleWidth = renderEmbeddedObject->style()->width();
    Length styleHeight = renderEmbeddedObject->style()->height();
    LayoutRect contentBoxRect = renderEmbeddedObject->contentBoxRect();
    int contentWidth = contentBoxRect.width();
    int contentHeight = contentBoxRect.height();
    int contentArea = contentWidth * contentHeight;
    IntSize visibleViewSize = document()->frame()->view()->visibleSize();
    int visibleArea = visibleViewSize.width() * visibleViewSize.height();

    if (inMainFrame && styleWidth.isPercent() && (styleWidth.percent() == 100)
        && styleHeight.isPercent() && (styleHeight.percent() == 100)
        && (static_cast<float>(contentArea) / visibleArea > sizingFullPageAreaRatioThreshold)) {
        LOG(Plugins, "%p Plug-in is top level full page, set to play", this);
        return;
    }

    if (contentWidth <= sizingTinyDimensionThreshold || contentHeight <= sizingTinyDimensionThreshold) {
        LOG(Plugins, "%p Plug-in is %dx%d, set to play", this, contentWidth, contentHeight);
        return;
    }

    if (!document()->page() || !document()->page()->plugInClient()) {
        setDisplayState(WaitingForSnapshot);
        return;
    }

    LOG(Plugins, "%p Plug-in URL: %s", this, m_url.utf8().data());
    LOG(Plugins, "            loaded URL: %s", url.string().utf8().data());

    m_plugInOriginHash = PlugInOriginHash::hash(this, url);
    if (m_plugInOriginHash && document()->page()->plugInClient()->isAutoStartOrigin(m_plugInOriginHash)) {
        LOG(Plugins, "%p Plug-in hash %x is auto-start, set to play", this, m_plugInOriginHash);
        return;
    }

    LOG(Plugins, "%p Plug-in hash %x is %dx%d, origin is not auto-start, set to wait for snapshot", this, m_plugInOriginHash, contentWidth, contentHeight);
    // We may have got to this point by restarting a snapshotted plug-in, in which case we don't want to
    // reset the display state.
    if (displayState() != PlayingWithPendingMouseClick)
        setDisplayState(WaitingForSnapshot);
}
Пример #25
0
bool HTMLPlugInImageElement::willRecalcStyle(StyleChange)
{
    // FIXME: Why is this necessary?  Manual re-attach is almost always wrong.
    if (!useFallbackContent() && needsWidgetUpdate() && renderer() && !isImageType() && (displayState() != DisplayingSnapshot))
        reattach();
    return true;
}
Пример #26
0
void HTMLPlugInImageElement::subframeLoaderWillCreatePlugIn(const KURL& url)
{
    LOG(Plugins, "%p Plug-in URL: %s", this, m_url.utf8().data());
    LOG(Plugins, "   Loaded URL: %s", url.string().utf8().data());

    m_loadedUrl = url;
    m_plugInWasCreated = false;
    m_deferredPromotionToPrimaryPlugIn = false;

    if (!document()->page() || !document()->page()->settings()->plugInSnapshottingEnabled()) {
        m_snapshotDecision = NeverSnapshot;
        return;
    }

    if (displayState() == Restarting) {
        LOG(Plugins, "%p Plug-in is explicitly restarting", this);
        m_snapshotDecision = NeverSnapshot;
        setDisplayState(Playing);
        return;
    }

    if (displayState() == RestartingWithPendingMouseClick) {
        LOG(Plugins, "%p Plug-in is explicitly restarting but also waiting for a click", this);
        m_snapshotDecision = NeverSnapshot;
        return;
    }

    if (m_snapshotDecision == NeverSnapshot) {
        LOG(Plugins, "%p Plug-in is blessed, allow it to start", this);
        return;
    }

    bool inMainFrame = document()->frame() == document()->page()->mainFrame();

    if (document()->isPluginDocument() && inMainFrame) {
        LOG(Plugins, "%p Plug-in document in main frame", this);
        m_snapshotDecision = NeverSnapshot;
        return;
    }

    if (ScriptController::processingUserGesture()) {
        LOG(Plugins, "%p Script is currently processing user gesture, set to play", this);
        m_snapshotDecision = NeverSnapshot;
        return;
    }

    if (m_createdDuringUserGesture) {
        LOG(Plugins, "%p Plug-in was created when processing user gesture, set to play", this);
        m_snapshotDecision = NeverSnapshot;
        return;
    }

    if (documentHadRecentUserGesture(document())) {
        LOG(Plugins, "%p Plug-in was created shortly after a user gesture, set to play", this);
        m_snapshotDecision = NeverSnapshot;
        return;
    }

    if (document()->page()->settings()->snapshotAllPlugIns()) {
        LOG(Plugins, "%p Plug-in forced to snapshot by user preference", this);
        m_snapshotDecision = Snapshotted;
        setDisplayState(WaitingForSnapshot);
        return;
    }

    if (document()->page()->settings()->autostartOriginPlugInSnapshottingEnabled() && document()->page()->plugInClient() && document()->page()->plugInClient()->shouldAutoStartFromOrigin(document()->page()->mainFrame()->document()->baseURL().host(), url.host(), loadedMimeType())) {
        LOG(Plugins, "%p Plug-in from (%s, %s) is marked to auto-start, set to play", this, document()->page()->mainFrame()->document()->baseURL().host().utf8().data(), url.host().utf8().data());
        m_snapshotDecision = NeverSnapshot;
        return;
    }

    RenderBox* renderEmbeddedObject = toRenderBox(renderer());
    Length styleWidth = renderEmbeddedObject->style()->width();
    Length styleHeight = renderEmbeddedObject->style()->height();
    LayoutRect contentBoxRect = renderEmbeddedObject->contentBoxRect();
    int contentWidth = contentBoxRect.width();
    int contentHeight = contentBoxRect.height();
    int contentArea = contentWidth * contentHeight;
    IntSize visibleViewSize = document()->frame()->view()->visibleSize();
    int visibleArea = visibleViewSize.width() * visibleViewSize.height();

    if (inMainFrame && styleWidth.isPercent() && (styleWidth.percent() == 100)
        && styleHeight.isPercent() && (styleHeight.percent() == 100)
        && (static_cast<float>(contentArea) / visibleArea > sizingFullPageAreaRatioThreshold)) {
        LOG(Plugins, "%p Plug-in is top level full page, set to play", this);
        m_snapshotDecision = NeverSnapshot;
        return;
    }

    if (contentWidth <= sizingTinyDimensionThreshold || contentHeight <= sizingTinyDimensionThreshold) {
        LOG(Plugins, "%p Plug-in is very small %dx%d, set to play", this, contentWidth, contentHeight);
        m_sizeWhenSnapshotted = IntSize(contentBoxRect.width().toInt(), contentBoxRect.height().toInt());
        m_snapshotDecision = MaySnapshotWhenResized;
        return;
    }

    if (!document()->page()->plugInClient()) {
        LOG(Plugins, "%p There is no plug-in client. Set to wait for snapshot", this);
        m_snapshotDecision = NeverSnapshot;
        setDisplayState(WaitingForSnapshot);
        return;
    }

    LOG(Plugins, "%p Plug-in from (%s, %s) is not auto-start, sized at %dx%d, set to wait for snapshot", this, document()->page()->mainFrame()->document()->baseURL().host().utf8().data(), url.host().utf8().data(), contentWidth, contentHeight);
    m_snapshotDecision = Snapshotted;
    setDisplayState(WaitingForSnapshot);
}
int main(void)		//main program
{
	ex_sask_init( );	//init sask

	ADCChannelInit	(pADCChannelHandle,adcBuffer);	//init audio input handler
	OCPWMInit		(pOCPWMHandle,ocPWMBuffer);

	ADCChannelStart	(pADCChannelHandle);	//start audio input handler
	OCPWMStart		(pOCPWMHandle);	

	while(1)
	{
		if(state==0)	//Program is in READY state
		{
			state=0; //set state to 0[READY]
			state=displayState(STATE_READY); //call ready state function and read new state back
			turnOffAll();	//turn off all LEDs when leaving ready state
		}
		else if(state==1)		//Program is in READ state
		{
			while(ADCChannelIsBusy(pADCChannelHandle)); //read audio input
				ADCChannelRead	(pADCChannelHandle,AudioIn,FFT_FRAME_SIZE);
			
			state=3;
		}
		else if(state==3)		//Program is in ANALZYE state
		{
			int i=0;

				analysingState(1);
			FFT(&AudioIn, &FFTcompResults); //FFT function used on audio input, using FFT_FRAME_SIZE and returning the results in FFTcompResults
			
				analysingState(2);
			generateAuralisation(&AuralisationWorkSpace, &FFTcompResults);
			
				analysingState(3);
			for(i=0;i<FFT_FRAME_SIZE;i++)
			{
				inverseFFT(AudioOut[i], AuralisationWorkSpace[i]);
			}

			state=displayState(STATE_ANALYSE);	//analising finished
		}
		else if(state==4)		//Program is in PLAY BACK state
		{
			int x;
			for(x=0;x<FFT_FRAME_SIZE;x++)
			{
				while(OCPWMIsBusy(pOCPWMHandle));	
					OCPWMWrite (pOCPWMHandle,AudioOut[x],FFT_FRAME_SIZE);

				playbackState();
			}

			OCPWMStop (pOCPWMHandle); //stop audio output
			state=0;
		}
		else		//Program is in ERROR state
		{
			state=displayState(STATE_ERROR);	//show error state on LEDs and read new state
		}
	}
}
int main(int argc, char* argv[])
{
    try
    {
        nvxio::Application &app = nvxio::Application::get();

        //
        // Parse command line arguments
        //

        std::string sourceUri = app.findSampleFilePath("cars.mp4");
        std::string configFile = app.findSampleFilePath("feature_tracker_demo_config.ini");

        app.setDescription("This demo demonstrates Feature Tracker algorithm");
        app.addOption('s', "source", "Source URI", nvxio::OptionHandler::string(&sourceUri));
        app.addOption('c', "config", "Config file path", nvxio::OptionHandler::string(&configFile));

#if defined USE_OPENCV || defined USE_GSTREAMER
        std::string maskFile;
        app.addOption('m', "mask", "Optional mask", nvxio::OptionHandler::string(&maskFile));
#endif

        app.init(argc, argv);

        //
        // Create OpenVX context
        //

        nvxio::ContextGuard context;

        //
        // Reads and checks input parameters
        //

        nvx::FeatureTracker::HarrisPyrLKParams params;
        std::string error;
        if (!read(configFile, params, error))
        {
            std::cout<<error;
            return nvxio::Application::APP_EXIT_CODE_INVALID_VALUE;
        }

        //
        // Create a Frame Source
        //

        std::unique_ptr<nvxio::FrameSource> source(
            nvxio::createDefaultFrameSource(context, sourceUri));

        if (!source || !source->open())
        {
            std::cerr << "Can't open source URI " << sourceUri << std::endl;
            return nvxio::Application::APP_EXIT_CODE_NO_RESOURCE;
        }

        if (source->getSourceType() == nvxio::FrameSource::SINGLE_IMAGE_SOURCE)
        {
            std::cerr << "Can't work on a single image." << std::endl;
            return nvxio::Application::APP_EXIT_CODE_INVALID_FORMAT;
        }

        nvxio::FrameSource::Parameters sourceParams = source->getConfiguration();

        //
        // Create a Render
        //

        std::unique_ptr<nvxio::Render> renderer(nvxio::createDefaultRender(
            context, "Feature Tracker Demo", sourceParams.frameWidth, sourceParams.frameHeight));

        if (!renderer)
        {
            std::cerr << "Can't create a renderer" << std::endl;
            return nvxio::Application::APP_EXIT_CODE_NO_RENDER;
        }

        EventData eventData;
        renderer->setOnKeyboardEventCallback(eventCallback, &eventData);

        //
        // Messages generated by the OpenVX framework will be processed by nvxio::stdoutLogCallback
        //

        vxRegisterLogCallback(context, &nvxio::stdoutLogCallback, vx_false_e);

        //
        // Create OpenVX Image to hold frames from video source
        //

        vx_image frameExemplar = vxCreateImage(context,
            sourceParams.frameWidth, sourceParams.frameHeight, sourceParams.format);
        NVXIO_CHECK_REFERENCE(frameExemplar);
        vx_delay frame_delay = vxCreateDelay(context, (vx_reference)frameExemplar, 2);
        NVXIO_CHECK_REFERENCE(frame_delay);
        vxReleaseImage(&frameExemplar);

        vx_image prevFrame = (vx_image)vxGetReferenceFromDelay(frame_delay, -1);
        vx_image frame = (vx_image)vxGetReferenceFromDelay(frame_delay, 0);

        //
        // Load mask image if needed
        //

        vx_image mask = NULL;

#if defined USE_OPENCV || defined USE_GSTREAMER
        if (!maskFile.empty())
        {
            mask = nvxio::loadImageFromFile(context, maskFile, VX_DF_IMAGE_U8);

            vx_uint32 mask_width = 0, mask_height = 0;
            NVXIO_SAFE_CALL( vxQueryImage(mask, VX_IMAGE_ATTRIBUTE_WIDTH, &mask_width, sizeof(mask_width)) );
            NVXIO_SAFE_CALL( vxQueryImage(mask, VX_IMAGE_ATTRIBUTE_HEIGHT, &mask_height, sizeof(mask_height)) );

            if (mask_width != sourceParams.frameWidth || mask_height != sourceParams.frameHeight)
            {
                std::cerr << "The mask must have the same size as the input source." << std::endl;
                return nvxio::Application::APP_EXIT_CODE_INVALID_DIMENSIONS;
            }
        }
#endif

        //
        // Create FeatureTracker instance
        //

        std::unique_ptr<nvx::FeatureTracker> tracker(nvx::FeatureTracker::createHarrisPyrLK(context, params));

        nvxio::FrameSource::FrameStatus frameStatus;

        do
        {
            frameStatus = source->fetch(frame);
        } while (frameStatus == nvxio::FrameSource::TIMEOUT);

        if (frameStatus == nvxio::FrameSource::CLOSED)
        {
            std::cerr << "Source has no frames" << std::endl;
            return nvxio::Application::APP_EXIT_CODE_NO_FRAMESOURCE;
        }

        tracker->init(frame, mask);

        vxAgeDelay(frame_delay);

        //
        // Run processing loop
        //

        nvx::Timer totalTimer;
        totalTimer.tic();
        double proc_ms = 0;
        while (!eventData.shouldStop)
        {
            if (!eventData.pause)
            {
                frameStatus = source->fetch(frame);

                if (frameStatus == nvxio::FrameSource::TIMEOUT) {
                    continue;
                }
                if (frameStatus == nvxio::FrameSource::CLOSED) {
                    if (!source->open()) {
                        std::cerr << "Failed to reopen the source" << std::endl;
                        break;
                    }
                    continue;
                }

                //
                // Process
                //

                nvx::Timer procTimer;
                procTimer.tic();

                tracker->track(frame, mask);

                proc_ms = procTimer.toc();

                //
                // Print performance results
                //

                tracker->printPerfs();
            }

            //
            // show the previous frame
            //
            renderer->putImage(prevFrame);

            //
            // Draw arrows & state
            //

            drawArrows(renderer.get(), tracker->getPrevFeatures(), tracker->getCurrFeatures());

            double total_ms = totalTimer.toc();

            std::cout << "Display Time : " << total_ms << " ms" << std::endl << std::endl;

            //
            // Add a delay to limit frame rate
            //

            app.sleepToLimitFPS(total_ms);

            total_ms = totalTimer.toc();

            totalTimer.tic();

            displayState(renderer.get(), sourceParams, proc_ms, total_ms);

            if (!renderer->flush())
            {
                eventData.shouldStop = true;
            }

            if (!eventData.pause)
            {
                vxAgeDelay(frame_delay);
            }
        }

        //
        // Release all objects
        //

        vxReleaseImage(&mask);
        vxReleaseDelay(&frame_delay);
    }
    catch (const std::exception& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return nvxio::Application::APP_EXIT_CODE_ERROR;
    }

    return nvxio::Application::APP_EXIT_CODE_SUCCESS;
}