コード例 #1
0
ファイル: vhd-util-read.c プロジェクト: borland667/blktap
static int
vhd_print_bitmap_extents(vhd_context_t *vhd, uint64_t sector, int count,
			 int hex)
{
	char *buf;
	uint64_t cur;
	int i, err, bit;
	uint32_t blk, bm_blk, sec;
	int64_t s, r;

	if (vhd_sectors_to_bytes(sector + count) > vhd->footer.curr_size) {
		printf("sector %s past end of file\n", conv(hex, sector));
		return -ERANGE;
	}

	bm_blk = -1;
	buf    = NULL;
	s = -1;
	r = 0;

	for (i = 0; i < count; i++) {
		cur = sector + i;
		blk = cur / vhd->spb;
		sec = cur % vhd->spb;

		if (blk != bm_blk) {
			bm_blk = blk;
			free(buf);
			buf = NULL;

			if (vhd->bat.bat[blk] != DD_BLK_UNUSED) {
				err = vhd_read_bitmap(vhd, blk, &buf);
				if (err)
					goto out;
			}
		}

		if (vhd->bat.bat[blk] == DD_BLK_UNUSED)
			bit = 0;
		else
			bit = vhd_bitmap_test(vhd, buf, sec);

		if (bit) {
			if (r == 0)
				s = cur;
			r++;
		} else {
			if (r > 0) {
				printf("%s ", conv(hex, s));
				printf("%s\n", conv(hex, r));
			}
			r = 0;
		}
	}
	if (r > 0) {
		printf("%s ", conv(hex, s));
		printf("%s\n", conv(hex, r));
	}

	err = 0;
 out:
	free(buf);
	return err;
}
コード例 #2
0
ファイル: CellView.drag.cpp プロジェクト: ModeenF/OpenSumIt
void CCellView::HandleDrop(BMessage *inMessage)
{
	long l;
	void * p;
	BPoint dp = inMessage->DropPoint();
	
	fDragIsAcceptable = false;
	
	if (inMessage->FindPointer("container", &p) == B_NO_ERROR)
	{
		key_info ki;
		get_key_info(&ki);
		
		CContainer *srcContainer;
		range srcRange, dstRange;
		CCellView *srcView;
		int action;
		
		srcContainer = (CContainer *)p;
		FailOSErr(inMessage->FindData("range", 'rang', (const void**)&p, &l), errMessageMissing);
		srcRange = *(range *)p;
		FailOSErr(inMessage->FindPointer("cellview", &p), errMessageMissing);
		srcView = (CCellView *)p;
		
		if (srcView != this)
			action = dragCopy;
		else
			action = dragMove;
		
		inMessage->FindBool("dragacopy", &fDragACopy);
		
		if (srcView == this &&
		    (ki.modifiers & B_CONTROL_KEY ||
			fDragACopy))
		{
			BPopUpMenu popup("dragpopup", false);
			popup.SetFont(be_plain_font);
			popup.AddItem(new BMenuItem(GetMessage(msgLinkHere), NULL));
			popup.AddItem(new BMenuItem(GetMessage(msgMoveHere), NULL));
			popup.AddItem(new BMenuItem(GetMessage(msgCopyHere), NULL));
			popup.AddSeparatorItem();
			popup.AddItem(new BMenuItem(GetMessage(msgCancel), NULL));
			
			BMenuItem *item = popup.Go(dp, false, true);
			int result = item ? popup.IndexOf(item) : -1;
			switch (result)
			{
				case 0: action = dragLink; break;
				case 1: action = dragMove; break;
				case 2: action = dragCopy; break;
				default:
					ClearAnts();
					fCurCell = fSelection.TopLeft();
					return;
			}
		}
	
		dstRange = srcRange;
		dstRange.OffsetBy(fCurCell.h - dstRange.left,
			fCurCell.v - dstRange.top);
		
		((CCellWindow *)Window())->
			RegisterCommand(new CDragCommand(this, srcContainer,
				fContainer, &srcRange, &dstRange, action));
	}
	else if (inMessage->FindData("text/plain", B_MIME_DATA, (const void **)&p, &l) == B_NO_ERROR)
	{
		cell dc;
		
		ConvertFromScreen(&dp);
		GetCellHitBy(dp, dc);
		
		BMemoryIO buf(p, l);
		CContainer *srcContainer = new CContainer;
		range srcRange, dstRange;
		
		CTextConverter conv(buf, srcContainer);
		conv.ConvertFromText(srcRange);
		
		dstRange = srcRange;
		dstRange.OffsetBy(dc.h - srcRange.left, dc.v - srcRange.top);
		
		((CCellWindow *)Window())->
			RegisterCommand(new CDragCommand(this, srcContainer,
				fContainer, &srcRange, &dstRange, dragMove));

		srcContainer->Release();
	}
	else
	{
		beep();
		ClearAnts();
		fCurCell = fSelection.TopLeft();
	}
} /* CCellView::HandleDrop */
コード例 #3
0
		void SofaHAPIHapticsDevice::onBeginAnimationStep(const double /*dt*/)
		{
			if (!device.get()) return;
			sofa::helper::AdvancedTimer::stepBegin("SofaHAPIHapticsDevice");

			sofa::helper::AdvancedTimer::stepBegin("DeviceValues");
			HAPI::HAPIHapticsDevice::DeviceValues dv = device->getDeviceValues();
			sofa::helper::AdvancedTimer::stepEnd("DeviceValues");

			sofa::helper::AdvancedTimer::stepBegin("XForm");
			/// COMPUTATION OF THE virtualTool 6D POSITION IN THE World COORDINATES
			Vec3d pos = conv(dv.position);
			Quat quat = conv(dv.orientation);
			Transform baseDevice_H_endDevice(pos*data.scale, quat);
			Transform world_H_virtualTool = data.world_H_baseDevice * baseDevice_H_endDevice * data.endDevice_H_virtualTool;
			lastToolPosition = world_H_virtualTool;
			/*
				Transform baseDevice_H_endDevice2 = data.world_H_baseDevice.inversed() * world_H_virtualTool * data.endDevice_H_virtualTool.inversed();
				sout << "bHe = " << baseDevice_H_endDevice << sendl;
				sout << "wHb = " << data.world_H_baseDevice << sendl;
				sout << "dHt = " << data.endDevice_H_virtualTool << sendl;
				sout << "wHv = " << world_H_virtualTool << sendl;
				sout << "bHe2 = " << baseDevice_H_endDevice2 << sendl;
				sout << sendl;
			*/
			sofa::helper::AdvancedTimer::stepEnd("XForm");


			sofa::helper::AdvancedTimer::stepBegin("Button");

			int buttonState = fakeButtonState | device->getButtonStatus();

			int buttonChanged = buttonState ^ lastButtonState;
			// special case: btn2 is mapped to tool selection if "toolSelector" is used
			if (toolSelector.getValue() && (buttonChanged & HapticDeviceEvent::Button2StateMask))
			{
				if ((buttonState & HapticDeviceEvent::Button2StateMask) != 0)
				{
					// start tool switch : disable feedback on previous instrument
					int currentToolIndex = toolIndex.getValue();
					int newToolIndex = ((currentToolIndex+1)%toolCount.getValue());
					toolIndex.setValue(newToolIndex);
					if (toolTransitionSpringStiffness.getValue() != 0.0 && mState)
					{
						sout << "Enabling tool transition spring" << sendl;

						sofa::helper::ReadAccessor<Data<sofa::helper::vector<sofa::defaulttype::RigidCoord<3,double> > > > x = *this->mState->read(sofa::core::VecCoordId::position());
						Transform world_H_virtualTool(x[newToolIndex].getCenter(), x[newToolIndex].getOrientation());
						Transform baseDevice_H_endDevice2 = data.world_H_baseDevice.inversed() * world_H_virtualTool * data.endDevice_H_virtualTool.inversed();
						transitionEffect.reset(
							new HAPI::HapticSpring( conv(baseDevice_H_endDevice2.getOrigin()*(1/data.scale)),
									toolTransitionSpringStiffness.getValue()));
						device->addEffect(transitionEffect.get(), 1.0);
					}
					setToolFeedback(currentToolIndex, false);
					isToolControlled = false; // we disable update of the tool position and feedback until the button is released
				}
				else
				{
					if (transitionEffect.get())
					{
						sout << "Disabling tool transition spring" << sendl;
						device->removeEffect(transitionEffect.get());
						transitionEffect.reset();
					}
					setToolFeedback(toolIndex.getValue(), true);
					isToolControlled = true;
				}
			}
			sofa::helper::AdvancedTimer::stepNext("Button", "Event");

			if (buttonState != lastButtonState)
			{
				lastButtonState = buttonState;
				sendHapticDeviceEvent();
			}
			sofa::helper::AdvancedTimer::stepEnd("Event");

			if (isToolControlled) // ignore haptic device if tool is unselected
			{
				const int currentToolIndex = toolIndex.getValue();
				sofa::helper::AdvancedTimer::stepBegin("FFB");
				// store actual position of interface for the forcefeedback (as it will be used as soon as new LCP will be computed)
				for (unsigned int i=0; i < feedbackEffects.size(); ++i)
				{
					SofaHAPIForceFeedbackEffect::SPtr ffe = feedbackEffects[i];
					if (ffe->getIndice() != currentToolIndex) continue;
					if (ffe->getForceFeedback())
						ffe->getForceFeedback()->setReferencePosition(world_H_virtualTool);
				}
				sofa::helper::AdvancedTimer::stepEnd("FFB");
				if (mState)
				{
					sofa::helper::AdvancedTimer::stepBegin("SetState");
					/// TODO : SHOULD INCLUDE VELOCITY !!

					sofa::helper::WriteAccessor<Data<sofa::helper::vector<sofa::defaulttype::RigidCoord<3,double> > > > x = *this->mState->write(sofa::core::VecCoordId::position());
					sofa::helper::WriteAccessor<Data<sofa::helper::vector<sofa::defaulttype::RigidCoord<3,double> > > > xfree = *this->mState->write(sofa::core::VecCoordId::freePosition());

					xfree[currentToolIndex].getCenter() = world_H_virtualTool.getOrigin();
					x[currentToolIndex].getCenter() = world_H_virtualTool.getOrigin();

					//      std::cout << world_H_virtualTool << std::endl;

					xfree[currentToolIndex].getOrientation() = world_H_virtualTool.getOrientation();
					x[currentToolIndex].getOrientation() = world_H_virtualTool.getOrientation();

					sofa::helper::AdvancedTimer::stepEnd("SetState", "UpdateMapping");
					sofa::simulation::Node *node = dynamic_cast<sofa::simulation::Node*> (this->getContext());
					if (node)
					{
						sofa::helper::AdvancedTimer::stepBegin("UpdateMapping");
						sofa::simulation::MechanicalPropagateOnlyPositionAndVelocityVisitor mechaVisitor(sofa::core::MechanicalParams::defaultInstance()); mechaVisitor.execute(node);
						sofa::simulation::UpdateMappingVisitor updateVisitor(sofa::core::ExecParams::defaultInstance()); updateVisitor.execute(node);
						sofa::helper::AdvancedTimer::stepEnd("UpdateMapping");
					}
				}
			}
			else
			{
			}

			sofa::helper::AdvancedTimer::stepEnd("SofaHAPIHapticsDevice");
		}
