/**
  Paints the actual data area.

  \param painter the QPainter onto which the chart should be painted
  \param data the data that will be displayed as a chart
  \param paint2nd specifies whether the main chart or the additional chart is to be drawn now
  \param regions a pointer to a list of regions that will be filled
  with regions representing the data segments, if not null
  */
void KDChartPiePainter::paintData( QPainter* painter,
        KDChartTableDataBase* data,
        bool paint2nd,
        KDChartDataRegionList* regions )
{
//bHelp=true;
    uint chart = paint2nd ? 1 : 0;

    QRect ourClipRect( _dataRect );
    ourClipRect.addCoords( -1,-1,1,1 );

    const QWMatrix & world = painter->worldMatrix();
    ourClipRect =
#if COMPAT_QT_VERSION >= 0x030000
        world.mapRect( ourClipRect );
#else
    world.map( ourClipRect );
#endif

    painter->setClipRect( ourClipRect );

    // find which dataset to paint
    uint dataset;
    if ( !params()->findDataset( KDChartParams::DataEntry
                ,
                dataset, dataset ) ) {
        return ; // nothing to draw
    }

    if ( dataset == KDCHART_ALL_DATASETS )
        // setChartSourceMode() has not been used (or all datasets have been
        // configured to be used); use the first dataset by
        // default
        dataset = 0;


    // Number of values: If -1, use all values, otherwise use the
    // specified number of values.
    if ( params()->numValues() != -1 )
        _numValues = params()->numValues();
    else
        _numValues = data->usedCols();

    _startAngles.resize( _numValues );
    _angleLens.resize( _numValues );

    // compute position
    _size = QMIN( _dataRect.width(), _dataRect.height() ); // initial size
    // if the pies explode, we need to give them additional space =>
    // make the basic size smaller
    if ( params()->explode() ) {
        double doubleSize = ( double ) _size;
        doubleSize /= ( 1.0 + params()->explodeFactor() * 2 );
        _size = ( int ) doubleSize;
    }

    int sizeFor3DEffect = 0;
    if ( !params()->threeDPies() ) {

        int x = ( _dataRect.width() == _size ) ? 0 : ( ( _dataRect.width() - _size ) / 2 );
        int y = ( _dataRect.height() == _size ) ? 0 : ( ( _dataRect.height() - _size ) / 2 );
        _position = QRect( x, y, _size, _size );
        _position.moveBy( _dataRect.left(), _dataRect.top() );
    } else {
        // threeD: width is the maximum possible width; height is 1/2 of that
        int x = ( _dataRect.width() == _size ) ? 0 : ( ( _dataRect.width() - _size ) / 2 );
        int height = _size;
        // make sure that the height plus the threeDheight is not more than the
        // available size
        if ( params()->threeDPieHeight() >= 0 ) {
            // positive pie height: absolute value
            sizeFor3DEffect = params()->threeDPieHeight();
            height = _size - sizeFor3DEffect;
        } else {
            // negative pie height: relative value
            sizeFor3DEffect = -( int ) ( ( ( double ) params()->threeDPieHeight() / 100.0 ) * ( double ) height );
            height = _size - sizeFor3DEffect;
        }
        int y = ( _dataRect.height() == height ) ? 0 : ( ( _dataRect.height() - height - sizeFor3DEffect ) / 2 );

        _position = QRect( _dataRect.left() + x, _dataRect.top() + y,
                _size, height );
        //  _position.moveBy( _dataRect.left(), _dataRect.top() );
    }

    double sum = data->rowAbsSum( dataset );
    if( sum==0 ) //nothing to draw
        return;
    double sectorsPerValue = 5760.0 / sum; // 5760 == 16*360, number of sections in Qt circle

    int currentValue = params()->pieStart() * 16;
    bool atLeastOneValue = false; // guard against completely empty tables
    QVariant vValY;
    for ( int value = 0; value < _numValues; value++ ) {
        // is there anything at all at this value
        /* see above for meaning of 16 */

        if( data->cellCoord( dataset, value, vValY, 1 ) &&
            QVariant::Double == vValY.type() ){
            _startAngles[ value ] = currentValue;
            const double cellValue = fabs( vValY.toDouble() );
            _angleLens[ value ] = ( int ) floor( cellValue * sectorsPerValue + 0.5 );
            atLeastOneValue = true;
        } else { // mark as non-existent
            _angleLens[ value ] = 0;
            if ( value > 0 )
                _startAngles[ value ] = _startAngles[ value - 1 ];
            else
                _startAngles[ value ] = currentValue;
        }

        currentValue = _startAngles[ value ] + _angleLens[ value ];
    }

    // If there was no value at all, bail out, to avoid endless loops
    // later on (e.g. in findPieAt()).
    if( !atLeastOneValue )
        return;


    // Find the backmost pie which is at +90° and needs to be drawn
    // first
    int backmostpie = findPieAt( 90 * 16 );
    // Find the frontmost pie (at -90°/+270°) that should be drawn last
    int frontmostpie = findPieAt( 270 * 16 );
    // and put the backmost pie on the TODO stack to initialize it,
    // but only if it is not the frontmostpie
    QValueStack < int > todostack;
    if ( backmostpie != frontmostpie )
        todostack.push( backmostpie );
    else {
        // Otherwise, try to find something else
        int leftOfCurrent = findLeftPie( backmostpie );
        if ( leftOfCurrent != frontmostpie ) {
            todostack.push( leftOfCurrent );
        } else {
            int rightOfCurrent = findRightPie( backmostpie );
            if ( rightOfCurrent != frontmostpie ) {
                todostack.push( rightOfCurrent );
            }
        }
        // If we get here, there was nothing else, and we will bail
        // out of the while loop below.
    }

    // The list with pies that have already been drawn

    QValueList < int > donelist;

    // Draw pies until the todostack is empty or only the frontmost
    // pie is there
    while ( !todostack.isEmpty() &&
            !( ( todostack.count() == 1 ) &&
                ( ( todostack.top() == frontmostpie ) ) ) ) {
        // The while loop cannot be cancelled if frontmostpie is on
        // top of the stack, but this is also backmostpie (can happen
        // when one of the pies covers more than 1/2 of the circle. In
        // this case, we need to find something else to put on the
        // stack to get things going.

        // take one pie from the stack
        int currentpie = todostack.pop();
        // if this pie was already drawn, ignore it
        if ( donelist.find( currentpie ) != donelist.end() )
            continue;

        // If this pie is the frontmost pie, put it back, but at the
        // second position (otherwise, there would be an endless
        // loop). If this pie is the frontmost pie, there must be at
        // least one other pie, otherwise the loop would already have
        // been terminated by the loop condition.
        if ( currentpie == frontmostpie ) {
            Q_ASSERT( !todostack.isEmpty() );
            // QValueStack::exchange() would be nice here...
            int secondpie = todostack.pop();
            if ( currentpie == secondpie )
                // no need to have the second pie twice on the stack,
                // forget about one instance and take the third
                // instead
                if ( todostack.isEmpty() )
                    break; // done anyway
                else
                    secondpie = todostack.pop();
            todostack.push( currentpie );
            todostack.push( secondpie );
            continue;
        }

        // When we get here, we can just draw the pie and proceed.
        drawOnePie( painter, data, dataset, currentpie, chart,
                sizeFor3DEffect,
                regions );

        // Mark the pie just drawn as done.
        donelist.append( currentpie );

        // Now take the pie to the left and to the right, check
        // whether these have not been painted already, and put them
        // on the stack.
        int leftOfCurrent = findLeftPie( currentpie );
        if ( donelist.find( leftOfCurrent ) == donelist.end() )
            todostack.push( leftOfCurrent );
        int rightOfCurrent = findRightPie( currentpie );
        if ( donelist.find( rightOfCurrent ) == donelist.end() )
            todostack.push( rightOfCurrent );
    }

    // now only the frontmost pie is left to draw
    drawOnePie( painter, data, dataset, frontmostpie, chart,
            sizeFor3DEffect,
            regions );
}
status_t CedarXRecorder::prepare() 
{
	LOGV("prepare");

	int ret = OK;
	VIDEOINFO_t vInfo;
	AUDIOINFO_t aInfo;

	// Create audio recorder
	if (mRecModeFlag & RECORDER_MODE_AUDIO)
	{
		ret = CreateAudioRecorder();
		if (ret != OK)
		{
			LOGE("CreateAudioRecorder failed");
			return ret;
		}
	}
	
	// set recorder mode to CDX_Recorder
	CDXRecorder_Control(CDX_CMD_SET_REC_MODE, mRecModeFlag, 0);
	
	// create CedarX component
	ret = CDXRecorder_Control(CDX_CMD_PREPARE, 0, 0);
	if( ret == -1)
	{
		printf("CEDARX REPARE ERROR!\n");
		return UNKNOWN_ERROR;
	}

	// register callback
	CDXRecorder_Control(CDX_CMD_REGISTER_CALLBACK, (unsigned int)&CedarXRecorderCallbackWrapper, (unsigned int)this);
	
	// set file handle to CDX_Recorder render component
	ret = CDXRecorder_Control(CDX_CMD_SET_SAVE_FILE, (unsigned int)mOutputFd, 0);
	if(ret != OK)
	{
		LOGE("CedarXRecorder::prepare, CDX_CMD_SET_SAVE_FILE failed\n");
		return ret;
	}

	int64_t token = IPCThreadState::self()->clearCallingIdentity();
	// Set the actual video recording frame size
    CameraParameters params(mCamera->getParameters());
    params.setPreviewSize(mVideoWidth, mVideoHeight);
    String8 s = params.flatten();
    if (OK != mCamera->setParameters(s)) {
        LOGE("Could not change settings."
             " Someone else is using camera %d?", mCameraId);
		IPCThreadState::self()->restoreCallingIdentity(token);
        return -EBUSY;
    }
    CameraParameters newCameraParams(mCamera->getParameters());

    // Check on video frame size
    int srcWidth = 0, srcHeight = 0;
    newCameraParams.getPreviewSize(&srcWidth, &srcHeight);
    if (srcWidth  == 0 || srcHeight == 0) {
        LOGE("Failed to set the video frame size to %dx%d",
                mVideoWidth, mVideoHeight);
		IPCThreadState::self()->restoreCallingIdentity(token);
        return UNKNOWN_ERROR;
    }
	IPCThreadState::self()->restoreCallingIdentity(token);

	LOGV("src: %dx%d, video: %dx%d", srcWidth, srcHeight, mVideoWidth, mVideoHeight);
	
	// set video size and FrameRate to CDX_Recorder
	memset((void *)&vInfo, 0, sizeof(VIDEOINFO_t));
#if 0
	vInfo.src_width		= 176;
	vInfo.src_height	= 144;
	vInfo.width			= 160;			// mVideoWidth;
	vInfo.height		= 120;			// mVideoHeight;
	vInfo.frameRate		= 30*1000;		// mFrameRate;
	vInfo.bitRate		= 200000;		// mVideoBitRate;
	vInfo.profileIdc	= 66;
	vInfo.levelIdc		= 31;
#else
	vInfo.src_width		= srcWidth;
	vInfo.src_height	= srcHeight;
	vInfo.width			= mVideoWidth;
	vInfo.height		= mVideoHeight;
	vInfo.frameRate		= mFrameRate*1000;
	vInfo.bitRate		= mVideoBitRate;
	vInfo.profileIdc	= 66;
	vInfo.levelIdc		= 31;
#endif
	if (mVideoWidth == 0
		|| mVideoHeight == 0
		|| mFrameRate == 0
		|| mVideoBitRate == 0)
	{
		LOGE("error video para");
		return -1;
	}
	
	ret = CDXRecorder_Control(CDX_CMD_SET_VIDEO_INFO, (unsigned int)&vInfo, 0);
	if(ret != OK)
	{
		LOGE("CedarXRecorder::prepare, CDX_CMD_SET_VIDEO_INFO failed\n");
		return ret;
	}

	if (mRecModeFlag & RECORDER_MODE_AUDIO)
	{
		// set audio parameters
		memset((void*)&aInfo, 0, sizeof(AUDIOINFO_t));
		aInfo.bitRate = mAudioBitRate;
		aInfo.channels = mAudioChannels;
		aInfo.sampleRate = mSampleRate;
		aInfo.bitsPerSample = 16;
		if (mAudioBitRate == 0
			|| mAudioChannels == 0
			|| mSampleRate == 0)
		{
			LOGE("error audio para");
			return -1;
		}
		
		ret = CDXRecorder_Control(CDX_CMD_SET_AUDIO_INFO, (unsigned int)&aInfo, 0);
		if(ret != OK)
		{
			LOGE("CedarXRecorder::prepare, CDX_CMD_SET_AUDIO_INFO failed\n");
			return ret;
		}	
	}

    return OK;
}
Example #3
0
void
cg_connect( ConnectionGeneratorDatum& cg,
  RangeSet& sources,
  std::vector< long >& source_gids,
  RangeSet& targets,
  std::vector< long >& target_gids,
  DictionaryDatum params_map,
  index syn )
{
  cg_set_masks( cg, sources, targets );
  cg->start();

  int source, target, num_parameters = cg->arity();
  if ( num_parameters == 0 )
  {
    // connect source to target
    while ( cg->next( source, target, NULL ) )
    {
      if ( ConnectionGeneratorModule::get_network().is_local_gid( target_gids.at( target ) ) )
      {
        Node* const target_node =
          ConnectionGeneratorModule::get_network().get_node( target_gids.at( target ) );
        const thread target_thread = target_node->get_thread();
        ConnectionGeneratorModule::get_network().connect(
          source_gids.at( source ), target_node, target_thread, syn );
      }
    }
  }
  else if ( num_parameters == 2 )
  {
    if ( !params_map->known( names::weight ) || !params_map->known( names::delay ) )
      throw BadProperty( "The parameter map has to contain the indices of weight and delay." );

    long w_idx = ( *params_map )[ names::weight ];
    long d_idx = ( *params_map )[ names::delay ];
    std::vector< double > params( 2 );

    // connect source to target with weight and delay
    while ( cg->next( source, target, &params[ 0 ] ) )
    {
      if ( ConnectionGeneratorModule::get_network().is_local_gid( target_gids.at( target ) ) )
      {
        Node* const target_node =
          ConnectionGeneratorModule::get_network().get_node( target_gids.at( target ) );
        const thread target_thread = target_node->get_thread();
        ConnectionGeneratorModule::get_network().connect( source_gids.at( source ),
          target_node,
          target_thread,
          syn,
          params[ d_idx ],
          params[ w_idx ] );
      }
    }
  }
  else
  {
    ConnectionGeneratorModule::get_network().message( SLIInterpreter::M_ERROR,
      "Connect",
      "Either two or no parameters in the Connection Set expected." );
    throw DimensionMismatch();
  }
}
Example #4
0
status_t CameraSource::initWithCameraAccess(
        const sp<ICamera>& camera,
        const sp<ICameraRecordingProxy>& proxy,
        int32_t cameraId,
        const String16& clientName,
        uid_t clientUid,
        Size videoSize,
        int32_t frameRate,
        bool storeMetaDataInVideoBuffers) {
    ALOGV("initWithCameraAccess");
    status_t err = OK;

    if ((err = isCameraAvailable(camera, proxy, cameraId,
            clientName, clientUid)) != OK) {
        ALOGE("Camera connection could not be established.");
        return err;
    }
    CameraParameters params(mCamera->getParameters());
    if ((err = isCameraColorFormatSupported(params)) != OK) {
        return err;
    }

    // Set the camera to use the requested video frame size
    // and/or frame rate.
    if ((err = configureCamera(&params,
                    videoSize.width, videoSize.height,
                    frameRate))) {
        return err;
    }

    // Check on video frame size and frame rate.
    CameraParameters newCameraParams(mCamera->getParameters());
    if ((err = checkVideoSize(newCameraParams,
                videoSize.width, videoSize.height)) != OK) {
        return err;
    }
    if ((err = checkFrameRate(newCameraParams, frameRate)) != OK) {
        return err;
    }

    // Set the preview display. Skip this if mSurface is null because
    // applications may already set a surface to the camera.
    if (mSurface != NULL) {
        // This CHECK is good, since we just passed the lock/unlock
        // check earlier by calling mCamera->setParameters().
        CHECK_EQ((status_t)OK, mCamera->setPreviewTarget(mSurface));
    }

    // By default, do not store metadata in video buffers
    mIsMetaDataStoredInVideoBuffers = false;
    mCamera->storeMetaDataInBuffers(false);
    if (storeMetaDataInVideoBuffers) {
        if (OK == mCamera->storeMetaDataInBuffers(true)) {
            mIsMetaDataStoredInVideoBuffers = true;
        }
    }

    int64_t glitchDurationUs = (1000000LL / mVideoFrameRate);
    if (glitchDurationUs > mGlitchDurationThresholdUs) {
        mGlitchDurationThresholdUs = glitchDurationUs;
    }

    // XXX: query camera for the stride and slice height
    // when the capability becomes available.
    mMeta = new MetaData;
    mMeta->setCString(kKeyMIMEType,  MEDIA_MIMETYPE_VIDEO_RAW);
    mMeta->setInt32(kKeyColorFormat, mColorFormat);
    mMeta->setInt32(kKeyWidth,       mVideoSize.width);
    mMeta->setInt32(kKeyHeight,      mVideoSize.height);
    mMeta->setInt32(kKeyStride,      mVideoSize.width);
    mMeta->setInt32(kKeySliceHeight, mVideoSize.height);
    mMeta->setInt32(kKeyFrameRate,   mVideoFrameRate);
    return OK;
}
Example #5
0
int StructureManager::declareResidence(CreatureObject* player, StructureObject* structureObject) {
	if (!structureObject->isBuildingObject()) {
		player->sendSystemMessage("@player_structure:residence_must_be_building"); //Your declared residence must be a building.
		return 1;
	}

	PlayerObject* ghost = player->getPlayerObject();

	if (!player->checkCooldownRecovery("declare_residence") && !ghost->isPrivileged()) {
		Time* timeremaining = player->getCooldownTime("declare_residence");
		StringIdChatParameter params("player_structure", "change_residence_time"); //You cannot change residence for %NO hours.
		params.setTO(String::valueOf(ceil(timeremaining->miliDifference() / -3600000.f)));

		player->sendSystemMessage(params);
		return 1;
	}

	ManagedReference<BuildingObject*> buildingObject = cast<BuildingObject*>(structureObject);

	if (!buildingObject->isOwnerOf(player)) {
		player->sendSystemMessage("@player_structure:declare_must_be_owner"); //You must be the owner of the building to declare residence.
		return 1;
	}


	uint64 objectid = player->getObjectID();

	uint64 declaredOidResidence = ghost->getDeclaredResidence();

	ManagedReference<BuildingObject*> declaredResidence = server->getObject(declaredOidResidence).castTo<BuildingObject*>();
	ManagedReference<CityRegion*> cityRegion = buildingObject->getCityRegion();

	CityManager* cityManager = server->getCityManager();

	if (declaredResidence != NULL) {
		if (declaredResidence == buildingObject) {
			player->sendSystemMessage("@player_structure:already_residence"); //This building is already your residence.
			return 1;
		}

		ManagedReference<CityRegion*> residentCity = declaredResidence->getCityRegion();

		if (residentCity != NULL) {
			Locker lock(residentCity, player);

			if (residentCity->isMayor(objectid)) {
				player->sendSystemMessage("@city/city:mayor_residence_change"); //As a city Mayor, your residence is always the city hall of the city in which you are mayor.  You cannot declare a new residence.
				return 1;
			}

			cityManager->unregisterCitizen(residentCity, player);
		}

		player->sendSystemMessage("@player_structure:change_residence"); //You change your residence to this building.
	} else {
		player->sendSystemMessage("@player_structure:declared_residency"); //You have declared your residency here.
	}

	if (cityRegion != NULL) {
		Locker lock(cityRegion, player);

		if (cityRegion->isMayor(objectid) && structureObject != cityRegion->getCityHall()) {
			player->sendSystemMessage("@city/city:mayor_residence_change"); //As a city Mayor, your residence is always the city hall of the city in which you are mayor.  You cannot declare a new residence.
			return 1;
		}

		cityManager->registerCitizen(cityRegion, player);
	}

	//Set the characters home location to this structure.
	ghost->setDeclaredResidence(buildingObject);

	if(declaredResidence != NULL) {
		Locker oldLock(declaredResidence, player);
		declaredResidence->setResidence(false);
	}

	Locker newLock(buildingObject,player);
	buildingObject->setResidence(true);

	player->addCooldown("declare_residence", 24 * 3600 * 1000); //1 day

	return 0;
}
void BasicInteractiveObject::removeMultiTouch(mtRay ray, int touchId) {

  if (isMultiTouchActive(touchId)) {

    // copy that touch in case we need to dispatch it with an event
    MultiTouchPoint *oldMtp = activeMultiTouches[touchId];
    MultiTouchPoint *mtp = new MultiTouchPoint();
    mtp->starttime = oldMtp->starttime;
    mtp->globalmovedist = oldMtp->globalmovedist;
    mtp->screenpos = oldMtp->screenpos;
    mtp->localoffset = oldMtp->localoffset;
    mtp->localstartpos = oldMtp->localstartpos;
    mtp->localpos = oldMtp->localpos;
    mtp->localposbef = oldMtp->localposbef;
    mtp->localspeed = oldMtp->localspeed;
    mtp->localspeeddamped = oldMtp->localspeeddamped;
    mtp->globalstartpos = oldMtp->globalstartpos;
    mtp->globalpos = oldMtp->globalpos;
    mtp->globalposbef = oldMtp->globalposbef;
    mtp->globalspeed = oldMtp->globalspeed;

    activeMultiTouches.erase(activeMultiTouches.find(touchId));

    if (getNumActiveTouches() == 0 && mtcounter > 0) {

      // End of Scope
      mtscoperunning = false;
      mtscopeduration = ofGetElapsedTimeMillis() - mtstarttime;

      if (!isrotating && !isscaling) {
        // check for taps
        if (!isdragging && mtscopeduration < tapThreshold) {
          if (mtcounter == 1) {
            MultiTouchEvent params(this, mtp);
            ofNotifyEvent(tapEvent, params, this);

          } else if (mtcounter == 2) {
            MultiTouchEvent params(this, mtp);
            ofNotifyEvent(doubleTapEvent, params, this);
          }

          // check for swipe
        } else if (mtscopeduration < 1000 && mttranslatespeed.length() > 0.0) {

          MultiTouchEvent params(this, mtp);

          if (abs(mttranslatespeed.x) > abs(mttranslatespeed.y)) {
            if (mttranslatespeed.x < 0) {
              ofNotifyEvent(swipeLeftEvent, params, this);
            } else {
              ofNotifyEvent(swipeRightEvent, params, this);
            }
          } else {
            if (mttranslatespeed.y < 0) {
              ofNotifyEvent(swipeUpEvent, params, this);
            } else {
              ofNotifyEvent(swipeDownEvent, params, this);
            }
          }
        }
      }

      if (isdragging == true) {
        isdragging = false;
        MultiTouchEvent params(this);
        ofNotifyEvent(dragStopEvent, params, this);
      }

      MultiTouchEvent params(this, mtp);
      ofNotifyEvent(lastTouchUpEvent, params, this);

      mtcounter = 0;
    }

    if (getNumActiveTouches() < 2 && mtcounter >= 2) {
      if (isrotating == true) {
        isrotating = false;
        MultiTouchEvent params(this);
        ofNotifyEvent(rotateStopEvent, params, this);
      }
      if (isscaling == true) {
        isscaling = false;
        MultiTouchEvent params(this);
        ofNotifyEvent(scaleStopEvent, params, this);
      }

      MultiTouchEvent params(this);
      ofNotifyEvent(endMultiTouchScopeEvent, params, this);
    }

    resetMTStartValues();
  }
}
Example #7
0
void MyApp::DoMIMEDemo(wxCommandEvent& WXUNUSED(event))
{
    static wxString s_defaultExt = _T("xyz");

    wxString ext = wxGetTextFromUser(_T("Enter a file extension: "),
                                     _T("MIME database test"),
                                     s_defaultExt);
    if ( !!ext )
    {
        s_defaultExt = ext;

        // init MIME database if not done yet
        if ( !m_mimeDatabase )
        {
            m_mimeDatabase = new wxMimeTypesManager;

            static const wxFileTypeInfo fallbacks[] =
            {
                wxFileTypeInfo(_T("application/xyz"),
                               _T("XyZ %s"),
                               _T("XyZ -p %s"),
                               _T("The one and only XYZ format file"),
                               _T("xyz"), _T("123"), NULL),
                wxFileTypeInfo(_T("text/html"),
                               _T("lynx %s"),
                               _T("lynx -dump %s | lpr"),
                               _T("HTML document (from fallback)"),
                               _T("htm"), _T("html"), NULL),

                // must terminate the table with this!
                wxFileTypeInfo()
            };

            m_mimeDatabase->AddFallbacks(fallbacks);
        }

        wxTextCtrl& textCtrl = * GetTextCtrl();

        wxFileType *filetype = m_mimeDatabase->GetFileTypeFromExtension(ext);
        if ( !filetype )
        {
            textCtrl << _T("Unknown extension '") << ext << _T("'\n");
        }
        else
        {
            wxString type, desc, open;
            filetype->GetMimeType(&type);
            filetype->GetDescription(&desc);

            wxString filename = _T("filename");
            filename << _T(".") << ext;
            wxFileType::MessageParameters params(filename, type);
            filetype->GetOpenCommand(&open, params);

            textCtrl << _T("MIME information about extension '") << ext << _T('\n')
                     << _T("\tMIME type: ") << ( !type ? wxT("unknown")
                                                   : type.c_str() ) << _T('\n')
                     << _T("\tDescription: ") << ( !desc ? wxEmptyString : desc.c_str() )
                        << _T('\n')
                     << _T("\tCommand to open: ") << ( !open ? wxT("no") : open.c_str() )
                        << _T('\n');

            delete filetype;
        }
    }
    //else: cancelled by user
}
//-----------------------------------------------------------------------------------------------//
HRESULT CMyTrackPriceInfoWithNotify::OnQuoteUpdate(CComVariant &varParams, CComVariant &varResults)
{
	_QuoteUpdateParams params(varParams);
	_QuoteUpdateInfo   results(varResults);

	_bstr_t bsFullSymbol  = params->Symbol;
	bsFullSymbol +=_T("_");
	bsFullSymbol += params->Exchange;
	if(params->Type == enOPT)
		bsFullSymbol +=_T("_");

	try
	{
		if(results->LastPrice>0.0001)
		{
			// Update Last, Min, Max prices
			CCriticalSectionWrapper wr(m_csCache);
			if(m_SymbolsCache.find(bsFullSymbol)!=m_SymbolsCache.end())
			{
				_QuoteUpdateInfo cache(m_SymbolsCache[bsFullSymbol]);
				CComVariant vtReq;

				cache->LastPrice = results->LastPrice;

				if(cache->HighPrice < results->HighPrice)
					cache->HighPrice = results->HighPrice;

				if(cache->LowPrice <0.001 || cache->LowPrice > results->LowPrice)
					cache->LowPrice = results->LowPrice;

				results->HighPrice = cache->HighPrice;
				results->LowPrice = cache->LowPrice;

				cache.CopyTo(vtReq);
				m_SymbolsCache[bsFullSymbol] = vtReq;
			}
		}
		else
		{
			CCriticalSectionWrapper wr(m_csCache);
			if(m_SymbolsCache.find(bsFullSymbol)!=m_SymbolsCache.end())
			{
				_QuoteUpdateInfo cache(m_SymbolsCache[bsFullSymbol]);

				results->LastPrice = cache->LastPrice;
				results->HighPrice = cache->HighPrice;
				results->LowPrice = cache->LowPrice;
				results->OpenPrice = cache->OpenPrice;
				results->ClosePrice = cache->ClosePrice;
			}
		}
	}
	catch(...){}

	CComVariant vtUpdate;
	results.CopyTo(vtUpdate);

	{
		CCriticalSectionWrapper d(m_csResponce);

		for(RESPONCE::iterator iter = m_Responce.begin(); iter!=m_Responce.end(); iter++)
		{
			if(iter->m_enType == CResponce::enQuoteUpdate && iter->m_bsFullSymbol == bsFullSymbol)
			{
				iter->m_vtResponce = vtUpdate;
				iter->m_lSkip++;
				return S_OK;
			}
		}

		CResponce resp;

		resp.m_enType = CResponce::enQuoteUpdate;
		resp.m_bsFullSymbol = bsFullSymbol;
		resp.m_vtRequest = varParams;
		resp.m_vtResponce = vtUpdate;

		m_Responce.insert(m_Responce.end(), resp);		

	}
	SetEvent(m_hResponce);

	return S_OK;
}
Example #9
0
void Func::show(Ostream& os) const {
	os << "function" << params();
}
Example #10
0
void RenderViewport::AllocateRenderTargets(rhi::GfxSetting & gfxSetting)
{
	if (m_RenderPass)
	{
		VkFormat depthFormat = g_FormatTable[gfxSetting.DepthStencilFormat];
		GetSupportedDepthFormat(GetPhysicalDevice(), &depthFormat);
		VkImage depthImage;
		VkImageCreateInfo image = {};
		image.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
		image.imageType = VK_IMAGE_TYPE_2D;
		image.format = depthFormat;
		// Use example's height and width
		image.extent = { GetWidth(), GetHeight(), 1 };
		image.mipLevels = 1;
		image.arrayLayers = 1;
		image.samples = VK_SAMPLE_COUNT_1_BIT;
		image.tiling = VK_IMAGE_TILING_OPTIMAL;
		image.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
		image.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
		vkCreateImage(GetRawDevice(), &image, nullptr, &depthImage);


		VkDeviceMemory depthMem;
		// Allocate memory for the image (device local) and bind it to our image
		VkMemoryAllocateInfo memAlloc = {};
		memAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
		VkMemoryRequirements memReqs;
		vkGetImageMemoryRequirements(GetRawDevice(), depthImage, &memReqs);
		memAlloc.allocationSize = memReqs.size;
		GetDevice()->FindMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memAlloc.memoryTypeIndex);
		vkAllocateMemory(GetRawDevice(), &memAlloc, nullptr, &depthMem);
		vkBindImageMemory(GetRawDevice(), depthImage, depthMem, 0);

		auto layoutCmd = static_cast<CommandContext*>(GetDevice()->NewCommandContext(rhi::ECMD_Graphics));
		ImageMemoryBarrierParams params(depthImage,
			VK_IMAGE_LAYOUT_UNDEFINED,
			VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
			VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
			VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
		layoutCmd->Begin();
		params.MipLevelCount(1).AspectMask(VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT).LayerCount(1);
		layoutCmd->PipelineBarrierImageMemory(params);
		layoutCmd->End();
		layoutCmd->Execute(false);

		VkImageView depthView;
		VkImageViewCreateInfo depthStencilView = {};
		depthStencilView.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
		depthStencilView.viewType = VK_IMAGE_VIEW_TYPE_2D;
		depthStencilView.format = depthFormat;
		depthStencilView.subresourceRange = {};
		depthStencilView.subresourceRange.aspectMask = DetermineAspectMask(depthFormat);
		depthStencilView.subresourceRange.baseMipLevel = 0;
		depthStencilView.subresourceRange.levelCount = 1;
		depthStencilView.subresourceRange.baseArrayLayer = 0;
		depthStencilView.subresourceRange.layerCount = 1;
		depthStencilView.image = depthImage;
		vkCreateImageView(GetRawDevice(), &depthStencilView, nullptr, &depthView);

		m_RenderTargets.resize(m_NumBufferCount);
		RenderpassOptions option = m_RenderPass->GetOption();
		VkFormat colorFmt = option.GetAttachments()[0].GetFormat();
		for (uint32_t i = 0; i < m_NumBufferCount; ++i)
		{
			VkImage colorImage = m_pSwapChain->GetBackImage(i);
			auto colorImageInfo = ImageViewInfo::CreateColorImageView(GetRawDevice(), colorFmt, colorImage);
			VKLOG(Info, "swapchain imageView created . (0x%0x).", colorImageInfo.first);
			colorImageInfo.second.components = {
				VK_COMPONENT_SWIZZLE_R,
				VK_COMPONENT_SWIZZLE_G,
				VK_COMPONENT_SWIZZLE_B,
				VK_COMPONENT_SWIZZLE_A
			};
			auto colorTex = Texture::CreateFromSwapChain(colorImage, colorImageInfo.first, colorImageInfo.second, GetDevice());

			FrameBuffer::Attachment colorAttach(colorImageInfo.first);
			FrameBuffer::Attachment depthAttach(depthView);
			FrameBuffer::Option op;
			op.Width = GetWidth();
			op.Height = GetHeight();
			op.Attachments.push_back(colorAttach);
			op.Attachments.push_back(depthAttach);
			auto framebuffer = SpFramebuffer(new FrameBuffer(GetDevice(), m_RenderPass->GetPass(), op));
			m_RenderTargets[i] = std::make_shared<RenderTarget>(GetDevice(), colorTex, framebuffer, m_RenderPass->GetPass());
		}
	}
}
Example #11
0
int main(int argc,char *argv[])
{
	int opt;
	PsimagLite::String file("");
	SizeType total=0;
	RealType offset = 0;
	SizeType site3 = 0;

	RealType step = 0;
	while ((opt = getopt(argc, argv, "f:p:t:o:i:")) != -1) {
		switch (opt) {
		case 'f':
			file=optarg;
			break;
		case 'p':
			site3 = atoi(optarg);
			break;
		case 't':
			total = atoi(optarg);
			break;
		case 'i':
			step = atof(optarg);
			break;
		case 'o':
			offset = atof(optarg);
			break;
		default: /* '?' */
			throw std::runtime_error("Wrong usage\n");
		}
	}
	if (file=="") throw std::runtime_error("Wrong usage\n");

	FreeFermions::InputCheck inputCheck;
	InputNgType::Writeable ioWriteable(file,inputCheck);
	InputNgType::Readable io(ioWriteable);

	GeometryParamsType geometryParams(io);
	SizeType electronsUp = GeometryParamsType::readElectrons(io,geometryParams.sites);
	PsimagLite::Vector<SizeType>::Type sites;
	GeometryParamsType::readVector(sites,file,"TSPSites");
	sites.resize(3);
	sites[2] = site3;
	SizeType nthreads = 1;

	try {
		GeometryParamsType::readLabel(nthreads,file,"Threads=");
	} catch (std::exception& e) {}

	assert(nthreads>0);

	typedef PsimagLite::Concurrency ConcurrencyType;
	ConcurrencyType concurrency(&argc,&argv,nthreads);

	SizeType dof = 2; // spin up and down

	GeometryLibraryType geometry(geometryParams);

	std::cerr<<geometry;
	
	EngineType engine(geometry.matrix(),dof,false);

	PsimagLite::Vector<SizeType>::Type ne(dof,electronsUp); // 8 up and 8 down
	bool debug = false;
	bool verbose = false;

	
	RealType sum = 0;
	for (SizeType i=0;i<electronsUp;i++) sum += engine.eigenvalue(i);
	std::cerr<<"Energy="<<dof*sum<<"\n";

	SizeType sigma3 = 0;

	std::cout<<"#sites= ";
	for (SizeType i=0;i<sites.size();i++) std::cout<<sites[i]<<" ";
	std::cout<<"\n";

	typedef FreeFermions::ParallelHolonDoublon<RealType,FieldType,EngineType> ParallelHolonDoublonType;
	typedef PsimagLite::Parallelizer<ParallelHolonDoublonType> ParallelizerType;
	ParallelizerType threadedHolonDoublon(PsimagLite::Concurrency::npthreads,
	                                      PsimagLite::MPI::COMM_WORLD);

	ParallelHolonDoublonType::HolonDoublonParamsType params(ne,
															sites,
															sigma3,
															offset,
															step,
															debug,
															verbose);
	ParallelHolonDoublonType helperHolonDoublon(engine,params);

	FieldType superdensity = helperHolonDoublon.calcSuperDensity(sites[0],sites[1]);
	std::cout<<"#superdensity="<<superdensity<<"\n";

	threadedHolonDoublon.loopCreate(total,helperHolonDoublon);
}
Example #12
0
GrTexture* GaussianBlur(GrContext* context,
                        GrTexture* srcTexture,
                        bool canClobberSrc,
                        const SkRect& dstBounds,
                        const SkRect* srcBounds,
                        float sigmaX,
                        float sigmaY,
                        GrTextureProvider::SizeConstraint constraint) {
    SkASSERT(context);
    SkIRect clearRect;
    int scaleFactorX, radiusX;
    int scaleFactorY, radiusY;
    int maxTextureSize = context->caps()->maxTextureSize();
    sigmaX = adjust_sigma(sigmaX, maxTextureSize, &scaleFactorX, &radiusX);
    sigmaY = adjust_sigma(sigmaY, maxTextureSize, &scaleFactorY, &radiusY);

    SkPoint srcOffset = SkPoint::Make(-dstBounds.x(), -dstBounds.y());
    SkRect localDstBounds = SkRect::MakeWH(dstBounds.width(), dstBounds.height());
    SkRect localSrcBounds;
    SkRect srcRect;
    if (srcBounds) {
        srcRect = localSrcBounds = *srcBounds;
        srcRect.offset(srcOffset);
        srcBounds = &localSrcBounds;
    } else {
        srcRect = localDstBounds;
    }

    scale_rect(&srcRect, 1.0f / scaleFactorX, 1.0f / scaleFactorY);
    srcRect.roundOut(&srcRect);
    scale_rect(&srcRect, static_cast<float>(scaleFactorX),
                         static_cast<float>(scaleFactorY));

    // setup new clip
    GrClip clip(localDstBounds);

    SkASSERT(kBGRA_8888_GrPixelConfig == srcTexture->config() ||
             kRGBA_8888_GrPixelConfig == srcTexture->config() ||
             kAlpha_8_GrPixelConfig == srcTexture->config());

    GrSurfaceDesc desc;
    desc.fFlags = kRenderTarget_GrSurfaceFlag;
    desc.fWidth = SkScalarFloorToInt(dstBounds.width());
    desc.fHeight = SkScalarFloorToInt(dstBounds.height());
    desc.fConfig = srcTexture->config();

    GrTexture* dstTexture;
    GrTexture* tempTexture;
    SkAutoTUnref<GrTexture> temp1, temp2;

    temp1.reset(context->textureProvider()->createTexture(desc, constraint));
    dstTexture = temp1.get();
    if (canClobberSrc) {
        tempTexture = srcTexture;
    } else {
        temp2.reset(context->textureProvider()->createTexture(desc, constraint));
        tempTexture = temp2.get();
    }

    if (nullptr == dstTexture || nullptr == tempTexture) {
        return nullptr;
    }

    SkAutoTUnref<GrDrawContext> srcDrawContext;

    for (int i = 1; i < scaleFactorX || i < scaleFactorY; i *= 2) {
        GrPaint paint;
        SkMatrix matrix;
        matrix.setIDiv(srcTexture->width(), srcTexture->height());
        SkRect dstRect(srcRect);
        if (srcBounds && i == 1) {
            SkRect domain;
            matrix.mapRect(&domain, *srcBounds);
            domain.inset((i < scaleFactorX) ? SK_ScalarHalf / srcTexture->width() : 0.0f,
                         (i < scaleFactorY) ? SK_ScalarHalf / srcTexture->height() : 0.0f);
            SkAutoTUnref<const GrFragmentProcessor> fp(GrTextureDomainEffect::Create(
                srcTexture,
                matrix,
                domain,
                GrTextureDomain::kDecal_Mode,
                GrTextureParams::kBilerp_FilterMode));
            paint.addColorFragmentProcessor(fp);
            srcRect.offset(-srcOffset);
            srcOffset.set(0, 0);
        } else {
            GrTextureParams params(SkShader::kClamp_TileMode, GrTextureParams::kBilerp_FilterMode);
            paint.addColorTextureProcessor(srcTexture, matrix, params);
        }
        paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
        scale_rect(&dstRect, i < scaleFactorX ? 0.5f : 1.0f,
                             i < scaleFactorY ? 0.5f : 1.0f);

        SkAutoTUnref<GrDrawContext> dstDrawContext(
                                             context->drawContext(dstTexture->asRenderTarget()));
        if (!dstDrawContext) {
            return nullptr;
        }
        dstDrawContext->fillRectToRect(clip, paint, SkMatrix::I(), dstRect, srcRect);

        srcDrawContext.swap(dstDrawContext);
        srcRect = dstRect;
        srcTexture = dstTexture;
        SkTSwap(dstTexture, tempTexture);
        localSrcBounds = srcRect;
    }

    // For really small blurs (certainly no wider than 5x5 on desktop gpus) it is faster to just
    // launch a single non separable kernel vs two launches
    srcRect = localDstBounds;
    if (sigmaX > 0.0f && sigmaY > 0.0f &&
            (2 * radiusX + 1) * (2 * radiusY + 1) <= MAX_KERNEL_SIZE) {
        // We shouldn't be scaling because this is a small size blur
        SkASSERT((1 == scaleFactorX) && (1 == scaleFactorY));

        SkAutoTUnref<GrDrawContext> dstDrawContext(
                                             context->drawContext(dstTexture->asRenderTarget()));
        if (!dstDrawContext) {
            return nullptr;
        }
        convolve_gaussian_2d(dstDrawContext, clip, srcRect, srcOffset,
                             srcTexture, radiusX, radiusY, sigmaX, sigmaY, srcBounds);

        srcDrawContext.swap(dstDrawContext);
        srcRect.offsetTo(0, 0);
        srcTexture = dstTexture;
        SkTSwap(dstTexture, tempTexture);

    } else {
        scale_rect(&srcRect, 1.0f / scaleFactorX, 1.0f / scaleFactorY);
        srcRect.roundOut(&srcRect);
        const SkIRect srcIRect = srcRect.roundOut();
        if (sigmaX > 0.0f) {
            if (scaleFactorX > 1) {
                // TODO: if we pass in the source draw context we don't need this here
                if (!srcDrawContext) {
                    srcDrawContext.reset(context->drawContext(srcTexture->asRenderTarget()));
                    if (!srcDrawContext) {
                        return nullptr;
                    }        
                }

                // Clear out a radius to the right of the srcRect to prevent the
                // X convolution from reading garbage.
                clearRect = SkIRect::MakeXYWH(srcIRect.fRight, srcIRect.fTop,
                                              radiusX, srcIRect.height());
                srcDrawContext->clear(&clearRect, 0x0, false);
            }

            SkAutoTUnref<GrDrawContext> dstDrawContext(
                                             context->drawContext(dstTexture->asRenderTarget()));
            if (!dstDrawContext) {
                return nullptr;
            }
            convolve_gaussian(dstDrawContext, clip, srcRect,
                              srcTexture, Gr1DKernelEffect::kX_Direction, radiusX, sigmaX,
                              srcBounds, srcOffset);
            srcDrawContext.swap(dstDrawContext);
            srcTexture = dstTexture;
            srcRect.offsetTo(0, 0);
            SkTSwap(dstTexture, tempTexture);
            localSrcBounds = srcRect;
            srcOffset.set(0, 0);
        }

        if (sigmaY > 0.0f) {
            if (scaleFactorY > 1 || sigmaX > 0.0f) {
                // TODO: if we pass in the source draw context we don't need this here
                if (!srcDrawContext) {
                    srcDrawContext.reset(context->drawContext(srcTexture->asRenderTarget()));
                    if (!srcDrawContext) {
                        return nullptr;
                    }        
                }

                // Clear out a radius below the srcRect to prevent the Y
                // convolution from reading garbage.
                clearRect = SkIRect::MakeXYWH(srcIRect.fLeft, srcIRect.fBottom,
                                              srcIRect.width(), radiusY);
                srcDrawContext->clear(&clearRect, 0x0, false);
            }

            SkAutoTUnref<GrDrawContext> dstDrawContext(
                                               context->drawContext(dstTexture->asRenderTarget()));
            if (!dstDrawContext) {
                return nullptr;
            }
            convolve_gaussian(dstDrawContext, clip, srcRect,
                              srcTexture, Gr1DKernelEffect::kY_Direction, radiusY, sigmaY,
                              srcBounds, srcOffset);

            srcDrawContext.swap(dstDrawContext);
            srcTexture = dstTexture;
            srcRect.offsetTo(0, 0);
            SkTSwap(dstTexture, tempTexture);
        }
    }
    const SkIRect srcIRect = srcRect.roundOut();

    if (scaleFactorX > 1 || scaleFactorY > 1) {
        SkASSERT(srcDrawContext);

        // Clear one pixel to the right and below, to accommodate bilinear
        // upsampling.
        clearRect = SkIRect::MakeXYWH(srcIRect.fLeft, srcIRect.fBottom,
                                      srcIRect.width() + 1, 1);
        srcDrawContext->clear(&clearRect, 0x0, false);
        clearRect = SkIRect::MakeXYWH(srcIRect.fRight, srcIRect.fTop,
                                      1, srcIRect.height());
        srcDrawContext->clear(&clearRect, 0x0, false);
        SkMatrix matrix;
        matrix.setIDiv(srcTexture->width(), srcTexture->height());

        GrPaint paint;
        // FIXME:  this should be mitchell, not bilinear.
        GrTextureParams params(SkShader::kClamp_TileMode, GrTextureParams::kBilerp_FilterMode);
        paint.addColorTextureProcessor(srcTexture, matrix, params);
        paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);

        SkRect dstRect(srcRect);
        scale_rect(&dstRect, (float) scaleFactorX, (float) scaleFactorY);

        SkAutoTUnref<GrDrawContext> dstDrawContext(
                                context->drawContext(dstTexture->asRenderTarget()));
        if (!dstDrawContext) {
            return nullptr;
        }
        dstDrawContext->fillRectToRect(clip, paint, SkMatrix::I(), dstRect, srcRect);

        srcDrawContext.swap(dstDrawContext);
        srcRect = dstRect;
        srcTexture = dstTexture;
        SkTSwap(dstTexture, tempTexture);
    }

    return SkRef(srcTexture);
}
Example #13
0
int main(int argc, char **argv)
{
	char **files = calloc(2, sizeof(char*)); //0 is input, 1 is output

	if(files == NULL) //allocation failure
	{
		exit(1); //exit failure
	}

	params(argc, argv, files); //handle the parameters

	FILE *input; //the input file
	FILE *output; //the output file

	if(files[0] != NULL) //if there is an input file specified as parameter..
	{
		input = fopen(files[0], "r"); //..then open it for reading
	}

	if(files[1] != NULL) //if there is an output file specified as parameter..
	{
		output = fopen(files[1], "w"); //..then open it for writing
	}

	char foo = READCHAR; //read a char from the input
	node *head = calloc(1, sizeof(node)); //allocate the head node
	node *current = head; //the current node is the head as we haven't made reads yet
	int sentences = 0; //0 sentences so far
	int currSentence = 0; //0 words in the first sentence so far
	int *distArray = calloc(21, sizeof(int)); //the array used for storing word count in sentences
	if(distArray == NULL) //if the allocation failed
		exit(1); //exit failure

	
	while(foo != EOF) //until the end of the file or ^C
	{
		if(foo == '!' || foo == '?' || foo == '.') //if it's the end of a sentence
		{
			if(current != head) //if current = head, the next sentence hasn't begun ("Really?!", "Oh.." and so on)
			{
				sentences = sentences + 1; //Another finished sentence
				(*current).val += 1; //Also the end of the word
				current = head; //move back to the head as we are starting a new word

				if(currSentence > 20) //over 20 words in this sentence
					distArray[20] += 1; //[20] is the "over 20 words" cell
				else
					distArray[currSentence-1] += 1; //note down the amount of words in the last sentence

				currSentence = 1; //grows by 1 each space, n words are separated by n-1 spaces
			}
		}
		else //the sentence is not complete
		{
			if(current != head && (foo == ' ' || foo == '\n')) //if we're at the start of a space.. 
				currSentence += 1; //..add the word that will begin

			if(foo >= 'A' && foo <= 'Z') //if capitalized
			{
				foo = foo + 32; //turn capitals into small letters
			}	

			if(foo > 'z' || foo < 'a') //if not alphabetic
			{
				(*current).val += 1; //the last word is considered ended
				current = head; //prepare for the start of a new word
			}
			else //it's alphabetic
			{
				if((*current).children == NULL)
				{
					(*current).children = calloc(256, sizeof(node*)); //then allocate it
					if((*current).children == NULL) //if the allocation failed
						exit(1); //exit failure
				}
				if((*current).children[(short)foo] == NULL) //if the specific child isn't ready
				{
					(*current).children[(short)foo] = calloc(1, sizeof(node)); //then allocate it
					if((*current).children[(short)foo] == NULL) //if the allocation failed
						exit(1); //exit failure

					(*((*current).children[(short)foo])).val = 0;	
				}
				current = (*current).children[(short)foo]; //move current to the next letter in the trie descent				
			}
		}
		foo = READCHAR; //read in the next char
	} //the read ends here

	if((*head).children != NULL) //if the head node has a child array 
	{
		char *string = calloc(2, sizeof(char)); //make a short array for making a char into a null-terminated array
		string[1] = '\0'; //the null that terminates; this is handy for using string methods

		for(char a='a';a<='z';a++) //for each character of the alphabet
		{
			string[0] = a; //put it into the short array
			if((*head).children[(short)a] != NULL) //if that child exists, then recurse
				recurse((*head).children[(short)a], string, input, output, files);
		}
	}

	PRINT("\nThere were %i sentences.\n", sentences);

	PRINT("Sentence word count distribution:\n\n");


	PRINT(" %i  word : %i\n", 1, distArray[0]); //one-word sentences
	for(int i=1;i<9;i++) //one-number word counts
	{
		PRINT(" %i  words: %i\n", i+1, distArray[i]);
	}
	for(int i=10;i<20;i++) //the rest
	{
		PRINT("%i  words: %i\n", i+1, distArray[i]);
	}

	PRINT("%i+ words: %i\n", 21, distArray[20]); //the 21+ word sentences

	return 0; //we're done, good night
}
Example #14
0
//针对系统变量中有些集合形式的参数,取出来,存入集合中
void parse_env(string param_name,vector<string>& v,string delims){
	string params(getenv(param_name.c_str()));
	parse_strings(params,v,delims);
}
Example #15
0
int exception_dtable::create(int dfd, const char * file, const params & config, dtable::iter * source, const ktable * shadow)
{
	int excp_dfd, r;
	memory_dtable alt_mdt;
	reject_iter * handler;
	params base_config, alt_config;
	blob reject_value;
	const dtable_factory * base = dtable_factory::lookup(config, "base");
	const dtable_factory * alt = dtable_factory::lookup(config, "alt");
	if(!base || !alt)
		return -EINVAL;
	if(!config.get("base_config", &base_config, params()))
		return -EINVAL;
	if(!config.get("alt_config", &alt_config, params()))
		return -EINVAL;
	if(!config.get_blob_or_string("reject_value", &reject_value))
		return -EINVAL;
	/* the reject value must exist, because nonexistent values
	 * can get pruned out if the shadow does not require them */
	if(!reject_value.exists())
		return -EINVAL;
	
	if(!source_shadow_ok(source, shadow))
		return -EINVAL;
	
	r = mkdirat(dfd, file, 0755);
	if(r < 0)
		return r;
	excp_dfd = openat(dfd, file, O_RDONLY);
	if(excp_dfd < 0)
		goto fail_open;
	/* we should really save the reject_value in a meta file here */
	
	/* we'll always be appending, but it's faster if we say false here */
	r = alt_mdt.init(source->key_type(), false, true);
	if(r < 0)
		goto fail_mdt;
	if(source->get_blob_cmp())
		alt_mdt.set_blob_cmp(source->get_blob_cmp());
	
	handler = new reject_iter(source, &alt_mdt, reject_value);
	if(!handler)
		goto fail_mdt;
	
	r = base->create(excp_dfd, "base", base_config, handler, shadow);
	if(r < 0)
		goto fail_base;
	
	/* no shadow - this only has exceptions */
	r = alt->create(excp_dfd, "alt", alt_config, &alt_mdt, NULL);
	if(r < 0)
		goto fail_alt;
	
	delete handler;
	close(excp_dfd);
	return 0;
	
fail_alt:
	util::rm_r(excp_dfd, "base");
fail_base:
	delete handler;
fail_mdt:
	close(excp_dfd);
fail_open:
	unlinkat(dfd, file, AT_REMOVEDIR);
	return -1;
}
Example #16
0
int main (int argc, char * argv[])
{
  //ofstream fout("/dev/null");
  //cout.rdbuf(fout.rdbuf());
	if (strcmp(argv[ARG_EVAL_MODE], "evalGrad") == 0)
	{
			estimationMode = EVALGRAD;
	}	else if (strcmp(argv[ARG_EVAL_MODE], "oneStep") == 0) {
			estimationMode = ONESTEPPROJECT;
	}	else if (strcmp(argv[ARG_EVAL_MODE], "fullMini") == 0) {
			estimationMode = FULLMINIMIZATION;
	}	else	{
		std::cerr << "incorrect evaluation mode" << std::endl;
		exit(0);
	}


	

  //set the directory with thread information
  /*if (argc > 2 && !strcmp(argv[1], "est"))
  {
    sprintf(opt_info_dir, "%s", argv[2]);
  } else {
    sprintf(opt_info_dir, "config");
  }
  */
  sprintf(opt_info_dir, "config");

  char thread_file[256];
  sprintf(thread_file, "%s/%s", opt_info_dir, argv[ARG_PARAM_FILE]); 
  Trajectory_Reader traj_reader(thread_file);
  traj_reader.read_threads_from_file();
  
  //all_threads.resize(traj_reader.get_all_threads().size());
	all_threads.resize(0);
  scores_each_thread.resize(traj_reader.get_all_threads().size());
  angle_scores_each_thread.resize(traj_reader.get_all_threads().size());
  orig_points.resize(traj_reader.get_all_threads().size());
	orig_twist_angles.resize(traj_reader.get_all_threads().size());
  for (int i=0; i < traj_reader.get_all_threads().size(); i++)
  {
		all_threads.push_back(traj_reader.get_all_threads()[i]);
		all_threads.back().get_thread_data(orig_points[i], orig_twist_angles[i]);
//    all_threads[i] = traj_reader.get_all_threads()[i];
//		all_threads[i].get_thread_data(orig_points[i], orig_twist_angles[i]);
  }
	
	double min_twist = atof(argv[ARG_MIN_TWIST]);
	double iter_twist = atof(argv[ARG_ITER_TWIST]);
	double max_twist = atof(argv[ARG_MAX_TWIST]);
	double min_bend = atof(argv[ARG_MIN_BEND]);
	double iter_bend = atof(argv[ARG_ITER_BEND]);
	double max_bend = atof(argv[ARG_MAX_BEND]);

  sprintf(data_write_base, "results/%s_%s_%f_%f_%f_%f_%f_%f_", argv[ARG_PARAM_FILE], argv[ARG_EVAL_MODE], min_twist, iter_twist, max_twist, min_bend, iter_bend, max_bend);

	char results_filename[256];
	sprintf(results_filename, "%sresults.txt", data_write_base);
	std::ofstream results_out;
	results_out.precision(10);
	results_out.open(results_filename);

	vector<double> params(3);
	double grav=0.0001;
	for (double bend=min_bend; bend <= max_bend; bend+=iter_bend)
	{
		for (double twist=min_twist; twist <= max_twist; twist+=iter_twist)
		{

      double bend_param = pow(2,bend);
      double twist_param = pow(2, twist)*pow(2,bend);
      //double bend_param = bend;
      //double twist_param = twist;
      double grav_param = grav;

			params[0] = bend_param;
      params[1] = twist_param;
      //params[0] = bend;
			//params[1] = twist;
			params[2] = grav_param;

			double this_score;


			if (estimationMode == EVALGRAD)
				this_score = evalEnergyGradient(params);
			else if (estimationMode == ONESTEPPROJECT)
				this_score = oneStepDistance(params);
			else if (estimationMode == FULLMINIMIZATION)
				this_score = full_minimization(params);
			
			results_out <<bend_param << " " <<twist_param << " " << grav_param << " " << this_score;
			for (int thread_ind=0; thread_ind < scores_each_thread.size(); thread_ind++)
			{
				results_out << " " << scores_each_thread[thread_ind];
			}
			results_out << "\n";
      
			//std::cout << pow(2,bend) << " " << pow(2, twist)*pow(2,bend) << " " << grav << " " << this_score << "\n";
			std::cout << bend_param << " " << twist_param << " " << grav_param << " " << this_score << "\n";
		}
	}

	results_out.close();

  std::cout << "finished " << std::endl;
}
Example #17
0
int main (int argc, char *argv[])
{
	payguide::time_start=time(NULL);
	int Ppid=CheckIfPayguideAlreadyUp();
	if (Ppid==0)
	{
		if (MakeLockFile()!=0)
		{
			std::cout << "Error while creating lock file. Can't write /tmp/payguide.lock" << std::endl;
			LogWrite(LOGMSG_CRITICAL, "Error while creating lock file. Can't write /tmp/payguide.lock");
		}
	}
	else
	{
		
		char msg[512];
		snprintf(msg, 511,"Error: payguide already running as process %i. Balling out.", Ppid);
		std::cout << msg << std::endl;
		LogWrite(LOGMSG_CRITICAL, msg);
		exit(0);
	}
	
	PayguideInit();
	WorkInit();
	bool work_init_already=true;
	
	bonbon::BonbonInit();
	
	
	PerlInit(argv[0], payguide::perl_module.c_str());
	payguide::data_conventor.Init();
	for (EVER)
	{
		std::cout << "Running xml paycheck..." << std::endl;
	        const char *main_config_file="/etc/payguide.cfg";
	        paycheck::CPaycheckCore paycheck_core;
	        paycheck_core.LoadConfig(main_config_file);
	        paycheck::CServer server_code;
	        bonbon::CJobManager in_manager;
	        std::vector <paycheck::CSocket *> connections_store;
	        paycheck::CPaycheckThreadParam params(&in_manager, &connections_store, &paycheck_core);
	        bonbon::CThread xml_server1(server_code, params);
	        payguide::xml_paycheck_core=&paycheck_core;

		payguide::quit=false;
		if (!work_init_already)
			WorkInit();
		int sleep_count=0;
		timespec req;
		req.tv_sec=0;
		req.tv_nsec=50000000;
		
		
		payguide::working=true;
		
		LogWrite(LOGMSG_SYSTEM, "Payguide server started sucessful and ready for a work");
		
		/* Ok, lets rock */
		
		SPay *new_pay=NULL;
		sem_wait(&payguide::shutdown_lock);
		bool working_state=payguide::working;
		sem_post(&payguide::shutdown_lock);
		
		printf("TESTING printf(): if you see that in log - world gone mad\n");
		std::cout << "TESTING std::cout: if you see that in log - world gone mad" << std::endl;
		
		while (working_state)
		{
			sem_wait(&payguide::shutdown_lock);
			working_state=payguide::working;
			sem_post(&payguide::shutdown_lock);

			/* Get next pay from DB */
			if (new_pay==NULL)
			{
				new_pay=paycheck_core.XMLGetNextPay();
				if (new_pay==NULL)
				{
					new_pay=PCGetNextPay();
				
					if (new_pay==NULL)
					{
						//printf("get new pay from DB\n");
						if (sleep_count==1)
							new_pay=DBGetNextPay();
					}
					else if (new_pay->test==NO_TEST)
					{
						LogWrite(LOGMSG_CRITICAL, "Payguide received from BIN PAYCHECK (payd) must be marked as testing. Shutdown.");
						char tmp[1024];
						snprintf(tmp, 1024, "Pay params: id/session=[%lli] terminal=[%lli] operator=%i", new_pay->id, new_pay->terminal_id, new_pay->provider_id); 
						LogWrite(LOGMSG_CRITICAL, tmp);
						exit(-1);
					}
				}
				else if (new_pay->test==NO_TEST)
				{
					LogWrite(LOGMSG_CRITICAL, "Payguide received from XML PAYCHECK must be marked as testing. Shutdown.");
					char tmp[1024];
					snprintf(tmp, 1024, "Pay params: id/session=[%lli] terminal=[%lli] operator=%i", new_pay->id, new_pay->terminal_id, new_pay->provider_id); 
					LogWrite(LOGMSG_CRITICAL, tmp);
					exit(-1);
				}
			}

			if (new_pay!=NULL)
			{
//				char logmsg[101]; snprintf(logmsg, 100,"Working on pay %lli", new_pay->id); SendLogMessages(0, logmsg);
				sem_wait(&payguide::free_workers_lock);
				//printf("lock catched\n");
				/* If were is no free worker - find one or create new. */
				if (payguide::free_worker==NULL)
					SetFreeWorker(NULL);
				
				/* If it's ok - init free worker with a new pay */
				if (payguide::free_worker!=NULL)
				{
					LaunchNewPay(new_pay);
					new_pay=NULL;
					sem_post(&payguide::free_workers_lock);	
				}
				
				/* We can't create a new worker - threads limit hit. */
				else
				{
					//LogWrite(LOGMSG_WARNING, "Threads limit hit. Payguide server is overloaded.");
					sem_post(&payguide::free_workers_lock);
					
					if (sleep_count==20)
					{
						ReloadConfigIfImportant();
						ManagerEx();
						sleep_count=0;
						
					}

					nanosleep(&req, NULL);sleep_count++;
					StatisticTick(0.2);

					
				}
			}
			
			/* No new pays, sleep (nojobs_sleep_time) sec*/
			else
			{
				
				/* Manage inactive workers */
				if (sleep_count==20)
				{
					ReloadConfigIfImportant();
					ManagerEx();
					sleep_count=0;
				}
//				sleep(SLEEP_TIME); sleep_count=20;
				nanosleep(&req, NULL);sleep_count++;
				StatisticTick(0.2);

			}
		}
		
		/* Waiting for all workers, or even cancel all pays if force_quit is 1 ... */
		LogWrite(LOGMSG_SYSTEM, "Waiting for all active pays to end - for safe exit - you had to specify right timeouts in your modules.");
		WaitForAllPaysToFinish(force_quit);
		
		/* If it's not reboot - exit */
		sem_wait(&payguide::shutdown_lock);
		bool quit_state=payguide::quit;
		sem_post(&payguide::shutdown_lock);
		if (quit_state)
		{
			LogWrite(LOGMSG_SYSTEM, "Payguide server shutdown normally.");
			LogWrite(LOGMSG_SYSTEM, "Bye-bye!");
			
			/* Stop connection with MySQL database */
			DBShutdown();
		
			/* Stop control server. */
			//CtlServerStop();
			
			mysql_library_end();
			
			if (ossl_lock!=NULL)
				delete [] ossl_lock;
			if (pc_init_result==0)
				PCShutdown();
			/* CleanUp will be automatically called by atexit() function */
			if (RemoveLockFile()!=0)
			{
				std::cout << "Can't remove /tmp/payguide.lock. File doesn't exist or maybe you should delete it manually."  << std::endl;
				LogWrite(LOGMSG_CRITICAL, "Can't remove /tmp/payguide.lock. File doesn't exist or maybe you should delete it manually.");
			}
			OperatorsShutdown();
			EVP_cleanup();
			payguide::data_conventor.Clean();
			PerlShutdown();
			printf("destroying queue\n");
			in_manager.Destroy();
			printf("done\n");
			exit (0);
		}
		
		/* Stop connection with MySQL database */
		DBShutdown();
		
		printf("destroying queue\n");
		in_manager.Destroy();
		printf("done\n");
	        server_code.Kill();
		LogWrite(LOGMSG_SYSTEM, "Rebooting...");
		work_init_already=false;
		CleanUp();
	}
	return 0;
}
Thread::Thread(Thread::ThreadFn threadFunction, void*  userHandle, UPInt stackSize,
                 int processor, Thread::ThreadState initialState)
{
    CreateParams params(threadFunction, userHandle, stackSize, processor, initialState);
    Init(params);
}
void BasicInteractiveObject::updateMtTransform() {
  if (!mtscoperunning)
    return;
  if (!isDraggable() && !isRotateable() && !isScaleable())
    return;

  bool matrixNeedsUpdate = false;

  mttransform = getCurrentMtTransform();
  mttransformmatrix.makeIdentityMatrix();

  if (getNumActiveTouches() > 1) {

    mttransformmatrix.translate(-(mttranslatestart + mtpivot));
    matrixNeedsUpdate = true;

    if (isScaleable()) {

      mtscalespeed = mtscale;

      float endscale = (float)mttransform.length() / mttransformstart.length();
      mtscale += (endscale - mtscale) * scaledamp;

      mtscalespeed = mtscale - mtscalespeed;
      mtscaledist += fabs(mtscalespeed);

      if (isscaling == false) {
        if (mtscaledist > scalethreshold) {
          isscaling = true;
          MultiTouchEvent params(this);
          ofNotifyEvent(scaleStartEvent, params, this);
        }
      }

      if (isScaleAuto() && isscaling) {
        mttransformmatrix.scale(mtscale, mtscale, mtscale);
      }
    }

    if (isRotateable()) {
      mtrotatespeed = mtrotate;

      ofQuaternion newrotate;
      newrotate.makeRotate(mttransformstart, mttransform);
      mtrotate.slerp(rotatedamp, mtrotate, newrotate);
      mtrotatespeed = mtrotate * mtrotatespeed.inverse();
      mtrotatedist += fabs(mtrotatespeed.getEuler().z);

      if (isrotating == false) {
        if (mtrotatedist > rotatethreshold) {
          isrotating = true;
          MultiTouchEvent params(this);
          ofNotifyEvent(rotateStartEvent, params, this);
        }
      }

      if (isRotateAuto() && isrotating) {
        mttransformmatrix.rotate(mtrotate);
      }
    }
    mttransformmatrix.translate(mttranslatestart + mtpivot);
  }

  bool stAlsoOk = true;

  if (getNumActiveTouches() == 1) {
    if (!isSingleTouchDraggable()) {
      stAlsoOk = false;
    }
  }

  if (isDraggable() && stAlsoOk) {

    mttranslatespeed.set(mttranslate);
    mttranslate.interpolate(getCurrentMtTranslate() - mtpivot - mttranslatestart, dragdamp);
    mttranslatespeed = mttranslate - mttranslatespeed;
    mttranslatedist += mttranslatespeed.length();

    if (isdragging == false) {
      if (mttranslatedist > dragthreshold) {
        isdragging = true;
        MultiTouchEvent params(this);
        ofNotifyEvent(dragStartEvent, params, this);
      }
    }

    if (isDragAuto() && isdragging) {
      mttransformmatrix.translate(mttranslate);
      matrixNeedsUpdate = true;
    }
  }

  // only affect current matrix if we're actual
  if (matrixNeedsUpdate && (isDraggable() || isRotateable() || isScaleable())) {
    ofMatrix4x4 currentmatrix;

    currentmatrix.set(mttransformmatrixstart);
    currentmatrix.postMult(mttransformmatrix);

    mttarget->setTransformMatrix(currentmatrix);
  }

  MultiTouchEvent params(this);
  ofNotifyEvent(updateMultiTouchScopeEvent, params, this);
}
Example #20
0
void
load_params(int argc, char *argv[])
{
    unsigned node = Node::kNoNode;
    bool defaults = false;
    int ch;

    while ((ch = getopt(argc, argv, "dn:")) != -1) {
        switch (ch) {
        case 'd':
            defaults = true;
            break;

        case 'n':
            node = strtoul(optarg, nullptr, 0);
            break;

        default:
            RAISE(ExUsageError, "unrecognised option '-" << (char)ch << "'");
        }
    }

    argc -= optind;
    argv += optind;

    Node::scan(node);

    if (defaults) {
        for (auto n : Node::nodes()) {
            n->set_defaults();
        }

        return;
    }

    if (Node::exists(Bootloader::kNodeAddress) && (node == Node::kNoNode)) {
        RAISE(ExFailure, "cannot load all parameters, there is a node that needs recovery");
    }

    const char *pfile = (argc > 0) ? argv[0] : "/dev/stdin";
    ParamDB pdb;

    try {
        pdb.read(pfile);

    } catch (std::runtime_error &e) {
        RAISE(ExFailure, "reading " << pfile << ": " << e.what());
    }

    // iterate nodes within the database
    for (auto dbnode : pdb.nodes()) {

        // extract node address & function
        unsigned nodeAddress = dbnode["node"].ToInt();
        unsigned nodeFunction = dbnode["function"].ToInt();

        // look for a matching node in the scan results
        auto node = Node::matching(nodeAddress, nodeFunction);

        // if we didn't find a node present...
        if (node == nullptr) {
            if (Node::exists(nodeAddress)) {
                std::cerr << "WARNING: node at "
                          << nodeAddress
                          << " does not match function "
                          << nodeFunction
                          << "."
                          << std::endl;

            } else {
                std::cerr << "WARNING: node at "
                          << nodeAddress
                          << " is not responding."
                          << std::endl;
            }

            std::cerr << "WARNING: Skipping parameter load for node at "
                      << nodeAddress
                      << "."
                      << std::endl;
            continue;
        }

        // update node parameter set from database
        auto &pset = node->params();

        for (auto dbparam : dbnode["parameters"].ToArray()) {
            pset.set(dbparam.ToObject());
            // allow exceptions to fail the operation
        }

        pset.sync();
    }
}
Example #21
0
// Version of voxel distributor that sends the deepest LOD level at once
void deepestLevelVoxelDistributor(NodeList* nodeList, 
                                  NodeList::iterator& node,
                                  VoxelNodeData* nodeData,
                                  bool viewFrustumChanged) {


    pthread_mutex_lock(&::treeLock);

    int truePacketsSent = 0;
    int trueBytesSent = 0;

    // FOR NOW... node tells us if it wants to receive only view frustum deltas
    bool wantDelta = viewFrustumChanged && nodeData->getWantDelta();

    // If our packet already has content in it, then we must use the color choice of the waiting packet.    
    // If we're starting a fresh packet, then... 
    //     If we're moving, and the client asked for low res, then we force monochrome, otherwise, use 
    //     the clients requested color state.
    bool wantColor = LOW_RES_MONO && nodeData->getWantLowResMoving() && viewFrustumChanged ? false : nodeData->getWantColor();

    // If we have a packet waiting, and our desired want color, doesn't match the current waiting packets color
    // then let's just send that waiting packet.    
    if (wantColor != nodeData->getCurrentPacketIsColor()) {
    
        if (nodeData->isPacketWaiting()) {
            if (::debugVoxelSending) {
                printf("wantColor=%s --- SENDING PARTIAL PACKET! nodeData->getCurrentPacketIsColor()=%s\n", 
                       debug::valueOf(wantColor), debug::valueOf(nodeData->getCurrentPacketIsColor()));
            }

            handlePacketSend(nodeList, node, nodeData, trueBytesSent, truePacketsSent);

        } else {
            if (::debugVoxelSending) {
                printf("wantColor=%s --- FIXING HEADER! nodeData->getCurrentPacketIsColor()=%s\n", 
                       debug::valueOf(wantColor), debug::valueOf(nodeData->getCurrentPacketIsColor()));
            }
            nodeData->resetVoxelPacket();
        }
    }
    
    if (::debugVoxelSending) {
        printf("wantColor=%s getCurrentPacketIsColor()=%s, viewFrustumChanged=%s, getWantLowResMoving()=%s\n", 
               debug::valueOf(wantColor), debug::valueOf(nodeData->getCurrentPacketIsColor()),
               debug::valueOf(viewFrustumChanged), debug::valueOf(nodeData->getWantLowResMoving()));
    }

    const ViewFrustum* lastViewFrustum =  wantDelta ? &nodeData->getLastKnownViewFrustum() : NULL;

    if (::debugVoxelSending) {
        printf("deepestLevelVoxelDistributor() viewFrustumChanged=%s, nodeBag.isEmpty=%s, viewSent=%s\n",
                debug::valueOf(viewFrustumChanged), debug::valueOf(nodeData->nodeBag.isEmpty()), 
                debug::valueOf(nodeData->getViewSent())
            );
    }
    
    // If the current view frustum has changed OR we have nothing to send, then search against 
    // the current view frustum for things to send.
    if (viewFrustumChanged || nodeData->nodeBag.isEmpty()) {
        uint64_t now = usecTimestampNow();
        if (::debugVoxelSending) {
            printf("(viewFrustumChanged=%s || nodeData->nodeBag.isEmpty() =%s)...\n",
                   debug::valueOf(viewFrustumChanged), debug::valueOf(nodeData->nodeBag.isEmpty()));
            if (nodeData->getLastTimeBagEmpty() > 0) {
                float elapsedSceneSend = (now - nodeData->getLastTimeBagEmpty()) / 1000000.0f;
                if (viewFrustumChanged) {
                    printf("viewFrustumChanged resetting after elapsed time to send scene = %f seconds", elapsedSceneSend);
                } else {
                    printf("elapsed time to send scene = %f seconds", elapsedSceneSend);
                }
                printf(" [occlusionCulling:%s, wantDelta:%s, wantColor:%s ]\n", 
                       debug::valueOf(nodeData->getWantOcclusionCulling()), debug::valueOf(wantDelta), 
                       debug::valueOf(wantColor));
            }
        }
                
        // if our view has changed, we need to reset these things...
        if (viewFrustumChanged) {
            nodeData->nodeBag.deleteAll();
            nodeData->map.erase();
        } 
        
        if (!viewFrustumChanged && !nodeData->getWantDelta()) {
            // only set our last sent time if we weren't resetting due to frustum change
            uint64_t now = usecTimestampNow();
            nodeData->setLastTimeBagEmpty(now);
        }
        
        nodeData->stats.sceneCompleted();
        
        if (::displayVoxelStats) {
            nodeData->stats.printDebugDetails();
        }
        
        // This is the start of "resending" the scene.
        nodeData->nodeBag.insert(serverTree.rootNode);
        
        // start tracking our stats
        bool isFullScene = (!viewFrustumChanged || !nodeData->getWantDelta()) && nodeData->getViewFrustumJustStoppedChanging();
        nodeData->stats.sceneStarted(isFullScene, viewFrustumChanged, ::serverTree.rootNode);
    }

    // If we have something in our nodeBag, then turn them into packets and send them out...
    if (!nodeData->nodeBag.isEmpty()) {
        static unsigned char tempOutputBuffer[MAX_VOXEL_PACKET_SIZE - 1]; // save on allocs by making this static
        int bytesWritten = 0;
        int packetsSentThisInterval = 0;
        uint64_t start = usecTimestampNow();

        bool shouldSendEnvironments = shouldDo(ENVIRONMENT_SEND_INTERVAL_USECS, VOXEL_SEND_INTERVAL_USECS);
        while (packetsSentThisInterval < PACKETS_PER_CLIENT_PER_INTERVAL - (shouldSendEnvironments ? 1 : 0)) {        
            // Check to see if we're taking too long, and if so bail early...
            uint64_t now = usecTimestampNow();
            long elapsedUsec = (now - start);
            long elapsedUsecPerPacket = (truePacketsSent == 0) ? 0 : (elapsedUsec / truePacketsSent);
            long usecRemaining = (VOXEL_SEND_INTERVAL_USECS - elapsedUsec);
            
            if (elapsedUsecPerPacket + SENDING_TIME_TO_SPARE > usecRemaining) {
                if (::debugVoxelSending) {
                    printf("packetLoop() usecRemaining=%ld bailing early took %ld usecs to generate %d bytes in %d packets (%ld usec avg), %d nodes still to send\n",
                            usecRemaining, elapsedUsec, trueBytesSent, truePacketsSent, elapsedUsecPerPacket,
                            nodeData->nodeBag.count());
                }
                break;
            }            
            
            if (!nodeData->nodeBag.isEmpty()) {
                VoxelNode* subTree = nodeData->nodeBag.extract();
                bool wantOcclusionCulling = nodeData->getWantOcclusionCulling();
                CoverageMap* coverageMap = wantOcclusionCulling ? &nodeData->map : IGNORE_COVERAGE_MAP;
                int boundaryLevelAdjust = viewFrustumChanged && nodeData->getWantLowResMoving() 
                                          ? LOW_RES_MOVING_ADJUST : NO_BOUNDARY_ADJUST;

                bool isFullScene = (!viewFrustumChanged || !nodeData->getWantDelta()) && 
                                 nodeData->getViewFrustumJustStoppedChanging();
                
                EncodeBitstreamParams params(INT_MAX, &nodeData->getCurrentViewFrustum(), wantColor, 
                                             WANT_EXISTS_BITS, DONT_CHOP, wantDelta, lastViewFrustum,
                                             wantOcclusionCulling, coverageMap, boundaryLevelAdjust,
                                             nodeData->getLastTimeBagEmpty(),
                                             isFullScene, &nodeData->stats);
                      
                nodeData->stats.encodeStarted();
                bytesWritten = serverTree.encodeTreeBitstream(subTree, &tempOutputBuffer[0], MAX_VOXEL_PACKET_SIZE - 1,
                                                              nodeData->nodeBag, params);
                nodeData->stats.encodeStopped();

                if (nodeData->getAvailable() >= bytesWritten) {
                    nodeData->writeToPacket(&tempOutputBuffer[0], bytesWritten);
                } else {
                    handlePacketSend(nodeList, node, nodeData, trueBytesSent, truePacketsSent);
                    packetsSentThisInterval++;
                    nodeData->resetVoxelPacket();
                    nodeData->writeToPacket(&tempOutputBuffer[0], bytesWritten);
                }
            } else {
                if (nodeData->isPacketWaiting()) {
                    handlePacketSend(nodeList, node, nodeData, trueBytesSent, truePacketsSent);
                    nodeData->resetVoxelPacket();
                }
                packetsSentThisInterval = PACKETS_PER_CLIENT_PER_INTERVAL; // done for now, no nodes left
            }
        }
        // send the environment packet
        if (shouldSendEnvironments) {
            int numBytesPacketHeader = populateTypeAndVersion(tempOutputBuffer, PACKET_TYPE_ENVIRONMENT_DATA);
            int envPacketLength = numBytesPacketHeader;
            
            for (int i = 0; i < sizeof(environmentData) / sizeof(EnvironmentData); i++) {
                envPacketLength += environmentData[i].getBroadcastData(tempOutputBuffer + envPacketLength);
            }
            
            nodeList->getNodeSocket()->send(node->getActiveSocket(), tempOutputBuffer, envPacketLength);
            trueBytesSent += envPacketLength;
            truePacketsSent++;
        }
        
        uint64_t end = usecTimestampNow();
        int elapsedmsec = (end - start)/1000;
        if (elapsedmsec > 100) {
            if (elapsedmsec > 1000) {
                int elapsedsec = (end - start)/1000000;
                printf("WARNING! packetLoop() took %d seconds to generate %d bytes in %d packets %d nodes still to send\n",
                        elapsedsec, trueBytesSent, truePacketsSent, nodeData->nodeBag.count());
            } else {
                printf("WARNING! packetLoop() took %d milliseconds to generate %d bytes in %d packets, %d nodes still to send\n",
                        elapsedmsec, trueBytesSent, truePacketsSent, nodeData->nodeBag.count());
            }
        } else if (::debugVoxelSending) {
            printf("packetLoop() took %d milliseconds to generate %d bytes in %d packets, %d nodes still to send\n",
                    elapsedmsec, trueBytesSent, truePacketsSent, nodeData->nodeBag.count());
        }
        
        // if after sending packets we've emptied our bag, then we want to remember that we've sent all 
        // the voxels from the current view frustum
        if (nodeData->nodeBag.isEmpty()) {
            nodeData->updateLastKnownViewFrustum();
            nodeData->setViewSent(true);
            if (::debugVoxelSending) {
                nodeData->map.printStats();
            }
            nodeData->map.erase(); // It would be nice if we could save this, and only reset it when the view frustum changes
        }
        
    } // end if bag wasn't empty, and so we sent stuff...

    pthread_mutex_unlock(&::treeLock);
}
Example #22
0
bool
brw_blorp_clear_color(struct brw_context *brw, struct gl_framebuffer *fb,
                      bool partial_clear)
{
   struct gl_context *ctx = &brw->ctx;

   /* The constant color clear code doesn't work for multisampled surfaces, so
    * we need to support falling back to other clear mechanisms.
    * Unfortunately, our clear code is based on a bitmask that doesn't
    * distinguish individual color attachments, so we walk the attachments to
    * see if any require fallback, and fall back for all if any of them need
    * to.
    */
   for (unsigned buf = 0; buf < ctx->DrawBuffer->_NumColorDrawBuffers; buf++) {
      struct gl_renderbuffer *rb = ctx->DrawBuffer->_ColorDrawBuffers[buf];
      struct intel_renderbuffer *irb = intel_renderbuffer(rb);

      if (irb && irb->mt->msaa_layout != INTEL_MSAA_LAYOUT_NONE)
         return false;
   }

   for (unsigned buf = 0; buf < ctx->DrawBuffer->_NumColorDrawBuffers; buf++) {
      struct gl_renderbuffer *rb = ctx->DrawBuffer->_ColorDrawBuffers[buf];
      struct intel_renderbuffer *irb = intel_renderbuffer(rb);

      /* If this is an ES2 context or GL_ARB_ES2_compatibility is supported,
       * the framebuffer can be complete with some attachments missing.  In
       * this case the _ColorDrawBuffers pointer will be NULL.
       */
      if (rb == NULL)
         continue;

      brw_blorp_clear_params params(brw, fb, rb, ctx->Color.ColorMask[buf],
                                    partial_clear);

      bool is_fast_clear =
         (params.fast_clear_op == GEN7_FAST_CLEAR_OP_FAST_CLEAR);
      if (is_fast_clear) {
         /* Record the clear color in the miptree so that it will be
          * programmed in SURFACE_STATE by later rendering and resolve
          * operations.
          */
         uint32_t new_color_value =
            compute_fast_clear_color_bits(&ctx->Color.ClearColor);
         if (irb->mt->fast_clear_color_value != new_color_value) {
            irb->mt->fast_clear_color_value = new_color_value;
            brw->state.dirty.brw |= BRW_NEW_SURFACES;
         }

         /* If the buffer is already in INTEL_MCS_STATE_CLEAR, the clear is
          * redundant and can be skipped.
          */
         if (irb->mt->mcs_state == INTEL_MCS_STATE_CLEAR)
            continue;

         /* If the MCS buffer hasn't been allocated yet, we need to allocate
          * it now.
          */
         if (!irb->mt->mcs_mt) {
            if (!intel_miptree_alloc_non_msrt_mcs(brw, irb->mt)) {
               /* MCS allocation failed--probably this will only happen in
                * out-of-memory conditions.  But in any case, try to recover
                * by falling back to a non-blorp clear technique.
                */
               return false;
            }
            brw->state.dirty.brw |= BRW_NEW_SURFACES;
         }
      }

      DBG("%s to mt %p level %d layer %d\n", __FUNCTION__,
          irb->mt, irb->mt_level, irb->mt_layer);

      brw_blorp_exec(brw, &params);

      if (is_fast_clear) {
         /* Now that the fast clear has occurred, put the buffer in
          * INTEL_MCS_STATE_CLEAR so that we won't waste time doing redundant
          * clears.
          */
         irb->mt->mcs_state = INTEL_MCS_STATE_CLEAR;
      }
   }

   return true;
}
Example #23
0
 bpy::dict config_get_inherited_parameters(const Configuration* config)
 {
     ParamArray params(config->get_inherited_parameters());
     return param_array_to_bpy_dict(params);
 }
