Пример #1
0
void KToolTipWindow::showEvent(QShowEvent *)
{
    KWindowEffects::enableBlurBehind(winId(), true, mask());
}
Пример #2
0
	void ecg_power_off() { AVR32_GPIO.port[0].ovrc = mask(PIN_POWER_ON);  }
Пример #3
0
bool apiSimpleShapeUI::selectVertices( MSelectInfo &selectInfo,
							 MSelectionList &selectionList,
							 MPointArray &worldSpaceSelectPts ) const
//
// Description:
//
//     Vertex selection.
//
// Arguments:
//
//     selectInfo           - the selection state information
//     selectionList        - the list of selected items to add to
//     worldSpaceSelectPts  -
//
{
	bool selected = false;
	M3dView view = selectInfo.view();

	MPoint 		xformedPoint;
	MPoint 		currentPoint;
	MPoint 		selectionPoint;
	double		z,previousZ = 0.0;
 	int			closestPointVertexIndex = -1;

	const MDagPath & path = selectInfo.multiPath();

	// Create a component that will store the selected vertices
	//
	MFnSingleIndexedComponent fnComponent;
	MObject surfaceComponent = fnComponent.create( MFn::kMeshVertComponent );
	int vertexIndex;

	// if the user did a single mouse click and we find > 1 selection
	// we will use the alignmentMatrix to find out which is the closest
	//
	MMatrix	alignmentMatrix;
	MPoint singlePoint; 
	bool singleSelection = selectInfo.singleSelection();
	if( singleSelection ) {
		alignmentMatrix = selectInfo.getAlignmentMatrix();
	}

	// Get the geometry information
	//
	apiSimpleShape* shape = (apiSimpleShape*) surfaceShape();
	MVectorArray* geomPtr = shape->getControlPoints();
	MVectorArray& geom = *geomPtr;


	// Loop through all vertices of the mesh and
	// see if they lie withing the selection area
	//
	int numVertices = geom.length();
	for ( vertexIndex=0; vertexIndex<numVertices; vertexIndex++ )
	{
		const MVector& point = geom[ vertexIndex ];

		// Sets OpenGL's render mode to select and stores
		// selected items in a pick buffer
		//
		view.beginSelect();

		glBegin( GL_POINTS );
		glVertex3f( (float)point[0], 
					(float)point[1], 
					(float)point[2] );
		glEnd();

		if ( view.endSelect() > 0 )	// Hit count > 0
		{
			selected = true;

			if ( singleSelection ) {
				xformedPoint = currentPoint;
				xformedPoint.homogenize();
				xformedPoint*= alignmentMatrix;
				z = xformedPoint.z;
				if ( closestPointVertexIndex < 0 || z > previousZ ) {
					closestPointVertexIndex = vertexIndex;
					singlePoint = currentPoint;
					previousZ = z;
				}
			} else {
				// multiple selection, store all elements
				//
				fnComponent.addElement( vertexIndex );
			}
		}
	}

	// If single selection, insert the closest point into the array
	//
	if ( selected && selectInfo.singleSelection() ) {
		fnComponent.addElement(closestPointVertexIndex);

		// need to get world space position for this vertex
		//
		selectionPoint = singlePoint;
		selectionPoint *= path.inclusiveMatrix();
	}

	// Add the selected component to the selection list
	//
	if ( selected ) {
		MSelectionList selectionItem;
		selectionItem.add( path, surfaceComponent );

		MSelectionMask mask( MSelectionMask::kSelectComponentsMask );
		selectInfo.addSelection(
			selectionItem, selectionPoint,
			selectionList, worldSpaceSelectPts,
			mask, true );
	}

	return selected;
}
Пример #4
0
/*
 * Sequence a cfgadm state change command into driver commands.
 * The rstate and ostate of the AP are needed at this point
 * in order to compute the proper sequence.
 */
static int
ap_seq_get(apd_t *a, int cmd, int *first, int *last)
{
	int done = 0;
	int f = CMD_NONE;
	int l = CMD_NONE;
	cfga_stat_t rs, os;

	ap_state(a, &rs, &os);

	switch (rs) {
	case CFGA_STAT_EMPTY:
		switch (os) {
		case CFGA_STAT_UNCONFIGURED:
			switch (cmd) {
			case CMD_UNCONFIGURE:
				done++;
				break;
			default:
				break;
			}
			break;
		default:
			break;
		}
		break;
	case CFGA_STAT_DISCONNECTED:
		switch (os) {
		case CFGA_STAT_UNCONFIGURED:
			switch (cmd) {
			case CMD_DISCONNECT:
				/*
				 * skip the disconnect command since
				 * the rstate is already disconnected
				 */
				f = CMD_DISCONNECT;
				a->opts.skip |= mask(CMD_DISCONNECT);
				l = CMD_UNASSIGN;
				break;
			case CMD_UNCONFIGURE:
				done++;
				break;
			case CMD_CONNECT:
				f = CMD_ASSIGN;
				l = CMD_CONNECT;
				break;
			case CMD_CONFIGURE:
				f = CMD_ASSIGN;
				l = CMD_RCM_CAP_ADD;
				break;
			default:
				break;
			}
			break;
		default:
			break;
		}
		break;
	case CFGA_STAT_CONNECTED:
		switch (os) {
		case CFGA_STAT_UNCONFIGURED:
			switch (cmd) {
			case CMD_CONNECT:
			case CMD_UNCONFIGURE:
				done++;
				break;
			case CMD_DISCONNECT:
				f = CMD_DISCONNECT;
				l = CMD_UNASSIGN;
				break;
			case CMD_CONFIGURE:
				f = CMD_CONFIGURE;
				l = CMD_RCM_CAP_ADD;
				break;
			default:
				break;
			}
			break;
		case CFGA_STAT_CONFIGURED:
			switch (cmd) {
			case CMD_CONNECT:
				done++;
				break;
			case CMD_DISCONNECT:
				f = CMD_SUSPEND_CHECK;
				l = CMD_UNASSIGN;
				break;
			case CMD_CONFIGURE:
				f = CMD_CONFIGURE;
				l = CMD_RCM_CAP_ADD;
				break;
			case CMD_UNCONFIGURE:
				f = CMD_SUSPEND_CHECK;
				l = CMD_RCM_CAP_NOTIFY;
				break;
			default:
				break;
			}
			break;
		default:
			break;
		}
		break;
	default:
		break;
	}

	if (f == CMD_NONE) {
		if (done)
			return (AP_SEQ_NULL);
		ap_err(a, ERR_TRANS_INVAL, cmd);
		return (AP_SEQ_FAIL);
	}

	*first = f;
	*last = l;

	DBG("ap_seq(%d, %d, %d, %p, %p) = (%d, %d)\n",
	    rs, os, cmd, (void *)first, (void *)last, f, l);

	return (AP_SEQ_OK);
}
Пример #5
0
	void led2_toggle()
	{
		AVR32_GPIO.port[0].ovrt = mask(PIN_LED2); 
	}
Пример #6
0
  void Offsets<word>::compute_offsets()
  {
    offset_pair_t *offset = offsets;
    uint_t         cword  = 0;    // current word in block
    uint_t         cboff  = 0;    // current offset in word
    uint_t         lcword;        // idem for large fields
    uint_t         lcboff;
    uint_t         ocboff;

    memset(offsets, '\0', sizeof(offsets));
    do {
      offset->normal.key.woff    = offset->large.key.woff = lcword = cword;
      ocboff                     = lcboff = cboff;
      offset->normal.key.boff    = cboff + 1;
      offset->normal.key.lb_mask = mask(1, cboff);
      if(update_current_offsets(cword, cboff, key_len + 1)) {
        // key extends over two words -> add extra set bits
        update_current_offsets(cword, cboff, 2);
        offset->normal.key.mask1    = mask(bsizeof(word) - ocboff, ocboff);
        offset->normal.key.mask2    = mask(cboff, 0);
        offset->normal.key.shift    = key_len + 1 - cboff;
        offset->normal.key.cshift   = cboff - 1;
        offset->normal.key.sb_mask1 = mask(1, bsizeof(word) - 1);
        offset->normal.key.sb_mask2 = mask(1, cboff - 1);
      } else {
        offset->normal.key.mask1    = mask(key_len + 1, ocboff);
        offset->normal.key.mask2    = 0;
        offset->normal.key.shift    = 0;
        offset->normal.key.cshift   = 0;
        offset->normal.key.sb_mask1 = 0;
        offset->normal.key.sb_mask2 = 0;
      }
      offset->normal.val.woff  = cword;
      offset->normal.val.boff  = cboff;
      offset->normal.val.mask1 = mask(val_len, cboff);
      if(update_current_offsets(cword, cboff, val_len)) {
        offset->normal.val.mask2  = mask(cboff, 0);
        offset->normal.val.shift  = val_len - cboff;
        offset->normal.val.cshift = cboff;
      } else {
        offset->normal.val.mask2  = 0;
        offset->normal.val.shift  = val_len;
        offset->normal.val.cshift = 0;
      }

      ocboff                    = lcboff;
      offset->large.key.boff    = lcboff + 1;
      offset->large.key.lb_mask = mask(1, lcboff);
      if(update_current_offsets(lcword, lcboff, reprobe_len + 1)) {
        update_current_offsets(lcword, lcboff, 2);
        offset->large.key.mask1    = mask(bsizeof(word) - ocboff, ocboff);
        offset->large.key.mask2    = mask(lcboff, 0);
        offset->large.key.shift    = reprobe_len + 1 - lcboff;
        offset->large.key.cshift   = lcboff - 1;
        offset->large.key.sb_mask1 = mask(1, bsizeof(word) - 1);
        offset->large.key.sb_mask2 = mask(1, lcboff - 1);
      } else {
        offset->large.key.mask1    = mask(reprobe_len + 1, ocboff);
        offset->large.key.mask2    = 0;
        offset->large.key.boff     = ocboff + 1;
        offset->large.key.shift    = 0;
        offset->large.key.cshift   = 0;
        offset->large.key.sb_mask1 = 0;
        offset->large.key.sb_mask2 = 0;
      }
      offset->large.val.woff  = lcword;
      offset->large.val.boff  = lcboff;
      offset->large.val.mask1 = mask(lval_len, lcboff);
      if(update_current_offsets(lcword, lcboff, lval_len)) {
        offset->large.val.mask2  = mask(lcboff, 0);
        offset->large.val.shift  = lval_len - lcboff;
        offset->large.val.cshift = lcboff;
      } else {
        offset->large.val.mask2  = 0;
        offset->large.val.shift  = lval_len;
        offset->large.val.cshift = 0;
      }

      offset++;
    } while(cboff != 0 && cboff < bsizeof(word) - 2);

    block_len = offset - offsets;
    block_word_len = cword + (cboff == 0 ? 0 : 1);
  }
Пример #7
0
CPLErr JPEG_Codec::DecompressJPEG(buf_mgr &dst, buf_mgr &isrc)
#endif