コード例 #4
0
ファイル: misc.cpp プロジェクト: tell/pbkz
void conv(ZZ& a,bkzfloat& b) {
    conv(a,to_stdstring(b).c_str());
}
コード例 #5
0
ファイル: main.cpp プロジェクト: CasyWang/treefrog-framework
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    int res = 0;
    QString appIni;
    QMap<QString, QString> args = convertArgs(QCoreApplication::arguments());

    if (!args.value("-f").isEmpty()) {
        appIni = args.value("-f");
        devIni = QFileInfo(appIni).dir().path() + QDir::separator() + "development.ini";
    } else {
        QString dir = QLatin1String("..") + QDir::separator() + QLatin1String("..") + QDir::separator() + "config" +  QDir::separator();
        appIni = dir + "application.ini";
        devIni = dir + "development.ini";
    }

    if (!QFile::exists(appIni)) {
        usage();
        return 1;
    }

    QSettings appSetting(appIni, QSettings::IniFormat);
    QSettings devSetting(devIni, QSettings::IniFormat);

    // Default codec
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QString codecName = appSetting.value("InternalEncoding").toString();
    if (!codecName.isEmpty()) {
        QTextCodec *c = QTextCodec::codecForName(codecName.toLatin1().constData());
        if (c) {
            codec = c;
        }
    }
    QTextCodec::setCodecForLocale(codec);

    defaultTrimMode = devSetting.value("Erb.DefaultTrimMode", "1").toInt();
    printf("Erb.DefaultTrimMode: %d\n", defaultTrimMode);

    QDir viewDir(".");
    if (!args.value("-v").isEmpty()) {
        viewDir.setPath(args.value("-v"));
    }
    if (!viewDir.exists()) {
        usage();
        return 1;
    }

    QDir outputDir(DEFAULT_OUTPUT_DIR);
    if (!args.value("-d").isEmpty()) {
        outputDir.setPath(args.value("-d"));
    }

    if (outputDir.exists()) {
        if (outputDir.path() != ".") {
            printf("  exists   %s\n", qPrintable(outputDir.path()));
        }
    } else {
        if (outputDir.mkpath(".")) {
            printf("  created  %s\n", qPrintable(outputDir.path()));
        } else {
            usage();
            return 1;
        }
    }

    bool createProFile = (args.contains("-p") || !args.contains("-P"));
    ViewConverter conv(viewDir, outputDir, createProFile);
    QString templateSystem = devSetting.value("TemplateSystem").toString();
    if (templateSystem.isEmpty()) {
        templateSystem = appSetting.value("TemplateSystem", "Erb").toString();
    }

    res = conv.convertView(templateSystem);
    return res;
}  
コード例 #6
0
ファイル: swscale_unscaled.c プロジェクト: Tjoppen/FFmpeg
/* {RGB,BGR}{15,16,24,32,32_1} -> {RGB,BGR}{15,16,24,32} */
static int rgbToRgbWrapper(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
                           int srcSliceH, uint8_t* dst[], int dstStride[])
{
    const enum PixelFormat srcFormat= c->srcFormat;
    const enum PixelFormat dstFormat= c->dstFormat;
    const int srcBpp= (c->srcFormatBpp + 7) >> 3;
    const int dstBpp= (c->dstFormatBpp + 7) >> 3;
    const int srcId= c->srcFormatBpp >> 2; /* 1:0, 4:1, 8:2, 15:3, 16:4, 24:6, 32:8 */
    const int dstId= c->dstFormatBpp >> 2;
    void (*conv)(const uint8_t *src, uint8_t *dst, int src_size)=NULL;

#define CONV_IS(src, dst) (srcFormat == PIX_FMT_##src && dstFormat == PIX_FMT_##dst)

    if (isRGBA32(srcFormat) && isRGBA32(dstFormat)) {
        if (     CONV_IS(ABGR, RGBA)
              || CONV_IS(ARGB, BGRA)
              || CONV_IS(BGRA, ARGB)
              || CONV_IS(RGBA, ABGR)) conv = shuffle_bytes_3210;
        else if (CONV_IS(ABGR, ARGB)
              || CONV_IS(ARGB, ABGR)) conv = shuffle_bytes_0321;
        else if (CONV_IS(ABGR, BGRA)
              || CONV_IS(ARGB, RGBA)) conv = shuffle_bytes_1230;
        else if (CONV_IS(BGRA, RGBA)
              || CONV_IS(RGBA, BGRA)) conv = shuffle_bytes_2103;
        else if (CONV_IS(BGRA, ABGR)
              || CONV_IS(RGBA, ARGB)) conv = shuffle_bytes_3012;
    } else
    /* BGR -> BGR */
    if (  (isBGRinInt(srcFormat) && isBGRinInt(dstFormat))
       || (isRGBinInt(srcFormat) && isRGBinInt(dstFormat))) {
        switch(srcId | (dstId<<4)) {
        case 0x34: conv= rgb16to15; break;
        case 0x36: conv= rgb24to15; break;
        case 0x38: conv= rgb32to15; break;
        case 0x43: conv= rgb15to16; break;
        case 0x46: conv= rgb24to16; break;
        case 0x48: conv= rgb32to16; break;
        case 0x63: conv= rgb15to24; break;
        case 0x64: conv= rgb16to24; break;
        case 0x68: conv= rgb32to24; break;
        case 0x83: conv= rgb15to32; break;
        case 0x84: conv= rgb16to32; break;
        case 0x86: conv= rgb24to32; break;
        }
    } else if (  (isBGRinInt(srcFormat) && isRGBinInt(dstFormat))
             || (isRGBinInt(srcFormat) && isBGRinInt(dstFormat))) {
        switch(srcId | (dstId<<4)) {
        case 0x33: conv= rgb15tobgr15; break;
        case 0x34: conv= rgb16tobgr15; break;
        case 0x36: conv= rgb24tobgr15; break;
        case 0x38: conv= rgb32tobgr15; break;
        case 0x43: conv= rgb15tobgr16; break;
        case 0x44: conv= rgb16tobgr16; break;
        case 0x46: conv= rgb24tobgr16; break;
        case 0x48: conv= rgb32tobgr16; break;
        case 0x63: conv= rgb15tobgr24; break;
        case 0x64: conv= rgb16tobgr24; break;
        case 0x66: conv= rgb24tobgr24; break;
        case 0x68: conv= rgb32tobgr24; break;
        case 0x83: conv= rgb15tobgr32; break;
        case 0x84: conv= rgb16tobgr32; break;
        case 0x86: conv= rgb24tobgr32; break;
        }
    }

    if (!conv) {
        av_log(c, AV_LOG_ERROR, "internal error %s -> %s converter\n",
               av_get_pix_fmt_name(srcFormat), av_get_pix_fmt_name(dstFormat));
    } else {
        const uint8_t *srcPtr= src[0];
              uint8_t *dstPtr= dst[0];
        if ((srcFormat == PIX_FMT_RGB32_1 || srcFormat == PIX_FMT_BGR32_1) && !isRGBA32(dstFormat))
            srcPtr += ALT32_CORR;

        if ((dstFormat == PIX_FMT_RGB32_1 || dstFormat == PIX_FMT_BGR32_1) && !isRGBA32(srcFormat))
            dstPtr += ALT32_CORR;

        if (dstStride[0]*srcBpp == srcStride[0]*dstBpp && srcStride[0] > 0 && !(srcStride[0] % srcBpp))
            conv(srcPtr, dstPtr + dstStride[0]*srcSliceY, srcSliceH*srcStride[0]);
        else {
            int i;
            dstPtr += dstStride[0]*srcSliceY;

            for (i=0; i<srcSliceH; i++) {
                conv(srcPtr, dstPtr, c->srcW*srcBpp);
                srcPtr+= srcStride[0];
                dstPtr+= dstStride[0];
            }
        }
    }
    return srcSliceH;
}
コード例 #7
0
ファイル: Process.cpp プロジェクト: AmesianX/A-Protect
void ProcessVerify(HWND hWnd,CMyList *m_list,int Type)
{
	CString PidNum;
	CString FilePath;
	DWORD dwReadByte;

	POSITION pos = m_list->GetFirstSelectedItemPosition(); //判断列表框中是否有选择项
	int Item = m_list->GetNextSelectedItem(pos); //将列表中被选择的下一项索引值保存到数组中

	FilePath.Format(L"%s",m_list->GetItemText(Item,3));

	WCHAR lpwzNum[50];
	WCHAR lpwzFilePath[260];
	WCHAR lpwzTrue[260];
	CHAR lpszFilePath[5024];

	memset(lpwzNum,0,sizeof(lpwzNum));
	memset(lpszFilePath,0,sizeof(lpszFilePath));
	memset(lpwzFilePath,0,sizeof(lpwzFilePath));

	wcscat(lpwzFilePath,FilePath);
	if (!wcslen(lpwzFilePath))
	{
		return;
	}
	if (GetFileAttributes(lpwzFilePath) == INVALID_FILE_ATTRIBUTES)
	{
		MessageBoxW(hWnd,L"文件无法访问!",L"A盾电脑防护",0);
		return;
	}
	//1为验证数字签名
	if (Type == 1){
		if (VerifyEmbeddedSignature(lpwzFilePath)){
			AfxMessageBox(L"通过数字签名验证");
		}else
			AfxMessageBox(L"没有通过数字签名验证");
		return;
	}
	WideCharToMultiByte (CP_OEMCP,NULL,lpwzFilePath,-1,lpszFilePath,wcslen(lpwzFilePath)*2,NULL,FALSE);

	FILE * fp=fopen(lpszFilePath,"rb");
	if(fp)
	{
		MD5VAL val;
		val = md5File(fp);
		wsprintfW(lpwzNum,L"%08x%08x%08x%08x",conv(val.a),conv(val.b),conv(val.c),conv(val.d));
		fclose(fp);
	}
	FileVerify(lpszFilePath,lpwzNum,lpwzTrue);

	WCHAR lpwzMessageBox[256] = {0};
	WCHAR lpszSuccess[256];

	memset(lpszSuccess,0,sizeof(lpszSuccess));
	memset(lpwzMessageBox,0,sizeof(lpwzMessageBox));

	if (_wcsnicmp(lpwzTrue,L"不支持当前系统",wcslen(L"不支持当前系统")) == 0)
	{
		wsprintfW(lpwzMessageBox,L"%s\r\n\r\n是否允许\"A盾电脑防护\"收集您的计算机版本以便作为后续版本更新?",L"不支持当前系统");
		if (MessageBoxW(hWnd,lpwzMessageBox,L"A盾电脑防护",MB_YESNO | MB_ICONWARNING) == IDYES)
		{
			//开始收集系统信息
		}
	}
	else if (_wcsnicmp(lpwzTrue,L"MD5(√)/签名(-)",wcslen(L"MD5(√)/签名(-)")) == 0)
	{
		wsprintfW(lpszSuccess,L"文件:%ws\r\nMD5值:%ws\r\n\r\n已经通过验证,属于系统原生文件!\r\n",lpwzFilePath,lpwzNum);
		AfxMessageBox(lpszSuccess);
	}
	else
	{
		wsprintfW(lpszSuccess,L"文件:%ws\r\nMD5值:%ws\r\n\r\n%ws!\r\n",lpwzFilePath,lpwzNum,lpwzTrue);
		AfxMessageBox(lpszSuccess);
	}
}
コード例 #8
0
void determinant(GF2E& d, const mat_GF2E& M_in)
{
   long k, n;
   long i, j;
   long pos;
   GF2X t1, t2;
   GF2X *x, *y;

   const GF2XModulus& p = GF2E::modulus();

   n = M_in.NumRows();

   if (M_in.NumCols() != n)
      LogicError("determinant: nonsquare matrix");

   if (n == 0) {
      set(d);
      return;
   }

   vec_GF2XVec M;

   M.SetLength(n);
   for (i = 0; i < n; i++) {
      M[i].SetSize(n, 2*GF2E::WordLength());
      for (j = 0; j < n; j++)
         M[i][j] = rep(M_in[i][j]);
   }

   GF2X det;
   set(det);

   for (k = 0; k < n; k++) {
      pos = -1;
      for (i = k; i < n; i++) {
         rem(t1, M[i][k], p);
         M[i][k] = t1;
         if (pos == -1 && !IsZero(t1))
            pos = i;
      }

      if (pos != -1) {
         if (k != pos) {
            swap(M[pos], M[k]);
         }

         MulMod(det, det, M[k][k], p);

         // make M[k, k] == -1 mod p, and make row k reduced

         InvMod(t1, M[k][k], p);
         for (j = k+1; j < n; j++) {
            rem(t2, M[k][j], p);
            MulMod(M[k][j], t2, t1, p);
         }

         for (i = k+1; i < n; i++) {
            // M[i] = M[i] + M[k]*M[i,k]

            t1 = M[i][k];   // this is already reduced

            x = M[i].elts() + (k+1);
            y = M[k].elts() + (k+1);

            for (j = k+1; j < n; j++, x++, y++) {
               // *x = *x + (*y)*t1

               mul(t2, *y, t1);
               add(*x, *x, t2);
            }
         }
      }
      else {
         clear(d);
         return;
      }
   }

   conv(d, det);
}
コード例 #9
0
static
void solve_impl(GF2E& d, vec_GF2E& X, const mat_GF2E& A, const vec_GF2E& b, bool trans)