Example #24
0
string CSRADataLoader::GetLoaderNameFromArgs(ETrim trim)
{
    SLoaderParams params(trim == eTrim);
    return GetLoaderNameFromArgs(params);
}
void CalibrationDrawHelpersParametersControlWidget::loadParamWidget(WidgetLoader &loader)
{
    std::unique_ptr<CalibrationDrawHelpersParameters> params(createParameters());
    loader.loadParameters(*params, rootPath);
    setParameters(*params);
}
Example #26
0
void InfoScreens::handleScreenUpdateTimer() {
//	debugf("canUpdateDisplay=%i, internalCanUpdateDisplay=%i",canUpdateDisplay() ,internalCanUpdateDisplay );
	if(canUpdateDisplay() && internalCanUpdateDisplay) {
		if (mChildern.size() == 0) {
			debugf("I cannot print anything, no Pages declared, setting to NOT update display");
			setCanUpdateDisplay(false);
			return;
		}
//		debugf("1");
		if (paramValueMap["currentPage"].dirty) {
//				debugf("currentPage = %i, paramValueMap['currentPage'].dirty= %d",paramValueMap["currentPage"].val.toInt(), (int)paramValueMap["currentPage"].dirty);
			display->clearDisplay();
			display->setCursor(0,0);
			print(paramValueMap["currentPage"].val->toInt());
			paramValueMap["currentPage"].clearDirty();
//			debugf("2");
		}
		else {
			internalCanUpdateDisplay = false;
			Vector<paramStruct*> params(getCurrent()->getAllParamsInPage());
//				debugf("params in page = %i", params.size());
			boolean updated = false;

			//need localcopy of params
			Vector<String> tempIds;
			for (int i = 0; i < params.size(); ++i) {
				paramStruct* param = params.get(i);
				if(paramValueMap[param->id].dirty) {
					tempIds.add(param->id);
					paramValueMap[param->id].clearDirty();
				}
			}

			for (int i = 0; i < params.size(); ++i) {
				paramStruct* param = params.get(i);
				if (tempIds.contains(param->id)) {
//						debugf("updating param %s", param->id.c_str());
					int inverse = false;
					if(viewMode == ViewMode::EDIT_FIELD && param->editable) {
						inverse = true;
					}
					display->writeover(param->t, *paramValueMap[param->id].val, inverse);
					updated = true;
				}
			}
			internalCanUpdateDisplay = true;
			if (updated) {
				display->display();
			}

			if (editModeBlinkInfo.shouldEraseLast()) {
				drawBlinkParamLine(editModeBlinkInfo.lastSelectedParam, display->getBlack());
				editModeBlinkInfo.lastSelectedParam = NULL;
			}

			long current = millis();
			int linecolor = display->getBlack();
			int symbleColor = display->getBlack();
			editModeBlinkInfo.handleTimeElapsed(current);

			if (viewMode == ViewMode::EDIT || viewMode == ViewMode::EDIT_FIELD) {
				if (editModeBlinkInfo.blinkDrawn) {
					linecolor = display->getWhite();
					symbleColor = display->getWhite();
					if (viewMode == ViewMode::EDIT_FIELD){
//						linecolor = WHITE;
					}
				}

				drawEditModeSign(124, 0, symbleColor);
				paramStruct* p = getCurrent()->getCurrentEditParam();
				if (p) {
					int extraW = (p->maxSize) - p->t.w;
//					debugf("extraw = %i",extraW);
					if (viewMode == ViewMode::EDIT_FIELD) {
						display->writeover(p->t, *paramValueMap[p->id].val, true);
						if (extraW >0) {
							display->fillRect(p->t.x + p->t.w, p->t.y, extraW, p->t.h, display->getWhite());
						}
					} else {
						display->writeover(p->t, *paramValueMap[p->id].val);
						if (extraW >0) {
							display->fillRect(p->t.x + p->t.w, p->t.y, extraW, p->t.h, display->getBlack());
						}
					}
//					debugf("linecolor = %i, currnet param %s", linecolor, getCurrent()->getCurrentEditParam()->toString().c_str() );
					drawBlinkParamLine(p, linecolor);
				}

			}
		}
	}
}
Example #27
0
    PlanStage* buildStages(const string& ns, const QuerySolutionNode* root, WorkingSet* ws) {
        if (STAGE_COLLSCAN == root->getType()) {
            const CollectionScanNode* csn = static_cast<const CollectionScanNode*>(root);
            CollectionScanParams params;
            params.ns = csn->name;
            params.tailable = csn->tailable;
            params.direction = (csn->direction == 1) ? CollectionScanParams::FORWARD
                                                     : CollectionScanParams::BACKWARD;
            return new CollectionScan(params, ws, csn->filter.get());
        }
        else if (STAGE_IXSCAN == root->getType()) {
            const IndexScanNode* ixn = static_cast<const IndexScanNode*>(root);
            //
            // XXX XXX
            // Given that this grabs data from the catalog, we must do this inside of a lock.
            // We should change this to take a (ns, index key pattern) pair so that the params
            // don't involve any on-disk data, just descriptions thereof.
            // XXX XXX
            //
            IndexScanParams params;
            NamespaceDetails* nsd = nsdetails(ns.c_str());
            if (NULL == nsd) {
                warning() << "Can't ixscan null ns " << ns << endl;
                return NULL;
            }
            int idxNo = nsd->findIndexByKeyPattern(ixn->indexKeyPattern);
            if (-1 == idxNo) {
                warning() << "Can't find idx " << ixn->indexKeyPattern.toString()
                          << "in ns " << ns << endl;
                return NULL;
            }
            params.descriptor = CatalogHack::getDescriptor(nsd, idxNo);
            params.bounds = ixn->bounds;
            params.direction = ixn->direction;
            params.limit = ixn->limit;
            return new IndexScan(params, ws, ixn->filter.get());
        }
        else if (STAGE_FETCH == root->getType()) {
            const FetchNode* fn = static_cast<const FetchNode*>(root);
            PlanStage* childStage = buildStages(ns, fn->child.get(), ws);
            if (NULL == childStage) { return NULL; }
            return new FetchStage(ws, childStage, fn->filter.get());
        }
        else if (STAGE_SORT == root->getType()) {
            const SortNode* sn = static_cast<const SortNode*>(root);
            PlanStage* childStage = buildStages(ns, sn->child.get(), ws);
            if (NULL == childStage) { return NULL; }
            SortStageParams params;
            params.pattern = sn->pattern;
            return new SortStage(params, ws, childStage);
        }
        else if (STAGE_PROJECTION == root->getType()) {
            const ProjectionNode* pn = static_cast<const ProjectionNode*>(root);
            PlanStage* childStage = buildStages(ns, pn->child.get(), ws);
            if (NULL == childStage) { return NULL; }
            return new ProjectionStage(pn->projection, ws, childStage, NULL);
        }
        else if (STAGE_LIMIT == root->getType()) {
            const LimitNode* ln = static_cast<const LimitNode*>(root);
            PlanStage* childStage = buildStages(ns, ln->child.get(), ws);
            if (NULL == childStage) { return NULL; }
            return new LimitStage(ln->limit, ws, childStage);
        }
        else if (STAGE_SKIP == root->getType()) {
            const SkipNode* sn = static_cast<const SkipNode*>(root);
            PlanStage* childStage = buildStages(ns, sn->child.get(), ws);
            if (NULL == childStage) { return NULL; }
            return new SkipStage(sn->skip, ws, childStage);
        }
        else if (STAGE_AND_HASH == root->getType()) {
            const AndHashNode* ahn = static_cast<const AndHashNode*>(root);
            auto_ptr<AndHashStage> ret(new AndHashStage(ws, ahn->filter.get()));
            for (size_t i = 0; i < ahn->children.size(); ++i) {
                PlanStage* childStage = buildStages(ns, ahn->children[i], ws);
                if (NULL == childStage) { return NULL; }
                ret->addChild(childStage);
            }
            return ret.release();
        }
        else if (STAGE_OR == root->getType()) {
            const OrNode * orn = static_cast<const OrNode*>(root);
            auto_ptr<OrStage> ret(new OrStage(ws, orn->dedup, orn->filter.get()));
            for (size_t i = 0; i < orn->children.size(); ++i) {
                PlanStage* childStage = buildStages(ns, orn->children[i], ws);
                if (NULL == childStage) { return NULL; }
                ret->addChild(childStage);
            }
            return ret.release();
        }
        else if (STAGE_AND_SORTED == root->getType()) {
            const AndSortedNode* asn = static_cast<const AndSortedNode*>(root);
            auto_ptr<AndSortedStage> ret(new AndSortedStage(ws, asn->filter.get()));
            for (size_t i = 0; i < asn->children.size(); ++i) {
                PlanStage* childStage = buildStages(ns, asn->children[i], ws);
                if (NULL == childStage) { return NULL; }
                ret->addChild(childStage);
            }
            return ret.release();
        }
        else if (STAGE_SORT_MERGE == root->getType()) {
            const MergeSortNode* msn = static_cast<const MergeSortNode*>(root);
            MergeSortStageParams params;
            params.dedup = msn->dedup;
            params.pattern = msn->sort;
            auto_ptr<MergeSortStage> ret(new MergeSortStage(params, ws));
            for (size_t i = 0; i < msn->children.size(); ++i) {
                PlanStage* childStage = buildStages(ns, msn->children[i], ws);
                if (NULL == childStage) { return NULL; }
                ret->addChild(childStage);
            }
            return ret.release();
        }
        else if (STAGE_GEO_2D == root->getType()) {
            const Geo2DNode* node = static_cast<const Geo2DNode*>(root);
            TwoDParams params;
            params.gq = node->gq;
            params.filter = node->filter.get();
            params.indexKeyPattern = node->indexKeyPattern;
            params.ns = ns;
            return new TwoD(params, ws);
        }
        else if (STAGE_GEO_NEAR_2D == root->getType()) {
            const GeoNear2DNode* node = static_cast<const GeoNear2DNode*>(root);
            TwoDNearParams params;
            params.nearQuery = node->nq;
            params.ns = ns;
            params.indexKeyPattern = node->indexKeyPattern;
            params.filter = node->filter.get();
            params.numWanted = node->numWanted;
            // XXX XXX where do we grab this from??  the near query...modify geo parser... :(
            params.uniqueDocs = false;
            // XXX XXX where do we grab this from??  the near query...modify geo parser... :(
            return new TwoDNear(params, ws);
        }
        else if (STAGE_GEO_NEAR_2DSPHERE == root->getType()) {
            const GeoNear2DSphereNode* node = static_cast<const GeoNear2DSphereNode*>(root);
            return new S2NearStage(ns, node->indexKeyPattern, node->nq, node->baseBounds,
                                   node->filter.get(), ws);
        }
        else if (STAGE_TEXT == root->getType()) {
            const TextNode* node = static_cast<const TextNode*>(root);

            NamespaceDetails* nsd = nsdetails(ns.c_str());
            if (NULL == nsd) { return NULL; }
            vector<int> idxMatches;
            nsd->findIndexByType("text", idxMatches);
            if (1 != idxMatches.size()) { return NULL; }
            IndexDescriptor* index = CatalogHack::getDescriptor(nsd, idxMatches[0]);
            auto_ptr<FTSAccessMethod> fam(new FTSAccessMethod(index));
            TextStageParams params(fam->getSpec());

            params.ns = ns;
            params.index = index;
            params.spec = fam->getSpec();
            params.limit = node->_numWanted;
            Status s = fam->getSpec().getIndexPrefix(BSONObj(), &params.indexPrefix);
            if (!s.isOK()) { return NULL; }

            string language = ("" == node->_language
                               ? fam->getSpec().defaultLanguage()
                               : node->_language);

            FTSQuery ftsq;
            Status parseStatus = ftsq.parse(node->_query, language);
            if (!parseStatus.isOK()) { return NULL; }
            params.query = ftsq;

            return new TextStage(params, ws, node->_filter.get());
        }
        else {
            stringstream ss;
            root->appendToString(&ss, 0);
            warning() << "Could not build exec tree for node " << ss.str() << endl;
            return NULL;
        }
    }