{
    int nbands = img.pagesize.c;
    // Locals, clean up after themselves
    jpeg_decompress_struct cinfo;
    MRFJPEGStruct sJPEGStruct;
    struct jpeg_error_mgr sJErr;
    BitMask mask(img.pagesize.x, img.pagesize.y);
    RLEC3Packer packer;
    mask.set_packer(&packer);

    memset(&cinfo, 0, sizeof(cinfo));
    // Pass the mask address to the decompressor
    sJPEGStruct.mask = &mask;

    struct jpeg_source_mgr src;

    cinfo.err = jpeg_std_error( &sJErr );
    sJErr.error_exit = errorExit;
    sJErr.emit_message = emitMessage;
    cinfo.client_data = (void *) &(sJPEGStruct);

    src.next_input_byte = (JOCTET *)isrc.buffer;
    src.bytes_in_buffer = isrc.size;
    src.term_source = stub_source_dec;
    src.init_source = stub_source_dec;
    src.skip_input_data = skip_input_data_dec;
    src.fill_input_buffer = fill_input_buffer_dec;
    src.resync_to_restart = jpeg_resync_to_restart;

    jpeg_create_decompress(&cinfo);

    if (setjmp(sJPEGStruct.setjmpBuffer)) {
        CPLError(CE_Failure, CPLE_AppDefined, "MRF: Error reading JPEG page");
        jpeg_destroy_decompress(&cinfo);
        return CE_Failure;
    }

    cinfo.src = &src;
    jpeg_set_marker_processor(&cinfo, JPEG_APP0 + 3, MaskProcessor);
    jpeg_read_header(&cinfo, TRUE);

    /* In some cases, libjpeg needs to allocate a lot of memory */
    /* http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf */
    if( jpeg_has_multiple_scans(&(cinfo)) )
    {
        /* In this case libjpeg will need to allocate memory or backing */
        /* store for all coefficients */
        /* See call to jinit_d_coef_controller() from master_selection() */
        /* in libjpeg */
        vsi_l_offset nRequiredMemory = 
            static_cast<vsi_l_offset>(cinfo.image_width) *
            cinfo.image_height * cinfo.num_components *
            ((cinfo.data_precision+7)/8);
        /* BLOCK_SMOOTHING_SUPPORTED is generally defined, so we need */
        /* to replicate the logic of jinit_d_coef_controller() */
        if( cinfo.progressive_mode )
            nRequiredMemory *= 3;

#ifndef GDAL_LIBJPEG_LARGEST_MEM_ALLOC
#define GDAL_LIBJPEG_LARGEST_MEM_ALLOC (100 * 1024 * 1024)
#endif

        if( nRequiredMemory > GDAL_LIBJPEG_LARGEST_MEM_ALLOC &&
            CPLGetConfigOption("GDAL_ALLOW_LARGE_LIBJPEG_MEM_ALLOC", nullptr) == nullptr )
        {
                CPLError(CE_Failure, CPLE_NotSupported,
                    "Reading this image would require libjpeg to allocate "
                    "at least " CPL_FRMT_GUIB " bytes. "
                    "This is disabled since above the " CPL_FRMT_GUIB " threshold. "
                    "You may override this restriction by defining the "
                    "GDAL_ALLOW_LARGE_LIBJPEG_MEM_ALLOC environment variable, "
                    "or recompile GDAL by defining the "
                    "GDAL_LIBJPEG_LARGEST_MEM_ALLOC macro to a value greater "
                    "than " CPL_FRMT_GUIB,
                    static_cast<GUIntBig>(nRequiredMemory),
                    static_cast<GUIntBig>(GDAL_LIBJPEG_LARGEST_MEM_ALLOC),
                    static_cast<GUIntBig>(GDAL_LIBJPEG_LARGEST_MEM_ALLOC));
                jpeg_destroy_decompress(&cinfo);
                return CE_Failure;
        }
    }

    // Use float, it is actually faster than the ISLOW method by a tiny bit
    cinfo.dct_method = JDCT_FLOAT;

    //
    // Tolerate different input if we can do the conversion
    // Gray and RGB for example
    // This also means that a RGB MRF can be read as grayscale and vice versa
    // If libJPEG can't convert it will throw an error
    //
    if (nbands == 3 && cinfo.num_components != nbands)
        cinfo.out_color_space = JCS_RGB;
    if (nbands == 1 && cinfo.num_components != nbands)
        cinfo.out_color_space = JCS_GRAYSCALE;

    const int datasize = ((cinfo.data_precision == 8) ? 1 : 2);
    if( cinfo.image_width > static_cast<unsigned>(INT_MAX / (nbands * datasize)) )
    {
        CPLError(CE_Failure, CPLE_AppDefined, "MRF: JPEG decompress buffer overflow");
        jpeg_destroy_decompress(&cinfo);
        return CE_Failure;
    }
    int linesize = cinfo.image_width * nbands * datasize;

    // We have a mismatch between the real and the declared data format
    // warn and fail if output buffer is too small
    if (linesize > static_cast<int>(INT_MAX / cinfo.image_height)) {
        CPLError(CE_Failure, CPLE_AppDefined, "MRF: JPEG decompress buffer overflow");
        jpeg_destroy_decompress(&cinfo);
        return CE_Failure;
    }
    if (linesize*cinfo.image_height != dst.size) {
        CPLError(CE_Warning, CPLE_AppDefined, "MRF: read JPEG size is wrong");
        if (linesize*cinfo.image_height > dst.size) {
            CPLError(CE_Failure, CPLE_AppDefined, "MRF: JPEG decompress buffer overflow");
            jpeg_destroy_decompress(&cinfo);
            return CE_Failure;
        }
    }

    struct jpeg_progress_mgr sJProgress;
    sJProgress.progress_monitor = ProgressMonitor;
    cinfo.progress = &sJProgress;

    jpeg_start_decompress(&cinfo);

    // Decompress, two lines at a time is what libjpeg does
    while (cinfo.output_scanline < cinfo.image_height) {
        char *rp[2];
        rp[0] = (char *)dst.buffer + linesize*cinfo.output_scanline;
        rp[1] = rp[0] + linesize;
        // if this fails, it calls the error handler
        // which will report an error
        if( jpeg_read_scanlines(&cinfo, JSAMPARRAY(rp), 2) == 0 )
        {
            jpeg_destroy_decompress(&cinfo);
            return CE_Failure;
        }
    }
    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);

    // Apply the mask
    if (datasize == 1)
      apply_mask(sJPEGStruct, reinterpret_cast<char *>(dst.buffer), img.pagesize.c);
    else
      apply_mask(sJPEGStruct, reinterpret_cast<GUInt16 *>(dst.buffer), img.pagesize.c);

    return CE_None;
}
KJS::Value Pixmap::call( KJS::ExecState *exec, KJS::Object &self, const KJS::List &args ) {

    if( !JSProxy::checkType( self, JSProxy::ValueProxy, "QPixmap") )
        return KJS::Value();

    JSValueProxy *op = JSProxy::toValueProxy( self.imp() );
    pix = op->toVariant().toPixmap();

    KJS::Value retValue = KJS::Value();
    switch ( mid ) {
    case Methodwidth:
        retValue = KJS::Number(width());
        break;
    case Methodheight:
        retValue = KJS::Number(height());
        break;
    case Methoddepth:
        retValue = KJS::Number(depth());
        break;
    case MethodisNull:
        retValue = KJS::Boolean(isNull());
        break;
    case Methodsize:
        retValue = convertToValue(exec, size());
        break;
    case Methodrect:
        retValue = convertToValue(exec, rect());
        break;
    case Methodresize:
    {
        if( args.size() == 2)
		resize(extractInt(exec, args, 0), extractInt(exec, args, 1));
	else if( args.size() == 1)
	    resize(extractQSize(exec, args, 0) );
	break;
    }
    case Methodfill:
        fill( extractQColor(exec, args, 0));
        break;
    case Methodmask:
    {
        retValue = convertToValue(exec, mask() );
        break;
    }
    case MethodsetMask:
    {
       setMask(extractQPixmap(exec, args, 0));
       break;
    }
    case MethodcreateHeuristicMask:
    {
       retValue = convertToValue(exec, createHeuristicMask(extractBool(exec, args, 0)));
       break;
    }
    case MethodgrabWindow:
    {
    	int winid = extractInt(exec, args,0);
	int x = extractInt(exec, args,1);
	int y = extractInt(exec, args,2);
	int w = extractInt(exec, args,3);
	int h = extractInt(exec, args,4);
    	grabWindow(winid,x,y,w,h);
	break;
    }
    default:
        kdWarning() << "Image has no method " << mid << endl;
        break;
    }

    op->setValue(pix);
    return retValue;
}
Пример #9
0
void muste_statmsf(char *argv)
        {
        int i;

// RS Variable init
		prind=1;
		sum=NULL;
		sum2=NULL;
		f=NULL;
		w=NULL;
		f2=NULL;
		X=NULL;
		rlabX=NULL;
		clabX=NULL;
		T=NULL;
		rlabT=NULL;
		clabT=NULL;
		v=NULL;

        s_init(argv);

        typeT=lrT=lcT=0; // to avoid warnings from compiler

  //    specs=spec_msf;
        if (g<2)
            {
            init_remarks();
            rem_pr("STATMSF <Survo_data>,<output_line>                                      ");
            rem_pr("        LIMITS=<low1>,<up1>,<up2>,...");
            rem_pr("computes means, standard deviations, and frequency distributions");
            rem_pr("of active variables. Cases can be limited by IND and CASES specifications.");
            rem_pr("The frequencies are computed according to a classification given by the");
            rem_pr("LIMITS specification where <low1> is the lower limit of the first class 1");
            rem_pr("and <up1>,<up2>,... are the upper limits of the classes 1,2,...");
            rem_pr("The default setting is LIMITS=0,1,2,3,4,5 .");
            wait_remarks(1);
            rem_pr("STATMSF <Survo_data> / TRESHOLDS=<matrix_file>");
            rem_pr("where <matrix_file> is of the form");
            rem_pr("row label   1st column");
            rem_pr("variable_1  treshold_value_1");
            rem_pr("variable_2  treshold_value_2");
            rem_pr("...");
            rem_pr("computes relative frequencies of values exceeding treshold values");
            rem_pr("given as the first column of <matrix_file> for variables given");
            rem_pr("as row labels in <matrix_file> for active observations");
            rem_pr("in  <Survo_data>.");
            rem_pr("The results are saved in a matrix file TAILFREQ.M .");
            wait_remarks(2);
            return;
            }
        results_line=0;
        i=spec_init(r1+r-1); if (i<0) return;
        i=spfind("PRIND"); if (i>=0) prind=atoi(spb[i]);
        i=spfind("TRESHOLDS");
        if (i>=0) { pvalues(i); return; }

        if (g>2)
            {
            results_line=edline2(word[2],1,1);
            if (results_line==0) return;
            }
        i=data_read_open(word[1],&d); if (i<0) return;
        i=spfind("LIMITS");
        if (i<0)
            {
            n_class=5; limit[0]=0;
            for (i=1; i<=5; ++i) limit[i]=i;
            }
        else
            {
            strcpy(x,spb[i]);
            n_class=split(x,osa,MAXCLASS);
            for (i=0; i<n_class; ++i) limit[i]=atof(osa[i]);
            --n_class;
            }
        i=mask(&d); if (i<0) return;
        weight_variable=activated(&d,'W');
        i=m_test_scaletypes(); if (i<0) return;
        i=conditions(&d); if (i<0) return;  /* permitted only once */
        m=d.m_act;
        if (m==0)
            {
            sur_print("\nNo active (acceptable) variables!");
            WAIT; return;
            }
        i=m_space_allocation(); if (i<0) return;

//      i=optdim_d(); if (i && i<d.m) err(0);
//      i=optdim_o(); if (i && (long)i<d.n) err(0);

        compute_sums();
        m_printout();
        data_close(&d);
        s_end(argv);
        }