{
   long n = A.NumRows();
   if (A.NumCols() != n)
      LogicError("solve: nonsquare matrix");

   if (b.length() != n)
      LogicError("solve: dimension mismatch");

   if (n == 0) {
      set(d);
      X.SetLength(0);
      return;
   }

   long i, j, k, pos;
   GF2X t1, t2;
   GF2X *x, *y;

   const GF2XModulus& p = GF2E::modulus();

   vec_GF2XVec M;

   M.SetLength(n);

   for (i = 0; i < n; i++) {
      M[i].SetSize(n+1, 2*GF2E::WordLength());

      if (trans) 
         for (j = 0; j < n; j++) M[i][j] = rep(A[j][i]);
      else
         for (j = 0; j < n; j++) M[i][j] = rep(A[i][j]);

      M[i][n] = rep(b[i]);
   }

   GF2X det;
   set(det);

   for (k = 0; k < n; k++) {
      pos = -1;
      for (i = k; i < n; i++) {
         rem(t1, M[i][k], p);
         M[i][k] = t1;
         if (pos == -1 && !IsZero(t1)) {
            pos = i;
         }
      }

      if (pos != -1) {
         if (k != pos) {
            swap(M[pos], M[k]);
         }

         MulMod(det, det, M[k][k], p);

         // make M[k, k] == -1 mod p, and make row k reduced

         InvMod(t1, M[k][k], p);
         for (j = k+1; j <= n; j++) {
            rem(t2, M[k][j], p);
            MulMod(M[k][j], t2, t1, p);
         }

         for (i = k+1; i < n; i++) {
            // M[i] = M[i] + M[k]*M[i,k]

            t1 = M[i][k];   // this is already reduced

            x = M[i].elts() + (k+1);
            y = M[k].elts() + (k+1);

            for (j = k+1; j <= n; j++, x++, y++) {
               // *x = *x + (*y)*t1

               mul(t2, *y, t1);
               add(*x, *x, t2);
            }
         }
      }
      else {
         clear(d);
         return;
      }
   }

   X.SetLength(n);
   for (i = n-1; i >= 0; i--) {
      clear(t1);
      for (j = i+1; j < n; j++) {
         mul(t2, rep(X[j]), M[i][j]);
         add(t1, t1, t2);
      }
      add(t1, t1, M[i][n]);
      conv(X[i], t1);
   }

   conv(d, det);
}
コード例 #10
0
ファイル: codigo.c プロジェクト: aldajo92/Procesadores
void main()
{

TRISC=0;
// Variables para controlador
int16 valor;     
float control;                //valor del PWM
float a1,b1,c1;                  //constantes del PID
float ref;            //temperatura a alcanzar
float rT,eT,iT,dT,yT,uT,iT0,eT0,iT_1,eT_1;     //variables de ecuaciones            
float max,min;               //límites máximo y mínimo de control.
float T ,Kp1, Ti1,Td1;  


setup_adc_ports(RA0_ANALOG);//entrada del LM35
setup_adc(ADC_CLOCK_INTERNAL);
setup_COUNTERS(RTCC_internal.rtcc_div_1);
set_adc_channel(0);

  setup_timer_2(t2_div_by_4,500,1);     //periodo de la señal PWM a 1ms
setup_ccp1(ccp_pwm);                  //Módulo CCP a modo PWM
setup_adc(ADC_CLOCK_INTERNAL);       //reloj convertidor AD interno
set_adc_channel(0);

setup_timer_0(rtcc_ext_l_to_h|RTCC_DIV_2);   //Configuración TMR0
setup_timer_1(T1_internal|T1_DIV_BY_8);     //Configuración TMR1

  float Temp;
  int c;
  char k;
  char Kp[6];
  char Ki[6];
  char Kd[6];
  char Sp[6];
  int v;
  
   port_b_pullups(true),
   lcd_init();
   kbd_init();
   
   
   inicio:
   
   for (v=0;v<=5;v++){
   Kp[v]=0; Ki[v]=0; Kd[v]=0; Sp[v]=0;
   }
   
   lcd_gotoxy(1,1);
   lcd_putc("\f");
   lcd_putc("Kp:");
   lcd_gotoxy(9,1);
   lcd_putc("Ki:");
   lcd_gotoxy(1,2);
   lcd_putc("Kd:");
   lcd_gotoxy(9,2);
   lcd_putc("Sp:");
   
   while(true){
      K_p:
      lcd_gotoxy(4,1);
      lcd_send_byte(0,0x0f);
      c=0;
      k=0;
      while(c<=4){
      
      k=kbd_getc();
      if(k!=0){
      
         
        
         if(k!='A' && k!='*' && k!='C'){
            
            if(k=='B'){
               printf(lcd_putc,".");
               Kp[c]=k;
               lcd_gotoxy(4+c,1);      
            }
            else
            printf(lcd_putc,"%c",k);
            Kp[c]=k;
            lcd_gotoxy(4+c,1);            
                
         }
         
         if(k=='A'){
               c++;
               Kp[c]=-92;                
               lcd_gotoxy(4+c,1);
                  
          }
               
          
      }
      if(k=='D'){
         int j=0;
         for(;;){
            Kp[j]=0;
            if(j==5) break;
            j++;
         }
      c=0;
      lcd_gotoxy(1,1);
      lcd_putc("Kp:     ");
      lcd_gotoxy(4+c,1);
      
      }
      if(k=='*'){
            Kp[c+1]=-92;
            
            goto K_i;  
           
          }
      
      
      }  //FUERA DEL WHILE
      
      lcd_gotoxy(4+c-1,1);
      lcd_send_byte(0,0x0f);
      k=0;
      
      for(;;){
         k=kbd_getc();
         if(k!=0){
            if(k=='*'){
               break;
             }          
         }
      }
    
      
      K_i:
      lcd_gotoxy(12,1);
      lcd_send_byte(0,0x0f);
      c=0;
      k=0;
      
      ///KI
      while(c<=4){
      
      k=kbd_getc();
      if(k!=0){
      
         
        
         if(k!='A' && k!='*'){
            
            if(k=='B'){
               printf(lcd_putc,".");
               Ki[c]=k;
               lcd_gotoxy(12+c,1);      
            }
            else
            printf(lcd_putc,"%c",k);
            Ki[c]=k;
            lcd_gotoxy(12+c,1);            
                
         }
         
         if(k=='A'){
               c++; 
               Ki[c]=-92; 
               lcd_gotoxy(12+c,1);
                  
          }
          
          
          
      }
      if(k=='D'){
         int j=0;
         for(;;){
            Ki[j]=0;
            if(j==5) break;
            j++;
         }
      c=0;
      lcd_gotoxy(9,1);
      lcd_putc("Ki:      ");
      lcd_gotoxy(12+c,1);
      }
      
      if(k=='*'){
         Ki[c+1]=-92; 
         goto K_d;  
      }      
      }
     
      ///FIN KI 
      ///FUERA DEL WHILE
      lcd_gotoxy(12+c-1,1);
      lcd_send_byte(0,0x0f);
      k=0;
      
      for(;;){
         k=kbd_getc();
         if(k!=0){
            if(k=='*'){
               break;
             }          
         }
      }
      
      K_d:
      lcd_gotoxy(4,2);
      lcd_send_byte(0,0x0f);
      c=0;
      k=0;
      
      while(c<=4){
      
      k=kbd_getc();
      if(k!=0){
      
         
        
         if(k!='A' && k!='*'){
            
            if(k=='B'){
               printf(lcd_putc,".");
               Kd[c]=k;
               lcd_gotoxy(4+c,2);      
            }
            else
            printf(lcd_putc,"%c",k);
            Kd[c]=k;
            lcd_gotoxy(4+c,2);            
                
         }
         
         if(k=='A'){
               c++; 
               Kd[c]=-92;
               lcd_gotoxy(4+c,2);
                  
          }
          
          
          
      }
      if(k=='D'){
         int j=0;
         for(;;){
            Kd[j]=0;
            if(j==5) break;
            j++;
         }
      c=0; 
      lcd_gotoxy(1,2);
      lcd_putc("Kd:     ");
      lcd_gotoxy(4+c,2);
      }
      
      if(k=='*'){
         Kd[c+1]=-92;
         goto S_p;  
      }      
      }
      //FUERA WHILE
      lcd_gotoxy(4+c-1,2);
      lcd_send_byte(0,0x0f);
      k=0;
      
      for(;;){
         k=kbd_getc();
         if(k!=0){
            if(k=='*'){
               break;
             }          
         }
      }
      
      ///SP
      S_p:
      lcd_gotoxy(12,2);
      lcd_send_byte(0,0x0f);
      c=0;
      k=0;
      while(c<=4){
      
      k=kbd_getc();
      if(k!=0){
      
         
        
         if(k!='A' && k!='*'){
            
            if(k=='B'){
               printf(lcd_putc,".");
               Sp[c]=k;
               lcd_gotoxy(12+c,2);      
            }
            else
            printf(lcd_putc,"%c",k);
            Sp[c]=k;
            lcd_gotoxy(12+c,2);            
                
         }
         
         if(k=='A'){
               c++; 
               Sp[c]=-92;
               lcd_gotoxy(12+c,2);
                  
          }
          
          
          
      }
      if(k=='D'){
         int j=0;
         for(;;){
            Sp[j]=0;
            if(j==5) break;
            j++;
         }
      c=0; 
      lcd_gotoxy(9,4);
      lcd_putc("Sp:     ");
      lcd_gotoxy(12+c,2);
      }
      if(k=='*'){
         Sp[c+1]=-92;
         goto PID;  
      }      
      }
      
      lcd_gotoxy(12+c-1,2);
      lcd_send_byte(0,0x0f);
      k=0;
      
      for(;;){
         k=kbd_getc();
         if(k!=0){
            if(k=='*'){
               break;
             }          
         }
      }
          
      PID:
      
      printf(lcd_putc, "\f");             // Borra la pantalla
    lcd_gotoxy(4, 1);
    printf(lcd_putc, "procesando.. ");
    delay_ms(600);
    
      float result;
       a1 = conv(Kp); b1 = conv(Ki);c1 = conv(Kd);ref = conv(Sp);
      
     // strtod(cc,NULL);
      lcd_init();
      iT0=0.0;
      eT0=0.0;
      min=0.0;   //inicialización variables
      uT = 0.0;
      max=1023;
      while(True){
      Temp=(float)read_adc();
      
      yT=Temp*5.0/1024.0; 
      
      
      rT=ref;                    
      eT=rT-yT;   //Cálculo error
      lcd_gotoxy(1,2);
      printf(lcd_putc,"error:%f",eT);
      
      iT=b1*eT+iT0;                         //Cálculo del término integral
      dT=c1*(eT-eT0);                       //Cálculo del término derivativo 
      
      uT=iT+a1*eT+dT;     //Cálculo de la salida PID
      lcd_gotoxy(1,1);
      printf(lcd_putc,"Out:%f",uT);
      
 
      if (uT>max) {        //Salida PID si es mayor que el MAX
          uT=max;}                          
      else {
      if (uT<min){      //Salida PID si es menor que el MIN 
            uT=min;}                           
         }                             


      
       control=uT;  //Transferencia de salida PID a señal PWM
      lcd_gotoxy(10,1);
      printf(lcd_putc,"Sp:%f",ref);
       
       set_pwm1_duty(control);
       iT0=iT;                        //Guardar variables
       eT0=eT;
       
                                                                
   
      delay_ms(20);

      }
      
      

      
   }
   }
コード例 #11
0
		void Canvas::move(double x, double y){current = conv(x, y);}