Example #28
0
void GrAtlasTextBatch::onPrepareDraws(Target* target) const {
    // if we have RGB, then we won't have any SkShaders so no need to use a localmatrix.
    // TODO actually only invert if we don't have RGBA
    SkMatrix localMatrix;
    if (this->usesLocalCoords() && !this->viewMatrix().invert(&localMatrix)) {
        SkDebugf("Cannot invert viewmatrix\n");
        return;
    }

    GrTexture* texture = fFontCache->getTexture(this->maskFormat());
    if (!texture) {
        SkDebugf("Could not allocate backing texture for atlas\n");
        return;
    }

    GrMaskFormat maskFormat = this->maskFormat();

    FlushInfo flushInfo;
    if (this->usesDistanceFields()) {
        flushInfo.fGeometryProcessor.reset(
            this->setupDfProcessor(this->viewMatrix(), fFilteredColor, this->color(), texture));
    } else {
        GrTextureParams params(SkShader::kClamp_TileMode, GrTextureParams::kNone_FilterMode);
        flushInfo.fGeometryProcessor.reset(
            GrBitmapTextGeoProc::Create(this->color(),
                                        texture,
                                        params,
                                        maskFormat,
                                        localMatrix,
                                        this->usesLocalCoords()));
    }

    flushInfo.fGlyphsToFlush = 0;
    size_t vertexStride = flushInfo.fGeometryProcessor->getVertexStride();
    SkASSERT(vertexStride == GrAtlasTextBlob::GetVertexStride(maskFormat));

    int glyphCount = this->numGlyphs();
    const GrBuffer* vertexBuffer;

    void* vertices = target->makeVertexSpace(vertexStride,
                                             glyphCount * kVerticesPerGlyph,
                                             &vertexBuffer,
                                             &flushInfo.fVertexOffset);
    flushInfo.fVertexBuffer.reset(SkRef(vertexBuffer));
    flushInfo.fIndexBuffer.reset(target->resourceProvider()->refQuadIndexBuffer());
    if (!vertices || !flushInfo.fVertexBuffer) {
        SkDebugf("Could not allocate vertices\n");
        return;
    }

    unsigned char* currVertex = reinterpret_cast<unsigned char*>(vertices);

    // We cache some values to avoid going to the glyphcache for the same fontScaler twice
    // in a row
    const SkDescriptor* desc = nullptr;
    SkGlyphCache* cache = nullptr;
    GrFontScaler* scaler = nullptr;
    SkTypeface* typeface = nullptr;

    GrBlobRegenHelper helper(this, target, &flushInfo);

    for (int i = 0; i < fGeoCount; i++) {
        const Geometry& args = fGeoData[i];
        Blob* blob = args.fBlob;
        size_t byteCount;
        void* blobVertices;
        int subRunGlyphCount;
        blob->regenInBatch(target, fFontCache, &helper, args.fRun, args.fSubRun, &cache,
                           &typeface, &scaler, &desc, vertexStride, args.fViewMatrix, args.fX,
                           args.fY, args.fColor, &blobVertices, &byteCount, &subRunGlyphCount);

        // now copy all vertices
        memcpy(currVertex, blobVertices, byteCount);

#ifdef SK_DEBUG
        // bounds sanity check
        SkRect rect;
        rect.setLargestInverted();
        SkPoint* vertex = (SkPoint*) ((char*)blobVertices);
        rect.growToInclude(vertex, vertexStride, kVerticesPerGlyph * subRunGlyphCount);

        if (this->usesDistanceFields()) {
            args.fViewMatrix.mapRect(&rect);
        }
        // Allow for small numerical error in the bounds.
        SkRect bounds = fBounds;
        bounds.outset(0.001f, 0.001f);
        SkASSERT(bounds.contains(rect));
#endif

        currVertex += byteCount;
    }

    // Make sure to attach the last cache if applicable
    if (cache) {
        SkGlyphCache::AttachCache(cache);
    }
    this->flush(target, &flushInfo);
}
Example #29
0
VectorImage::Draw(gfxContext* aContext,
                  const nsIntSize& aSize,
                  const ImageRegion& aRegion,
                  uint32_t aWhichFrame,
                  GraphicsFilter aFilter,
                  const Maybe<SVGImageContext>& aSVGContext,
                  uint32_t aFlags)
{
  if (aWhichFrame > FRAME_MAX_VALUE) {
    return DrawResult::BAD_ARGS;
  }

  if (!aContext) {
    return DrawResult::BAD_ARGS;
  }

  if (mError) {
    return DrawResult::BAD_IMAGE;
  }

  if (!mIsFullyLoaded) {
    return DrawResult::NOT_READY;
  }

  if (mIsDrawing) {
    NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
    return DrawResult::TEMPORARY_ERROR;
  }

  if (mAnimationConsumers == 0 && mProgressTracker) {
    mProgressTracker->OnUnlockedDraw();
  }

  AutoRestore<bool> autoRestoreIsDrawing(mIsDrawing);
  mIsDrawing = true;

  float animTime =
    (aWhichFrame == FRAME_FIRST) ? 0.0f
                                 : mSVGDocumentWrapper->GetCurrentTime();
  AutoSVGRenderingState autoSVGState(aSVGContext, animTime,
                                     mSVGDocumentWrapper->GetRootSVGElem());

  // Pack up the drawing parameters.
  SVGDrawingParameters params(aContext, aSize, aRegion, aFilter,
                              aSVGContext, animTime, aFlags);

  if (aFlags & FLAG_BYPASS_SURFACE_CACHE) {
    CreateSurfaceAndShow(params);
    return DrawResult::SUCCESS;
  }

  LookupResult result =
    SurfaceCache::Lookup(ImageKey(this),
                         VectorSurfaceKey(params.size,
                                          params.svgContext,
                                          params.animationTime));

  // Draw.
  if (result) {
    RefPtr<SourceSurface> surface = result.DrawableRef()->GetSurface();
    if (surface) {
      nsRefPtr<gfxDrawable> svgDrawable =
        new gfxSurfaceDrawable(surface, result.DrawableRef()->GetSize());
      Show(svgDrawable, params);
      return DrawResult::SUCCESS;
    }

    // We lost our surface due to some catastrophic event.
    RecoverFromLossOfSurfaces();
  }

  CreateSurfaceAndShow(params);

  return DrawResult::SUCCESS;
}
Example #30
0
/**
  Internal method that draws the shadow creating the 3D effect of a pie

  \param painter the QPainter to draw in
  \param rect the position to draw at
  \param dataset the dataset to draw the pie for
  \param pie the pie to draw the shadow for
  \param the chart to draw the pie in
  \param threeDHeight the height of the shadow
  \param regions a pointer to a list of regions that will be filled
  with regions representing the data segments, if not null
  */