Пример #10
0
void FrameConsumer::run()
{
    cv::Mat prevFrame;
    cv::Mat alignedPrevFrame;
    cv::Mat currentDiffImage;

    int w = 320;
    int h = 240;
    float f = 0.0;

    while(1)
    {

        if(frameBuffer->size() > 0 )
        {
            cv::Mat frame_ = frameBuffer->front();

            cv::Mat frame = frame_.clone();

            //Do Processing
            pFrame = frame.clone();
            if( f == 0.0)
            {
                f = (float) frame.size().width / 320 ;
                w = cvRound(f*frame.size().width);
                h = cvRound(f*frame.size().height);
            }

            cv::resize(pFrame, pFrame, cv::Size(w,h));
            cv::cvtColor(pFrame,pFrame,CV_BGR2GRAY);


            cv::Mat copyCurrentFrame = pFrame.clone();
            cv::equalizeHist(copyCurrentFrame,copyCurrentFrame);
            cv::Mat H;
            calc.process(copyCurrentFrame);

            if(calc.getHomography(H) == true)
            {
                cv::Mat canImg = frame.clone();
                cv::Mat tarImg = frame.clone();

                qDebug()<<"Homography Found \n";
                // Düzgün dönüşüm matrisi bulunduysa
                cv::Mat mask(prevFrame.size(),CV_8U);
                mask=cv::Scalar(255);

                // Önceki frame aktif frame çevir
                aligner.process(prevFrame,H,alignedPrevFrame);
                // çevrilmiş önceki frame için maske oluştur
                aligner.process(mask,H,mask);
                mask=copyCurrentFrame&mask;
                cv::absdiff(alignedPrevFrame,mask,currentDiffImage);
                processedFrame2UiAbsDiff = currentDiffImage.clone();
                cv::Mat element = cv::getStructuringElement( cv::MORPH_RECT,cv::Size( 3, 3 ),cv::Point( 1, 1 ) );


                cv::threshold(currentDiffImage,currentDiffImage,dynamicThresholdValue(currentDiffImage),255,cv::THRESH_BINARY);
                cv::dilate(currentDiffImage,currentDiffImage, element,cv::Point(-1,-1),4 );
                cv::erode(currentDiffImage,currentDiffImage, element,cv::Point(-1,-1),4 );

                cDet.process(currentDiffImage);
                cDet.showCandidates(canImg);
                cFilt.process(&cDet.candidateList);
                cFilt.showTargets(tarImg,cDet.scaleFactor);

                processedFrame2UiCandidates = canImg.clone();
                processedFrame2UiTargets = tarImg.clone();

            }
            prevFrame = copyCurrentFrame;

            emit frameProcessed();

            frameBuffer->pop();

/* causes a error "Debug Assertion Failed!" and
 * "Expression: deque iterator not dereferencable."
 * mutex not solved

            QMutex mutex;
            mutex.lock();
            for(int i=0; i < nPass ; i++) // to by pass some frame
            {
                qDebug()<<"frame Buffersize : " <<frameBuffer->size()<<"\n";
                if(frameBuffer->size() < 1)
                    break;
                else
                    frameBuffer->pop();
            }
            mutex.unlock();
*/

        }
        else
        {
           QThread::msleep(100);
        }
    }

}
Пример #11
0
void Renderer2d::render(cv::Mat &image_out, cv::Mat &depth_out, cv::Mat &mask_out, cv::Rect &rect) const {
  // Figure out the transform from an original image pixel to a projected pixel
  // original frame: 0 is the top left corner of the pattern, X goes right, Y down, Z away from the camera
  // projected frame: 0 is the center of the projection image, X goes right, Y up, Z towards the camera

  // Scale the image properly
  float s = physical_width_ / img_ori_.cols;
  cv::Matx44f T_img_physical = cv::Matx44f(s,0,0,0, 0,s,0,0, 0,0,s,0, 0,0,0,1);

  // Flip axes and center at 0,0,0
  float physical_height = img_ori_.rows * s;
  T_img_physical = cv::Matx44f(1,0,0,-float(physical_width_) / 2, 0,1,0,float(physical_height) / 2, 0,0,1,0, 0,0,0,1) *
      cv::Matx44f(1,0,0,0, 0,-1,0,0, 0,0,-1,0, 0,0,0,1) * T_img_physical;

  // Define the perspective transform to apply to the image (z=0 so we can ignore the 3rd column of P)
  cv::Matx34f P_noK = cv::Matx34f(R_(0, 0), R_(0, 1), R_(0, 2), T_(0), R_(1, 0), R_(1, 1), R_(1, 2), T_(1), R_(2, 0),
      R_(2, 1), R_(2, 2), T_(2)) * T_img_physical;
  cv::Matx33f T_to3d = cv::Matx33f(P_noK(0, 0), P_noK(0, 1), P_noK(0, 3), P_noK(1, 0), P_noK(1, 1), P_noK(1, 3),
      P_noK(2, 0), P_noK(2, 1), P_noK(2, 3));

  // Apply the camera transform
  cv::Matx33f T_img = K_ * T_to3d;

  // And readapt to an OpenCV image
  T_img = cv::Matx33f(1, 0, 0, 0, -1, 0, 0, 0, 1) * T_img;

  // Define the image corners
  std::vector<cv::Vec2f> corners(4);
  corners[0] = cv::Vec2f(0, 0);
  corners[1] = cv::Vec2f(img_ori_.cols, 0);
  corners[2] = cv::Vec2f(img_ori_.cols, img_ori_.rows);
  corners[3] = cv::Vec2f(0, corners[2][1]);

  // Project the image corners
  float x_min = std::numeric_limits<float>::max(), y_min = x_min;

  std::vector<cv::Vec2f> corners_dst(4);
  for (size_t i = 0; i < corners.size(); ++i) {
    cv::Vec3f res = T_img * cv::Vec3f(corners[i][0], corners[i][1], 1);
    x_min = std::min(res[0] / res[2], x_min);
    y_min = std::min(res[1] / res[2], y_min);
  }

  // Warp the mask
  cv::Size final_size(width_, height_);
  cv::Mat_<uchar> mask;
  T_img = cv::Matx33f(1, 0, -x_min, 0, 1, -y_min, 0, 0, 1) * T_img;

  // Compute the inverse
  cv::Matx33f T_img_inv = T_img.inv();

  cv::warpPerspective(mask_ori_, mask, T_img, final_size, cv::INTER_NEAREST, cv::BORDER_CONSTANT, cv::Scalar(0));

  // Warp the image/depth
  cv::Mat_<cv::Vec3b> image = cv::Mat_<cv::Vec3b>::zeros(final_size);
  cv::Mat_<unsigned short> depth = cv::Mat_<unsigned short>::zeros(final_size);
  cv::Mat_<uchar>::iterator mask_it = mask.begin(), mask_end = mask.end();

  unsigned int i_min = width_, i_max = 0, j_min = height_, j_max = 0;
  for (unsigned int j = 0; j < height_; ++j)
    for (unsigned int i = 0; i < width_; ++i, ++mask_it) {
      if (!*mask_it)
        continue;
      // Figure out the coordinates of the original point
      cv::Vec3f point_ori = T_img_inv * cv::Vec3f(i, j, 1);

      int j_ori = point_ori[1] / point_ori[2], i_ori = point_ori[0] / point_ori[2];
      image(j, i) = img_ori_(j_ori, i_ori);

      // Figure out the 3d position of the point
      cv::Vec3f pos = T_to3d * cv::Vec3f(i_ori, j_ori, 1);
      // Do not forget to re-scale in millimeters
      depth(j, i) = -pos[2]*1000;

      // Figure the inclusive bounding box of the mask, just for performance reasons for later
      if (j > j_max)
        j_max = j;
      else if (j < j_min)
        j_min = j;
      if (i > i_max)
        i_max = i;
      else if (i < i_min)
        i_min = i;
    }

  // Crop the images, just so that they are smaller to write/read
  if (i_min > 0)
    --i_min;
  if (i_max < width_ - 1)
    ++i_max;
  if (j_min > 0)
    --j_min;
  if (j_max < height_ - 1)
    ++j_max;
  rect = cv::Rect(i_min, j_min, i_max - i_min + 1, j_max - j_min + 1);

  depth(rect).copyTo(depth_out);
  image(rect).copyTo(image_out);
  mask(rect).copyTo(mask_out);
}
Пример #12
0
void KPassivePopup::updateMask()
{
    // get screen-geometry for screen our anchor is on
    // (geometry can differ from screen to screen!
    QRect deskRect = QApplication::desktop()->screenGeometry(d->anchor);

    int xh = 70, xl = 40;
    if( width() < 80 )
        xh = xl = 40;
    else if( width() < 110 )
        xh = width() - 40;

    bool bottom = (d->anchor.y() + height()) > ((deskRect.y() + deskRect.height()-48));
    bool right = (d->anchor.x() + width()) > ((deskRect.x() + deskRect.width()-48));

    QPoint corners[4] = {
        QPoint( width() - 50, 10 ),
        QPoint( 10, 10 ),
        QPoint( 10, height() - 50 ),
        QPoint( width() - 50, height() - 50 )
    };

    QBitmap mask( width(), height() );
    mask.clear();
    QPainter p( &mask );
    QBrush brush( Qt::color1, Qt::SolidPattern );
    p.setBrush( brush );

    int i = 0, z = 0;
    for (; i < 4; ++i) {
        QPainterPath path;
        path.moveTo(corners[i].x(),corners[i].y());
        path.arcTo(corners[i].x(),corners[i].y(),40,40, i * 90 , 90);
        QPolygon corner = path.toFillPolygon().toPolygon();

        d->surround.resize( z + corner.count() - 1 );
        for (int s = 1; s < corner.count() - 1; s++, z++) {
            d->surround.setPoint( z, corner[s] );
        }

        if (bottom && i == 2) {
            if (right) {
                d->surround.resize( z + 3 );
                d->surround.setPoint( z++, QPoint( width() - xh, height() - 10 ) );
                d->surround.setPoint( z++, QPoint( width() - 20, height() ) );
                d->surround.setPoint( z++, QPoint( width() - xl, height() - 10 ) );
            } else {
                d->surround.resize( z + 3 );
                d->surround.setPoint( z++, QPoint( xl, height() - 10 ) );
                d->surround.setPoint( z++, QPoint( 20, height() ) );
                d->surround.setPoint( z++, QPoint( xh, height() - 10 ) );
            }
        } else if (!bottom && i == 0) {
            if (right) {
                d->surround.resize( z + 3 );
                d->surround.setPoint( z++, QPoint( width() - xl, 10 ) );
                d->surround.setPoint( z++, QPoint( width() - 20, 0 ) );
                d->surround.setPoint( z++, QPoint( width() - xh, 10 ) );
            } else {
                d->surround.resize( z + 3 );
                d->surround.setPoint( z++, QPoint( xh, 10 ) );
                d->surround.setPoint( z++, QPoint( 20, 0 ) );
                d->surround.setPoint( z++, QPoint( xl, 10 ) );
            }
        }
    }

    d->surround.resize( z + 1 );
    d->surround.setPoint( z, d->surround[0] );
    p.drawPolygon( d->surround );
    setMask(mask);

    move( right ? d->anchor.x() - width() + 20 : ( d->anchor.x() < 11 ? 11 : d->anchor.x() - 20 ),
          bottom ? d->anchor.y() - height() : ( d->anchor.y() < 11 ? 11 : d->anchor.y() ) );

    update();
}
Пример #13
0
//--------------------------------------------------------------------------------------
void ImplAlignandum::mask( const Position & from, const Position & to)
{
	Position j;
	for (j = from; j < to; j++)
		mask( j );
}
int main( int argc, char** argv ){

	/// Receive parameters about the template to track
	char *x, *y, *w, *h;
	int xpos = (int)strtol(argv[1],&x,10);
	int ypos = (int)strtol(argv[2],&y,10);
	int width = (int)strtol(argv[3],&w,10);
	int height = (int)strtol(argv[4],&h,10);
	std::cout << xpos << " "  << ypos << " " << width << " " << height << std::endl;

	///Read image and extract template
	std::cout << "Showing template" << std::endl;
	cv::Mat orig = cv::imread("examples/hole1/frame0003.jpg");
	cv::Mat orig_cp = orig.clone();
	cv::Rect patch_roi(xpos,ypos,width,height);
	cv::Mat img_patch = orig(patch_roi);
	cv::Point patch_center((int)(xpos+width/2),(int)(ypos+height/2));
	cv::ellipse(orig_cp, patch_center, cv::Size( width/2, height/2), 0, 0, 360, cv::Scalar( 255, 0, 0 ), 2, 8, 0);
	cv::imshow(disp_window,orig_cp);
	cv::waitKey();

	///Compute features to track
	std::cout << "Calculating features to track" << std::endl;
	cv::Mat orig_gray;
	cvtColor(orig, orig_gray, cv::COLOR_BGR2GRAY);
	const int MAX_CORNERS = 100;
	std::vector<cv::Point2f>corners[2];
	cv::Mat mask = cv::Mat::zeros(orig_gray.rows, orig_gray.cols, CV_8UC1);
	cv::Mat patch_mask = cv::Mat::ones(img_patch.rows, img_patch.cols, CV_8UC1);
	patch_mask.copyTo(mask(patch_roi));
	goodFeaturesToTrack(orig_gray,corners[0],MAX_CORNERS,0.01,10,mask,3,1,0.04);

	/// Set the neeed parameters to find the refined corners
  	cv::Size subPixWinSize = cv::Size( 5, 5 );
  	cv::Size zeroZone = cv::Size( -1, -1 );
  	cv::TermCriteria termcrit = cv::TermCriteria( CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 200, 0.003 );
  	cornerSubPix(orig_gray, corners[0], subPixWinSize, zeroZone, termcrit);
  	for(int i = 0; i < corners[0].size(); i++){
  		cv::circle(orig_cp, corners[0][i], 3, cv::Scalar(0,255,0), -1, 8);
  		//corners[1].push_back(corners[0][i]);
  	}
 	cv::imshow(disp_window,orig_cp);
	cv::waitKey(); 

	/// Calculate optical flow
	std::cout << "Calculating optical flow" << std::endl;
	std::vector<uchar> status;
    std::vector<float> err;
    cv::Size optFlowWinSize = cv::Size(31,31);
    cv::Mat next_frame = cv::imread("examples/hole1/frame0005.jpg");
    cv::Mat next_frame_cp = next_frame.clone();
    cv::Mat next_frame_gray;
    cvtColor(next_frame,next_frame_gray, cv::COLOR_BGR2GRAY);
    calcOpticalFlowPyrLK(orig_gray, next_frame_gray, corners[0], corners[1], status, err, optFlowWinSize, 5, termcrit, 
    	0, 0.01);
    for(int i = 0; i < corners[1].size(); i++){
    	if(!status[i]){
    		if(corners[1][i].x > 0 && corners[1][i].x < orig_gray.cols && corners[1][i].y > 0 && corners[1][i].y < orig_gray.rows ){
	    		std::cout << "good status " << corners[1][i].x << " " << corners[1][i].y << std::endl;
	    		cv::circle(next_frame_cp, corners[0][i], 5, cv::Scalar(0,255,0), -1, 8);
	  			cv::circle(next_frame_cp, corners[1][i], 3, cv::Scalar(255,0,255), -1, 8);
	  			cv::line(next_frame_cp, corners[0][i], corners[1][i], cv::Scalar(255, 0,0),1,8,0);
	  		}
    	}
  	}
  	std::cout << "Drawing" << std::endl;
  	cv::imshow(disp_window,next_frame_cp);
	cv::waitKey();



	return 0;

}
Пример #15
0
bool IPList::ifsreadIPMelangeList(std::ifstream *input, bool checkendstring, const char *endstring)
{
    // compile regexps for determining whether a list entry is an IP, a subnet (IP + mask), or a range
    RegExp matchIP, matchSubnet, matchRange, matchCIDR;
#ifdef HAVE_PCRE
    matchIP.comp("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
    matchSubnet.comp("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
    matchSubnet.comp("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
    matchCIDR.comp("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/\\d{1,2}$");
    matchRange.comp("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}-\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
#else
    matchIP.comp("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
    matchSubnet.comp("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
    matchCIDR.comp("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/[0-9]{1,2}$");
    matchRange.comp("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}-[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
#endif
    RegResult Rre;

    // read in the file
    String line;
    char buffer[2048];
    while (input) {
        if (!input->getline(buffer, sizeof(buffer))) {
            break;
        }
        line = buffer;
        if (checkendstring && line.startsWith(endstring)) {
            break;
        }

        // ignore comments
        if (buffer[0] == '#')
            continue;
        // ignore blank lines
        if (strlen(buffer) < 7)
            continue;
#ifdef DGDEBUG
        std::cout << "line: " << line << std::endl;
#endif
        // store the IP address (numerically, not as a string) and filter group in either the IP list, subnet list or range list
        if (matchIP.match(line.toCharArray(),Rre)) {
            struct in_addr address;
            if (inet_aton(line.toCharArray(), &address)) {
                uint32_t addr = ntohl(address.s_addr);
                iplist.push_back(addr);
            }
        } else if (matchSubnet.match(line.toCharArray(),Rre)) {
            struct in_addr address;
            struct in_addr addressmask;
            String subnet(line.before("/"));
            String mask(line.after("/"));
            if (inet_aton(subnet.toCharArray(), &address) && inet_aton(mask.toCharArray(), &addressmask)) {
                ipl_subnetstruct s;
                uint32_t addr = ntohl(address.s_addr);
                s.mask = ntohl(addressmask.s_addr);
                // pre-mask the address for quick comparison
                s.maskedaddr = addr & s.mask;
                ipsubnetlist.push_back(s);
            }
        } else if (matchCIDR.match(line.toCharArray(),Rre)) {
            struct in_addr address;
            struct in_addr addressmask;
            String subnet(line.before("/"));
            String cidr(line.after("/"));
            int m = cidr.toInteger();
            int host_part = 32 - m;
            if (host_part > -1) {
                String mask = (0xFFFFFFFF << host_part);
                if (inet_aton(subnet.toCharArray(), &address) && inet_aton(mask.toCharArray(), &addressmask)) {
                    ipl_subnetstruct s;
                    uint32_t addr = ntohl(address.s_addr);
                    s.mask = ntohl(addressmask.s_addr);
                    // pre-mask the address for quick comparison
                    s.maskedaddr = addr & s.mask;
                    ipsubnetlist.push_back(s);
                }
            }
        } else if (matchRange.match(line.toCharArray(),Rre)) {
            struct in_addr addressstart;
            struct in_addr addressend;
            String start(line.before("-"));
            String end(line.after("-"));
            if (inet_aton(start.toCharArray(), &addressstart) && inet_aton(end.toCharArray(), &addressend)) {
                ipl_rangestruct r;
                r.startaddr = ntohl(addressstart.s_addr);
                r.endaddr = ntohl(addressend.s_addr);
                iprangelist.push_back(r);
            }
        }
        // hmmm. the line didn't match any of our regular expressions.
        // assume it's a hostname.
        else {
            line.toLower();
            hostlist.push_back(line);
        }
    }
#ifdef DGDEBUG
    std::cout << "starting sort" << std::endl;
#endif
    std::sort(iplist.begin(), iplist.end());
    std::sort(hostlist.begin(), hostlist.end());
#ifdef DGDEBUG
    std::cout << "sort complete" << std::endl;
    std::cout << "ip list dump:" << std::endl;
    std::vector<uint32_t>::iterator i = iplist.begin();
    while (i != iplist.end()) {
        std::cout << "IP: " << *i << std::endl;
        ++i;
    }
    std::cout << "subnet list dump:" << std::endl;
    std::list<ipl_subnetstruct>::iterator j = ipsubnetlist.begin();
    while (j != ipsubnetlist.end()) {
        std::cout << "Masked IP: " << j->maskedaddr << " Mask: " << j->mask << std::endl;
        ++j;
    }
    std::cout << "range list dump:" << std::endl;
    std::list<ipl_rangestruct>::iterator k = iprangelist.begin();
    while (k != iprangelist.end()) {
        std::cout << "Start IP: " << k->startaddr << " End IP: " << k->endaddr << std::endl;
        ++k;
    }
    std::cout << "host list dump:" << std::endl;
    std::vector<String>::iterator l = hostlist.begin();
    while (l != hostlist.end()) {
        std::cout << "Hostname: " << *l << std::endl;
        ++l;
    }
#endif
    return true;
}
Пример #16
0
int main()
{
    CImg<float> img,img_hsi,img_hsi_p,maskRGB,maskHSI,resultado,resultado2,resultado0,resultado1,imgOrig,kernel,kernel2,eqGlobal,diferencia,hist;
    CImgDisplay displayImagen, displayMascaraRGB, displayMascaraHSI;
    float radioHSI=50, radioRGB=20;
    unsigned mx, my;

    imgOrig.load("../../../../images/Deforestacion.png");
    //img es la imagen auxiliar a procesar (RGB)
    img=imgOrig;
    //Recorte de la zona de interes
    img.crop(152,275,729,705); //recorte estilo bestia
    //Area total de la zona de interes
    float areaTotal= (img.width()*img.height())*areaPixel;
    //imagen auxiliar HSI
    img_hsi = img.get_RGBtoHSI();

    //Muestra el histograma del canal I de la HSI
    hist = img_hsi.get_channel(2).get_normalize(0,255).get_histogram(256,0,255);
    hist.display_graph();

    //Procesamiento final donde se normaliza se filtra multiples veces y luego se aplica umbralado
    //Todos sobre el canal de intensidad

    //Primero normalizo
    resultado = img_hsi.get_channel(2).normalize(0,255);
    resultado.display("Canal I Normalizado");

    //Ecualizo el resultado
    resultado = resultado.get_equalize(256);
    resultado.display("Ecualizando");

    //Separo los grises medios claros de los grises medios oscuros
    resultado = transformacion(resultado,(generar_lut_logb(float(1),0)));
    resultado.display("Aplicando una lut");

    //Aplicacion de mascaras de promediado

    //Mascara para detalles grandes
    int pasadas = 10;
    for (int i = 0 ; i <=pasadas ; i++){
        resultado = resultado.get_convolve(mask(3));
    }
    //Mascara para detalles chico
    pasadas = 1;
    for (int i = 0 ; i <=pasadas ; i++){
        resultado = resultado.get_convolve(mask(9));
    }

    resultado.display("Canal I Fitrado");
    hist = resultado.get_histogram(256,0,255);
    hist.display_graph("Histograma Canal I Filtrado");

    //Aplico el umbralado
    resultado = resultado.get_threshold(170);

    //Muestro la mascara obtenida
    resultado.display("Mascara Final");

    //poner rojo en la zona
    float areaLimpia=0; //acumulo la cantidad de pixel que tiene el area desmontada marcada de rojo
    //Trabajo sobre una auxiliar
    img_hsi_p = img_hsi;
    cimg_forXYZ(img_hsi,i,j,k){
        if(resultado(i,j)==1){
        img_hsi_p(i,j,k,0)=0.0;
        img_hsi_p(i,j,k,1)=1.0;
        areaLimpia+=areaPixel;
        }
    }

    //Muestra los resultados de los calculas de Area (en hectareas)
    cout<<"Area Total "<< areaTotal*0.0001<<" hectareas - Area Limpia "<<areaLimpia*0.0001<<" hectareas " <<endl;

    //Carga los canales en una lista y muestra el resultado final
    CImgList<float> lista(img,img_hsi.get_channel(0),img_hsi.get_channel(1),img_hsi.get_channel(2),img_hsi_p.get_HSItoRGB());
    lista.display("Original - H - S - I - Imagen Final");

    return 0;
}
Пример #17
0
void validateKeyPoints(const std::vector<cv::KeyPoint> & in_keypoints, const cv::Mat &in_mask, const cv::Mat & depth,
                       const cv::Mat &in_K, const cv::Mat & descriptors, std::vector<cv::KeyPoint> & final_keypoints,
                       cv::Mat &final_points, cv::Mat & final_descriptors) {
  cv::Mat K;
  in_K.convertTo(K, CV_32FC1);
  size_t n_points = descriptors.rows;
  cv::Mat clean_descriptors = cv::Mat(descriptors.size(), descriptors.type());
  cv::Mat_<cv::Vec2f> clean_points(1, n_points);
  final_keypoints.clear();
  final_keypoints.reserve(n_points);

  cv::Mat_<uchar> mask;
  in_mask.convertTo(mask, CV_8U);
  // Erode just because of the possible rescaling
  cv::erode(mask, mask, cv::Mat(), cv::Point(-1, -1), 4);

  int width = mask.cols, height = mask.rows;
  size_t clean_row_index = 0;
  for (size_t keypoint_index = 0; keypoint_index < n_points; ++keypoint_index) {
    // First, make sure that the keypoint belongs to the mask
    const cv::KeyPoint & in_keypoint = in_keypoints[keypoint_index];
    unsigned int x = roundWithinBounds(in_keypoint.pt.x, 0, width), y = roundWithinBounds(in_keypoint.pt.y, 0, height);
    float z;
    bool is_good = false;
    if (mask(y, x))
      is_good = true;
    else {
      // If the keypoint does not belong to the mask, look in a slightly bigger neighborhood
      int window_size = 2;
      float min_dist_sq = std::numeric_limits<float>::max();
      // Look into neighborhoods of different sizes to see if we have a point in the mask
      for (unsigned int i = roundWithinBounds(x - window_size, 0, width);
          i <= roundWithinBounds(x + window_size, 0, width); ++i)
        for (unsigned int j = roundWithinBounds(y - window_size, 0, height);
            j <= roundWithinBounds(y + window_size, 0, height); ++j)
          if (mask(j, i)) {
            float dist_sq = (i - in_keypoint.pt.x) * (i - in_keypoint.pt.x)
                + (j - in_keypoint.pt.y) * (j - in_keypoint.pt.y);
            if (dist_sq < min_dist_sq) {
              // If the point is in the mask and the closest from the keypoint
              x = i;
              y = j;
              min_dist_sq = dist_sq;
              is_good = true;
            }
          }
    }
    if (!is_good)
      continue;

    // Now, check that the depth of the keypoint is valid
    switch (depth.depth()) {
      case CV_16U:
        z = depth.at<uint16_t>(y, x);
        if (!cv::isValidDepth(uint16_t(z)))
          is_good = false;
        z /= 1000;
        break;
      case CV_16S:
        z = depth.at<int16_t>(y, x);
        if (!cv::isValidDepth(int16_t(z)))
          is_good = false;
        z /= 1000;
        break;
      case CV_32F:
        z = depth.at<float>(y, x);
        if (!cv::isValidDepth(float(z)))
          is_good = false;
        break;
      default:
        continue;
        break;
    }

    if (!is_good)
      continue;

    // Store the keypoint and descriptor
    clean_points.at<cv::Vec2f>(0, clean_row_index) = cv::Vec2f(x, y);
    cv::Mat clean_descriptor_row = clean_descriptors.row(clean_row_index++);
    descriptors.row(keypoint_index).copyTo(clean_descriptor_row);
    final_keypoints.push_back(in_keypoint);
  }

  if (clean_row_index > 0) {
    clean_points.colRange(0, clean_row_index).copyTo(final_points);
    clean_descriptors.rowRange(0, clean_row_index).copyTo(final_descriptors);
  }
}
Пример #18
0
void LightMaps::paintEvent(QPaintEvent *event)
{
    QPainter p;
    p.begin(this);
    m_normalMap->render(&p, event->rect());
    p.setPen(Qt::black);
#if defined(Q_OS_SYMBIAN)
    QFont font = p.font();
    font.setPixelSize(13);
    p.setFont(font);
#endif
    p.drawText(rect(),  Qt::AlignBottom | Qt::TextWordWrap,
                "Map data CCBYSA 2009 OpenStreetMap.org contributors");
    p.end();

    if (zoomed) {
        int dim = qMin(width(), height());
        int magnifierSize = qMin(MAX_MAGNIFIER, dim * 2 / 3);
        int radius = magnifierSize / 2;
        int ring = radius - 15;
        QSize box = QSize(magnifierSize, magnifierSize);

        // reupdate our mask
        if (maskPixmap.size() != box) {
            maskPixmap = QPixmap(box);
            maskPixmap.fill(Qt::transparent);

            QRadialGradient g;
            g.setCenter(radius, radius);
            g.setFocalPoint(radius, radius);
            g.setRadius(radius);
            g.setColorAt(1.0, QColor(255, 255, 255, 0));
            g.setColorAt(0.5, QColor(128, 128, 128, 255));

            QPainter mask(&maskPixmap);
            mask.setRenderHint(QPainter::Antialiasing);
            mask.setCompositionMode(QPainter::CompositionMode_Source);
            mask.setBrush(g);
            mask.setPen(Qt::NoPen);
            mask.drawRect(maskPixmap.rect());
            mask.setBrush(QColor(Qt::transparent));
            mask.drawEllipse(g.center(), ring, ring);
            mask.end();
        }

        QPoint center = dragPos - QPoint(0, radius);
        center = center + QPoint(0, radius / 2);
        QPoint corner = center - QPoint(radius, radius);

        QPoint xy = center * 2 - QPoint(radius, radius);

        // only set the dimension to the magnified portion
        if (zoomPixmap.size() != box) {
            zoomPixmap = QPixmap(box);
            zoomPixmap.fill(Qt::lightGray);
        }
        if (true) {
            QPainter p(&zoomPixmap);
            p.translate(-xy);
            m_largeMap->render(&p, QRect(xy, box));
            p.end();
        }

        QPainterPath clipPath;
        clipPath.addEllipse(center, ring, ring);

        QPainter p(this);
        p.setRenderHint(QPainter::Antialiasing);
        p.setClipPath(clipPath);
        p.drawPixmap(corner, zoomPixmap);
        p.setClipping(false);
        p.drawPixmap(corner, maskPixmap);
        p.setPen(Qt::gray);
        p.drawPath(clipPath);
    }
    if (invert) {
        QPainter p(this);
        p.setCompositionMode(QPainter::CompositionMode_Difference);
        p.fillRect(event->rect(), Qt::white);
        p.end();
    }
}
Пример #19
0
CPLErr JPEG_Codec::CompressJPEG(buf_mgr &dst, buf_mgr &src)
#endif

{
    // The cinfo should stay open and reside in the DS, since it can be left initialized
    // It saves some time because it has the tables initialized
    struct jpeg_compress_struct cinfo;
    MRFJPEGStruct sJPEGStruct;
    struct jpeg_error_mgr sJErr;
    ILSize sz = img.pagesize;

    jpeg_destination_mgr jmgr;
    jmgr.next_output_byte = (JOCTET *)dst.buffer;
    jmgr.free_in_buffer = dst.size;
    jmgr.init_destination = init_or_terminate_destination;
    jmgr.empty_output_buffer = empty_output_buffer;
    jmgr.term_destination = init_or_terminate_destination;

    memset(&cinfo, 0, sizeof(cinfo));

    // Look at the source of this, some interesting tidbits
    cinfo.err = jpeg_std_error(&sJErr);
    sJErr.error_exit = errorExit;
    sJErr.emit_message = emitMessage;
    cinfo.client_data = (void *)&(sJPEGStruct);
    jpeg_create_compress(&cinfo);
    cinfo.dest = &jmgr;

    // The page specific info, size and color spaces
    cinfo.image_width = sz.x;
    cinfo.image_height = sz.y;
    cinfo.input_components = sz.c;
    switch (cinfo.input_components) {
    case 1:cinfo.in_color_space = JCS_GRAYSCALE; break;
    case 3:cinfo.in_color_space = JCS_RGB; break;  // Stored as YCbCr 4:2:0 by default
    default:
        cinfo.in_color_space = JCS_UNKNOWN; // 2, 4-10 bands
    }

    // Set all required fields and overwrite the ones we want to change
    jpeg_set_defaults(&cinfo);

    // Override certain settings
    jpeg_set_quality(&cinfo, img.quality, TRUE);
    cinfo.dct_method = JDCT_FLOAT; // Pretty fast and precise
    cinfo.optimize_coding = optimize; // Set "OPTIMIZE=TRUE" in OPTIONS, default for 12bit

    // Do we explicitly turn off the YCC color and downsampling?

    if (cinfo.in_color_space == JCS_RGB) {
        if (rgb) {  // Stored as RGB
            jpeg_set_colorspace(&cinfo, JCS_RGB);  // Huge files
        }
        else if (sameres) { // YCC, somewhat larger files with improved color spatial detail
            cinfo.comp_info[0].h_samp_factor = 1;
            cinfo.comp_info[0].v_samp_factor = 1;

            // Enabling these lines will make the color components use the same tables as Y, even larger file with slightly better color depth detail
            // cinfo.comp_info[1].quant_tbl_no = 0;
            // cinfo.comp_info[2].quant_tbl_no = 0;

            // cinfo.comp_info[1].dc_tbl_no = 0;
            // cinfo.comp_info[2].dc_tbl_no = 0;

            // cinfo.comp_info[1].ac_tbl_no = 0;
            // cinfo.comp_info[2].ac_tbl_no = 0;
        }
    }

    int linesize = cinfo.image_width * cinfo.input_components * ((cinfo.data_precision == 8) ? 1 : 2);
    JSAMPROW *rowp = (JSAMPROW *)CPLMalloc(sizeof(JSAMPROW)*sz.y);
    if (!rowp) {
        CPLError(CE_Failure, CPLE_AppDefined, "MRF: JPEG compression error");
        jpeg_destroy_compress(&cinfo);
        return CE_Failure;
    }

    for (int i = 0; i < sz.y; i++)
        rowp[i] = (JSAMPROW)(src.buffer + i*linesize);

    if (setjmp(sJPEGStruct.setjmpBuffer)) {
        CPLError(CE_Failure, CPLE_AppDefined, "MRF: JPEG compression error");
        jpeg_destroy_compress(&cinfo);
        CPLFree(rowp);
        return CE_Failure;
    }

    // Build a bitmaps of the black pixels
    // If there are any black pixels, write a compressed mask in APP3 "C3Mask" chunk

    // Mask is initialized to all pixels valid
    BitMask mask(sz.x, sz.y);
    storage_manager mbuffer = { CHUNK_NAME, CHUNK_NAME_SIZE };

    int nzeros = (cinfo.data_precision == 8) ?
        update_mask(mask, reinterpret_cast<GByte *>(src.buffer), sz.c) :
        update_mask(mask, reinterpret_cast<GUInt16 *>(src.buffer), sz.c);

    // In case we need to build a Zen chunk
    char *buffer = nullptr; 

    if (nzeros != 0) { // build the Zen chunk
        mbuffer.size = 2 * mask.size() + CHUNK_NAME_SIZE;
        buffer = reinterpret_cast<char *>(CPLMalloc(mbuffer.size));
        if (!buffer) {
            jpeg_destroy_compress(&cinfo);
            CPLFree(rowp);
            CPLError(CE_Failure, CPLE_OutOfMemory, "MRF: JPEG Zen mask compression");
            return CE_Failure;
        }

        memcpy(buffer, CHUNK_NAME, CHUNK_NAME_SIZE);
        mbuffer.buffer = buffer + CHUNK_NAME_SIZE;
        mbuffer.size -= CHUNK_NAME_SIZE;

        RLEC3Packer c3;
        mask.set_packer(&c3);
        if (!mask.store(&mbuffer)) {
            CPLError(CE_Failure, CPLE_AppDefined, "MRF: JPEG Zen mask compression");
            CPLFree(rowp);
            CPLFree(buffer);
            return CE_Failure;
        }

        // Change the buffer pointer to include the signature, on output the size is the compressed size
        mbuffer.buffer = buffer;
        mbuffer.size += CHUNK_NAME_SIZE;

        // Check that the size fits in one JPEG chunk
        if (mbuffer.size + 2 + CHUNK_NAME_SIZE > 65535) {
            // Should split it in multiple chunks, for now mark this tile as all data and emit a warning
            CPLError(CE_Warning, CPLE_NotSupported, "MRF: JPEG Zen mask too large");
            mbuffer.size = CHUNK_NAME_SIZE; // Write just the signature
        }
    }

    // Everything is ready
    jpeg_start_compress(&cinfo, TRUE);

    // Always write the Zen app chunk, App3
    jpeg_write_marker(&cinfo, JPEG_APP0 + 3,
      reinterpret_cast<JOCTET *>(mbuffer.buffer),
      static_cast<unsigned int>(mbuffer.size));

    jpeg_write_scanlines(&cinfo, rowp, sz.y);
    jpeg_finish_compress(&cinfo);
    jpeg_destroy_compress(&cinfo);

    CPLFree(rowp);
    CPLFree(buffer);     // Safe to call on null

    // Figure out the size
    dst.size -= jmgr.free_in_buffer;

    return CE_None;
}
Пример #20
0
bool yee_compare(CompareArgs &args)
{
    if ((args.image_a_->get_width()  != args.image_b_->get_width()) or
        (args.image_a_->get_height() != args.image_b_->get_height()))
    {
        args.error_string_ = "Image dimensions do not match\n";
        return false;
    }

    const auto w = args.image_a_->get_width();
    const auto h = args.image_a_->get_height();
    const auto dim = w * h;

    auto identical = true;
    for (auto i = 0u; i < dim; i++)
    {
        if (args.image_a_->get(i) != args.image_b_->get(i))
        {
            identical = false;
            break;
        }
    }
    if (identical)
    {
        args.error_string_ = "Images are binary identical\n";
        return true;
    }

    // Assuming colorspaces are in Adobe RGB (1998) convert to XYZ.
    std::vector<float> a_lum(dim);
    std::vector<float> b_lum(dim);

    std::vector<float> a_a(dim);
    std::vector<float> b_a(dim);
    std::vector<float> a_b(dim);
    std::vector<float> b_b(dim);

    if (args.verbose_)
    {
        std::cout << "Converting RGB to XYZ\n";
    }

    const auto gamma = args.gamma_;
    const auto luminance = args.luminance_;

    #pragma omp parallel for shared(args, a_lum, b_lum, a_a, a_b, b_a, b_b)
    for (auto y = 0; y < static_cast<ptrdiff_t>(h); y++)
    {
        for (auto x = 0u; x < w; x++)
        {
            const auto i = x + y * w;
            const auto a_color_r = powf(args.image_a_->get_red(i) / 255.0f,
                                        gamma);
            const auto a_color_g = powf(args.image_a_->get_green(i) / 255.0f,
                                        gamma);
            const auto a_color_b = powf(args.image_a_->get_blue(i) / 255.0f,
                                        gamma);
            float a_x;
            float a_y;
            float a_z;
            adobe_rgb_to_xyz(a_color_r, a_color_g, a_color_b, a_x, a_y, a_z);
            float l;
            xyz_to_lab(a_x, a_y, a_z, l, a_a[i], a_b[i]);
            const auto b_color_r = powf(args.image_b_->get_red(i) / 255.0f,
                                        gamma);
            const auto b_color_g = powf(args.image_b_->get_green(i) / 255.0f,
                                        gamma);
            const auto b_color_b = powf(args.image_b_->get_blue(i) / 255.0f,
                                        gamma);
            float b_x;
            float b_y;
            float b_z;
            adobe_rgb_to_xyz(b_color_r, b_color_g, b_color_b, b_x, b_y, b_z);
            xyz_to_lab(b_x, b_y, b_z, l, b_a[i], b_b[i]);
            a_lum[i] = a_y * luminance;
            b_lum[i] = b_y * luminance;
        }
    }

    if (args.verbose_)
    {
        std::cout << "Constructing Laplacian Pyramids\n";
    }

    const LPyramid la(a_lum, w, h);
    const LPyramid lb(b_lum, w, h);

    const auto num_one_degree_pixels =
        to_degrees(2 *
                   std::tan(args.field_of_view_ * to_radians(.5f)));
    const auto pixels_per_degree = w / num_one_degree_pixels;

    if (args.verbose_)
    {
        std::cout << "Performing test\n";
    }

    const auto adaptation_level = adaptation(num_one_degree_pixels);

    float cpd[MAX_PYR_LEVELS];
    cpd[0] = 0.5f * pixels_per_degree;
    for (auto i = 1u; i < MAX_PYR_LEVELS; i++)
    {
        cpd[i] = 0.5f * cpd[i - 1];
    }
    const auto csf_max = csf(3.248f, 100.0f);

    static_assert(MAX_PYR_LEVELS > 2,
                  "MAX_PYR_LEVELS must be greater than 2");

    float f_freq[MAX_PYR_LEVELS - 2];
    for (auto i = 0u; i < MAX_PYR_LEVELS - 2; i++)
    {
        f_freq[i] = csf_max / csf(cpd[i], 100.0f);
    }

    auto pixels_failed = 0u;
    auto error_sum = 0.;

    #pragma omp parallel for reduction(+ : pixels_failed, error_sum) \
        shared(args, a_a, a_b, b_a, b_b, cpd, f_freq)
    for (auto y = 0; y < static_cast<ptrdiff_t>(h); y++)
    {
        for (auto x = 0u; x < w; x++)
        {
            const auto index = y * w + x;
            const auto adapt = std::max((la.get_value(x, y, adaptation_level) +
                                         lb.get_value(x, y, adaptation_level)) * 0.5f,
                                        1e-5f);
            auto sum_contrast = 0.f;
            auto factor = 0.f;
            for (auto i = 0u; i < MAX_PYR_LEVELS - 2; i++)
            {
                const auto n1 =
                    fabsf(la.get_value(x, y, i) - la.get_value(x, y, i + 1));
                const auto n2 =
                    fabsf(lb.get_value(x, y, i) - lb.get_value(x, y, i + 1));
                const auto numerator = std::max(n1, n2);
                const auto d1 = fabsf(la.get_value(x, y, i + 2));
                const auto d2 = fabsf(lb.get_value(x, y, i + 2));
                const auto denominator = std::max(std::max(d1, d2), 1e-5f);
                const auto contrast = numerator / denominator;
                const auto f_mask = mask(contrast * csf(cpd[i], adapt));
                factor += contrast * f_freq[i] * f_mask;
                sum_contrast += contrast;
            }
            sum_contrast = std::max(sum_contrast, 1e-5f);
            factor /= sum_contrast;
            factor = std::min(std::max(factor, 1.f), 10.f);
            const auto delta =
                fabsf(la.get_value(x, y, 0) - lb.get_value(x, y, 0));
            error_sum += delta;
            auto pass = true;

            // pure luminance test
            if (delta > factor * tvi(adapt))
            {
                pass = false;
            }

            if (not args.luminance_only_)
            {
                // CIE delta E test with modifications
                auto color_scale = args.color_factor_;
                // ramp down the color test in scotopic regions
                if (adapt < 10.0f)
                {
                    // Don't do color test at all.
                    color_scale = 0.0;
                }
                const auto da = a_a[index] - b_a[index];
                const auto db = a_b[index] - b_b[index];
                const auto delta_e = (da * da + db * db) * color_scale;
                error_sum += delta_e;
                if (delta_e > factor)
                {
                    pass = false;
                }
            }

            if (not pass)
            {
                pixels_failed++;
                if (args.image_difference_)
                {
                    args.image_difference_->set(255, 0, 0, 255, index);
                }
            }
            else
            {
                if (args.image_difference_)
                {
                    args.image_difference_->set(0, 0, 0, 255, index);
                }
            }
        }
    }

    const auto error_sum_buff =
        std::to_string(error_sum) + " error sum\n";

    const auto different =
        std::to_string(pixels_failed) + " pixels are different\n";

    // Always output image difference if requested.
    if (args.image_difference_)
    {
        args.image_difference_->write_to_file(args.image_difference_->get_name());

        args.error_string_ += "Wrote difference image to ";
        args.error_string_ += args.image_difference_->get_name();
        args.error_string_ += "\n";
    }

    if (pixels_failed < args.threshold_pixels_)
    {
        args.error_string_ = "Images are perceptually indistinguishable\n";
        args.error_string_ += different;
        return true;
    }

    args.error_string_ = "Images are visibly different\n";
    args.error_string_ += different;
    if (args.sum_errors_)
    {
        args.error_string_ += error_sum_buff;
    }

    return false;
}
Пример #21
0
cfga_err_t
ap_seq_exec(apd_t *a, int cmd, int first, int last)
{
	int c;
	int skip;
	int suspend;
	int resume;
	cfga_err_t rc;
	int recover_f = CMD_NONE;	/* first recovery cmd */
	int recover_l = CMD_NONE;	/* last recovery cmd */


	suspend = 0;
	resume = 0;

	skip = a->opts.skip;

	/*
	 * The unassign step is skipped unless explicity requested
	 * either by a -x request or as an option to a disconnect
	 * request.
	 */
	if (cmd != CMD_UNASSIGN && ap_getopt(a, OPT_UNASSIGN) == 0)
		skip |= mask(CMD_UNASSIGN);

	/*
	 * Check for platform options
	 */
	rc = ap_platopts_check(a, first, last);

	if (rc != CFGA_OK) {
		goto done;
	}

	for (c = first; c <= last; c++) {
		if (mask(c) & skip) {
			ap_msg(a, MSG_SKIP, c, a->target);
			continue;
		}

		DBG("exec %s\n", ap_cmd_name(c));

		/*
		 * If the suspend operation does not
		 * succeed, resume any devices already
		 * suspended as well as the device on
		 * which the operation failed.
		 */
		switch (c) {
		case CMD_SUSPEND_CHECK:
			/*
			 * Check whether the user allows a suspend
			 * operation if the suspend is required.
			 * Next step is to allow RCM clients to
			 * interpose on the suspend operation.
			 */
			rc = ap_suspend_check(a, cmd,
			    first + 1, last, &suspend);
			break;
		case CMD_RCM_SUSPEND:
			if (suspend && ((rc = ap_rcm_ctl(a, c)) == CFGA_OK)) {
				/*
				 * Mark the fact that a suspend operation
				 * is required, and that RCM clients have
				 * allowed the suspend.
				 */
				ap_setopt(a, OPT_SUSPEND_OK);
				resume++;
			}
			break;
		case CMD_RCM_RESUME:
			if (resume) {
				(void) ap_rcm_ctl(a, c);
				resume--;
			}
			break;
		case CMD_RCM_OFFLINE:
		case CMD_RCM_CAP_DEL:
			rc = ap_rcm_ctl(a, c);
			break;
		case CMD_RCM_ONLINE:
		case CMD_RCM_CAP_ADD:
		case CMD_RCM_REMOVE:
		case CMD_RCM_CAP_NOTIFY:
			(void) ap_rcm_ctl(a, c);
			break;

#ifdef	__x86
		/*
		 * Disable fast reboot if a CPU/MEM/IOH hotplug event happens.
		 * Note: this is a temporary solution and will be revised when
		 * fast reboot can support CPU/MEM/IOH DR operations in the
		 * future.
		 *
		 * ACPI BIOS generates some static ACPI tables, such as MADT,
		 * SRAT and SLIT, to describe the system hardware configuration
		 * on power-on. When a CPU/MEM/IOH hotplug event happens, those
		 * static tables won't be updated and will become stale.
		 *
		 * If we reset the system by fast reboot, BIOS will have no
		 * chance to regenerate those staled static tables. Fast reboot
		 * can't tolerate such inconsistency between staled ACPI tables
		 * and real hardware configuration yet.
		 *
		 * A temporary solution is introduced to disable fast reboot if
		 * CPU/MEM/IOH hotplug event happens. This solution should be
		 * revised when fast reboot is enhanced to support CPU/MEM/IOH
		 * DR operations.
		 */
		case CMD_ASSIGN:
		case CMD_POWERON:
		case CMD_POWEROFF:
		case CMD_UNASSIGN:
			if (!fastreboot_disabled &&
			    scf_fastreboot_default_set_transient(B_FALSE) ==
			    SCF_SUCCESS) {
				fastreboot_disabled = 1;
			}
			/* FALLTHROUGH */
#endif	/* __x86 */

		default:
			rc = ap_ioctl(a, c);
			break;
		}

		if (rc != CFGA_OK)
			break;

	}
done:

	if (resume)
		(void) ap_rcm_ctl(a, CMD_RCM_RESUME);

	/*
	 * Check if any operations failed. If so, attempt to rollback
	 * to previously known states.
	 * Note: The rollback is currently limited to RCM operations.
	 */
	if (rc != CFGA_OK) {
		if (c == CMD_UNCONFIGURE ||
		    c == CMD_RCM_OFFLINE ||
		    c == CMD_RCM_CAP_DEL) {
			DBG("ap_seq_exec: %s failed\n", ap_cmd_name(c));

			switch (c) {
			case CMD_UNCONFIGURE:
				/*
				 * If the unconfigure operation fails, perform
				 * an RCM_ONLINE and RCM_CAP_NOTIFY only. This
				 * keeps RCM clients consistent with the domain.
				 */
				recover_f = CMD_RCM_ONLINE;
				recover_l = CMD_RCM_ONLINE;
				DBG_RECOVER_MSG(recover_f, recover_l);
				(void) ap_seq_exec(a, cmd, recover_f,
				    recover_l);

				recover_f = CMD_RCM_CAP_NOTIFY;
				recover_l = CMD_RCM_CAP_NOTIFY;
				DBG_RECOVER_MSG(recover_f, recover_l);
				(void) ap_seq_exec(a, cmd, recover_f,
				    recover_l);
				break;
			case CMD_RCM_OFFLINE:
				recover_f = CMD_RCM_ONLINE;
				recover_l = CMD_RCM_CAP_ADD;
				DBG_RECOVER_MSG(recover_f, recover_l);
				(void) ap_seq_exec(a, cmd, recover_f,
				    recover_l);
				break;
			case CMD_RCM_CAP_DEL:
				recover_f = CMD_RCM_CAP_ADD;
				recover_l = CMD_RCM_CAP_ADD;
				DBG_RECOVER_MSG(recover_f, recover_l);
				(void) ap_seq_exec(a, cmd, recover_f,
				    recover_l);
				break;
			default:
				break;
			}

			DBG("recovery complete!\n");
		}
	}
	return (rc);
}
Пример #22
0
// HWP entry point, comments in header
fapi::ReturnCode proc_chiplet_scominit(const fapi::Target & i_target)
{
    fapi::ReturnCode rc;
    uint32_t rc_ecmd = 0;

    fapi::TargetType target_type;
    std::vector<fapi::Target> initfile_targets;
    std::vector<fapi::Target> ex_targets;
    std::vector<fapi::Target> mcs_targets;
    uint8_t nx_enabled;
    uint8_t mcs_pos;
    uint8_t ex_pos;
    uint8_t num_ex_targets;
    uint8_t master_mcs_pos = 0xFF;
    fapi::Target master_mcs;
    uint8_t enable_xbus_resonant_clocking = 0x0;
    uint8_t i2c_slave_address = 0x0;
    uint8_t dual_capp_present = 0x0;

    ecmdDataBufferBase data(64);
    ecmdDataBufferBase cfam_data(32);
    ecmdDataBufferBase mask(64);

    bool               is_master = false;

    // mark HWP entry
    FAPI_INF("proc_chiplet_scominit: Start");

    do
    {
        rc = proc_check_master_sbe_seeprom(i_target, is_master);
        if (!rc.ok())
        {
            FAPI_ERR("proc_cen_ref_clk_enable: Error from proc_check_master_sbe_seeprom");
            break;
        }

        // obtain target type to determine which initfile(s) to execute
        target_type = i_target.getType();

        // chip level target
        if (target_type == fapi::TARGET_TYPE_PROC_CHIP)
        {
            // execute FBC SCOM initfile
            initfile_targets.push_back(i_target);
            FAPI_INF("proc_chiplet_scominit: Executing %s on %s",
                     PROC_CHIPLET_SCOMINIT_FBC_IF, i_target.toEcmdString());
            FAPI_EXEC_HWP(
                rc,
                fapiHwpExecInitFile,
                initfile_targets,
                PROC_CHIPLET_SCOMINIT_FBC_IF);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: Error from fapiHwpExecInitfile executing %s on %s",
                         PROC_CHIPLET_SCOMINIT_FBC_IF,
                         i_target.toEcmdString());
                break;
            }

            // execute PSI SCOM initfile
            FAPI_INF("proc_chiplet_scominit: Executing %s on %s",
                     PROC_CHIPLET_SCOMINIT_PSI_IF, i_target.toEcmdString());
            FAPI_EXEC_HWP(
                rc,
                fapiHwpExecInitFile,
                initfile_targets,
                PROC_CHIPLET_SCOMINIT_PSI_IF);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: Error from fapiHwpExecInitfile executing %s on %s",
                         PROC_CHIPLET_SCOMINIT_PSI_IF,
                         i_target.toEcmdString());
                break;
            }

            // execute TP bridge SCOM initfile
            FAPI_INF("proc_chiplet_scominit: Executing %s on %s",
                     PROC_CHIPLET_SCOMINIT_TPBRIDGE_IF, i_target.toEcmdString());
            FAPI_EXEC_HWP(
                rc,
                fapiHwpExecInitFile,
                initfile_targets,
                PROC_CHIPLET_SCOMINIT_TPBRIDGE_IF);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: Error from fapiHwpExecInitfile executing %s on %s",
                         PROC_CHIPLET_SCOMINIT_TPBRIDGE_IF,
                         i_target.toEcmdString());
                break;
            }

            // query NX partial good attribute
            rc = FAPI_ATTR_GET(ATTR_PROC_NX_ENABLE,
                               &i_target,
                               nx_enabled);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: Error querying ATTR_PROC_NX_ENABLE");
                break;
            }

            // apply NX/AS SCOM initfiles only if partial good attribute is set
            if (nx_enabled == fapi::ENUM_ATTR_PROC_NX_ENABLE_ENABLE)
            {
                // execute NX SCOM initfile
                FAPI_INF("proc_chiplet_scominit: Executing %s on %s",
                         PROC_CHIPLET_SCOMINIT_NX_IF, i_target.toEcmdString());
                FAPI_EXEC_HWP(
                    rc,
                    fapiHwpExecInitFile,
                    initfile_targets,
                    PROC_CHIPLET_SCOMINIT_NX_IF);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: Error from fapiHwpExecInitfile executing %s on %s",
                             PROC_CHIPLET_SCOMINIT_NX_IF,
                             i_target.toEcmdString());
                    break;
                }

                // execute CXA SCOM initfile
                FAPI_INF("proc_chiplet_scominit: Executing %s on %s",
                         PROC_CHIPLET_SCOMINIT_CXA_IF, i_target.toEcmdString());
                FAPI_EXEC_HWP(
                    rc,
                    fapiHwpExecInitFile,
                    initfile_targets,
                    PROC_CHIPLET_SCOMINIT_CXA_IF);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: Error from fapiHwpExecInitfile executing %s on %s",
                             PROC_CHIPLET_SCOMINIT_CXA_IF,
                             i_target.toEcmdString());
                    break;
                }

                // configure CXA APC master LCO settings
                rc = fapiGetChildChiplets(i_target,
                                          fapi::TARGET_TYPE_EX_CHIPLET,
                                          ex_targets,
                                          fapi::TARGET_STATE_FUNCTIONAL);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: Error from fapiGetChildChiplets (EX) on %s",
                             i_target.toEcmdString());
                    break;
                }

                // form valid LCO target list
                for (std::vector<fapi::Target>::iterator i = ex_targets.begin();
                     i != ex_targets.end();
                     i++)
                {
                    // determine EX chiplet number
                    rc = FAPI_ATTR_GET(ATTR_CHIP_UNIT_POS, &(*i), ex_pos);

                    if (!rc.ok())
                    {
                        FAPI_ERR("proc_chiplet_scominit: Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS) on %s",
                                 i->toEcmdString());
                        break;
                    }

                    rc_ecmd |= data.setBit(ex_pos-((ex_pos < 8)?(1):(3)));
                }
                if (!rc.ok())
                {
                    break;
                }

                num_ex_targets = ex_targets.size();
                rc_ecmd |= data.insertFromRight(
                    num_ex_targets,
                    CAPP_APC_MASTER_LCO_TARGET_MIN_START_BIT,
                    (CAPP_APC_MASTER_LCO_TARGET_MIN_END_BIT-
                     CAPP_APC_MASTER_LCO_TARGET_MIN_START_BIT+1));

                if (rc_ecmd)
                {
                    FAPI_ERR("proc_chiplet_scominit: Error 0x%x setting APC Master LCO Target register data buffer",
                             rc_ecmd);
                    rc.setEcmdError(rc_ecmd);
                    break;
                }

                rc = fapiPutScom(i_target,
                                 CAPP_APC_MASTER_LCO_TARGET_0x02013021,
                                 data);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: fapiPutScom error (CAPP_APC_MASTER_LCO_TARGET_0x02013021) on %s",
                             i_target.toEcmdString());
                    break;
                }

                // get dual CAPP presence attribute
                FAPI_DBG("proc_chiplet_scominit: Querying dual CAPP feature attribute");
                rc = FAPI_ATTR_GET(ATTR_CHIP_EC_FEATURE_DUAL_CAPP_PRESENT,
                                   &i_target,
                                   dual_capp_present);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: Error querying ATTR_CHIP_EC_FEATURE_DUAL_CAPP_PRESENT");
                    break;
                }
                
                if (dual_capp_present != 0)
                {
                    rc = fapiPutScom(i_target,
                                     CAPP1_APC_MASTER_LCO_TARGET_0x020131A1,
                                     data);
                    if (!rc.ok())
                    {
                        FAPI_ERR("proc_chiplet_scominit: fapiPutScom error (CAPP1_APC_MASTER_LCO_TARGET_0x020131A1) on %s",
                                 i_target.toEcmdString());
                        break;
                    }
                }

                // execute AS SCOM initfile
                FAPI_INF("proc_chiplet_scominit: Executing %s on %s",
                         PROC_CHIPLET_SCOMINIT_AS_IF, i_target.toEcmdString());
                FAPI_EXEC_HWP(
                    rc,
                    fapiHwpExecInitFile,
                    initfile_targets,
                    PROC_CHIPLET_SCOMINIT_AS_IF);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: Error from fapiHwpExecInitfile executing %s on %s",
                             PROC_CHIPLET_SCOMINIT_AS_IF,
                             i_target.toEcmdString());
                    break;
                }
            }
            else
            {
                FAPI_DBG("proc_chiplet_scominit: Skipping execution of %s/%s/%s (partial good)",
                         PROC_CHIPLET_SCOMINIT_NX_IF, PROC_CHIPLET_SCOMINIT_CXA_IF, PROC_CHIPLET_SCOMINIT_AS_IF);
            }

            // conditionally enable I2C Slave
            rc = FAPI_ATTR_GET(ATTR_I2C_SLAVE_ADDRESS,
                               &i_target,
                               i2c_slave_address);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: Error querying ATTR_I2C_SLAVE_ADDRESS on %s",
                         i_target.toEcmdString());
                break;
            }
            rc = fapiGetScom(i_target,
                             I2C_SLAVE_CONFIG_REG_0x000D0000,
                             data);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: fapiGetScom error (I2C_SLAVE_CONFIG_REG_0x000D0000) on %s",
                         i_target.toEcmdString());
                break;
            }
            if (i2c_slave_address)
            {
                FAPI_DBG("proc_chiplet_scominit: I2C Slave enabled (%s) address = %d",
                     i_target.toEcmdString(),i2c_slave_address);

                //set I2C address
                rc_ecmd |= data.insert(i2c_slave_address,0,7);

                // disable error state.  when this is enabled and there
                // is an error from I2CS it locks up the I2CS and no
                // more operations are allowed unless cleared
                // through FSI.  Not good for a FSPless system.
                rc_ecmd |= data.clearBit(23);

                // enable I2C interface
                rc_ecmd |= data.setBit(21);

            }
            else
            {
                FAPI_DBG("proc_chiplet_scominit: I2C Slave disabled (%s)",
                     i_target.toEcmdString());

                // disable I2C interface when attribute = 0x0
                rc_ecmd |= data.clearBit(21);
            }

            if (rc_ecmd)
            {
                FAPI_ERR("proc_chiplet_scominit: Error 0x%x setting I2C Slave register data buffer",
                         rc_ecmd);
                rc.setEcmdError(rc_ecmd);
                break;
            }

            rc = fapiPutScom(i_target,
                             I2C_SLAVE_CONFIG_REG_0x000D0000,
                             data);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: fapiPutScom error (I2C_SLAVE_CONFIG_REG_0x000D0000) on %s",
                         i_target.toEcmdString());
                break;
            }

            // conditionally enable resonant clocking for XBUS
            rc = FAPI_ATTR_GET(ATTR_CHIP_EC_FEATURE_XBUS_RESONANT_CLK_VALID,
                               &i_target,
                               enable_xbus_resonant_clocking);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: Error querying ATTR_CHIP_EC_FEATURE_XBUS_RESONANT_CLK_VALID on %s",
                         i_target.toEcmdString());
                break;
            }

            if (enable_xbus_resonant_clocking)
            {
                FAPI_DBG("proc_chiplet_scominit: Enabling XBUS resonant clocking");
                rc = fapiGetScom(i_target,
                                 MBOX_FSIGP6_0x00050015,
                                 data);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: fapiGetScom error (MBOX_FSIGP6_0x00050015) on %s",
                             i_target.toEcmdString());
                    break;
                }

                rc_ecmd |= data.insertFromRight(
                    XBUS_RESONANT_CLOCK_CONFIG,
                    MBOX_FSIGP6_XBUS_RESONANT_CLOCK_CONFIG_START_BIT,
                    (MBOX_FSIGP6_XBUS_RESONANT_CLOCK_CONFIG_END_BIT-
                     MBOX_FSIGP6_XBUS_RESONANT_CLOCK_CONFIG_START_BIT+1));

                if (rc_ecmd)
                {
                    FAPI_ERR("proc_chiplet_scominit: Error 0x%x setting FSI GP6 register data buffer",
                             rc_ecmd);
                    rc.setEcmdError(rc_ecmd);
                    break;
                }

                if (is_master) 
                {
                    rc = fapiPutScom(i_target,
                                 MBOX_FSIGP6_0x00050015,
                                 data);
                    if (!rc.ok())
                    {
                        FAPI_ERR("proc_chiplet_scominit: fapiPutScom error (MBOX_FSIGP6_0x00050015) on %s",
                             i_target.toEcmdString());
                        break;
                    }
                }
                else 
                {
                    cfam_data.insert(data, 0, 32, 0);
                    rc = fapiPutCfamRegister(i_target, CFAM_FSI_GP6_0x00002815, cfam_data);
                    if (rc)
                    {
                        FAPI_ERR("proc_cen_ref_clk_enable: fapiPutCfamRegister error (CFAM_FSI_GP8_0x00001017)");
                        break;
                    }
                }
            }

            // execute A/X/PCI/DMI FIR init SCOM initfile
            FAPI_INF("proc_chiplet_scominit: Executing %s on %s",
                     PROC_CHIPLET_SCOMINIT_A_X_PCI_DMI_IF, i_target.toEcmdString());
            FAPI_EXEC_HWP(
                rc,
                fapiHwpExecInitFile,
                initfile_targets,
                PROC_CHIPLET_SCOMINIT_A_X_PCI_DMI_IF);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: Error from fapiHwpExecInitfile executing %s on %s",
                         PROC_CHIPLET_SCOMINIT_A_X_PCI_DMI_IF,
                         i_target.toEcmdString());
                break;
            }

            // execute NV scominit file
            uint8_t exist_NV = 0x00;
            rc = FAPI_ATTR_GET(ATTR_CHIP_EC_FEATURE_NV_PRESENT, &i_target, exist_NV);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: Error getting attribute value ATTR_CHIP_EC_FEATURE_NV_PRESENT");
                break;
            }
            if (exist_NV)
            {
                // mask NPU FIR bit 27
                rc_ecmd = data.flushTo0();
                rc_ecmd = data.setBit(NPU_FIR_NTL_DL2TL_PARITY_ERR_BIT);
                if (rc_ecmd)
                {
                    FAPI_ERR("proc_chiplet_scominit: Error 0x%Xforming NPU FIR mask data buffer",
                  	   rc_ecmd);
                    rc.setEcmdError(rc_ecmd);
                    break;
                }
                rc = fapiPutScom(i_target, NPU_FIR_MASK_OR_0x08013D85, data);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: fapiPutScom error (NPU_FIR_MASK_OR_0x08013D85) on %s",
                             i_target.toEcmdString());
                    break;
                }

                FAPI_INF("proc_chiplet_scominit: Executing  %s on %s",
                         PROC_CHIPLET_SCOMINIT_NPU_IF, i_target.toEcmdString());
                FAPI_EXEC_HWP(
                        rc,
                        fapiHwpExecInitFile,
                        initfile_targets,
                        PROC_CHIPLET_SCOMINIT_NPU_IF);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: Error from fapiHwpExecInitfile executing %s on %s",
                             PROC_CHIPLET_SCOMINIT_NPU_IF,
                             i_target.toEcmdString());
                    break;
                }

                // cleanup FIR bit (NPU FIR bit 27) caused by NDL/NTL parity error
                rc_ecmd = data.invert();
                if (rc_ecmd)
                {
                    FAPI_ERR("proc_chiplet_scominit: Error 0x%Xforming NPU FIR cleanup data buffer",
                  	   rc_ecmd);
                    rc.setEcmdError(rc_ecmd);
                    break;
                }
                rc = fapiPutScom(i_target, NPU_FIR_AND_0x08013D81, data);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: fapiPutScom error (NPU_FIR_AND_0x08013D81) on %s",
                             i_target.toEcmdString());
                    break;
                }
                rc = fapiPutScom(i_target, NPU_FIR_MASK_AND_0x08013D84, data);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: fapiPutScom error (NPU_FIR_MASK_AND_0x08013D84) on %s",
                             i_target.toEcmdString());
                    break;
                }
            }
            else
            {
                FAPI_INF("proc_chiplet_scominit: NV link logic not present, scom initfile processing skipped");
            }

            // determine set of functional MCS chiplets
            rc = fapiGetChildChiplets(i_target,
                                      fapi::TARGET_TYPE_MCS_CHIPLET,
                                      mcs_targets,
                                      fapi::TARGET_STATE_FUNCTIONAL);
            if (!rc.ok())
            {
                FAPI_ERR("proc_chiplet_scominit: Error from fapiGetChildChiplets (MCS) on %s",
                         i_target.toEcmdString());
                break;
            }

            // apply MCS SCOM initfile only for functional chiplets
            for (std::vector<fapi::Target>::iterator i = mcs_targets.begin();
                 (i != mcs_targets.end()) && rc.ok();
                 i++)
            {
                // execute MCS SCOM initfile
                initfile_targets.clear();
                initfile_targets.push_back(*i);
                initfile_targets.push_back(i_target);
                FAPI_INF("proc_chiplet_scominit: Executing %s on %s",
                         PROC_CHIPLET_SCOMINIT_MCS_IF, i->toEcmdString());
                FAPI_EXEC_HWP(
                    rc,
                    fapiHwpExecInitFile,
                    initfile_targets,
                    PROC_CHIPLET_SCOMINIT_MCS_IF);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: Error from fapiHwpExecInitfile executing %s on %s",
                             PROC_CHIPLET_SCOMINIT_MCS_IF,
                             i->toEcmdString());
                    break;
                }

                // determine MCS position
                rc = FAPI_ATTR_GET(ATTR_CHIP_UNIT_POS, &(*i), mcs_pos);

                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS) on %s",
                             i->toEcmdString());
                    break;
                }

                if (mcs_pos < master_mcs_pos)
                {
                    fapi::Target cen_target_unused;
                    rc = fapiGetOtherSideOfMemChannel(*i,
                                                      cen_target_unused,
                                                      fapi::TARGET_STATE_FUNCTIONAL);
                    // use return code only to indicate presence of connected Centaur,
                    // do not propogate/emit error if not connected
                    if (rc.ok())
                    {
                        FAPI_DBG("Updating master_mcs_pos to %d", mcs_pos);
                        FAPI_DBG("  Target: %s", cen_target_unused.toEcmdString());
                        master_mcs = *i;
                        master_mcs_pos = mcs_pos;
                    }
                    else
                    {
                        rc = fapi::FAPI_RC_SUCCESS;
                    }
                }

            }
            if (!rc.ok())
            {
                break;
            }

            if (master_mcs.getType() == fapi::TARGET_TYPE_MCS_CHIPLET)
            {
                // set MCMODE0Q_ENABLE_CENTAUR_SYNC on first target only
                // (this bit is required to be set on at most one MCS/chip)
                rc_ecmd |= data.flushTo0();
                rc_ecmd |= data.setBit(MCSMODE0_EN_CENTAUR_SYNC_BIT);
                rc_ecmd |= mask.setBit(MCSMODE0_EN_CENTAUR_SYNC_BIT);

                // check buffer manipulation return codes
                if (rc_ecmd)
                {
                    FAPI_ERR("proc_chiplet_scominit: Error 0x%X setting up MCSMODE0 data buffer",
                             rc_ecmd);
                    rc.setEcmdError(rc_ecmd);
                    break;
                }

                // write register with updated content
                rc = fapiPutScomUnderMask(master_mcs,
                                          MCS_MCSMODE0_0x02011807,
                                          data,
                                          mask);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_chiplet_scominit: fapiPutScomUnderMask error (MCS_MCSMODE0_0x02011807) on %s",
                             master_mcs.toEcmdString());
                    break;
                }

            }
        }
        // unsupported target type
        else
        {
            FAPI_ERR("proc_chiplet_scominit: Unsupported target type");
            const fapi::Target & TARGET = i_target;
            FAPI_SET_HWP_ERROR(rc, RC_PROC_CHIPLET_SCOMINIT_INVALID_TARGET);
            break;
        }
    } while(0);

    // mark HWP exit
    FAPI_INF("proc_chiplet_scominit: End");
    return rc;
}
Пример #23
0
	void led2(bool on)
	{
		if(on) AVR32_GPIO.port[0].ovrs = mask(PIN_LED2); 
		else AVR32_GPIO.port[0].ovrc = mask(PIN_LED2); 
	}