コード例 #12
0
ファイル: Tools.cpp プロジェクト: petrmiko/Uni_PPR
//convert method from string to double
bool string_to_double(std::string & convert, double * result)
{
	std::istringstream conv(convert);
	return conv >> *result ? true : false ;
}
コード例 #13
0
void *NavigatePlugin::processEvent(Event *e)
{
#ifdef WIN32
    if (e->type() == EventGetURL){
        string *url = (string*)(e->param());
        *url = getCurrentUrl();
        return e->param();
    }
#endif
    if (e->type() == EventGoURL){
        string url = (const char*)(e->param());
        string proto;
        if (url.length() == 0)
            return NULL;
        int n = url.find(':');
        /* in textshow.cpp file:// is deleted because it seems on some
           Qt-version it is appended and on some not - so if no : is found,
           append file:// */
        if (n < 0){
            proto = "file";
            url = proto + "://" + url;
        }else{
            proto = url.substr(0, n);
            if ((proto != "http") &&
                    (proto != "https") &&
                    (proto != "ftp") &&
                    (proto != "file") &&
                    (proto != "mailto"))
                return NULL;
        }
#ifdef WIN32
        bool bExec = false;
        if (getNewWindow()){
            string key_name = proto;
            key_name += "\\Shell\\Open";
            RegEntry rp(HKEY_CLASSES_ROOT, key_name.c_str());
            string prg    = rp.value("command");
            string action = rp.value("ddeexec");
            string topic  = rp.value("ddeexec\\Topic");
            string server = rp.value("ddeexec\\Application");
            if (!action.empty()){
                int pos = action.find("%1");
                if (pos >= 0)
                    action = action.substr(0, pos) + url + action.substr(pos + 2);
                pos = prg.find("%1");
                if (pos >= 0)
                    prg = prg.substr(0, pos) + url + prg.substr(pos + 2);
                if (!prg.empty()){
                    STARTUPINFOA si;
                    PROCESS_INFORMATION pi;
                    ZeroMemory(&si, sizeof(si));
                    si.cb = sizeof(si);
                    ZeroMemory(&pi, sizeof(pi));
                    if (CreateProcessA(NULL, (char*)prg.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)){
                        WaitForInputIdle(pi.hProcess, INFINITE);
                        CloseHandle(pi.hProcess);
                        CloseHandle(pi.hThread);
                    }
                }
                DDEbase b;
                DDEconversation conv(server.c_str(), topic.c_str());
                if (conv.Execute(action.c_str()))
                    bExec = true;
            }
        }
        if (!bExec){
            if (proto == "file")
                url = url.substr(5);
            ShellExecuteA(NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL);
        }
#else
#ifdef USE_KDE
        if (getUseKDE())
        {
            if (proto == "mailto")
                kapp->invokeMailer(url.substr(proto.length() + 1), QString::null);
            else
                kapp->invokeBrowser(url);
            return e->param();
        }
#endif // USE_KDE
        ExecParam execParam;
        if (proto == "mailto"){
            execParam.cmd = getMailer();
            url = url.substr(proto.length() + 1);
        }else{
            execParam.cmd = getBrowser();
	    QUrl qurl(url);
	    QString encodedUrl = qurl.toString(true, false);
	    url = encodedUrl.latin1();
        }
        execParam.arg = url.c_str();
        Event eExec(EventExec, &execParam);
        eExec.process();
#endif // WIN32
        return e->param();
    }
    if (e->type() == EventEncodeText){
        QString *text = (QString*)(e->param());
        *text = parseUrl(*text);
        return e->param();
    }
    if (e->type() == EventCheckState){
        CommandDef *cmd = (CommandDef*)(e->param());
        if (cmd->id == CmdMail){
            Contact *contact = getContacts()->contact((unsigned long)(cmd->param));
            if (contact == NULL)
                return NULL;
            QString mails = contact->getEMails();
            if (mails.length() == 0)
                return NULL;
            int nMails = 0;
            while (mails.length()){
                getToken(mails, ';');
                nMails++;
            }
            cmd->popup_id = (nMails <= 1) ? 0 : MenuMail;
            return e->param();
        }
        if (cmd->id == CmdMailList){
            Contact *contact = getContacts()->contact((unsigned long)(cmd->param));
            if (contact == NULL)
                return NULL;
            QString mails = contact->getEMails();
            if (mails.length() == 0)
                return NULL;
            int nMails = 0;
            while (mails.length()){
                getToken(mails, ';');
                nMails++;
            }
            CommandDef *cmds = new CommandDef[nMails + 1];
            unsigned n = 0;
            mails = contact->getEMails();
            while (mails.length()){
                QString mail = getToken(mails, ';', false);
                mail = getToken(mail, '/');
                cmds[n] = *cmd;
                cmds[n].id = CmdMailList + n;
                cmds[n].flags = COMMAND_DEFAULT;
                cmds[n].text_wrk = strdup(mail.utf8());
                n++;
            }
            memset(&cmds[n], 0, sizeof(CommandDef));
            cmd->param = cmds;
            cmd->flags |= COMMAND_RECURSIVE;
            return e->param();
        }
    }
    if (e->type() == EventCommandExec){
        CommandDef *cmd = (CommandDef*)(e->param());
        if (cmd->id == CmdMail){
            QString mail;
            Contact *contact = getContacts()->contact((unsigned long)(cmd->param));
            if (contact)
                mail = contact->getEMails();
            mail = getToken(mail, ';', false);
            mail = getToken(mail, '/');
            if (mail.length()){
                string addr = "mailto:";
                addr += mail.local8Bit();
                Event eMail(EventGoURL, (void*)addr.c_str());
                eMail.process();
            }
            return e->param();
        }
        if (cmd->menu_id == MenuMail){
            unsigned n = cmd->id - CmdMailList;
            QString mails;
            Contact *contact = getContacts()->contact((unsigned long)(cmd->param));
            if (contact)
                mails = contact->getEMails();
            while (mails.length()){
                QString mail = getToken(mails, ';', false);
                if (n-- == 0){
                    mail = getToken(mail, '/');
                    if (mail.length()){
                        string addr = "mailto:";
                        addr += mail.local8Bit();
                        Event eMail(EventGoURL, (void*)addr.c_str());
                        eMail.process();
                    }
                    break;
                }
            }
            return e->param();
        }
    }
    return NULL;
}
コード例 #14
0
ファイル: vhd-util-read.c プロジェクト: borland667/blktap
static void
vhd_print_footer(vhd_footer_t *f, int hex)
{
	uint64_t  c, h, s;
	uint32_t  ff_maj, ff_min, cr_maj, cr_min, cksm;
	char      time_str[26], creator[5], uuid[37], cookie[9];

	printf("VHD Footer Summary:\n-------------------\n");

	snprintf(cookie, 9, "%s", f->cookie);
	printf("Cookie              : %s\n", cookie);

	printf("Features            : (0x%08x) %s%s\n", f->features,
		(f->features & HD_TEMPORARY) ? "<TEMP>" : "",
		(f->features & HD_RESERVED)  ? "<RESV>" : "");

	ff_maj = f->ff_version >> 16;
	ff_min = f->ff_version & 0xffff;
	printf("File format version : Major: %d, Minor: %d\n", 
		ff_maj, ff_min);

	printf("Data offset         : %s\n", conv(hex, f->data_offset));

	vhd_time_to_string(f->timestamp, time_str);
	printf("Timestamp           : %s\n", time_str);

	memcpy(creator, f->crtr_app, 4);
	creator[4] = '\0';
	printf("Creator Application : '%s'\n", creator);

	cr_maj = f->crtr_ver >> 16;
	cr_min = f->crtr_ver & 0xffff;
	printf("Creator version     : Major: %d, Minor: %d\n",
		cr_maj, cr_min);

	printf("Creator OS          : %s\n",
		((f->crtr_os == HD_CR_OS_WINDOWS) ? "Windows" :
		 ((f->crtr_os == HD_CR_OS_MACINTOSH) ? "Macintosh" : 
		  "Unknown!")));

	printf("Original disk size  : %s MB ", conv(hex, f->orig_size >> 20));
	printf("(%s Bytes)\n", conv(hex, f->orig_size));

	printf("Current disk size   : %s MB ", conv(hex, f->curr_size >> 20));
	printf("(%s Bytes)\n", conv(hex, f->curr_size));

	c = f->geometry >> 16;
	h = (f->geometry & 0x0000FF00) >> 8;
	s = f->geometry & 0x000000FF;
	printf("Geometry            : Cyl: %s, ", conv(hex, c));
	printf("Hds: %s, ", conv(hex, h));
	printf("Sctrs: %s\n", conv(hex, s));
	printf("                    : = %s MB ", conv(hex, (c * h * s) >> 11));
	printf("(%s Bytes)\n", conv(hex, c * h * s << 9));

	printf("Disk type           : %s\n", 
	       f->type <= HD_TYPE_MAX ? 
	       hd_type_str[f->type] : "Unknown type!\n");

	cksm = vhd_checksum_footer(f);
	printf("Checksum            : 0x%x|0x%x (%s)\n", f->checksum, cksm,
		f->checksum == cksm ? "Good!" : "Bad!");

	uuid_unparse(f->uuid, uuid);
	printf("UUID                : %s\n", uuid);

	printf("Saved state         : %s\n", f->saved == 0 ? "No" : "Yes");
	printf("Hidden              : %d\n", f->hidden);
	printf("\n");
}
コード例 #15
0
ファイル: misc.cpp プロジェクト: gentryx/rockNroll
int str2int(String str) {
    std::istringstream conv(str);
    int res;
    conv >> res;
    return res;
}
コード例 #16
0
void inv(GF2E& d, mat_GF2E& X, const mat_GF2E& A)
{
   long n = A.NumRows();
   if (A.NumCols() != n)
      LogicError("inv: nonsquare matrix");

   if (n == 0) {
      set(d);
      X.SetDims(0, 0);
      return;
   }

   long i, j, k, pos;
   GF2X t1, t2;
   GF2X *x, *y;

   const GF2XModulus& p = GF2E::modulus();

   vec_GF2XVec M;

   M.SetLength(n);

   for (i = 0; i < n; i++) {
      M[i].SetSize(2*n, 2*GF2E::WordLength());
      for (j = 0; j < n; j++) {
         M[i][j] = rep(A[i][j]);
         clear(M[i][n+j]);
      }
      set(M[i][n+i]);
   }

   GF2X det;
   set(det);

   for (k = 0; k < n; k++) {
      pos = -1;
      for (i = k; i < n; i++) {
         rem(t1, M[i][k], p);
         M[i][k] = t1;
         if (pos == -1 && !IsZero(t1)) {
            pos = i;
         }
      }

      if (pos != -1) {
         if (k != pos) {
            swap(M[pos], M[k]);
         }

         MulMod(det, det, M[k][k], p);

         // make M[k, k] == -1 mod p, and make row k reduced

         InvMod(t1, M[k][k], p);
         for (j = k+1; j < 2*n; j++) {
            rem(t2, M[k][j], p);
            MulMod(M[k][j], t2, t1, p);
         }

         for (i = k+1; i < n; i++) {
            // M[i] = M[i] + M[k]*M[i,k]

            t1 = M[i][k];   // this is already reduced

            x = M[i].elts() + (k+1);
            y = M[k].elts() + (k+1);

            for (j = k+1; j < 2*n; j++, x++, y++) {
               // *x = *x + (*y)*t1

               mul(t2, *y, t1);
               add(*x, *x, t2);
            }
         }
      }
      else {
         clear(d);
         return;
      }
   }

   X.SetDims(n, n);
   for (k = 0; k < n; k++) {
      for (i = n-1; i >= 0; i--) {
         clear(t1);
         for (j = i+1; j < n; j++) {
            mul(t2, rep(X[j][k]), M[i][j]);
            add(t1, t1, t2);
         }
         add(t1, t1, M[i][n+k]);
         conv(X[i][k], t1);
      }
   }

   conv(d, det);
}
コード例 #17
0
ファイル: sushape.c プロジェクト: gwowen/seismicunix
int
main(int argc, char **argv)
{
	int nt;			/* number of points on trace		*/
	float dt;		/* time sample interval (sec)		*/
	float *shaper;		/* shaping filter coefficients		*/
	float *spiker;		/* spiking decon filter (not used)	*/
	float *w;		/* input wavelet			*/
	int nw;			/* length of input wavelet in samples	*/
	float *d;		/* desired output wavelet		*/
	int nd;			/* length of desired wavelet in samples	*/
	int nshape;		/* length of shaping filter in samples	*/
	float pnoise;		/* pef additive noise level		*/
	float *crosscorr;	/* right hand side of Wiener eqs	*/
	float *autocorr;	/* vector of autocorrelations		*/
	int showshaper;		/* flag to display shaping filter	*/
        float f_zero=0.0;       /* zero valued item for comparison      */

	cwp_String wfile="";	/* input wavelet file name		*/
	cwp_String dfile="";	/* desired output wavelet file name	*/
	FILE *wfp;		/* input wavelet file pointer 		*/
	FILE *dfp;		/* desired wavelet file pointer		*/


	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);


	/* Get info from first trace */ 
	if (!gettr(&intrace)) err("can't get first trace");
	nt = intrace.ns;
	dt = intrace.dt/1000000.0;	if (!dt) MUSTGETPARFLOAT ("dt", &dt);


	/* Get parameters */
	if (!getparint("showshaper",  &showshaper))	showshaper = 0;
	if (!getparint("nshape",  &nshape))		nshape = nt;
	if (!getparfloat("pnoise",  &pnoise))		pnoise = PNOISE;

	/* Open dfile and wfile if they have been getparred */
	getparstring("dfile",&dfile);	
	getparstring("wfile",&wfile);	

	if ((*dfile=='\0')) { /* if no dfile, then get from command line */
		if (!(nd = countparval("d")))
			err("must specify d= desired wavelet");
		d = ealloc1float(nd);	getparfloat("d", d);

	} else { /* read from dfile  */

                if((dfp=fopen(dfile,"r"))==NULL)
                        err("cannot open dfile=%s\n",dfile);

        	if (!fgettr(dfp,&dtr))  err("can't get input wavelet");
        		nd = (int) dtr.ns;
		d = ealloc1float(nd);
		memcpy((void *) d, (const void *) dtr.data, nd*FSIZE);
	}
		
	if ((*wfile=='\0')) { /* then get w from command line */
		if (!(nw = countparval("w")))
			err("must specify w= desired wavelet");
		w = ealloc1float(nw);	getparfloat("w", w);

	} else { /* read from wfile  */

                if((wfp=fopen(wfile,"r"))==NULL)
                        err("cannot open wfile=%s\n",wfile);

        	if (!fgettr(wfp,&wtr))  err("can't get desired output wavelet");
        		nw = (int) wtr.ns;
		w = ealloc1float(nw);
		memcpy((void *) w, (const void *) wtr.data, nw*FSIZE);
	}


	/* Get shaping filter by Wiener-Levinson */
	shaper	  = ealloc1float(nshape);
	spiker 	  = ealloc1float(nshape);	/* not used */
	crosscorr = ealloc1float(nshape);
	autocorr  = ealloc1float(nshape);
	xcor(nw, 0, w, nw, 0, w, nshape, 0, autocorr);  /* for matrix */
	xcor(nw, 0, w, nd, 0, d, nshape, 0, crosscorr); /* right hand side */
        if (CLOSETO(autocorr[0],f_zero))  err("can't shape with zero wavelet");
	autocorr[0] *= (1.0 + pnoise);			/* whiten */
	stoepf(nshape, autocorr, crosscorr, shaper, spiker);
		

	/* Show shaper on request */
	if (showshaper) {
		register int i;
		warn("Shaping filter:");
		for (i = 0; i < nshape; ++i)
			fprintf(stderr, "%10g%c", shaper[i],
				(i%6==5 || i==nshape-1) ? '\n' : ' ');
	}



	/* Main loop over traces */
	do {
		/* Center and convolve shaping filter with trace */
		conv(nshape, (nw-nd)/2, shaper,
		     nt, 0, intrace.data, 
                     nt, 0, outtrace.data);        


		/* Output filtered trace */
		memcpy( (void *) &outtrace, (const void *) &intrace, HDRBYTES);
		puttr(&outtrace);

	} while (gettr(&intrace));


	return(CWP_Exit());
}
コード例 #18
0
long gauss(mat_GF2E& M_in, long w)
{
   long k, l;
   long i, j;
   long pos;
   GF2X t1, t2, t3;
   GF2X *x, *y;

   long n = M_in.NumRows();
   long m = M_in.NumCols();

   if (w < 0 || w > m)
      LogicError("gauss: bad args");

   const GF2XModulus& p = GF2E::modulus();

   vec_GF2XVec M;

   M.SetLength(n);
   for (i = 0; i < n; i++) {
      M[i].SetSize(m, 2*GF2E::WordLength());
      for (j = 0; j < m; j++) {
         M[i][j] = rep(M_in[i][j]);
      }
   }

   l = 0;
   for (k = 0; k < w && l < n; k++) {

      pos = -1;
      for (i = l; i < n; i++) {
         rem(t1, M[i][k], p);
         M[i][k] = t1;
         if (pos == -1 && !IsZero(t1)) {
            pos = i;
         }
      }

      if (pos != -1) {
         swap(M[pos], M[l]);

         InvMod(t3, M[l][k], p);

         for (j = k+1; j < m; j++) {
            rem(M[l][j], M[l][j], p);
         }

         for (i = l+1; i < n; i++) {
            // M[i] = M[i] + M[l]*M[i,k]*t3

            MulMod(t1, M[i][k], t3, p);

            clear(M[i][k]);

            x = M[i].elts() + (k+1);
            y = M[l].elts() + (k+1);

            for (j = k+1; j < m; j++, x++, y++) {
               // *x = *x + (*y)*t1

               mul(t2, *y, t1);
               add(t2, t2, *x);
               *x = t2;
            }
         }

         l++;
      }
   }
   
   for (i = 0; i < n; i++)
      for (j = 0; j < m; j++)
         conv(M_in[i][j], M[i][j]);

   return l;
}
コード例 #19
0
ファイル: Process.cpp プロジェクト: AmesianX/A-Protect
VOID QuerySystemProcess(HWND m_hWnd,ULONG ID,CMyList *m_list)
{
	DWORD dwReadByte;
	int ItemNum = m_list->GetItemCount();
	HANDLE hProcess;
	int i=0;
	//触发最后一个进程,不然无法列举最后一个执行的进程
	//hProcess = RunAProcess("ping 127.0.0.1 -n 100");
	//WinExec("ping 127.0.0.1 -n 5",SW_HIDE);

	if (bIsPhysicalCheck){
		SaveToFile("\r\n\r\n[---系统进程---]\r\n",PhysicalFile);
	}
	SetDlgItemTextW(m_hWnd,ID,L"正在扫描系统进程,请稍后...");

	if (NormalProcessInfo)
	{
		VirtualFree(NormalProcessInfo,sizeof(PROCESSINFO)*900,MEM_RESERVE | MEM_COMMIT);
		NormalProcessInfo = NULL;
	}

	NormalProcessInfo = (PPROCESSINFO)VirtualAlloc(0, sizeof(PROCESSINFO)*900,MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
	if (NormalProcessInfo)
	{
		//为进程图标服务
		SHFILEINFO shfileinfo;
		ProcessImg.Create(16,16, ILC_COLOR32, 2, 100);
		HIMAGELIST hImageList = NULL;
		CMyAProtectApp *imgApp=(CMyAProtectApp*)AfxGetApp();
		bool PathEmpty=true;

		memset(NormalProcessInfo,0,sizeof(PROCESSINFO)*900);
		ReadFile((HANDLE)LIST_PROCESS,NormalProcessInfo,sizeof(PROCESSINFO)*900,&dwReadByte,0);

		for ( i=0;i<NormalProcessInfo->ulCount;i++)
		{
			WCHAR lpwzTextOut[100];
			memset(lpwzTextOut,0,sizeof(lpwzTextOut));
			wsprintfW(lpwzTextOut,L"共有 %d 个数据,正在扫描第 %d 个,请稍后...",NormalProcessInfo->ulCount,i);
			SetDlgItemTextW(m_hWnd,ID,lpwzTextOut);

			WCHAR lpwzProcName[100];
			WCHAR lpwzPid[50];
			WCHAR lpwzInheritedPid[50];
			WCHAR lpwzFullProcName[256];

			WCHAR lpwzEProcess[100];
			WCHAR lpwzStatus[50];

			WCHAR lpwzFileServices[256];
			WCHAR lpwzTrue[256];

			memset(lpwzProcName,0,sizeof(lpwzProcName));
			memset(lpwzPid,0,sizeof(lpwzPid));
			memset(lpwzInheritedPid,0,sizeof(lpwzInheritedPid));
			memset(lpwzFullProcName,0,sizeof(lpwzFullProcName));
			memset(lpwzEProcess,0,sizeof(lpwzEProcess));
			memset(lpwzStatus,0,sizeof(lpwzStatus));
			memset(lpwzFileServices,0,sizeof(lpwzFileServices));

			//提取进程DOS路径
			WCHAR lpwzWinDir[256];
			WCHAR lpwzSysDisk[10];


			char  lpszString[256];
			char  lpszFullString[5024];
			WCHAR lpwzFullString[256];
			memset(lpszString,0,sizeof(lpszString));
			memset(lpszFullString,0,sizeof(lpszFullString));
			memset(lpwzFullString,0,sizeof(lpwzFullString));

			memset(lpwzTrue,0,sizeof(lpwzTrue));
			memset(lpwzWinDir,0,sizeof(lpwzWinDir));
			memset(lpwzSysDisk,0,sizeof(lpwzSysDisk));

			if (_wcsicmp(NormalProcessInfo->ProcessInfo[i].lpwzFullProcessPath,L"System") == 0)
			{
				wcscat(lpwzFullString,L"System");
				wcscat(lpwzProcName,L"System");
				goto Next;
			}
			if (_wcsicmp(NormalProcessInfo->ProcessInfo[i].lpwzFullProcessPath,L"System Idle") == 0)
			{
				wcscat(lpwzFullString,L"System Idle");
				wcscat(lpwzProcName,L"System Idle");
				goto Next;
			}

			if (wcsstr(NormalProcessInfo->ProcessInfo[i].lpwzFullProcessPath,L"\\Device\\") != NULL)
			{
				//开始处理dos路径
				NtFilePathToDosFilePath(NormalProcessInfo->ProcessInfo[i].lpwzFullProcessPath,lpwzFullString);
			}else
			{
				wcsncat(lpwzFullString,NormalProcessInfo->ProcessInfo[i].lpwzFullProcessPath,wcslen(NormalProcessInfo->ProcessInfo[i].lpwzFullProcessPath));
			}
			//----------------------
			WideCharToMultiByte( CP_ACP,
				0,
				lpwzFullString,
				-1,
				lpszFullString,
				wcslen(lpwzFullString)*2,
				NULL,
				NULL);
			char *p = strstr(lpszFullString,"\\");
			if (p)
			{
				wsprintfA(lpszString,"%s",ExtractFileName(lpszFullString));
				MultiByteToWideChar(
					CP_ACP,
					0, 
					lpszString,
					-1, 
					lpwzProcName, 
					strlen(lpszString)
					);
			}
			FILE * fp=fopen(lpszFullString,"rb");
			if(fp)
			{
				PathEmpty=false;
				if (!bIsProcMD5Check)
				{
					wcscat(lpwzTrue,L"未知(右键扫描)");
					fclose(fp);
					goto Next;
				}
				MD5VAL val;
				val = md5File(fp);
				wsprintfW(lpwzFileServices,L"%08x%08x%08x%08x",conv(val.a),conv(val.b),conv(val.c),conv(val.d));
				FileVerify(lpszFullString,lpwzFileServices,lpwzTrue);
				fclose(fp);
			}
			//MessageBoxW(NormalProcessInfo->ProcessInfo[i].lpwzFullProcessPath,lpwzFullProcName,0);
Next:
			wsprintfW(lpwzPid,L"%d",NormalProcessInfo->ProcessInfo[i].ulPid);
			wsprintfW(lpwzInheritedPid,L"%d",NormalProcessInfo->ProcessInfo[i].ulInheritedFromProcessId);
			wsprintfW(lpwzEProcess,L"0x%08X",NormalProcessInfo->ProcessInfo[i].EProcess);
			//wsprintfW(lpwzStatus,L"%d",NormalProcessInfo->ProcessInfo[i].ulKernelOpen);

			HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE,NormalProcessInfo->ProcessInfo[i].ulPid);
			if (hProcess)
			{
				wcscat(lpwzStatus,L"Yes/");
				CloseHandle(hProcess);
			}else
				wcscat(lpwzStatus,L"No/");

			if (NormalProcessInfo->ProcessInfo[i].ulKernelOpen == 1)
			{
				wcscat(lpwzStatus,L"Yes");
			}else
				wcscat(lpwzStatus,L"No");

			//这里是一键体检的数据,不需要插入界面了
			if (bIsPhysicalCheck){
				//如果没有hook,就返回
				if (NormalProcessInfo->ProcessInfo[i].IntHideType == 1 ||
					_wcsnicmp(lpwzTrue,L"无法确认文件来源",wcslen(L"无法确认文件来源")) == 0)
				{
					WCHAR lpwzSaveBuffer[1024] ={0};
					CHAR lpszSaveBuffer[2024] ={0};
					memset(lpwzSaveBuffer,0,sizeof(lpwzSaveBuffer));
					memset(lpszSaveBuffer,0,sizeof(lpszSaveBuffer));

					wsprintfW(lpwzSaveBuffer,L"          --> 发现无法识别进程:进程Pid:%ws | 进程名:%ws | EPROCESS:%ws | 进程路径:%ws\r\n",
						lpwzPid,lpwzProcName,lpwzEProcess,lpwzFullString);

					m_list->InsertItem(0,L"系统进程",RGB(77,77,77));
					m_list->SetItemText(0,1,lpwzSaveBuffer);

					WideCharToMultiByte( CP_ACP,
						0,
						lpwzSaveBuffer,
						-1,
						lpszSaveBuffer,
						wcslen(lpwzSaveBuffer)*2,
						NULL,
						NULL
						);
					SaveToFile(lpszSaveBuffer,PhysicalFile);
				}
				continue;
			}
			if (NormalProcessInfo->ProcessInfo[i].IntHideType == 1)
			{
				m_list->InsertItem(i,lpwzPid,RGB(255,20,147));  //隐藏
				memset(lpwzStatus,0,sizeof(lpwzStatus));
				wcscat(lpwzStatus,L"隐藏进程");
			}
			else
			{
				if (_wcsnicmp(lpwzTrue,L"无法确认文件来源",wcslen(L"无法确认文件来源")) == 0)
				{
					m_list->InsertItem(i,lpwzPid,RGB(238,118,0));

				}
				else
				{
					if (!wcslen(lpwzProcName))
					{
						wcscat(lpwzFullString,L"* (Warning:进程文件已被移动)");
						PathEmpty=true;
						wcscat(lpwzProcName,L"*");
						m_list->InsertItem(i,lpwzPid,RGB(255,20,147));

					}else
						m_list->InsertItem(i,lpwzPid,RGB(77,77,77));

				}
			}

			//m_list->InsertItem(ItemNum,lpwzHideType);
			m_list->SetItemText(i,1,lpwzInheritedPid);
			m_list->SetItemText(i,2,lpwzProcName);
			m_list->SetItemText(i,3,lpwzFullString);
			m_list->SetItemText(i,4,lpwzEProcess);
			m_list->SetItemText(i,5,lpwzStatus);
			m_list->SetItemText(i,6,lpwzTrue);

			if(PathEmpty)
				ProcessImg.Add(imgApp->LoadIconW(IDI_WHITE));
			else
			{
				hImageList=(HIMAGELIST)::SHGetFileInfo(lpwzFullString,0,&shfileinfo,sizeof(shfileinfo),SHGFI_ICON);
				ProcessImg.Add(shfileinfo.hIcon);
			}
			m_list->SetImageList(&ProcessImg);
			m_list->SetItemImageId(i,i);
			DestroyIcon(shfileinfo.hIcon);
			PathEmpty=true;
		}
		//VirtualFree(NormalProcessInfo,sizeof(NormalProcessInfo)*1050*200,MEM_RESERVE | MEM_COMMIT);
	}else{
		WCHAR lpwzTextOut[100];
		memset(lpwzTextOut,0,sizeof(lpwzTextOut));
		wsprintfW(lpwzTextOut,L"申请内存错误, 请重新运行A盾\r\n错误代码:%d\n",GetLastError());
		MessageBox(0,lpwzTextOut,0,0);
	}
	WCHAR lpwzTextOut[100];
	memset(lpwzTextOut,0,sizeof(lpwzTextOut));
	wsprintfW(lpwzTextOut,L"系统进程扫描完毕,共有 %d 个数据",i);
	SetDlgItemTextW(m_hWnd,ID,lpwzTextOut);

}
コード例 #20
0
void kernel(mat_GF2E& X, const mat_GF2E& A)
{
   long m = A.NumRows();
   long n = A.NumCols();

   mat_GF2E M;
   long r;

   transpose(M, A);
   r = gauss(M);

   X.SetDims(m-r, m);

   long i, j, k, s;
   GF2X t1, t2;

   GF2E T3;

   vec_long D;
   D.SetLength(m);
   for (j = 0; j < m; j++) D[j] = -1;

   vec_GF2E inverses;
   inverses.SetLength(m);

   j = -1;
   for (i = 0; i < r; i++) {
      do {
         j++;
      } while (IsZero(M[i][j]));

      D[j] = i;
      inv(inverses[j], M[i][j]); 
   }

   for (k = 0; k < m-r; k++) {
      vec_GF2E& v = X[k];
      long pos = 0;
      for (j = m-1; j >= 0; j--) {
         if (D[j] == -1) {
            if (pos == k)
               set(v[j]);
            else
               clear(v[j]);
            pos++;
         }
         else {
            i = D[j];

            clear(t1);

            for (s = j+1; s < m; s++) {
               mul(t2, rep(v[s]), rep(M[i][s]));
               add(t1, t1, t2);
            }

            conv(T3, t1);
            mul(T3, T3, inverses[j]);
            v[j] = T3;
         }
      }
   }
}
コード例 #21
0
ファイル: af_hrtf.c プロジェクト: DanielGit/Intrisit8000
/* Filter data through filter

Two "tricks" are used to compensate the "color" of the KEMAR data:

1. The KEMAR data is refiltered to ensure that the front L, R channels
on the same side of the ear are equalized (especially in the high
frequencies).

2. A bass compensation is introduced to ensure that 0-200 Hz are not
damped (without any real 3D acoustical image, however).
*/
static af_data_t* play(struct af_instance_s *af, af_data_t *data)
{
    af_hrtf_t *s = af->setup;
    short *in = data->audio; // Input audio data
    short *out = NULL; // Output audio data
    short *end = in + data->len / sizeof(short); // Loop end
    float common, left, right, diff, left_b, right_b;
    const int dblen = s->dlbuflen, hlen = s->hrflen, blen = s->basslen;

    if(AF_OK != RESIZE_LOCAL_BUFFER(af, data))
	return NULL;

    if(s->print_flag) {
	s->print_flag = 0;
	switch (s->decode_mode) {
	case HRTF_MIX_51:
	  mp_msg(MSGT_AFILTER, MSGL_INFO,
		 "[hrtf] Using HRTF to mix %s discrete surround into "
		 "L, R channels\n", s->matrix_mode ? "5+1" : "5");
	  break;
	case HRTF_MIX_STEREO:
	  mp_msg(MSGT_AFILTER, MSGL_INFO,
		 "[hrtf] Using HRTF to mix stereo into "
		 "L, R channels\n");
	  break;
	case HRTF_MIX_MATRIX2CH:
	  mp_msg(MSGT_AFILTER, MSGL_INFO,
		 "[hrtf] Using active matrix to decode 2 channel "
		 "input, HRTF to mix %s matrix surround into "
		 "L, R channels\n", "3/2");
	  break;
	default:
	  mp_msg(MSGT_AFILTER, MSGL_WARN,
		 "[hrtf] bogus decode_mode: %d\n", s->decode_mode);
	  break;
	}

       if(s->matrix_mode)
	  mp_msg(MSGT_AFILTER, MSGL_INFO,
		 "[hrtf] Using active matrix to decode rear center "
		 "channel\n");
    }

    out = af->data->audio;

    /* MPlayer's 5 channel layout (notation for the variable):
     *
     * 0: L (LF), 1: R (RF), 2: Ls (LR), 3: Rs (RR), 4: C (CF), matrix
     * encoded: Cs (CR)
     *
     * or: L = left, C = center, R = right, F = front, R = rear
     *
     * Filter notation:
     *
     *      CF
     * OF        AF
     *      Ear->
     * OR        AR
     *      CR
     *
     * or: C = center, A = same side, O = opposite, F = front, R = rear
     */

    while(in < end) {
	const int k = s->cyc_pos;

	update_ch(s, in, k);

	/* Simulate a 7.5 ms -20 dB echo of the center channel in the
	   front channels (like reflection from a room wall) - a kind of
	   psycho-acoustically "cheating" to focus the center front
	   channel, which is normally hard to be perceived as front */
	s->lf[k] += CFECHOAMPL * s->cf[(k + CFECHODELAY) % s->dlbuflen];
	s->rf[k] += CFECHOAMPL * s->cf[(k + CFECHODELAY) % s->dlbuflen];

	switch (s->decode_mode) {
	case HRTF_MIX_51:
	case HRTF_MIX_MATRIX2CH:
	   /* Mixer filter matrix */
	   common = conv(dblen, hlen, s->cf, s->cf_ir, k + s->cf_o);
	   if(s->matrix_mode) {
	      /* In matrix decoding mode, the rear channel gain must be
		 renormalized, as there is an additional channel. */
	      matrix_decode(in, k, 2, 3, 0, s->dlbuflen,
			    s->lr_fwr, s->rr_fwr,
			    s->lrprr_fwr, s->lrmrr_fwr,
			    &(s->adapt_lr_gain), &(s->adapt_rr_gain),
			    &(s->adapt_lrprr_gain), &(s->adapt_lrmrr_gain),
			    s->lr, s->rr, NULL, NULL, s->cr);
	      common +=
		 conv(dblen, hlen, s->cr, s->cr_ir, k + s->cr_o) *
		 M1_76DB;
	      left    =
		 ( conv(dblen, hlen, s->lf, s->af_ir, k + s->af_o) +
		   conv(dblen, hlen, s->rf, s->of_ir, k + s->of_o) +
		   (conv(dblen, hlen, s->lr, s->ar_ir, k + s->ar_o) +
		    conv(dblen, hlen, s->rr, s->or_ir, k + s->or_o)) *
		   M1_76DB + common);
	      right   =
		 ( conv(dblen, hlen, s->rf, s->af_ir, k + s->af_o) +
		   conv(dblen, hlen, s->lf, s->of_ir, k + s->of_o) +
		   (conv(dblen, hlen, s->rr, s->ar_ir, k + s->ar_o) +
		    conv(dblen, hlen, s->lr, s->or_ir, k + s->or_o)) *
		   M1_76DB + common);
	   } else {
	      left    =
		 ( conv(dblen, hlen, s->lf, s->af_ir, k + s->af_o) +
		   conv(dblen, hlen, s->rf, s->of_ir, k + s->of_o) +
		   conv(dblen, hlen, s->lr, s->ar_ir, k + s->ar_o) +
		   conv(dblen, hlen, s->rr, s->or_ir, k + s->or_o) +
		   common);
	      right   =
		 ( conv(dblen, hlen, s->rf, s->af_ir, k + s->af_o) +
		   conv(dblen, hlen, s->lf, s->of_ir, k + s->of_o) +
		   conv(dblen, hlen, s->rr, s->ar_ir, k + s->ar_o) +
		   conv(dblen, hlen, s->lr, s->or_ir, k + s->or_o) +
		   common);
	   }
	   break;
	case HRTF_MIX_STEREO:
	   left    =
	      ( conv(dblen, hlen, s->lf, s->af_ir, k + s->af_o) +
		conv(dblen, hlen, s->rf, s->of_ir, k + s->of_o));
	   right   =
	      ( conv(dblen, hlen, s->rf, s->af_ir, k + s->af_o) +
		conv(dblen, hlen, s->lf, s->of_ir, k + s->of_o));
	   break;
	default:
	    /* make gcc happy */
	    left = 0.0;
	    right = 0.0;
	    break;
	}

	/* Bass compensation for the lower frequency cut of the HRTF.  A
	   cross talk of the left and right channel is introduced to
	   match the directional characteristics of higher frequencies.
	   The bass will not have any real 3D perception, but that is
	   OK (note at 180 Hz, the wavelength is about 2 m, and any
	   spatial perception is impossible). */
	left_b  = conv(dblen, blen, s->ba_l, s->ba_ir, k);
	right_b = conv(dblen, blen, s->ba_r, s->ba_ir, k);
	left  += (1 - BASSCROSS) * left_b  + BASSCROSS * right_b;
	right += (1 - BASSCROSS) * right_b + BASSCROSS * left_b;
	/* Also mix the LFE channel (if available) */
	if(data->nch >= 6) {
	    left  += in[5] * M3_01DB;
	    right += in[5] * M3_01DB;
	}

	/* Amplitude renormalization. */
	left  *= AMPLNORM;
	right *= AMPLNORM;

	switch (s->decode_mode) {
	case HRTF_MIX_51:
	case HRTF_MIX_STEREO:
	   /* "Cheating": linear stereo expansion to amplify the 3D
	      perception.  Note: Too much will destroy the acoustic space
	      and may even result in headaches. */
	   diff = STEXPAND2 * (left - right);
	   out[0] = (int16_t)(left  + diff);
	   out[1] = (int16_t)(right - diff);
	   break;
	case HRTF_MIX_MATRIX2CH:
	   /* Do attempt any stereo expansion with matrix encoded
	      sources.  The L, R channels are already stereo expanded
	      by the steering, any further stereo expansion will sound
	      very unnatural. */
	   out[0] = (int16_t)left;
	   out[1] = (int16_t)right;
	   break;
	}

	/* Next sample... */
	in = &in[data->nch];
	out = &out[af->data->nch];
	(s->cyc_pos)--;
	if(s->cyc_pos < 0)
	    s->cyc_pos += dblen;
    }

    /* Set output data */
    data->audio = af->data->audio;
    data->len   = data->len / data->nch * 2;
    data->nch   = 2;

    return data;
}
コード例 #22
0
ファイル: wizard.cpp プロジェクト: DirtGamer301/rigs-of-rods
MyWizard::MyWizard(int startupMode, wxFrame *frame, bool _autoUpdateEnabled, bool _enforceUpdate, bool useSizer)
        : wxWizard(frame,ID_WIZARD,_T("Rigs of Rods Update Assistant"),
                   wxBitmap(licence_xpm),wxDefaultPosition,
                   wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER), startupMode(startupMode),
				   autoUpdateEnabled(_autoUpdateEnabled), enforceUpdate(_enforceUpdate)
{
	// first thing to do: remove old installer file if possible
	try
	{
	if(boost::filesystem::exists("updater.exe.old"))
		boost::filesystem::remove("updater.exe.old");
	} catch(...) {}
	// now continue with normal startup

	new ConfigManager();
	CONFIG->enforceUpdate = enforceUpdate;

	// create log
	boost::filesystem::path iPath = boost::filesystem::path(conv(CONFIG->getInstallationPath()));
	boost::filesystem::path lPath = iPath / std::string("wizard.log");
	new InstallerLog(lPath);
	LOG("installer log created\n");


	// check if there is a newer installer available
	if(autoUpdateEnabled)
	{
		wxEventLoopGuarantor ensureEventLoop;
		CONFIG->checkForNewUpdater();
	}

	// add some versions to the log file
	{
		std::string ourHash = CONFIG->getOwnHash();
		LOG("INSTALLER HASH: %s\n", ourHash.c_str());
		char platform_str[256]="";
#ifdef _WIN32
		sprintf(platform_str, "windows");
#else
		sprintf(platform_str, "linux");
#endif // _WIN32
		LOG("INSTALLER PLATFORM: %s\n", platform_str);
		LOG("INSTALLER BUILD DATE: %s, %s\n", __DATE__, __TIME__);
	}

	bool userPathExisting = CONFIG->getUserPathExists();
	CONFIG->installType = userPathExisting ? wxString("normal") : wxString("fixuserpath");

    PresentationPage *presentation = new PresentationPage(this, enforceUpdate);
	//ConfirmationPage *confirm = new ConfirmationPage(this);
	DownloadPage *download = new DownloadPage(this);
	LastPage *last = new LastPage(this);

	m_page1 = presentation;

	wxWizardPageSimple::Chain(presentation, download);
	//wxWizardPageSimple::Chain(confirm, download);
	wxWizardPageSimple::Chain(download, last);




    if ( useSizer )
    {
        // allow the wizard to size itself around the pages
        GetPageAreaSizer()->Add(presentation);
    }
}
コード例 #23
0
ファイル: main.c プロジェクト: stqism/DEMOS
main()
{
    register char c;
    register int fd, lgt;
    char buf[512+1];

    ini_mem();
    if( ini_screen() < 0 )  exit( 0 );
    dpo( увт );

    if( (fd=open("/usr/minihelp/dtest",0)) > 0 ) {
        while( read(fd,buf,512) > 0 ) {buf[lgt]=0;  dpc( buf );}
        close( fd );
    }

    state = 0;  radr=0177776;  wadr=0177776;

    dpp( xr, yr-1 ); dpc( " READ" );
    dpp( xr, yr );   dpo( '(' );  dpc( conv( radr, 6, 8, '0' ) );
    dpc( ")=" );     dpc( conv( get(radr), 6, 8, '0' ) );

    dpp( xw, yw-1 ); dpc( " WRITE" );
    dpp( xw, yw );   dpo( '(' );  dpc( conv( wadr, 6, 8, '0' ) );
    dpc( ")=" );     dpc( conv( wvalue, 6, 8, '0' ) );

    dpp( x=xr+1, y=yr );

    for(;;) {
        switch( state ) {
            case 0:  c = getnumb( &radr, x-xr-1, 0177777, 0160000 ); break;
            case 1:  c = getnumb( &wadr, x-xw-1, 0177777, 0160000 ); break;
            case 2:  c = getnumb(&wvalue,x-xw-9, 0177777, 0000000 ); break;
        }
rep:    switch( c ) {
            case CTRL(D):               end_screen();      exit(0);
            case 'r':  case 'R':        state=0;  x=xr+1;  dpp(x,y); break;
            case 'w':  case 'W':        state=1;  x=xw+1;  dpp(x,y); break;
            case 'v':  case 'V':        state=2;  x=xw+9;  dpp(x,y); break;
            case 'c':  case 'C':
                if( state ) {
                    wcycle = !wcycle;
                    dpp(xw+8,yw-1);  dpc( wcycle ? "(CYCLE)" : "       " );
                } else {
                    rcycle = !rcycle;
                    dpp(xr+8,yr-1);  dpc( rcycle ? "(CYCLE)" : "       " );
                }
                dpp( x, y );
                break;
            case CR:
                switch( state ) {
                    case 0:
                        rvalue = get( radr );
                        dpp( xr+9, yr );  dpc( conv(rvalue,6,8,'0') );
                        c='r';  goto rep;
                    case 1:
                        c='v';  goto rep;
                    case 2:
                        set( wadr, wvalue );
                        c='v';  goto rep;
                }
        }
    }
}
コード例 #24
0
ファイル: wizard.cpp プロジェクト: DirtGamer301/rigs-of-rods
// ----------------------------------------------------------------------------
// Wizard pages
// ----------------------------------------------------------------------------
//// PresentationPage
PresentationPage::PresentationPage(wxWizard *parent, bool enforceUpdate) : wxWizardPageSimple(parent)
{

	wxString a = conv(CONFIG->readVersionInfo());
	CONFIG->getCurrentVersionInfo();
	wxString b = conv(CONFIG->getOnlineVersion());


	m_bitmap = wxBitmap(welcome_xpm);
	wxBoxSizer *mainSizer = new wxBoxSizer(wxVERTICAL);
	wxStaticText *tst;
	//GetParent()->SetBackgroundColour(*wxWHITE);
	mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("Welcome to the online updater of Rigs of Rods\n")), 0, wxALL, 5);
	wxFont dfont=tst->GetFont();
	dfont.SetWeight(wxFONTWEIGHT_BOLD);
	dfont.SetPointSize(dfont.GetPointSize()+4);
	tst->SetFont(dfont);
	tst->Wrap(TXTWRAP);
	mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("This program will help you update Rigs of Rods on your computer.\n")), 0, wxALL, 5);
	tst->Wrap(TXTWRAP);
	mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("Before updating, make sure Rigs of Rods is not running, and that your internet connection is available.\n")), 0, wxALL, 5);
	tst->Wrap(TXTWRAP);
	mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("If you are using a firewall, please allow this program to access the Internet.\n")), 0, wxALL, 5);
	tst->Wrap(TXTWRAP);

	if(CONFIG->installType == wxString("fixuserpath"))
	{
		// need to restore user path
		mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("Your user path is not existing, please click next to restore it and try to update again after the restore.")), 0, wxALL, 5);
		dfont=tst->GetFont();
		dfont.SetWeight(wxFONTWEIGHT_BOLD);
		dfont.SetPointSize(dfont.GetPointSize()+4);
		tst->SetFont(dfont);
		tst->Wrap(TXTWRAP);

		LOG("[FIXUSERPATH_MODE]\n");
		setControlEnable(parent, wxID_FORWARD, true);
		setControlEnable(parent, wxID_BACKWARD, false);
	} else
	{
		// now: compare the versions
		mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("Installed Version: ") + a), 0, wxALL, 5);
		dfont=tst->GetFont();
		dfont.SetWeight(wxFONTWEIGHT_BOLD);
		dfont.SetPointSize(dfont.GetPointSize()+4);
		tst->SetFont(dfont);
		tst->Wrap(TXTWRAP);

		mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("Online Version: ") + b), 0, wxALL, 5);
		dfont=tst->GetFont();
		dfont.SetWeight(wxFONTWEIGHT_BOLD);
		dfont.SetPointSize(dfont.GetPointSize()+4);
		tst->SetFont(dfont);
		tst->Wrap(TXTWRAP);

		Version installed_version(conv(a));
		Version online_version(conv(b));

		LOG("INSTALLED VERSION: '%s'\n", conv(a).c_str());
		LOG("ONLINE VERSION:    '%s'\n", conv(b).c_str());

		if (installed_version < online_version)
		{
			// new version
			mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("Click on Next to continue.\n")), 0, wxALL, 5);
			tst->Wrap(TXTWRAP);
			LOG("install choice: new version available\n");
		} else if (online_version < installed_version)
		{
			// local newer
			mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("Your version is newer than the last public version, no need to update")), 0, wxALL, 5);
			dfont=tst->GetFont();
			dfont.SetWeight(wxFONTWEIGHT_BOLD);
			dfont.SetPointSize(dfont.GetPointSize()+4);
			tst->SetFont(dfont);
			tst->Wrap(TXTWRAP);

			setControlEnable(parent, wxID_FORWARD, false);
			setControlEnable(parent, wxID_BACKWARD, false);
			LOG("install choice: using newer version than public\n");
		} else
		{
			// no need to update
			mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("Already up to date, no need to update")), 0, wxALL, 5);
			dfont=tst->GetFont();
			dfont.SetWeight(wxFONTWEIGHT_BOLD);
			dfont.SetPointSize(dfont.GetPointSize()+4);
			tst->SetFont(dfont);
			tst->Wrap(TXTWRAP);

			setControlEnable(parent, wxID_FORWARD, false);
			setControlEnable(parent, wxID_BACKWARD, false);
			LOG("install choice: version recent, no need to update\n");
		}

		if(enforceUpdate)
		{
			mainSizer->Add(tst=new wxStaticText(this, wxID_ANY, _T("Update was enforced")), 0, wxALL, 5);
			dfont=tst->GetFont();
			dfont.SetWeight(wxFONTWEIGHT_BOLD);
			dfont.SetPointSize(dfont.GetPointSize()+4);
			tst->SetFont(dfont);
			tst->Wrap(TXTWRAP);

			setControlEnable(parent, wxID_FORWARD, true);
			setControlEnable(parent, wxID_BACKWARD, true);
			LOG("[UPDATE ENFORCED]\n");
		}
	}

	SetSizer(mainSizer);
	mainSizer->Fit(this);
}
コード例 #25
0
bool FileManager::WriteWxStringToFile(wxFile& f, const wxString& data, wxFontEncoding encoding, bool bom)
{
    const char* mark = nullptr;
    size_t mark_length = 0;
    if (bom)
    {
        switch (encoding)
        {
        case wxFONTENCODING_UTF8:
            mark = "\xEF\xBB\xBF";
            mark_length = 3;
            break;
        case wxFONTENCODING_UTF16BE:
            mark = "\xFE\xFF";
            mark_length = 2;
            break;
        case wxFONTENCODING_UTF16LE:
            mark = "\xFF\xFE";
            mark_length = 2;
            break;
        case wxFONTENCODING_UTF32BE:
            mark = "\x00\x00\xFE\xFF";
            mark_length = 4;
            break;
        case wxFONTENCODING_UTF32LE:
            mark = "\xFF\xFE\x00\x00";
            mark_length = 4;
            break;
        case wxFONTENCODING_SYSTEM:
        default:
            break;
        }

        if (f.Write(mark, mark_length) != mark_length)
            return false;
    }

    if (data.length() == 0)
        return true;

#if defined(UNICODE) || defined(_UNICODE)

    size_t inlen = data.Len(), outlen = 0;
    wxCharBuffer mbBuff;
    if ( encoding == wxFONTENCODING_UTF7 )
    {
        wxMBConvUTF7 conv;
        mbBuff = conv.cWC2MB(data.c_str(), inlen, &outlen);
    }
    else if ( encoding == wxFONTENCODING_UTF8 )
    {
        wxMBConvUTF8 conv;
        mbBuff = conv.cWC2MB(data.c_str(), inlen, &outlen);
    }
    else if ( encoding == wxFONTENCODING_UTF16BE )
    {
        wxMBConvUTF16BE conv;
        mbBuff = conv.cWC2MB(data.c_str(), inlen, &outlen);
    }
    else if ( encoding == wxFONTENCODING_UTF16LE )
    {
        wxMBConvUTF16LE conv;
        mbBuff = conv.cWC2MB(data.c_str(), inlen, &outlen);
    }
    else if ( encoding == wxFONTENCODING_UTF32BE )
    {
        wxMBConvUTF32BE conv;
        mbBuff = conv.cWC2MB(data.c_str(), inlen, &outlen);
    }
    else if ( encoding == wxFONTENCODING_UTF32LE )
    {
        wxMBConvUTF32LE conv;
        mbBuff = conv.cWC2MB(data.c_str(), inlen, &outlen);
    }
    else
    {
        // try wxEncodingConverter first, even it it only works for
        // wxFONTENCODING_ISO8859_1..15, wxFONTENCODING_CP1250..1257 and wxFONTENCODING_KOI8
        // but it's much, much faster than wxCSConv (at least on linux)
        wxEncodingConverter conv;
        // should be long enough
        char* tmp = new char[2*inlen];

        if (conv.Init(wxFONTENCODING_UNICODE, encoding) && conv.Convert(data.wx_str(), tmp))
        {
            mbBuff = tmp;
            outlen = strlen(mbBuff); // should be correct, because Convert has returned true
        }
        else
        {
            // try wxCSConv, if nothing else works
            wxCSConv csconv(encoding);
            mbBuff = csconv.cWC2MB(data.c_str(), inlen, &outlen);
        }
        delete[] tmp;
    }
     // if conversion to chosen encoding succeeded, we write the file to disk
    if (outlen > 0)
        return f.Write(mbBuff, outlen) == outlen;

    // if conversion to chosen encoding does not succeed, we try UTF-8 instead
    size_t size = 0;
    wxCSConv conv(encoding);
    wxCharBuffer buf = data.mb_str(conv);

    if (!buf || !(size = strlen(buf)))
    {
        buf = data.mb_str(wxConvUTF8);

        if (!buf || !(size = strlen(buf)))
        {
            cbMessageBox(_T(    "The file could not be saved because it contains characters "
                                "that can neither be represented in your current code page, "
                                "nor be converted to UTF-8.\n"
                                "The latter should actually not be possible.\n\n"
                                "Please check your language/encoding settings and try saving again." ),
                                _("Failure"), wxICON_WARNING | wxOK );
            return false;
        }
        else
        {
            InfoWindow::Display(_("Encoding Changed"),
                                _("The saved document contained characters\n"
                                  "which were illegal in the selected encoding.\n\n"
                                  "The file's encoding has been changed to UTF-8\n"
                                  "to prevent you from losing data."), 8000);
        }
    }

    return f.Write(buf, size) == size;

#else

    // For ANSI builds, dump the char* to file.
    return f.Write(data.c_str(), data.Length()) == data.Length();

#endif
}
コード例 #26
0
ファイル: estimator.cpp プロジェクト: davidkretch/bootrlm
void MMEstimator::operator()(const Data& data, double* coef_ptr,
                           double* fitted_ptr, double* resid_ptr,
                           double* scale_ptr) {

  const arma::vec& y = data.y;
  const arma::mat& x = data.x;

  arma::vec coef(p);
  arma::vec fitted(n);
  arma::vec resid(n);
  double scale;

  arma::vec y_wt(n);
  arma::mat x_wt(n, p);
  arma::vec wt(n);

  // S estimation
  double scale_prev;

  lqs_estimator(data, coef.memptr(), fitted.memptr(), resid.memptr(), &scale);

  for (int i = 0; i < 30; i++) {
    // calculate weights
    wt = resid / scale;
    wt.transform(util::psi(k0));
    wt = sqrt(wt);

    // apply weights to data
    y_wt = y % wt;
    // TODO: try sparse diagonal matrix multiplication, column-wise dot product
    for (int i = 0; i < n; i++) {
      x_wt.row(i) = x.row(i) * wt(i);
    }

    // find weighted least squares estimate
    coef = arma::solve(x_wt, y_wt);
    resid = y - x * coef;

    // re-calculate scale
    wt = resid / scale;
    wt.transform(util::chi(k0));
    scale_prev = scale;
    scale *= sqrt(sum(wt) / ((n - p) * beta));

    if (fabs(scale / scale_prev - 1) < 1e-5) break;
  }

  // M estimation
  int maxit = 50000;
  arma::vec resid_prev(n);
  double c = 4.685;
  arma::vec conv(1);

  for (int i = 0; i < maxit; i++) {
    resid_prev = resid;

    // calculate weights
    wt = resid / scale;
    wt.transform(util::psi(c));
    wt = sqrt(wt);

    // apply weights to data
    y_wt = y % wt;
    for (int i = 0; i < n; i++) {
      x_wt.row(i) = x.row(i) * wt(i);
    }

    // find weighted least squares estimate
    coef = arma::solve(x_wt, y_wt);
    resid = y - x * coef;

    // check for convergence
    conv = sqrt(sum(pow(resid - resid_prev, 2)) / sum(pow(resid_prev, 2)));
    if (conv(0) < 1e-4) break;
  }

  // output
  arma::vec coef_out(coef_ptr, p, false, true);
  arma::vec fitted_out(fitted_ptr, n, false, true);
  arma::vec resid_out(resid_ptr, n, false, true);
  arma::vec scale_out(scale_ptr, 1, false, true);

  coef_out = coef;
  fitted_out = x * coef;
  resid_out = resid;
  scale_out = scale;
}
コード例 #27
0
ファイル: BabylonMesh.cpp プロジェクト: 4dinterface/spaceship
BabylonMesh::BabylonMesh(BabylonNode* node) :
	BabylonAbstractMesh(node),
	_isEnabled(true),
	_isVisible(true),
	_billboardMode(0),
	_visibility(1),
	_skeletonId(-1),
	_pickable(true),
	_hasVertexAlpha(false),
	_checkCollision(false),
	_receiveShadows(false),
	_infiniteDistance(false),
	_autoAnimate(false),
	_autoAnimateFrom(0),
	_autoAnimateTo(0),
	_autoAnimateLoop(false),
	_showBoundingBox(false),
	_showSubMeshesBoundingBox(false),
	_applyFog(false),
	_alphaIndex(0)
{

	pivotMatrix.SetIdentity();
	auto fbxNode = node->fbxNode();
	
	std::string ansiName = fbxNode->GetName();
	name(std::wstring(ansiName.begin(), ansiName.end()));
	id(getNodeId(fbxNode));
	auto parent = fbxNode->GetParent();
	if (parent) {
		parentId(getNodeId(parent));
	}
	pivotMatrix = ConvertToBabylonCoordinateSystem( GetGeometryTransformation(fbxNode));

	auto animStack = fbxNode->GetScene()->GetCurrentAnimationStack();
	FbxString animStackName = animStack->GetName();
	//FbxTakeInfo* takeInfo = node->GetScene()->GetTakeInfo(animStackName);
	auto animTimeMode = GlobalSettings::Current().AnimationsTimeMode;
	auto animFrameRate = GlobalSettings::Current().AnimationsFrameRate();
	auto startFrame = animStack->GetLocalTimeSpan().GetStart().GetFrameCount(animTimeMode);
	auto endFrame = animStack->GetLocalTimeSpan().GetStop().GetFrameCount(animTimeMode);
	auto animLengthInFrame = endFrame - startFrame + 1;
	_visibility = static_cast<float>(node->fbxNode()->Visibility.Get());
	auto posAnim = std::make_shared<BabylonAnimation<babylon_vector3>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), L"position", L"position", true, 0, static_cast<int>(animLengthInFrame), true);
	auto rotAnim = std::make_shared<BabylonAnimation<babylon_vector4>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), L"rotationQuaternion", L"rotationQuaternion", true, 0, static_cast<int>(animLengthInFrame), true);
	auto scaleAnim = std::make_shared<BabylonAnimation<babylon_vector3>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), L"scaling", L"scaling", true, 0, static_cast<int>(animLengthInFrame), true);
	auto visibilityAnim = std::make_shared<BabylonAnimation<float>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), L"visibility", L"visibility", true, 0, static_cast<int>(animLengthInFrame), true);
	auto mesh = fbxNode->GetMesh();
	_isVisible = fbxNode->Show.Get();
	
	auto rotCurveNode = fbxNode->LclRotation.GetCurveNode();
	auto translateCurveNode = fbxNode->LclTranslation.GetCurveNode();
	auto scalingCurveNode = fbxNode->LclScaling.GetCurveNode();
	auto visibilityCurveNode = fbxNode->Visibility.GetCurveNode();
	if (rotCurveNode || translateCurveNode || scalingCurveNode) {
		for (auto ix = 0; ix < animLengthInFrame; ix++) {
			FbxTime currTime;
			currTime.SetFrame(startFrame + ix, animTimeMode);

			babylon_animation_key<babylon_vector3> poskey;
			babylon_animation_key<babylon_vector4> rotkey;
			babylon_animation_key<babylon_vector3> scalekey;
			poskey.frame = ix;
			rotkey.frame = ix;
			scalekey.frame = ix;
			auto currTransform = node->GetLocal(currTime);
			poskey.values = currTransform.translation();
			rotkey.values = currTransform.rotationQuaternion();
			scalekey.values = currTransform.scaling();
			posAnim->appendKey(poskey);
			rotAnim->appendKey(rotkey);
			scaleAnim->appendKey(scalekey);


		}
	}
	if (visibilityCurveNode) {
		for (auto ix = 0; ix < animLengthInFrame; ix++) {
			FbxTime currTime;
			currTime.SetFrame(startFrame + ix, animTimeMode);

			babylon_animation_key<float> visibilityKey;

			visibilityKey.frame = ix;

			visibilityKey.values = static_cast<float>(node->fbxNode()->Visibility.EvaluateValue(currTime));

			visibilityAnim->appendKey(visibilityKey);


		}
	}
	
	if (!posAnim->isConstant()){
		animations.push_back(posAnim);
	}
	if (!rotAnim->isConstant()){
		animations.push_back(rotAnim);
	}
	if (!scaleAnim->isConstant()){
		animations.push_back(scaleAnim);
	}
	if (!visibilityAnim->isConstant()) {
		animations.push_back(visibilityAnim);
	}
	if (!mesh) {
		return;
	}
	if (mesh->GetPolygonCount() == 0){
		return;
	}

	_receiveShadows =  mesh->ReceiveShadow.Get();
	FbxGeometryConverter conv(mesh->GetFbxManager());
	conv.ComputePolygonSmoothingFromEdgeSmoothing(mesh);
	if (!mesh->IsTriangleMesh()) {
		mesh = (FbxMesh*) conv.Triangulate(mesh, true);
	}


	mesh->RemoveBadPolygons();
	mesh->GenerateNormals();

	FbxStringList uvSetNameList;
	mesh->GetUVSetNames(uvSetNameList);
	std::vector<std::string> uniqueUVSets;

	int uvCount = uvSetNameList.GetCount();
	for (int i = 0; i < uvCount; ++i) {
		std::string value = uvSetNameList.GetStringAt(i);
		if (std::find(uniqueUVSets.begin(), uniqueUVSets.end(), value) == uniqueUVSets.end()) {
			uniqueUVSets.push_back(value);
		}
	}
	uvsets = uniqueUVSets;
	bool hasUv = uniqueUVSets.size() > 0;
	bool hasUv2 = uniqueUVSets.size() > 1;
	bool hasUv3 = uniqueUVSets.size() > 2;
	bool hasUv4 = uniqueUVSets.size() > 3;
	bool hasUv5 = uniqueUVSets.size() > 4;
	bool hasUv6 = uniqueUVSets.size() > 5;
	std::string uvSetName;
	std::string uv2SetName;
	std::string uv3SetName;
	std::string uv4SetName;
	std::string uv5SetName;
	std::string uv6SetName;
	if (hasUv) {
		uvSetName = uniqueUVSets[0];
	}
	if (hasUv2) {
		uv2SetName = uniqueUVSets[1];
	}
	if (hasUv3) {
		uv3SetName = uniqueUVSets[2];
	}
	if (hasUv4) {
		uv4SetName = uniqueUVSets[3];
	}
	if (hasUv5) {
		uv5SetName = uniqueUVSets[4];
	}
	if (hasUv6) {
		uv6SetName = uniqueUVSets[5];
	}
	auto colors = mesh->GetElementVertexColor();
	FbxLayerElement::EMappingMode colorMappingMode;
	FbxLayerElement::EReferenceMode colorReferenceMode;
	if (colors) {
		colorMappingMode = colors->GetMappingMode();
		colorReferenceMode = colors->GetReferenceMode();
	}
	auto normals = mesh->GetElementNormal();
	FbxGeometryElementUV* uvs = nullptr;
	FbxGeometryElementUV* uvs2 = nullptr;
	FbxGeometryElementUV* uvs3 = nullptr;
	FbxGeometryElementUV* uvs4 = nullptr;
	FbxGeometryElementUV* uvs5 = nullptr;
	FbxGeometryElementUV* uvs6 = nullptr;
	FbxLayerElement::EMappingMode uvsMappingMode;
	FbxLayerElement::EReferenceMode uvsReferenceMode;
	FbxLayerElement::EMappingMode uvs2MappingMode;
	FbxLayerElement::EReferenceMode uvs2ReferenceMode;
	FbxLayerElement::EMappingMode uvs3MappingMode;
	FbxLayerElement::EReferenceMode uvs3ReferenceMode;
	FbxLayerElement::EMappingMode uvs4MappingMode;
	FbxLayerElement::EReferenceMode uvs4ReferenceMode;
	FbxLayerElement::EMappingMode uvs5MappingMode;
	FbxLayerElement::EReferenceMode uvs5ReferenceMode;
	FbxLayerElement::EMappingMode uvs6MappingMode;
	FbxLayerElement::EReferenceMode uvs6ReferenceMode;
	if (hasUv) {
		uvs = mesh->GetElementUV(uvSetName.c_str());
		uvsMappingMode = uvs->GetMappingMode();
		uvsReferenceMode = uvs->GetReferenceMode();
	}
	if (hasUv2) {
		uvs2 = mesh->GetElementUV(uv2SetName.c_str());
		uvs2MappingMode = uvs2->GetMappingMode();
		uvs2ReferenceMode = uvs2->GetReferenceMode();
	}
	if (hasUv3) {
		uvs3 = mesh->GetElementUV(uv3SetName.c_str());
		uvs3MappingMode = uvs3->GetMappingMode();
		uvs3ReferenceMode = uvs3->GetReferenceMode();
	}
	if (hasUv4) {
		uvs4 = mesh->GetElementUV(uv4SetName.c_str());
		uvs4MappingMode = uvs4->GetMappingMode();
		uvs4ReferenceMode = uvs4->GetReferenceMode();
	}
	if (hasUv5) {
		uvs5 = mesh->GetElementUV(uv5SetName.c_str());
		uvs5MappingMode = uvs5->GetMappingMode();
		uvs5ReferenceMode = uvs5->GetReferenceMode();
	}
	if (hasUv6) {
		uvs6 = mesh->GetElementUV(uv6SetName.c_str());
		uvs6MappingMode = uvs6->GetMappingMode();
		uvs6ReferenceMode = uvs6->GetReferenceMode();
	}

	auto normalMappingMode = normals->GetMappingMode();
	auto normalReferenceMode = normals->GetReferenceMode();
	std::vector<SubmeshData> submeshes;

	auto materialCount = node->fbxNode()->GetMaterialCount();
	if (materialCount == 0) {
		materialCount = 1;
	}
	submeshes.resize(materialCount);
	auto baseLayer = mesh->GetLayer(0);
	auto materials = baseLayer->GetMaterials();
	FbxLayerElement::EMappingMode materialMappingMode = materials ?
		materials->GetMappingMode() : FbxLayerElement::eByPolygon;

	// extract deformers
	SkinInfo skinInfo(fbxNode);
	if (skinInfo.hasSkin()){
		associatedSkeleton = std::make_shared<BabylonSkeleton>();
		skinInfo.buildBabylonSkeleton(*associatedSkeleton);
	}

	auto triangleCount = mesh->GetPolygonCount();
	for (int triangleIndex = 0; triangleIndex < triangleCount; ++triangleIndex) {

		int materialIndex = 0;
		if (materialCount > 0 && materials) {
			switch (materialMappingMode) {
			case FbxLayerElement::eAllSame:
				materialIndex = materials->GetIndexArray().GetAt(0);
				break;
			case FbxLayerElement::eByPolygon:
				materialIndex = materials->GetIndexArray().GetAt(triangleIndex);
			}
		}

		auto& submesh = submeshes[materialIndex];
		triangle t;
		for (int cornerIndex = 0; cornerIndex < 3; ++cornerIndex) {
			auto controlPointIndex = mesh->GetPolygonVertex(triangleIndex, cornerIndex);
			auto vertexIndex = triangleIndex * 3 + cornerIndex;
			auto position = mesh->GetControlPoints()[controlPointIndex];
			position[2] = -position[2];

			BabylonVertex v;
			v.position = position;
			if (normals) {
				int normalMapIndex = (normalMappingMode == FbxLayerElement::eByControlPoint) ?
				controlPointIndex : vertexIndex;
				int normalValueIndex = (normalReferenceMode == FbxLayerElement::eDirect) ?
				normalMapIndex : normals->GetIndexArray().GetAt(normalMapIndex);
				v.normal = normals->GetDirectArray().GetAt(normalValueIndex);
				v.normal.z = -v.normal.z;
			}
			if (colors) {
				int mappingIndex = (colorMappingMode == FbxLayerElement::eByControlPoint) ?
				controlPointIndex : vertexIndex;
				int valueIndex = (colorReferenceMode == FbxLayerElement::eDirect) ?
				mappingIndex : colors->GetIndexArray().GetAt(mappingIndex);
				v.color = colors->GetDirectArray().GetAt(valueIndex);
			}
			if (uvs) {
				int mappingIndex = (uvsMappingMode == FbxLayerElement::eByControlPoint) ?
				controlPointIndex : vertexIndex;
				int valueIndex = (uvsReferenceMode == FbxLayerElement::eDirect) ?
				mappingIndex : uvs->GetIndexArray().GetAt(mappingIndex);
				v.uv = uvs->GetDirectArray().GetAt(valueIndex);
				//v.uv.y = 1 - v.uv.y;
			}

			if (uvs2) {
				int mappingIndex = (uvs2MappingMode == FbxLayerElement::eByControlPoint) ?
					controlPointIndex : vertexIndex;
				int valueIndex = (uvs2ReferenceMode == FbxLayerElement::eDirect) ?
					mappingIndex : uvs2->GetIndexArray().GetAt(mappingIndex);
				v.uv2 = uvs2->GetDirectArray().GetAt(valueIndex);
			}
			if (uvs3) {
				int mappingIndex = (uvs3MappingMode == FbxLayerElement::eByControlPoint) ?
					controlPointIndex : vertexIndex;
				int valueIndex = (uvs3ReferenceMode == FbxLayerElement::eDirect) ?
					mappingIndex : uvs3->GetIndexArray().GetAt(mappingIndex);
				v.uv3 = uvs3->GetDirectArray().GetAt(valueIndex);
			}
			if (uvs4) {
				int mappingIndex = (uvs4MappingMode == FbxLayerElement::eByControlPoint) ?
					controlPointIndex : vertexIndex;
				int valueIndex = (uvs4ReferenceMode == FbxLayerElement::eDirect) ?
					mappingIndex : uvs4->GetIndexArray().GetAt(mappingIndex);
				v.uv4 = uvs4->GetDirectArray().GetAt(valueIndex);
			}
			if (uvs5) {
				int mappingIndex = (uvs5MappingMode == FbxLayerElement::eByControlPoint) ?
					controlPointIndex : vertexIndex;
				int valueIndex = (uvs5ReferenceMode == FbxLayerElement::eDirect) ?
					mappingIndex : uvs5->GetIndexArray().GetAt(mappingIndex);
				v.uv5 = uvs5->GetDirectArray().GetAt(valueIndex);
			}
			if (uvs6) {
				int mappingIndex = (uvs6MappingMode == FbxLayerElement::eByControlPoint) ?
					controlPointIndex : vertexIndex;
				int valueIndex = (uvs6ReferenceMode == FbxLayerElement::eDirect) ?
					mappingIndex : uvs6->GetIndexArray().GetAt(mappingIndex);
				v.uv6 = uvs6->GetDirectArray().GetAt(valueIndex);
			}
			if (skinInfo.hasSkin()){
				auto& skinData = skinInfo.controlPointBoneIndicesAndWeights(controlPointIndex);
				for (std::size_t boneix = 0; boneix < skinData.size()&&boneix< (size_t)4; ++boneix){
					v.boneIndices[boneix] = skinData[boneix].index;
					v.boneWeights[boneix] = static_cast<float>(skinData[boneix].weight);
				}
				for (auto boneix = skinData.size(); boneix < 4; ++boneix){

					v.boneIndices[boneix] = skinInfo.bonesCount();
					v.boneWeights[boneix] = 0;
				}
			}
			auto foundVertex = submesh.knownVertices.find(v);
			if (foundVertex != submesh.knownVertices.end()) {
				//submesh.indices.push_back(foundVertex->second);
				t.indices[cornerIndex] = foundVertex->second;
			}
			else {
				auto index = static_cast<int>(submesh.vertices.size());
				submesh.vertices.push_back(v);
				//submesh.indices.push_back(index);
				submesh.knownVertices[v] = index;
				t.indices[cornerIndex] = index;
			}
		}
		if (submesh.knownTriangles.insert(t).second) {
			submesh.indices.push_back(t.indices[0]);
			submesh.indices.push_back(t.indices[1]);
			submesh.indices.push_back(t.indices[2]);
		}
		else {
			std::cout << "duplicate triangle found (and eliminated) in " << fbxNode->GetName() << std::endl;
		}

	}
	std::uint32_t vertexOffset = 0;

	for (auto matIndex = 0u; matIndex < submeshes.size(); ++matIndex) {
		auto& submesh = submeshes[matIndex];
		BabylonSubmesh babsubmesh;
		babsubmesh.indexCount = static_cast<int>(submesh.indices.size());
		babsubmesh.indexStart = static_cast<int>(_indices.size());
		babsubmesh.materialIndex = matIndex;
		babsubmesh.verticesCount = static_cast<int>(submesh.vertices.size());
		babsubmesh.verticesStart = static_cast<int>(_positions.size());
		for (auto& v : submesh.vertices) {
			_positions.push_back(v.position);
			if (normals) {
				_normals.push_back(v.normal);
			}
			if (colors) {
				_colors.push_back(v.color);
			}
			if (uvs) {
				_uvs.push_back(v.uv);
			}
			if (uvs2) {
				_uvs2.push_back(v.uv2);
			}
			if (uvs3) {
				_uvs3.push_back(v.uv3);
			}
			if (uvs4) {
				_uvs4.push_back(v.uv4);
			}
			if (uvs5) {
				_uvs5.push_back(v.uv5);
			}
			if (uvs6) {
				_uvs6.push_back(v.uv6);
			}
			if (skinInfo.hasSkin()){
				 float weight0 = v.boneWeights[0];
				 float weight1 = v.boneWeights[1];
				 float weight2 = v.boneWeights[2];
				 int bone0 = v.boneIndices[0];
				 int bone1 = v.boneIndices[1];
				 int bone2 = v.boneIndices[2];
				 int bone3 = v.boneIndices[3];
               
				_boneWeights.push_back(babylon_vector4( weight0, weight1, weight2, 1.0f - weight0 - weight1 - weight2));
                _boneIndices.push_back((bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0);
			}
		}
		for (auto i : submesh.indices) {
			_indices.push_back(i + vertexOffset);
		}

		vertexOffset = static_cast<int>(_positions.size());
		_submeshes.push_back(babsubmesh);
	}



}
コード例 #28
0
ファイル: main.cpp プロジェクト: DylanLEBLOND/CPP
int		main(int ac, char **av)
{
	char	c;
	int		i;
	float	f;
	double	d;

	if (ac > 2)
		std::cout << "Too Much Parameters" << std::endl;
	else if (ac < 2)
		std::cout << "Not Enough Parameters" << std::endl;
	else
	{
		Convert conv(av[1]);

		std::cout << std::fixed;
		std::cout << std::setprecision(1);
		if (conv.getValue() == "inf" || conv.getValue() == "inff")
		{
			std::cout << "char: Impossible" << std::endl;
			std::cout << "int: Impossible" << std::endl;
			std::cout << "float: inff" << std::endl;
			std::cout << "double: inf" << std::endl;
		}
		else if (conv.getValue() == "-inf" || conv.getValue() == "-inff")
		{
			std::cout << "char: Impossible" << std::endl;
			std::cout << "int: Impossible" << std::endl;
			std::cout << "float: -inf" << std::endl;
			std::cout << "double: -inf" << std::endl;
		}
		else if (conv.getValue() == "nan")
		{
			std::cout << "char: Impossible" << std::endl;
			std::cout << "int: Impossible" << std::endl;
			std::cout << "float: nanf" << std::endl;
			std::cout << "double: nan" << std::endl;
		}
		else if (conv.getType() == 'c')
		{
			c = static_cast<char>(conv.getValue().c_str()[1]);
			i = static_cast<int>(c);
			f = static_cast<float>(c);
			d = static_cast<double>(c);
			std::cout << "char: " << c << std::endl;
			std::cout << "int: " << i << std::endl;
			std::cout << "float: " << f << "f" << std::endl;
			std::cout << "double: " << d << std::endl;
		}
		else if (conv.getType() == 'i')
		{
			try
			{
				i = std::stoi(conv.getValue().c_str());
			}
			catch (std::exception const &err)
			{
				conv.getOver();
				return 0;
			}
			if (i > CHAR_MAX || i < CHAR_MIN)
				std::cout << "char: Impossible" << std::endl;
			else if (i < 32 || i == 127)
				std::cout << "char: Non displayable" << std::endl;
			else
			{
				c = static_cast<char>(i);
				std::cout << "char: '" << c << "'" << std::endl;
			}
			f = static_cast<float>(i);
			d = static_cast<double>(i);
			std::cout << "int: " << i << std::endl;
			std::cout << "float: " << f << "f" << std::endl;
			std::cout << "double: " << d << std::endl;
		}
		else if (conv.getType() == 'f')
		{
			try
			{
				f = std::stof(conv.getValue().c_str());
			}
			catch (std::exception const &err)
			{
				conv.getOver();
				return (0);
			}
			if (f > static_cast<float>(CHAR_MAX) || f < static_cast<float>(CHAR_MIN))
				std::cout << "char: Impossible" << std::endl;
			else if (static_cast<int>(f) < 32 || static_cast<int>(f) == 127)
				std::cout << "char: Non displayable" << std::endl;
			else
				std::cout << "char: '" << (c = static_cast<char>(f)) << "'" << std::endl;
			if (atol(av[1]) > static_cast<float>(INT_MAX) || atol(av[1]) < static_cast<float>(INT_MIN))
				std::cout << "int: Impossible" << std::endl;
			else
				std::cout << "int: " << (i = static_cast<int>(f)) << std::endl;
			d = static_cast<double>(f);
			std::cout << "float: " << f << "f" << std::endl;
			std::cout << "double: " << d << std::endl;
		}
		else
		{
			try
            {
                d = std::stod(conv.getValue().c_str());
            }
            catch (std::exception const &err)
            {
                conv.getOver();
                return (0);
            }
            if (d >= static_cast<double>(CHAR_MAX) || d < static_cast<double>(CHAR_MIN))
				std::cout << "char: Impossible" << std::endl;
            else if (static_cast<int>(d) < 32 || static_cast<int>(d) == 127)
				std::cout << "char: Non displayable" << std::endl;
            else
				std::cout << "char: '" << (c = static_cast<char>(d)) << "'" << std::endl;
            if (atol(av[1]) > static_cast<double>(INT_MAX) || atol(av[1]) < static_cast<double>(INT_MIN))
				std::cout << "int: Impossible" << std::endl;
            else
				std::cout << "int: " << (i = static_cast<int>(d)) << std::endl;
			if (d > static_cast<double>(FLT_MAX) || d < -1.0 * static_cast<double>(FLT_MAX))
				std::cout << "float: Impossible" << std::endl;
            else
				std::cout << "float: " << (f = static_cast<float>(d)) << "f" << std::endl;
			std::cout << "double: " << d << std::endl;
		}
	}
	return 0;
}
コード例 #29
0
bool EncodingDetector::ConvertToWxStr(const wxByte* buffer, size_t size)
{
    LogManager* logmgr = Manager::Get()->GetLogManager();
    wxString    logmsg;

    if (!buffer || size == 0)
    {
        if(m_UseLog)
        {
            logmsg.Printf(_T("Encoding conversion has failed (buffer is empty)!"));
            logmgr->DebugLog(logmsg);
        }
        return false;
    }

    if (m_BOMSizeInBytes > 0)
    {
        for (int i = 0; i < m_BOMSizeInBytes; ++i)
            buffer++;
    }

    size_t outlen = 0;

/* NOTE (Biplab#5#): FileManager returns a buffer with 4 extra NULL chars appended.
    But the buffer size is returned sans the NULL chars */

    wxWCharBuffer wideBuff;

    // if possible use the special conversion-routines, they are much faster than wxCSCov (at least on linux)
    if ( m_Encoding == wxFONTENCODING_UTF7 )
    {
        wxMBConvUTF7 conv;
        wideBuff = conv.cMB2WC((char*)buffer, size + 4 - m_BOMSizeInBytes, &outlen);
    }
    else if ( m_Encoding == wxFONTENCODING_UTF8 )
    {
        wxMBConvUTF8 conv;
        wideBuff = conv.cMB2WC((char*)buffer, size + 4 - m_BOMSizeInBytes, &outlen);
    }
    else if ( m_Encoding == wxFONTENCODING_UTF16BE )
    {
        wxMBConvUTF16BE conv;
        wideBuff = conv.cMB2WC((char*)buffer, size + 4 - m_BOMSizeInBytes, &outlen);
    }
    else if ( m_Encoding == wxFONTENCODING_UTF16LE )
    {
        wxMBConvUTF16LE conv;
        wideBuff = conv.cMB2WC((char*)buffer, size + 4 - m_BOMSizeInBytes, &outlen);
    }
    else if ( m_Encoding == wxFONTENCODING_UTF32BE )
    {
        wxMBConvUTF32BE conv;
        wideBuff = conv.cMB2WC((char*)buffer, size + 4 - m_BOMSizeInBytes, &outlen);
    }
    else if ( m_Encoding == wxFONTENCODING_UTF32LE )
    {
        wxMBConvUTF32LE conv;
        wideBuff = conv.cMB2WC((char*)buffer, size + 4 - m_BOMSizeInBytes, &outlen);
    }
    else
    {
        // try wxEncodingConverter first, even it it only works for
        // wxFONTENCODING_ISO8859_1..15, wxFONTENCODING_CP1250..1257 and wxFONTENCODING_KOI8
        // but it's much, much faster than wxCSConv (at least on linux)
        wxEncodingConverter conv;
        wchar_t* tmp = new wchar_t[size + 4 - m_BOMSizeInBytes];
        if(   conv.Init(m_Encoding, wxFONTENCODING_UNICODE)
		   && conv.Convert((char*)buffer, tmp) )
        {
            wideBuff = tmp;
            outlen = size + 4 - m_BOMSizeInBytes; // should be correct, because Convert has returned true
        }
        else
        {
            // try wxCSConv, if nothing else works
            wxCSConv conv(m_Encoding);
            wideBuff = conv.cMB2WC((char*)buffer, size + 4 - m_BOMSizeInBytes, &outlen);
        }
        delete [] tmp;
    }

    m_ConvStr = wxString(wideBuff);

    if (outlen == 0)
    {
        if(m_UseLog)
        {
            logmsg.Printf(_T("Encoding conversion using settings has failed!\n"
                             "Encoding choosen was: %s (ID: %d)"),
                          wxFontMapper::Get()->GetEncodingDescription(m_Encoding).c_str(),
                          m_Encoding);
            logmgr->DebugLog(logmsg);
        }

        // Try system locale (if requested by the settings)
        ConfigManager* cfgMgr = Manager::Get()->GetConfigManager(_T("editor"));
        if (cfgMgr->ReadBool(_T("/default_encoding/use_system"), true))
        {
            // Conversion has failed. Let's try with system-default encoding.
            if (platform::windows)
            {
                if(m_UseLog)
                {
                    logmgr->DebugLog(_T("Trying system locale as fallback..."));
                }
                m_Encoding = wxLocale::GetSystemEncoding();
            }
            else
            {
                // We can rely on the UTF-8 detection code ;-)
                if(m_UseLog)
                {
                    logmgr->DebugLog(_T("Trying ISO-8859-1 as fallback..."));
                }
                m_Encoding = wxFONTENCODING_ISO8859_1;
            }

            wxCSConv conv_system(m_Encoding);
            wideBuff = conv_system.cMB2WC((char*)buffer, size + 4 - m_BOMSizeInBytes, &outlen);
            m_ConvStr = wxString(wideBuff);

            if (outlen == 0)
            {
                if(m_UseLog)
                {
                    logmsg.Printf(_T("Encoding conversion using system locale fallback has failed!\n"
                                     "Last encoding choosen was: %s (ID: %d)\n"
                                     "Don't know what to do."),
                                  wxFontMapper::Get()->GetEncodingDescription(m_Encoding).c_str(),
                                  m_Encoding);
                    logmgr->DebugLog(logmsg);
                }
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    return true;
}
コード例 #30
0
ファイル: conv_deep.hpp プロジェクト: wichtounet/etl
 static void apply(const I& input, const K& kernel, C&& conv) {
     for (size_t i = 0; i < etl::dim<0>(input); ++i) {
         apply(input(i), kernel(i), conv(i));
     }
 }