void KDChartPiePainter::draw3DEffect( QPainter* painter,
        const QRect& drawPosition,
        uint dataset, uint pie, uint chart,
        uint threeDHeight,
        bool /*explode*/,
        QRegion* region )
{
    // NOTE: We cannot optimize away drawing some of the effects (even
    // when not exploding), because some of the pies might be left out
    // in future versions which would make some of the normally hidden
    // pies visible. Complex hidden-line algorithms would be much more
    // expensive than just drawing for nothing.

    // No need to save the brush, will be changed on return from this
    // method anyway.
    painter->setBrush( QBrush( params()->dataShadow1Color( pie ),
                params()->shadowPattern() ) );

    int startAngle = _startAngles[ ( int ) pie ];
    int endAngle = startAngle + _angleLens[ ( int ) pie ];
    // Normalize angles
    while ( startAngle >= 5760 )
        startAngle -= 5760;
    while ( endAngle >= 5760 )
        endAngle -= 5760;
    Q_ASSERT( startAngle >= 0 && startAngle <= 360 * 16 );
    Q_ASSERT( endAngle >= 0 && endAngle <= 360 * 16 );

    //int centerY = drawPosition.center().y();

    if ( startAngle == endAngle ||
            startAngle == endAngle - 5760 ) { // full circle
        drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                threeDHeight, 2880, 5760, region );
    } else if ( startAngle <= 90 * 16 ) {
        if ( endAngle <= 90 * 16 ) {
            if ( startAngle <= endAngle ) {
                /// starts and ends in first quadrant, less than 1/4
                drawStraightEffectSegment( painter, drawPosition, dataset,
                                           pie, chart, threeDHeight, startAngle,
                                           region );
            } else {
                /// starts and ends in first quadrant, more than 3/4
                drawStraightEffectSegment( painter, drawPosition, dataset,
                                           pie, chart, threeDHeight, startAngle,
                                           region );
                drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                                      threeDHeight, 2880, 5760, region );
            }
        } else if ( endAngle <= 180 * 16 ) {
            /// starts in first quadrant, ends in second quadrant,
            /// less than 1/2
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                                       threeDHeight, startAngle, region );
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                                       threeDHeight, endAngle, region );
        } else if ( endAngle <= 270 * 16 ) {
            /// starts in first quadrant, ends in third quadrant
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle,
                    region );
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, endAngle, region );
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, 2880, endAngle, region );
        } else { // 270*16 < endAngle < 360*16
            /// starts in first quadrant, ends in fourth quadrant,
            /// more than 3/4
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, region );
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, 2880, endAngle, region );
        }
    } else if ( startAngle <= 180 * 16 ) {
        if ( endAngle <= 90 * 16 ) {
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, 2880, 5760, region );
        } else if ( endAngle <= 180 * 16 ) {
            if ( startAngle <= endAngle ) {
                /// starts in second quadrant, ends in second
                /// quadrant, less than 1/4
                drawStraightEffectSegment( painter, drawPosition, dataset,
                        pie, chart, threeDHeight, endAngle,
                        region );
            } else {
                /// starts in second quadrant, ends in second
                /// quadrant, more than 1/4
                drawStraightEffectSegment( painter, drawPosition, dataset,
                        pie, chart, threeDHeight, endAngle,
                        region );
                drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                        threeDHeight, 2880, 5760, region );
            }
        } else if ( endAngle <= 270 * 16 ) {
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, endAngle, region );
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, 2880, endAngle, region );
        } else { // 270*16 < endAngle < 360*16
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, 2880, endAngle, region );
        }
    } else if ( startAngle <= 270 * 16 ) {
        if ( endAngle <= 90 * 16 ) {
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, 5760, region );
        } else if ( endAngle <= 180 * 16 ) {
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, endAngle, region );
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, 5760, region );
        } else if ( endAngle <= 270 * 16 ) {
            if ( startAngle <= endAngle ) {
                /// starts in third quadrant, ends in third quadrant,
                /// less than 1/4
                drawStraightEffectSegment( painter, drawPosition, dataset,
                        pie, chart, threeDHeight, endAngle,
                        region );
                drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                        threeDHeight, startAngle, endAngle,
                        region );
            } else {
                /// starts in third quadrant, ends in third quadrant,
                /// more than 3/4
                drawStraightEffectSegment( painter, drawPosition, dataset,
                        pie, chart, threeDHeight, endAngle,
                        region );
                drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                        threeDHeight, 2880, endAngle,
                        region );
                drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                        threeDHeight, startAngle, 5760,
                        region );
            }
        } else { // 270*16 < endAngle < 360*16
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, endAngle,
                    region );
        }
    } else { // 270*16 < startAngle < 360*16
        if ( endAngle <= 90 * 16 ) {
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, region );
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, 5760, region );
        } else if ( endAngle <= 180 * 16 ) {
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, region );
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, endAngle, region );
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, 5760, region );
        } else if ( endAngle <= 270 * 16 ) {
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, region );
            drawStraightEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, endAngle, region );
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, 2880, endAngle, region );
            drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                    threeDHeight, startAngle, 5760, region );
        } else { // 270*16 < endAngle < 360*16
            if ( startAngle <= endAngle ) {
                /// starts in fourth quadrant, ends in fourth
                /// quadrant, less than 1/4
                drawStraightEffectSegment( painter, drawPosition, dataset,
                        pie, chart, threeDHeight, startAngle,
                        region );
                drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                        threeDHeight, startAngle, endAngle,
                        region );
            } else {
                /// starts in fourth quadrant, ends in fourth
                /// quadrant, more than 3/4
                drawStraightEffectSegment( painter, drawPosition, dataset,
                        pie, chart, threeDHeight, startAngle,
                        region );
                drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                        threeDHeight, startAngle, 5760,
                        region );
                drawArcEffectSegment( painter, drawPosition, dataset, pie, chart,
                        threeDHeight, 2880, endAngle, region );
            }
        }
    }
}