Пример #24
0
int mri(
		float* img, 
		float complex* f, 
		float* mask, 
		float lambda,
		int N1,
		int N2)
{
	int i, j;

    // Use this to check the output of each API call
    cl_int status;

    // Retrieve the number of platforms
    cl_uint numPlatforms = 0;
    status = clGetPlatformIDs(0, NULL, &numPlatforms);

    // Allocate enough space for each platform
    cl_platform_id *platforms = NULL;
    platforms = (cl_platform_id*)malloc(
        numPlatforms*sizeof(cl_platform_id));

    // Fill in the platforms
    status = clGetPlatformIDs(numPlatforms, platforms, NULL);
    // Retrieve the number of devices
    cl_uint numDevices = 0;
    status = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_ALL, 0,
        NULL, &numDevices);

    // Allocate enough space for each device
    cl_device_id *devices;
    devices = (cl_device_id*)malloc(
        numDevices*sizeof(cl_device_id));

    // Fill in the devices
    status = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_ALL,
        numDevices, devices, NULL);

    // Create a context and associate it with the devices
    cl_context context;
    context = clCreateContext(NULL, numDevices, devices, NULL,
        NULL, &status);

    // Create a command queue and associate it with the device
    cl_command_queue cmdQueue;
    cmdQueue = clCreateCommandQueue(context, devices[0], 0,
        &status);

    // Create a buffer object that will contain the data
    // from the host array A
        
	float complex* f0	    = (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* dx	    = (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* dy	    = (float complex*) calloc(N1*N2,sizeof(float complex));

	float complex* dx_new   = (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* dy_new   = (float complex*) calloc(N1*N2,sizeof(float complex));

	float complex* dtildex	= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* dtildey	= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* u_fft2	= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* u		= (float complex*) calloc(N1*N2,sizeof(float complex));

	float complex* fftmul	= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* Lap		= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* diff		= (float complex*) calloc(N1*N2,sizeof(float complex));
    float complex *w1 = (float complex*)malloc(((N2-1)*(N2-1)+1)*sizeof(float complex));
	float complex *w2 = (float complex*)malloc(((N1-1)*(N1-1)+1)*sizeof(float complex));
	float complex *buff = (float complex*)malloc(N2*N1*sizeof(float complex));
       
    Lap(N1-1, N2-1)	= 0.f;
	Lap(N1-1, 0)	= 1.f; 
	Lap(N1-1, 1)	= 0.f;
	Lap(0, N2-1)	= 1.f;
	Lap(0, 0)		= -4.f; 
	Lap(0, 1)		= 1.f;
	Lap(1, N2-1)	= 0.f;
	Lap(1, 0)		= 1.f; 
	Lap(1, 1)		= 0.f;

    cl_mem cl_img = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(float), NULL, &status);
    cl_mem cl_mask = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(float), NULL, &status);
    cl_mem cl_f = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
    cl_mem cl_f0 = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_dx = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_dy = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);

	cl_mem cl_dx_new = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_dy_new = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);

	cl_mem cl_dtildex = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_dtildey = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_u_fft2 = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_u = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);

	cl_mem cl_fftmul = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_Lap = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_diff = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
    
    cl_mem cl_w1 = clCreateBuffer(context, CL_MEM_READ_WRITE, (N2*N2)*sizeof(cl_float2), NULL, &status);
    cl_mem cl_w2 = clCreateBuffer(context, CL_MEM_READ_WRITE, (N1*N1)*sizeof(cl_float2), NULL, &status);
    cl_mem cl_buff = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);

    status = clEnqueueWriteBuffer(cmdQueue, cl_mask, CL_FALSE, 0, N1*N2*sizeof(float), mask, 0, NULL, NULL);
    status = clEnqueueWriteBuffer(cmdQueue, cl_f, CL_FALSE, 0, N1*N2*sizeof(cl_float2), f, 0, NULL, NULL);
    status = clEnqueueWriteBuffer(cmdQueue, cl_Lap, CL_FALSE, 0, N1*N2*sizeof(cl_float2), Lap, 0, NULL, NULL);
        
	cl_program program = clCreateProgramWithSource(context, 1, 
        (const char**)&kernel, NULL, &status);
        
    status = clBuildProgram(program, numDevices, devices, NULL, NULL, NULL);
	cl_kernel ker;
	size_t globalWorkSize[2]={N1,N2};
	
	float sum = 0;

	for(i=0; i<N1; i++)
		for(j=0; j<N2; j++)
			sum += (SQR(crealf(f(i,j))/N1) + SQR(cimagf(f(i,j))/N1));
            
	float normFactor = 1.f/sqrtf(sum);
	float scale		 = sqrtf(N1*N2);

    ker = clCreateKernel(program, "loop1", &status);

    
    status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_f);
    status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_f0);
    status = clSetKernelArg(ker, 2, sizeof(cl_float2), &normFactor);
    status = clSetKernelArg(ker, 3, sizeof(int), &N1);
    status = clSetKernelArg(ker, 4, sizeof(int), &N2);
    
    
    
    
    status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
    w1[0] = 1;
	w2[0] = 1;
	dft_init(&w1, &w2, &buff, N1, N2);
    status = clEnqueueWriteBuffer(cmdQueue, cl_w1, CL_FALSE, 0, ((N2-1)*(N2-1)+1)*sizeof(cl_float2), w1, 0, NULL, NULL);
    status = clEnqueueWriteBuffer(cmdQueue, cl_w2, CL_FALSE, 0, ((N1-1)*(N1-1)+1)*sizeof(cl_float2), w2, 0, NULL, NULL);
    status = clEnqueueWriteBuffer(cmdQueue, cl_buff, CL_FALSE, 0, N1*N2*sizeof(cl_float2), buff, 0, NULL, NULL);

    ker = clCreateKernel(program, "dft1", &status);
    status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
    status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
    status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
    status = clSetKernelArg(ker, 5, sizeof(int), &N1);
    status = clSetKernelArg(ker, 6, sizeof(int), &N2);
    status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
                   if (status != CL_SUCCESS)
            	printf("error: %d\n", status); 
    ker = clCreateKernel(program, "dft2", &status);
    status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
    status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
    status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
    status = clSetKernelArg(ker, 5, sizeof(int), &N1);
    status = clSetKernelArg(ker, 6, sizeof(int), &N2);
    status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 
               if (status != CL_SUCCESS)
            	printf("error: %d\n", status); 
    ker = clCreateKernel(program, "loop2", &status);
    status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_fftmul);
    status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_mask);
    status = clSetKernelArg(ker, 3, sizeof(float), &lambda);
    status = clSetKernelArg(ker, 4, sizeof(int), &N1);
    status = clSetKernelArg(ker, 5, sizeof(int), &N2);
    status = clEnqueueNDRangeKernel(cmdQueue, ker,2, NULL, globalWorkSize, NULL, 0, NULL, NULL);    
    
    float complex *tmp = (float complex*)malloc(N2*N1*sizeof(float complex));
    float complex *tmp2 = (float complex*)malloc(N2*N1*sizeof(float complex));
    
    
    
	int OuterIter,iter;
	for(OuterIter= 0; OuterIter<MaxOutIter; OuterIter++) {
		for(iter = 0; iter<MaxIter; iter++) {
            ker = clCreateKernel(program, "loop3", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_dtildex);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_dtildey);
            status = clSetKernelArg(ker, 3, sizeof(int), &N1);
            status = clSetKernelArg(ker, 4, sizeof(int), &N2);

            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 

            ker = clCreateKernel(program, "dft1", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
            status = clSetKernelArg(ker, 5, sizeof(int), &N1);
            status = clSetKernelArg(ker, 6, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
             if (status != CL_SUCCESS)
            	printf("error: %d\n", status);
            	
            ker = clCreateKernel(program, "dft2", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
            status = clSetKernelArg(ker, 5, sizeof(int), &N1);
            status = clSetKernelArg(ker, 6, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 
            if (status != CL_SUCCESS)
            	printf("error: %d\n", status);
			//dft(diff, diff, w1, w2, buff, N1, N2);

            
            ker = clCreateKernel(program, "loop4", &status);
            int more = (iter == MaxIter - 1);

            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_fftmul);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_f);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_u_fft2);
            status = clSetKernelArg(ker, 4, sizeof(int), &N1);
            status = clSetKernelArg(ker, 5, sizeof(int), &N2);
            status = clSetKernelArg(ker, 6, sizeof(float), &scale);
            status = clSetKernelArg(ker, 7, sizeof(float), &lambda);
            status= clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 
            
            ker = clCreateKernel(program, "idft1", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_u);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_u_fft2);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
            status = clSetKernelArg(ker, 5, sizeof(int), &N1);
            status = clSetKernelArg(ker, 6, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
            
            ker = clCreateKernel(program, "idft2", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_u);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_u_fft2);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
            status = clSetKernelArg(ker, 5, sizeof(int), &N1);
            status = clSetKernelArg(ker, 6, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
            
         
            ker = clCreateKernel(program, "loop5", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_dx);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_dy);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_u);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_dtildex);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_dtildey);
            status = clSetKernelArg(ker, 5, sizeof(cl_mem), &cl_dx_new);
            status = clSetKernelArg(ker, 6, sizeof(cl_mem), &cl_dy_new);
            status = clSetKernelArg(ker, 7, sizeof(int), &N1);
            status = clSetKernelArg(ker, 8, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);

            
		}
        /*
          ker = clCreateKernel(program, "last_loop", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_f);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_f0);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_mask);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_u_fft2);
            status = clSetKernelArg(ker, 4, sizeof(float), &scale);
            status = clSetKernelArg(ker, 5, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
          if (status != CL_SUCCESS)
            	printf("error: %d\n", status);
          
          */
        clEnqueueReadBuffer(cmdQueue, cl_f, CL_TRUE, 0, N1*N2*sizeof(float), f, 0, NULL, NULL);    
        clEnqueueReadBuffer(cmdQueue, cl_f0, CL_TRUE, 0, N1*N2*sizeof(float), f0, 0, NULL, NULL);
        clEnqueueReadBuffer(cmdQueue, cl_u_fft2, CL_TRUE, 0, N1*N2*sizeof(float), u_fft2, 0, NULL, NULL);
        
        for(i=0;i<N1;i++) {
			for(j=0;j<N2;j++) {
				f(i,j) += f0(i,j) - mask(i,j)*u_fft2(i,j)/scale;  
			}
		}
        
        clEnqueueWriteBuffer(cmdQueue, cl_f, CL_TRUE, 0, N1*N2*sizeof(float), f, 0, NULL, NULL);
        
       
	}
    
    
            ker = clCreateKernel(program, "loop7", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_img);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_u);
            status = clSetKernelArg(ker, 2, sizeof(int), &N1);
            status = clSetKernelArg(ker, 3, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 


    clEnqueueReadBuffer(cmdQueue, cl_img, CL_TRUE, 0, N1*N2*sizeof(float), img, 0, NULL, NULL);
    clReleaseKernel(ker);
    clReleaseProgram(program);
    clReleaseCommandQueue(cmdQueue);
    clReleaseMemObject(cl_img);
    clReleaseMemObject(cl_mask);
    clReleaseMemObject(cl_f);
    clReleaseMemObject(cl_f0);
    clReleaseMemObject(cl_dx);
    clReleaseMemObject(cl_dy);
    clReleaseMemObject(cl_dx_new);
    clReleaseMemObject(cl_dy_new);
    clReleaseMemObject(cl_dtildex);
    clReleaseMemObject(cl_dtildey);
    clReleaseMemObject(cl_u_fft2);
    clReleaseMemObject(cl_u);
    clReleaseMemObject(cl_fftmul);
    clReleaseMemObject(cl_Lap);
    clReleaseMemObject(cl_diff);
    clReleaseMemObject(cl_w1);
    clReleaseMemObject(cl_w2);
    clReleaseMemObject(cl_buff);
    
    clReleaseContext(context);
    free(platforms);
    free(devices);
	free(w1);
	free(w2);
	free(buff);
	return 0;
}
Пример #25
0
	void iso_power_off() { AVR32_GPIO.port[0].ovrs = mask(PIN_ISO_POWER); }
Пример #26
0
// read in a list linking IPs, subnets & IP ranges to filter groups
// return 0 for success, -1 for failure, 1 for warning
int ipinstance::readIPMelangeList(const char *filename) {
	// load in the list file
	std::ifstream input ( filename );
	if (!input) {
		if (!is_daemonised) {
			std::cerr << "Error reading file (does it exist?): " << filename << std::endl;
		}
		syslog(LOG_ERR, "%s%s","Error reading file (does it exist?): ",filename);
		return -1;
	}

	// compile regexps for determining whether a list entry is an IP, a subnet (IP + mask), or a range
	RegExp matchIP, matchSubnet, matchRange;
#ifdef HAVE_PCRE
	matchIP.comp("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
	matchSubnet.comp("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
	matchRange.comp("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}-\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
#else
	matchIP.comp("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
	matchSubnet.comp("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
	matchRange.comp("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}-[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
#endif

	// read in the file
	String line;
	String key, value;
	char buffer[ 2048 ];
	bool warn = false;
	while (input) {
		if (!input.getline(buffer, sizeof( buffer ))) {
			break;
		}
		// ignore comments
		if (buffer[0] == '#')
			continue;
		// ignore blank lines
		if (strlen(buffer) < 10)
			continue;
		line = buffer;
		// split into key & value
		if (line.contains("=")) {
			key = line.before("=");
			key.removeWhiteSpace();
			value = line.after("filter");
		}
		else {
			if (!is_daemonised)
				std::cerr << "No filter group given; entry " << line << " in " << filename << std::endl;
			syslog(LOG_ERR, "No filter group given; entry %s in %s", line.toCharArray(), filename);
			warn = true;
			continue;
		}
#ifdef DGDEBUG
		std::cout << "key: " << key << std::endl;
		std::cout << "value: " << value.toInteger() << std::endl;
#endif
		if ((value.toInteger() < 1) || (value.toInteger() > o.filter_groups)) {
			if (!is_daemonised)
				std::cerr << "Filter group out of range; entry " << line << " in " << filename << std::endl;
			syslog(LOG_ERR, "Filter group out of range; entry %s in %s", line.toCharArray(), filename);
			warn = true;
			continue;
		}
		// store the IP address (numerically, not as a string) and filter group in either the IP list, subnet list or range list
		if (matchIP.match(key.toCharArray())) {
			struct in_addr address;
			if (inet_aton(key.toCharArray(), &address)) {
				iplist.push_back(ip(ntohl(address.s_addr),value.toInteger()-1));
			}
		}
		else if (matchSubnet.match(key.toCharArray())) {
			struct in_addr address;
			struct in_addr addressmask;
			String subnet(key.before("/"));
			String mask(key.after("/"));
			if (inet_aton(subnet.toCharArray(), &address) && inet_aton(mask.toCharArray(), &addressmask)) {
				subnetstruct s;
				int addr = ntohl(address.s_addr);
				s.mask = ntohl(addressmask.s_addr);
				// pre-mask the address for quick comparison
				s.maskedaddr = addr & s.mask;
				s.group = value.toInteger()-1;
				ipsubnetlist.push_back(s);
			}
		}
		else if (matchRange.match(key.toCharArray())) {
			struct in_addr addressstart;
			struct in_addr addressend;
			String start(key.before("-"));
			String end(key.after("-"));
			if (inet_aton(start.toCharArray(), &addressstart) && inet_aton(end.toCharArray(), &addressend)) {
				rangestruct r;
				r.startaddr = ntohl(addressstart.s_addr);
				r.endaddr = ntohl(addressend.s_addr);
				r.group = value.toInteger()-1;
				iprangelist.push_back(r);
			}
		}
		// hmmm. the key didn't match any of our regular expressions. output message & return a warning value.
		else {
			if (!is_daemonised)
				std::cerr << "Entry " << line << " in " << filename << " was not recognised as an IP address, subnet or range" << std::endl;
			syslog(LOG_ERR, "Entry %s in %s was not recognised as an IP address, subnet or range", line.toCharArray(), filename);
			warn = true;
		}
	}
	input.close();
#ifdef DGDEBUG
	std::cout << "starting sort" << std::endl;
#endif
	std::sort(iplist.begin(), iplist.end());
#ifdef DGDEBUG
	std::cout << "sort complete" << std::endl;
	std::cout << "ip list dump:" << std::endl;
	std::vector<ip>::const_iterator i = iplist.begin();
	while (i != iplist.end()) {
		std::cout << "IP: " << i->addr << " Group: " << i->group << std::endl;
		++i;
	}
	std::cout << "subnet list dump:" << std::endl;
	std::list<subnetstruct>::const_iterator j = ipsubnetlist.begin();
	while (j != ipsubnetlist.end()) {
		std::cout << "Masked IP: " << j->maskedaddr << " Mask: " << j->mask << " Group: " << j->group << std::endl;
		++j;
	}
	std::cout << "range list dump:" << std::endl;
	std::list<rangestruct>::const_iterator k = iprangelist.begin();
	while (k != iprangelist.end()) {
		std::cout << "Start IP: " << k->startaddr << " End IP: " << k->endaddr << " Group: " << k->group << std::endl;
		++k;
	}
#endif
	// return either warning or success
	return warn ? 1 : 0;
}
Пример #27
0
	void init()
	{
		AVR32_GPIO.port[0].gper = 
			mask(PIN_LED1) |
			mask(PIN_LED2) |
			mask(PIN_POWER_ON) |
			mask(PIN_POWER_FAULT) |
			mask(PIN_ISO_POWER);

		AVR32_GPIO.port[0].oder = 
			mask(PIN_LED1) |
			mask(PIN_LED2) |
			mask(PIN_POWER_ON) |
			mask(PIN_ISO_POWER);

		AVR32_GPIO.port[0].puer = 
			mask(PIN_POWER_FAULT);

		iso_power_off();
		ecg_power_off();

		AVR32_GPIO.port[0].ovrc = mask(PIN_LED1) | mask(PIN_LED2);
	}
Пример #28
0
int main(int argc, char **argv)
{
    MythBackendCommandLineParser cmdline;
    if (!cmdline.Parse(argc, argv))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_INVALID_CMDLINE;
    }

    if (cmdline.toBool("showhelp"))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_OK;
    }

    if (cmdline.toBool("showversion"))
    {
        cmdline.PrintVersion();
        return GENERIC_EXIT_OK;
    }

#ifndef _WIN32
    for (int i = UNUSED_FILENO; i < sysconf(_SC_OPEN_MAX) - 1; ++i)
        close(i);
    QCoreApplication a(argc, argv);
#else
    // MINGW application needs a window to receive messages
    // such as socket notifications :[
    QApplication a(argc, argv);
#endif
    QCoreApplication::setApplicationName(MYTH_APPNAME_MYTHBACKEND);

    pidfile = cmdline.toString("pidfile");
    int retval = cmdline.Daemonize();
    if (retval != GENERIC_EXIT_OK)
        return retval;

    bool daemonize = cmdline.toBool("daemon");
    QString mask("general");
    if ((retval = cmdline.ConfigureLogging(mask, daemonize)) != GENERIC_EXIT_OK)
        return retval;

    if (daemonize)
        // Don't listen to console input if daemonized
        close(0);

    CleanupGuard callCleanup(cleanup);

#ifndef _WIN32
    QList<int> signallist;
    signallist << SIGINT << SIGTERM << SIGSEGV << SIGABRT << SIGBUS << SIGFPE
               << SIGILL;
    SignalHandler handler(signallist);
    signal(SIGHUP, SIG_IGN);
#endif

    gContext = new MythContext(MYTH_BINARY_VERSION);
    if (!gContext->Init(false))
    {
        LOG(VB_GENERAL, LOG_CRIT, "Failed to init MythContext.");
        return GENERIC_EXIT_NO_MYTHCONTEXT;
    }

    setHttpProxy();

    cmdline.ApplySettingsOverride();

    if (cmdline.toBool("event")         || cmdline.toBool("systemevent") ||
        cmdline.toBool("setverbose")    || cmdline.toBool("printsched") ||
        cmdline.toBool("testsched")     || cmdline.toBool("resched") ||
        cmdline.toBool("scanvideos")    || cmdline.toBool("clearcache") ||
        cmdline.toBool("printexpire")   || cmdline.toBool("setloglevel"))
    {
        gCoreContext->SetBackend(false);
        return handle_command(cmdline);
    }

    gCoreContext->SetBackend(true);
    retval = run_backend(cmdline);
    return retval;
}
Пример #29
0
BOOL CALLBACK selection_properties_config_t::on_message(HWND wnd, UINT msg, WPARAM wp, LPARAM lp)
{
	switch (msg)
	{
	case WM_INITDIALOG:
	{
		pfc::vartoggle_t<bool> init(m_initialising, true);

		HWND wnd_fields = m_field_list.create_in_dialog_units(wnd, ui_helpers::window_position_t(21, 17, 226, 150));
		SetWindowPos(wnd_fields, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
		ShowWindow(wnd_fields, SW_SHOWNORMAL);

		HWND wnd_lv = GetDlgItem(wnd, IDC_INFOSECTIONS);
		ListView_SetExtendedListViewStyleEx(wnd_lv, LVS_EX_CHECKBOXES, LVS_EX_CHECKBOXES);
		g_set_listview_window_explorer_theme(wnd_lv);

		RECT rc;
		GetClientRect(wnd_lv, &rc);
		ListView_InsertColumnText(wnd_lv, 0, L"", RECT_CX(rc));

		t_size i, count = tabsize(g_info_sections);
		for (i = 0; i < count; i++)
		{
			ListView_InsertItemText(wnd_lv, i, 0, g_info_sections[i].name);
			ListView_SetCheckState(wnd_lv, i, (m_info_sections_mask & (1 << g_info_sections[i].id)) ? TRUE : FALSE);
		}

		HWND wnd_combo = GetDlgItem(wnd, IDC_EDGESTYLE);
		ComboBox_AddString(wnd_combo, L"None");
		ComboBox_AddString(wnd_combo, L"Sunken");
		ComboBox_AddString(wnd_combo, L"Grey");
		ComboBox_SetCurSel(wnd_combo, m_edge_style);

		Button_SetCheck(GetDlgItem(wnd, IDC_SHOWCOLUMNS), m_show_columns ? BST_CHECKED : BST_UNCHECKED);
		Button_SetCheck(GetDlgItem(wnd, IDC_SHOWGROUPS), m_show_groups ? BST_CHECKED : BST_UNCHECKED);
	}
	break;
	case WM_DESTROY:
	{
		m_field_list.destroy();
	}
	break;
	case WM_ERASEBKGND:
		SetWindowLongPtr(wnd, DWL_MSGRESULT, TRUE);
		return TRUE;
	case WM_PAINT:
		ui_helpers::innerWMPaintModernBackground(wnd, GetDlgItem(wnd, IDOK));
		return TRUE;
	case WM_CTLCOLORSTATIC:
		SetBkColor((HDC)wp, GetSysColor(COLOR_WINDOW));
		SetTextColor((HDC)wp, GetSysColor(COLOR_WINDOWTEXT));
		return (BOOL)GetSysColorBrush(COLOR_WINDOW);
	case WM_NOTIFY:
	{
		LPNMHDR lpnm = (LPNMHDR)lp;
		switch (lpnm->idFrom)
		{
		case IDC_INFOSECTIONS:
			switch (lpnm->code)
			{
			case LVN_ITEMCHANGED:
			{
				LPNMLISTVIEW lpnmlv = (LPNMLISTVIEW)lp;
				if (!m_initialising && lpnmlv->iItem < tabsize(g_info_sections) && (lpnmlv->uChanged & LVIF_STATE))
				{
					m_info_sections_mask = m_info_sections_mask & ~(1 << g_info_sections[lpnmlv->iItem].id);

					//if (((((UINT)(lpnmlv->uNewState & LVIS_STATEIMAGEMASK )) >> 12) -1))
					if (ListView_GetCheckState(lpnm->hwndFrom, lpnmlv->iItem))
						m_info_sections_mask = m_info_sections_mask | (1 << g_info_sections[lpnmlv->iItem].id);

				}
			}
			break;
			};
			break;
		};
	}
	break;
	case WM_COMMAND:
		switch (LOWORD(wp))
		{
		case IDOK:
			EndDialog(wnd, 1);
			break;
		case IDCANCEL:
			EndDialog(wnd, 0);
			break;
		case IDC_SHOWCOLUMNS:
			m_show_columns = Button_GetCheck((HWND)lp) != 0;
			break;
		case IDC_SHOWGROUPS:
			m_show_groups = Button_GetCheck((HWND)lp) != 0;
			break;
		case IDC_EDGESTYLE:
			switch (HIWORD(wp))
			{
			case CBN_SELCHANGE:
				m_edge_style = ComboBox_GetCurSel((HWND)lp);
				break;
			}
			break;
		case IDC_UP:
		{
			if (m_field_list.get_selection_count(2) == 1)
			{
				t_size index = 0, count = m_field_list.get_item_count();
				while (!m_field_list.get_item_selected(index) && index < count) index++;
				if (index && m_fields.get_count())
				{
					m_fields.swap_items(index, index - 1);

					pfc::list_t<t_list_view::t_item_insert> items;
					m_field_list.get_insert_items(index - 1, 2, items);
					m_field_list.replace_items(index - 1, items);
					m_field_list.set_item_selected_single(index - 1);
				}
			}
		}
		break;
		case IDC_DOWN:
		{
			if (m_field_list.get_selection_count(2) == 1)
			{
				t_size index = 0, count = m_field_list.get_item_count();
				while (!m_field_list.get_item_selected(index) && index < count) index++;
				if (index + 1 < count && index + 1 < m_fields.get_count())
				{
					m_fields.swap_items(index, index + 1);

					pfc::list_t<t_list_view::t_item_insert> items;
					m_field_list.get_insert_items(index, 2, items);
					m_field_list.replace_items(index, items);
					m_field_list.set_item_selected_single(index + 1);
				}
			}
		}
		break;
		case IDC_NEW:
		{
			field_t temp;
			temp.m_name_friendly = "<enter name here>";
			temp.m_name = "<ENTER FIELD HERE>";
			t_size index = m_fields.add_item(temp);

			pfc::list_t<t_list_view::t_item_insert> items;
			m_field_list.get_insert_items(index, 1, items);
			m_field_list.insert_items(index, 1, items.get_ptr());
			m_field_list.set_item_selected_single(index);
			SetFocus(m_field_list.get_wnd());
			m_field_list.activate_inline_editing();

		}
		break;
		case IDC_REMOVE:
		{
			if (m_field_list.get_selection_count(2) == 1)
			{
				bit_array_bittable mask(m_field_list.get_item_count());
				m_field_list.get_selection_state(mask);
				//bool b_found = false;
				t_size index = 0, count = m_field_list.get_item_count();
				while (index < count)
				{
					if (mask[index]) break;
					index++;
				}
				if (index < count && index < m_fields.get_count())
				{
					m_fields.remove_by_idx(index);
					m_field_list.remove_item(index);
					t_size new_count = m_field_list.get_item_count();
					if (new_count)
					{
						if (index < new_count)
							m_field_list.set_item_selected_single(index);
						else if (index)
							m_field_list.set_item_selected_single(index - 1);
					}
				}
			}
		}
		break;
		}
		break;
	}
	return FALSE;
}
Пример #30
0
DirBrowser::DirBrowser(const char* path)
{
	BString<1024> mask("%s%c*.*", path, (int)PATH_SEPARATOR);
	m_file = FindFirstFileW(FileSystem::UtfPathToWidePath(mask), &m_findData);
	m_first = true;
}