コード例 #1
0
ファイル: niash_winusb.cpp プロジェクト: mkentie/3300c
void NiashLibUsbInit(TFnReportDevice* const pfnReportDevice)
{
	class HDEVINFODeleter //RAII wrapper
	{
	public:
		typedef HDEVINFO pointer;
		void operator()(HDEVINFO h) {::SetupDiDestroyDeviceInfoList(h);}
	};

	//Get device
	std::unique_ptr<HDEVINFO, HDEVINFODeleter> hDevInfo(SetupDiGetClassDevs(&s_NiashInterfaceClassGUID, NULL, NULL, DIGCF_PRESENT|DIGCF_PROFILE|DIGCF_DEVICEINTERFACE));
	if(hDevInfo.get() == INVALID_HANDLE_VALUE)
	{
		wprintf_s(L"SetupDiGetClassDevs: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}
	
	//Get device info for the devices
	SP_DEVINFO_DATA DeviceInfoData;
	DeviceInfoData.cbSize = sizeof(DeviceInfoData);
	SetupDiEnumDeviceInfo(hDevInfo.get(),0,&DeviceInfoData);
	if(GetLastError()==ERROR_NO_MORE_ITEMS)
	{
		puts("No devices with the driver installed found.");
	}
	else
	{
		wprintf_s(L"SetupDiEnumDeviceInfo: %s\n", _com_error(GetLastError()).ErrorMessage());
	}

	//Get the first matching device interface of that device
	SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
	DeviceInterfaceData.cbSize = sizeof(DeviceInterfaceData);	
	if(!SetupDiEnumDeviceInterfaces(hDevInfo.get(), &DeviceInfoData, &s_NiashInterfaceClassGUID, 0, &DeviceInterfaceData))
	{
		wprintf_s(L"SetupDiEnumDeviceInterfaces: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}

	//Get size of detailed device interface data
	DWORD dwRequiredSize;
	if(!SetupDiGetDeviceInterfaceDetail(hDevInfo.get(), &DeviceInterfaceData, nullptr, 0, &dwRequiredSize, nullptr) && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
	{
		wprintf_s(L"SetupDiGetDeviceInterfaceDetail: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}

	//SP_DEVICE_INTERFACE_DETAIL_DATA's actual size isn't declared
	std::unique_ptr<SP_DEVICE_INTERFACE_DETAIL_DATA_A> pInterfaceDetailData(reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA_A*>(new BYTE[dwRequiredSize]));
	pInterfaceDetailData->cbSize = sizeof(*pInterfaceDetailData);
	if(!SetupDiGetDeviceInterfaceDetailA(hDevInfo.get(), &DeviceInterfaceData, pInterfaceDetailData.get(), dwRequiredSize, nullptr, nullptr))
	{
		wprintf_s(L"SetupDiGetDeviceInterfaceDetail: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}

	//Get name size
	ULONG ulPropType = DEVPROP_TYPE_STRING;
	if(!SetupDiGetDeviceProperty(hDevInfo.get(), &DeviceInfoData, &DEVPKEY_NAME, &ulPropType, nullptr, 0, &dwRequiredSize, 0) && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
	{
		wprintf_s(L"SetupDiGetDeviceProperty: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}

	//Get device name
	std::vector<TCHAR> Buf(dwRequiredSize);
	if(!SetupDiGetDeviceProperty(hDevInfo.get(), &DeviceInfoData, &DEVPKEY_NAME, &ulPropType, reinterpret_cast<PBYTE>(Buf.data()), dwRequiredSize, 0, 0))
	{
		wprintf_s(L"SetupDiGetDeviceProperty: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}
	wprintf_s(L"Found device: %s ", Buf.data());
	printf_s("%s\n", pInterfaceDetailData->DevicePath);

	//Let driver recognize the device so it knows what parameters to use
	int vid = 0;
	int pid = 0;
	if(sscanf_s(pInterfaceDetailData->DevicePath,"\\\\?\\usb#vid_%x&pid_%x#", &vid, &pid) == 2 && MatchUsbDevice(vid,pid,&s_pScannerModel))
	{
		pfnReportDevice(s_pScannerModel, pInterfaceDetailData->DevicePath);
	}
}
コード例 #2
0
ファイル: dxf.cpp プロジェクト: Ychuan1115/libarea
bool CDxfRead::ReadLwPolyLine(bool undoably)
{
	PolyLineStart();

	bool x_found = false;
	bool y_found = false;
	double x = 0.0;
	double y = 0.0;
	bool bulge_found = false;
	double bulge = 0.0;
	bool closed = false;
	int flags;
	bool next_item_found = false;

	while(!((*m_ifs).eof()) && !next_item_found)
	{
		get_line();
		int n;
		if(sscanf_s(m_str, "%d", &n) != 1)return false;
		std::istringstream ss;
		ss.imbue(std::locale("C"));
		switch(n){
			case 0:
				// next item found
				if(x_found && y_found){
					// add point
					AddPolyLinePoint(this, x, y, bulge_found, bulge, undoably);
					bulge_found = false;
					x_found = false;
					y_found = false;
				}
				next_item_found = true;
				break;
			case 10:
				// x
				get_line();
				if(x_found && y_found){
					// add point
					AddPolyLinePoint(this, x, y, bulge_found, bulge, undoably);
					bulge_found = false;
					x_found = false;
					y_found = false;
				}
				ss.str(m_str); ss >> x; if(ss.fail()) return false;
				x_found = true;
				break;
			case 20:
				// y
				get_line();
				ss.str(m_str); ss >> y; if(ss.fail()) return false;
				y_found = true;
				break;
			case 42:
				// bulge
				get_line();
				ss.str(m_str); ss >> bulge; if(ss.fail()) return false;
				bulge_found = true;
				break;
			case 70:
				// flags
				get_line();
				if(sscanf_s(m_str, "%d", &flags) != 1)return false;
				closed = ((flags & 1) != 0);
				break;
			default:
				// skip the next line
				get_line();
				break;
		}
	}

	if(next_item_found)
	{
		if(closed && poly_first_found)
		{
			// repeat the first point
			AddPolyLinePoint(this, poly_first_x, poly_first_y, false, 0.0, undoably);
		}
		return true;
	}

	return false;
}
コード例 #3
0
ファイル: pods.cpp プロジェクト: nmovshov/ARSS_win
bool PlaceActor(NxVec3 position, NxVec3 velocity, unsigned int actind)
/*	This function is an intermediate step between CreateInitialPile that defines that initial positions
	and velocities of each actor in the pile, and the actor creation routine, which may be simply the
	familiar CreateRubbleGrain if actors should have a generic (or random) shape, or the more specialized
	CreateSpecificActor, that reads the shape information from a shapes file. The branching is decided
	simply by looking for the existence of a shapes file. EDIT: a shape file for non-uniform spheres is now
	implemented, as is a mixed polyhedra-non-uniform-sphere file. Branching determined by the section
	separator: SPHERE or SHAPE. EDIT: this function should not be called except by CreateInitialPile.
*/
{
	bool success=false;
	static bool skipSHFile=false;

	// attempt to open a shapes file
	char shfile[255];
	sprintf(shfile,"%s\\%s\\%s.sh",_getcwd(NULL,0),gRunBaseName,gRunBaseName);
	static ifstream fp(shfile);
	if (fp.fail() || skipSHFile) {// the easy default path. creating actors based on grain_type form ini file.
		NxActor* actor=CreateRubbleGrain(position);
		if (actor) actor->setLinearVelocity(velocity);
		if (actor) success=true;
	}
	else // this is the more complex path. read shapes from the shapes file.
	{
		// sigh. ok, here we go. the .sh file remains open so we just need to skip the header once:
		static char line[255];
		if (actind==0){
			while (fp.good()){
				fp.getline(line,255);
				if (strcmp(line,"SHAPE")==0 || strcmp(line,"SPHERE")==0) break;
			}
			if (fp.eof()) {cout<<"ERROR:shape segments not found in shape file."<<endl; fp.close(); skipSHFile=true; return false;}
		}

		// otherwise, we should be in position to start reading vertex info.
		if (strcmp(line,"SHAPE")==0)
		{
			float xx,yy,zz;
			NxVec3 vertex;
			vector<NxVec3> verts;
			while (fp.good())
			{
				fp.getline(line,255);
				if (strcmp(line,"\0")==0) continue; //skip empty lines. (but lines with nothing but ws are a problem.)
				if (strcmp(line,"SHAPE")==0 || strcmp(line,"SPHERE")==0 || fp.eof()) break;
				if (sscanf_s(line,"%f%f%f",&xx,&yy,&zz)<3) {cout<<"ERROR:bad format in shapes file."<<endl; fp.close(); return false;}
				vertex.x=xx; vertex.y=yy; vertex.z=zz;
				verts.push_back(vertex);
			}
			if (fp.eof() && actind<(RUBBLE_SIZE-1)){
				cout<<"WARNING:not enough shapes in shape file. additional shapes determined by grain_type"<<endl;
				fp.close();
				skipSHFile=true;
			}

			// well well. i do believe we have extracted the vertex information for shape actind. now what?
			NxActor* actor=CreateSpecificConvexShape(position,gDefaultDensity,verts); // someone else's problem now.
			if (actor){
				actor->setLinearVelocity(velocity);
				success=true;
			}
		}
		else if (strcmp(line,"SPHERE")==0)
		{
			float rr;
			fp.getline(line,255);
			if (sscanf_s(line,"%f",&rr)<1) {cout<<"ERROR:bad format in shapes file."<<endl; fp.close(); return false;}
			while (fp.good())
			{
				fp.getline(line,255);
				if (strcmp(line,"\0")==0) continue; //skip empty lines. (but lines with nothing but ws are a problem.)
				if (strcmp(line,"SHAPE")==0 || strcmp(line,"SPHERE")==0 || fp.eof()) break;
				cout<<"ERROR:bad format in shapes file."<<endl; fp.close(); return false;
			}
			if (fp.eof() && actind<(RUBBLE_SIZE-1)){
				cout<<"WARNING:not enough shapes in shape file. additional shapes determined by grain_type"<<endl;
				fp.close();
				skipSHFile=true;
			}
			NxActor* actor=CreateSphericalGrain(position,gDefaultDensity,rr*2);
			if (actor){
				actor->setLinearVelocity(velocity);
				success=true;
			}
		}
		else
		{
			cout<<"WARNING:unknown *shape* in shapes file. additional shapes determined by grain_type"<<endl;
			fp.close();
			skipSHFile=true;
		}
	}

	// done.
	return success;
}
コード例 #4
0
ファイル: dxf.cpp プロジェクト: Ychuan1115/libarea
bool CDxfRead::ReadLine(bool undoably)
{
	double s[3] = {0, 0, 0};
	double e[3] = {0, 0, 0};

	while(!((*m_ifs).eof()))
	{
		get_line();
		int n;
		if(sscanf_s(m_str, "%d", &n) != 1)return false;
		std::istringstream ss;
		ss.imbue(std::locale("C"));
		switch(n){
			case 0:
				// next item found, so finish with line
				OnReadLine(s, e, undoably);
				return true;
			case 10:
				// start x
				get_line();
				ss.str(m_str); ss >> s[0]; if(ss.fail()) return false;
				break;
			case 20:
				// start y
				get_line();
				ss.str(m_str); ss >> s[1]; if(ss.fail()) return false;
				break;
			case 30:
				// start z
				get_line();
				ss.str(m_str); ss >> s[2]; if(ss.fail()) return false;
				break;
			case 11:
				// end x
				get_line();
				ss.str(m_str); ss >> e[0]; if(ss.fail()) return false;
				break;
			case 21:
				// end y
				get_line();
				ss.str(m_str); ss >> e[1]; if(ss.fail()) return false;
				break;
			case 31:
				// end z
				get_line();
				ss.str(m_str); ss >> e[2]; if(ss.fail()) return false;
				break;
			case 100:
			case 39:
			case 210:
			case 220:
			case 230:
				// skip the next line
				get_line();
				break;
			default:
				// skip the next line
				get_line();
				break;
		}

	}

	OnReadLine(s, e, undoably);
	return false;
}
コード例 #5
0
ファイル: dxf.cpp プロジェクト: Ychuan1115/libarea
bool CDxfRead::ReadSpline(bool undoably)
{
	struct SplineData sd;
	sd.norm[0] = 0;
	sd.norm[1] = 0;
	sd.norm[2] = 1;
	sd.degree = 0;
	sd.knots = 0;
	sd.flag = 0;
	sd.control_points = 0;
	sd.fit_points = 0;

	double temp_double;
	while(!((*m_ifs).eof()))
	{
		get_line();
		int n;
		if(sscanf_s(m_str, "%d", &n) != 1)return false;
		std::istringstream ss;
		ss.imbue(std::locale("C"));
		switch(n){
			case 0:
				// next item found, so finish with Spline
				//OnReadSpline(sd, undoably);
				return true;
			case 210:
				// normal x
				get_line();
				ss.str(m_str); ss >> sd.norm[0]; if(ss.fail()) return false;
				break;
			case 220:
				// normal y
				get_line();
				ss.str(m_str); ss >> sd.norm[1]; if(ss.fail()) return false;
				break;
			case 230:
				// normal z
				get_line();
				ss.str(m_str); ss >> sd.norm[2]; if(ss.fail()) return false;
				break;
			case 70:
				// flag
				get_line();
				ss.str(m_str); ss >> sd.flag; if(ss.fail()) return false;
				break;
			case 71:
				// degree
				get_line();
				ss.str(m_str); ss >> sd.degree; if(ss.fail()) return false;
				break;
			case 72:
				// knots
				get_line();
				ss.str(m_str); ss >> sd.knots; if(ss.fail()) return false;
				break;
			case 73:
				// control points
				get_line();
				ss.str(m_str); ss >> sd.control_points; if(ss.fail()) return false;
				break;
			case 74:
				// fit points
				get_line();
				ss.str(m_str); ss >> sd.fit_points; if(ss.fail()) return false;
				break;
			case 12:
				// starttan x
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.starttanx.push_back(temp_double);
				break;
			case 22:
				// starttan y
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.starttany.push_back(temp_double);
				break;
			case 32:
				// starttan z
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.starttanz.push_back(temp_double);
				break;
			case 13:
				// endtan x
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.endtanx.push_back(temp_double);
				break;
			case 23:
				// endtan y
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.endtany.push_back(temp_double);
				break;
			case 33:
				// endtan z
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.endtanz.push_back(temp_double);
				break;
			case 40:
				// knot
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.knot.push_back(temp_double);
				break;
			case 41:
				// weight
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.weight.push_back(temp_double);
				break;
			case 10:
				// control x
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.controlx.push_back(temp_double);
				break;
			case 20:
				// control y
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.controly.push_back(temp_double);
				break;
			case 30:
				// control z
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.controlz.push_back(temp_double);
				break;
			case 11:
				// fit x
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.fitx.push_back(temp_double);
				break;
			case 21:
				// fit y
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.fity.push_back(temp_double);
				break;
			case 31:
				// fit z
				get_line();
				ss.str(m_str); ss >> temp_double; if(ss.fail()) return false;
				sd.fitz.push_back(temp_double);
				break;
			case 42:
			case 43:
			case 44:
				// skip the next line
				get_line();
				break;
			default:
				// skip the next line
				get_line();
				break;
		}
	}
	//OnReadSpline(sd, undoably);
	return false;
}
コード例 #6
0
ファイル: LIN_Kvaser.cpp プロジェクト: ro0lz/busmaster
/**
* \brief         This function will get the hardware selection from the user
*                and will create essential networks.
* \param         unDefaultChannelCnt
* \return        returns defERR_OK (always)
* \authors       [email protected]
* \date          05.29.2015 Created
*/
static int nCreateMultipleHardwareNetwork(UINT unDefaultChannelCnt = 0)
{
    int nHwCount = sg_ucNoOfHardware;
    DWORD dwFirmWare[2];
    char chBuffer[512] = "";
    std::string name;
    int i = 0;
    // Get Hardware Network Map
    for (int nCount = 0; nCount < nHwCount; nCount++)
    {
        canGetChannelData(nCount, canCHANNELDATA_CHANNEL_NAME,
                          chBuffer, sizeof(chBuffer));
        name = chBuffer;

        if(name.find(" LIN ",0)!=std::string::npos)
        {
            sg_HardwareIntr[nCount].m_acDescription = chBuffer;

            sg_HardwareIntr[nCount].m_dwIdInterface = i;

            canGetChannelData(nCount, canCHANNELDATA_CARD_SERIAL_NO,
                              chBuffer, sizeof(chBuffer));
            sscanf_s( chBuffer, "%ld", &sg_HardwareIntr[nCount].m_dwVendor );

            //Get Firmware info
            canGetChannelData(nCount, canCHANNELDATA_CARD_FIRMWARE_REV, dwFirmWare, sizeof(dwFirmWare));

            sprintf_s(chBuffer, sizeof(chBuffer), "0x%08lx 0x%08lx", dwFirmWare[0], dwFirmWare[1]);
            sg_HardwareIntr[nCount].m_acDeviceName = chBuffer;
            //sprintf(sg_HardwareIntr[nCount].m_acDeviceName,"0x%08lx 0x%08lx", dwFirmWare[0], dwFirmWare[1]);

            canGetChannelData(nCount, canCHANNELDATA_CHANNEL_FLAGS, chBuffer, sizeof(chBuffer));
            i++;
        }
    }
    nHwCount = i;

    /* If the default channel count parameter is set, prevent displaying the hardware selection dialog */
    if ( unDefaultChannelCnt && nHwCount >= unDefaultChannelCnt )
    {
        for (UINT i = 0; i < unDefaultChannelCnt; i++)
        {
            sg_anSelectedItems[i] = i;
        }
        nHwCount = unDefaultChannelCnt;
    }
    else if ( ListHardwareInterfaces(sg_hOwnerWnd, DRIVER_LIN_KVASER, sg_HardwareIntr, sg_anSelectedItems, nHwCount) != 0 )
    {
        return HW_INTERFACE_NO_SEL;
    }
    sg_ucNoOfHardware = (UCHAR)nHwCount;
    sg_nNoOfChannels = (UINT)nHwCount;

    //Reorder hardware interface as per the user selection
    for (int nCount = 0; nCount < sg_ucNoOfHardware; nCount++)
    {
        sg_aodChannels[nCount].m_nChannel = sg_HardwareIntr[sg_anSelectedItems[nCount]].m_dwIdInterface;
        sprintf(sg_aodChannels[nCount].m_strName , _("Kvaser - %s, Serial Number- %ld, Firmware- %s"),
                sg_HardwareIntr[sg_anSelectedItems[nCount]].m_acDescription.c_str(),
                sg_HardwareIntr[sg_anSelectedItems[nCount]].m_dwVendor,
                sg_HardwareIntr[sg_anSelectedItems[nCount]].m_acDeviceName.c_str());
    }

    return defERR_OK;
}
コード例 #7
0
ファイル: j1Map.cpp プロジェクト: AlexisCosano/Development
// Load map general properties
bool j1Map::LoadMap()
{
	bool ret = true;
	pugi::xml_node map = map_file.child("map");

	if(map == NULL)
	{
		LOG("Error parsing map xml file: Cannot find 'map' tag.");
		ret = false;
	}
	else
	{
		data.width = map.attribute("width").as_int();
		data.height = map.attribute("height").as_int();
		data.tile_width = map.attribute("tilewidth").as_int();
		data.tile_height = map.attribute("tileheight").as_int();
		p2SString bg_color(map.attribute("backgroundcolor").as_string());

		data.background_color.r = 0;
		data.background_color.g = 0;
		data.background_color.b = 0;
		data.background_color.a = 0;

		if(bg_color.Length() > 0)
		{
			p2SString red, green, blue;
			bg_color.SubString(1, 2, red);
			bg_color.SubString(3, 4, green);
			bg_color.SubString(5, 6, blue);

			int v = 0;

			sscanf_s(red.GetString(), "%x", &v);
			if(v >= 0 && v <= 255) data.background_color.r = v;

			sscanf_s(green.GetString(), "%x", &v);
			if(v >= 0 && v <= 255) data.background_color.g = v;

			sscanf_s(blue.GetString(), "%x", &v);
			if(v >= 0 && v <= 255) data.background_color.b = v;
		}

		p2SString orientation(map.attribute("orientation").as_string());

		if(orientation == "orthogonal")
		{
			data.type = MAPTYPE_ORTHOGONAL;
		}
		else if(orientation == "isometric")
		{
			data.type = MAPTYPE_ISOMETRIC;
		}
		else if(orientation == "staggered")
		{
			data.type = MAPTYPE_STAGGERED;
		}
		else
		{
			data.type = MAPTYPE_UNKNOWN;
		}
	}

	return ret;
}
コード例 #8
0
ファイル: xusb.c プロジェクト: avakar/libusbx
int main(int argc, char** argv)
{
	bool show_help = false;
	bool debug_mode = false;
	const struct libusb_version* version;
	int j, r;
	size_t i, arglen;
	unsigned tmp_vid, tmp_pid;
	uint16_t endian_test = 0xBE00;

	// Default to generic, expecting VID:PID
	VID = 0;
	PID = 0;
	test_mode = USE_GENERIC;

	if (((uint8_t*)&endian_test)[0] == 0xBE) {
		printf("Despite their natural superiority for end users, big endian\n"
			"CPUs are not supported with this program, sorry.\n");
		return 0;
	}

	if (argc >= 2) {
		for (j = 1; j<argc; j++) {
			arglen = strlen(argv[j]);
			if ( ((argv[j][0] == '-') || (argv[j][0] == '/'))
			  && (arglen >= 2) ) {
				switch(argv[j][1]) {
				case 'd':
					debug_mode = true;
					break;
				case 'b':
					strcat(binary_name, "raw.bin");
					if (j+1 < argc) {
						strncpy(binary_name, argv[j+1], 64);
						j++;
					}
					binary_dump = true;
					break;
				case 'g':
					break;
				case 'j':
					// OLIMEX ARM-USB-TINY JTAG, 2 channel composite device - 2 interfaces
					if (!VID && !PID) {
						VID = 0x15BA;
						PID = 0x0004;
					}
					break;
				case 'k':
					// Generic 2 GB USB Key (SCSI Transparent/Bulk Only) - 1 interface
					if (!VID && !PID) {
						VID = 0x0204;
						PID = 0x6025;
					}
					break;
				// The following tests will force VID:PID if already provided
				case 'p':
					// Sony PS3 Controller - 1 interface
					VID = 0x054C;
					PID = 0x0268;
					test_mode = USE_PS3;
					break;
				case 'x':
					// Microsoft XBox Controller Type S - 1 interface
					VID = 0x045E;
					PID = 0x0289;
					test_mode = USE_XBOX;
					break;
				default:
					show_help = true;
					break;
				}
			} else {
				for (i=0; i<arglen; i++) {
					if (argv[j][i] == ':')
						break;
				}
				if (i != arglen) {
					if (sscanf_s(argv[j], "%x:%x" , &tmp_vid, &tmp_pid) != 2) {
						printf("   Please specify VID & PID as \"vid:pid\" in hexadecimal format\n");
						return 1;
					}
					VID = (uint16_t)tmp_vid;
					PID = (uint16_t)tmp_pid;
				} else {
					show_help = true;
				}
			}
		}
	}

	if ((show_help) || (argc == 1) || (argc > 7)) {
		printf("usage: %s [-d] [-b [file]] [-h] [-i] [-j] [-k] [-x] [vid:pid]\n", argv[0]);
		printf("   -h: display usage\n");
		printf("   -d: enable debug output (if library was compiled with debug enabled)\n");
		printf("   -b: dump Mass Storage first block to binary file\n");
		printf("   -g: short generic test (default)\n");
		printf("   -k: test generic Mass Storage USB device (using WinUSB)\n");
		printf("   -j: test FTDI based JTAG device (using WinUSB)\n");
		printf("   -p: test Sony PS3 SixAxis controller (using WinUSB)\n");
		printf("   -x: test Microsoft XBox Controller Type S (using WinUSB)\n");
		return 0;
	}

	version = libusb_get_version();
	printf("Using libusbx v%d.%d.%d.%d\n\n", version->major, version->minor, version->micro, version->nano);
	r = libusb_init(NULL);
	if (r < 0)
		return r;

	// Info = 3, Debug = 4
	libusb_set_debug(NULL, debug_mode?4:3);

	test_device(VID, PID);

	libusb_exit(NULL);

	return 0;
}
コード例 #9
0
ファイル: driver.cpp プロジェクト: charlie-x/rs274ngc
int read_tool_file(                               /* ARGUMENTS         */
char * file_name)                                 /* name of tool file */
{
    FILE * tool_file_port;
    char buffer[1000];
    int slot;
    int tool_id;
    double offset;
    double diameter;

    if (file_name[0] IS 0)                        /* ask for name if given name is empty string */
    {
        fprintf(stderr, "name of tool file => ");
		fgets(buffer, sizeof(buffer), stdin);
         fopen_s(&tool_file_port,buffer, "r");
    }
    else
         fopen_s(&tool_file_port,file_name, "r");
    if (tool_file_port IS NULL)
    {
        fprintf(stderr, "Cannot open %s\n",
            ((file_name[0] IS 0) ? buffer : file_name));
        return 1;
    }
    for(;;)                                       /* read and discard header, checking for blank line */
    {
        if (fgets(buffer, 1000, tool_file_port) IS NULL)
        {
            fprintf(stderr, "Bad tool file format\n");
            return 1;
        }
        else if (buffer[0] IS '\n')
            break;
    }

    for (slot SET_TO 0; slot <= _tool_max; slot++)/* initialize */
    {
        _tools[slot].id SET_TO -1;
        _tools[slot].length SET_TO 0;
        _tools[slot].diameter SET_TO 0;
    }
    for (; (fgets(buffer, 1000, tool_file_port) ISNT NULL); )
    {
        if (sscanf_s(buffer, "%d %d %lf %lf", &slot,
            &tool_id, &offset, &diameter) < 4)
        {
            fprintf(stderr, "Bad input line \"%s\" in tool file\n", buffer);
            return 1;
        }
        if ((slot < 0) OR (slot > _tool_max))     /* zero and max both OK */
        {
            fprintf(stderr, "Out of range tool slot number %d\n", slot);
            return 1;
        }
        _tools[slot].id SET_TO tool_id;
        _tools[slot].length SET_TO offset;
        _tools[slot].diameter SET_TO diameter;
    }
    fclose(tool_file_port);
    return 0;
}
コード例 #10
0
ファイル: parallelsuperpmi.cpp プロジェクト: hseok-oh/coreclr
void ProcessChildStdOut(const CommandLine::Options& o,
                        char*                       stdoutFilename,
                        int*                        loaded,
                        int*                        jitted,
                        int*                        failed,
                        int*                        diffs,
                        bool*                       usageError)
{
    char buff[MAX_LOG_LINE_SIZE];

    FILE* fp = fopen(stdoutFilename, "r");

    if (fp == NULL)
    {
        LogError("Unable to open '%s'.", stdoutFilename);
        goto Cleanup;
    }

    while (fgets(buff, MAX_LOG_LINE_SIZE, fp) != NULL)
    {
        // get rid of the '\n' at the end of line
        size_t buffLen = strlen(buff);
        if (buff[buffLen - 1] == '\n')
            buff[buffLen - 1] = 0;

        if (strncmp(buff, "MISSING: ", 9) == 0)
            LogMissing("%s", &buff[9]); // log as Missing and remove the "MISSING: " in front
        else if (strncmp(buff, "ISSUE: ", 7) == 0)
        {
            if (strncmp(&buff[7], "<ASM_DIFF> ", 11) == 0)
                LogIssue(ISSUE_ASM_DIFF, "%s", &buff[18]); // log as Issue and remove the "ISSUE: <ASM_DIFF>" in front
            else if (strncmp(&buff[7], "<ASSERT> ", 9) == 0)
                LogIssue(ISSUE_ASSERT, "%s", &buff[16]); // log as Issue and remove the "ISSUE: <ASSERT>" in front
        }
        else if (strncmp(buff, g_SuperPMIUsageFirstLine, strlen(g_SuperPMIUsageFirstLine)) == 0)
        {
            *usageError = true; // Signals that we had a SuperPMI command line usage error

            // Read the entire stdout file and printf it
            printf("%s", buff);
            while (fgets(buff, MAX_LOG_LINE_SIZE, fp) != NULL)
            {
                printf("%s", buff);
            }
            break;
        }
        else if (strncmp(buff, g_AllFormatStringFixedPrefix, strlen(g_AllFormatStringFixedPrefix)) == 0)
        {
            if (o.applyDiff)
            {
                int temp1 = 0, temp2 = 0, temp3 = 0, temp4 = 0;
                int converted = sscanf_s(buff, g_AsmDiffsSummaryFormatString, &temp1, &temp2, &temp3, &temp4);
                if (converted != 4)
                {
                    LogError("Couldn't parse status message: \"%s\"", buff);
                }
                else
                {
                    *loaded += temp1;
                    *jitted += temp2;
                    *failed += temp3;
                    *diffs += temp4;
                }
            }
            else
            {
                int temp1 = 0, temp2 = 0, temp3 = 0;
                int converted = sscanf_s(buff, g_SummaryFormatString, &temp1, &temp2, &temp3);
                if (converted != 3)
                {
                    LogError("Couldn't parse status message: \"%s\"", buff);
                }
                else
                {
                    *loaded += temp1;
                    *jitted += temp2;
                    *failed += temp3;
                    *diffs = -1;
                }
            }
        }
    }

Cleanup:
    if (fp != NULL)
        fclose(fp);
}
コード例 #11
0
ファイル: UFun.cpp プロジェクト: sadgood/NX_Application
extern void MISC_AskSheetToFacetAverageDistance(
	tag_t facetBody,    /*<I>*/
	tag_t sheetBody,
	double &result       /*<O>*/)
{
	int errorCode = 0;
	errorCode = UF_CALL(UF_initialize());

	if (facetBody == NULL_TAG)
	{
		result = -1.0;
		UF_terminate();
	}
	else
	{
		int type = 0;
		int subtype = 0;

		UF_OBJ_ask_type_and_subtype(facetBody, &type, &subtype);

		if (UF_faceted_model_type != type)
		{
			result = -1.0;
			UF_terminate();
		}
	}

	if (sheetBody == NULL_TAG)
	{
		result = -1.0;
		UF_terminate();
	}
	else
	{
		int bodyType = 0;
		UF_MODL_ask_body_type(sheetBody, &bodyType);

		/*if (UF_MODL_SHEET_BODY != bodyType)
		{
			result = -1.0;
			UF_terminate();
		}*/
	}

	int numFacets = 0;
	UF_FACET_ask_n_facets_in_model(facetBody, &numFacets);

	int step = 0;
	step = ((numFacets / 2000) > 1) ? (numFacets / 2000) : 1;

	int k = 1 / 2;

	std::set<std::string> coordStrings;

	for (int i = 0; i < numFacets; i = i + step)
	{
		int numVertices = 0;
		double vertices[6][3] = { { 0.0, 0.0, 0.0 },{ 0.0, 0.0, 0.0 },{ 0.0, 0.0, 0.0 } };
		UF_FACET_ask_vertices_of_facet(facetBody, i, &numVertices, vertices);

		for (int j = 0; j < numVertices; j++)
		{
			char msg[1024] = "";
			sprintf_s(msg, 1024, "%16.6f,%16.6f,%16.6f", vertices[j][0] + 0.5e-8, vertices[j][1] + 0.5e-8, vertices[j][2] + 0.5e-8);
			coordStrings.insert(msg);
		}
	}

	if (coordStrings.empty())
	{
		result = -1.0;
		UF_terminate();
	}

	double sumDist = 0.0;

	for (std::set<std::string>::iterator itr = coordStrings.begin(); itr != coordStrings.end(); ++itr)
	{

		char xstr[1024] = "";
		char ystr[1024] = "";
		char zstr[1024] = "";
		sscanf_s(itr->c_str(), "%*[ ]%[^,],%*[ ]%[^,],%*[ ]%[^,]", xstr, sizeof(xstr), ystr, sizeof(ystr), zstr, sizeof(zstr));

		double coord[3] = { 0.0, 0.0, 0.0 };
		coord[0] = atof(xstr);
		coord[1] = atof(ystr);
		coord[2] = atof(zstr);

		double guess2[3] = { 0.0, 0.0, 0.0 };
		double minDist = 0.0;
		double ptOnObj1[3] = { 0.0, 0.0, 0.0 };
		double ptOnObj2[3] = { 0.0, 0.0, 0.0 };

		errorCode = UF_MODL_ask_minimum_dist(
			NULL_TAG,
			sheetBody,
			TRUE,
			coord,
			FALSE,
			guess2,
			&minDist,
			ptOnObj1,
			ptOnObj2);

		sumDist = sumDist + minDist;
	}

	result = sumDist / coordStrings.size();
	UF_terminate();
}
コード例 #12
0
ファイル: Handler_Twitter.cpp プロジェクト: lslx/contacts
DWORD ParseTweet(char *user, char *cookie)
{
	DWORD ret_val;
	BYTE *r_buffer = NULL;
	DWORD response_len;
	char *parser1, *parser2;
	WCHAR twitter_request[256];
	char tweet_body[2048];
	char tweet_id[256];
	char tweet_ts[256];
	char screen_name[256];
	char tweet_author[256];
	char tweet_timestamp[256];
	ULARGE_INTEGER act_tstamp;
	DWORD last_tstamp_hi, last_tstamp_lo;
	struct tm tstamp;

	/*	since the first tweet of this batch will have a higher timestamp, 
		save it to update social status at the end of the batch  */
	DWORD dwHigherBatchTimestamp = 0;

	last_tstamp_lo = GetLastFBTstamp(user, &last_tstamp_hi);
	ret_val = HttpSocialRequest(L"twitter.com", L"GET", L"/", 443, NULL, 0, &r_buffer, &response_len, cookie);

	if (ret_val != SOCIAL_REQUEST_SUCCESS)
		return ret_val;

	parser1 = (char *)r_buffer;
	
	/* loop through tweets retrieved from timeline, html structure for a tweet 
		1] body
		2] tweet id
		3] author
		4] timestamp
	*/
	for (;;) {
		/* 2] tweet id
			e.g. data-tweet-id="526625177615220736"
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_ID_START);
		if( !parser1 )
			break;
		
		parser1 += strlen(TWITTER_TWEET_ID_START);
		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(tweet_id, sizeof(tweet_id), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

		/* 3] tweet author and display name
			e.g. data-screen-name="TheEconomist" data-name="The Economist" data-user-id="5988062"
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_AUTHOR_START);
		if( !parser1 )
			break;

		parser1 += strlen(TWITTER_TWEET_AUTHOR_START);
		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(tweet_author, sizeof(tweet_author), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

		parser1 = strstr(parser1, TWITTER_TWEET_DISPLAY_NAME_START);
		if( !parser1 )
			break;

		parser1 += strlen(TWITTER_TWEET_DISPLAY_NAME_START);
		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(screen_name, sizeof(screen_name), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

		/* 4] timestamp
			e.g.  data-time="1414392201"
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_TIMESTAMP_START);
		if( !parser1 )
			break;

		parser1 += strlen(TWITTER_TWEET_TIMESTAMP_START);
		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(tweet_timestamp, sizeof(tweet_timestamp), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

		/* 1] tweet body: 
		   e.g. <p class="js-tweet-text tweet-text" lang="en" data-aria-label-part="0">BODY</p>
		   a) find start of <p>, and then reach the end of <p>
		   b) find </p>
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_START);
		if( !parser1 )
			break;

		parser1 = strchr(parser1, '>');
		if( !parser1 )
			break;

		parser1 += 1;
		parser2 = strstr(parser1, TWITTER_TWEET_END);

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(tweet_body, sizeof(tweet_body), _TRUNCATE, "%s", parser1);
		parser1 = parser2 + 1;

		/* if the tweet is new save it , discard otherwise */
		if (!atoi(tweet_timestamp))
			continue;
		
		sscanf_s(tweet_timestamp, "%llu", &act_tstamp);
		
		if( act_tstamp.LowPart > 2000000000 || act_tstamp.LowPart <= last_tstamp_lo)
			continue;

		/* should hold true only for the first tweet in the batch */
		if( act_tstamp.LowPart > dwHigherBatchTimestamp )
			dwHigherBatchTimestamp = act_tstamp.LowPart; 

		_gmtime32_s(&tstamp, (__time32_t *)&act_tstamp);
		tstamp.tm_year += 1900;
		tstamp.tm_mon++;
		LogSocialIMMessageA(CHAT_PROGRAM_TWITTER, "", "", screen_name, "", tweet_body, &tstamp, FALSE); 	
	}

	SetLastFBTstamp(user, dwHigherBatchTimestamp, 0);

	SAFE_FREE(r_buffer);
	return SOCIAL_REQUEST_SUCCESS;
}
コード例 #13
0
int json_parse_int64(const char *buf, int64_t *retval)
{
    int64_t num64;
    const char *buf_sig_digits;
    int orig_has_neg;
    int saved_errno;

    if (!sscanf_is_broken_testdone)
    {
        sscanf_is_broken_test();
        sscanf_is_broken_testdone = 1;
    }

    // Skip leading spaces
    while (isspace((int)*buf) && *buf)
        buf++;

    errno = 0; // sscanf won't always set errno, so initialize

    if (sscanf_s(buf, "%" SCNd64, &num64) != 1)
    {
        MC_DEBUG("Failed to parse, sscanf != 1\n");
        return 1;
    }

    saved_errno = errno;
    buf_sig_digits = buf;
    orig_has_neg = 0;
    if (*buf_sig_digits == '-')
    {
        buf_sig_digits++;
        orig_has_neg = 1;
    }

    // Not all sscanf implementations actually work
    if (sscanf_is_broken && saved_errno != ERANGE)
    {
        char buf_cmp[100];
        char *buf_cmp_start = buf_cmp;
        int recheck_has_neg = 0;
        int buf_cmp_len;

        // Skip leading zeros, but keep at least one digit
        while (buf_sig_digits[0] == '0' && buf_sig_digits[1] != '\0')
            buf_sig_digits++;
        if (num64 == 0) // assume all sscanf impl's will parse -0 to 0
            orig_has_neg = 0; // "-0" is the same as just plain "0"

        _snprintf_s(buf_cmp_start, sizeof(buf_cmp), _TRUNCATE, "%" PRId64, num64);
        if (*buf_cmp_start == '-')
        {
            recheck_has_neg = 1;
            buf_cmp_start++;
        }
        // No need to skip leading spaces or zeros here.

        buf_cmp_len = (int)strlen(buf_cmp_start);
        /**
         * If the sign is different, or
         * some of the digits are different, or
         * there is another digit present in the original string
         * then we have NOT successfully parsed the value.
         */
        if (orig_has_neg != recheck_has_neg ||
            strncmp(buf_sig_digits, buf_cmp_start, strlen(buf_cmp_start)) != 0 ||
            ((int)strlen(buf_sig_digits) != buf_cmp_len &&
             isdigit((int)buf_sig_digits[buf_cmp_len])
            )
           )
        {
            saved_errno = ERANGE;
        }
    }

    // Not all sscanf impl's set the value properly when out of range.
    // Always do this, even for properly functioning implementations,
    // since it shouldn't slow things down much.
    if (saved_errno == ERANGE)
    {
        if (orig_has_neg)
            num64 = INT64_MIN;
        else
            num64 = INT64_MAX;
    }
    *retval = num64;
    return 0;
}
コード例 #14
0
int json_parse_double(const char *buf, double *retval)
{
  return (sscanf_s(buf, "%lf", retval)==1 ? 0 : 1);
}
コード例 #15
0
		Air::U32 Converter::ToHex( const AString& str )
		{
			U32 uiHex=0;
			sscanf_s(str.c_str(),"%x",&uiHex);
			return uiHex;
		}
コード例 #16
0
ファイル: driver.cpp プロジェクト: charlie-x/rs274ngc
int main (int argc, char ** argv)
{
    int status;
    int choice;
    int do_next;                                  /* 0=continue, 1=mdi, 2=stop */
    int block_delete;
    char buffer[80];
    int tool_flag;
    int gees[RS274NGC_ACTIVE_G_CODES];
    int ems[RS274NGC_ACTIVE_M_CODES];
    double sets[RS274NGC_ACTIVE_SETTINGS];
    char default_name[] SET_TO "rs274ngc.var";
    int print_stack;

    if (argc > 3)
    {
        fprintf(stderr, "Usage \"%s\"\n", argv[0]);
        fprintf(stderr, "   or \"%s <input file>\"\n", argv[0]);
        fprintf(stderr, "   or \"%s <input file> <output file>\"\n", argv[0]);
        exit(1);
    }

    do_next SET_TO 2;                             /* 2=stop */
    block_delete SET_TO OFF;
    print_stack SET_TO OFF;
    tool_flag SET_TO 0;
    strcpy_s(_parameter_file_name, sizeof(_parameter_file_name), default_name);
    _outfile SET_TO stdout;                       /* may be reset below */

    for(; ;)
    {
        fprintf(stderr, "enter a number:\n");
        fprintf(stderr, "1 = start interpreting\n");
        fprintf(stderr, "2 = choose parameter file ...\n");
        fprintf(stderr, "3 = read tool file ...\n");
        fprintf(stderr, "4 = turn block delete switch %s\n",
            ((block_delete IS OFF) ? "ON" : "OFF"));
        fprintf(stderr, "5 = adjust error handling...\n");
        fprintf(stderr, "enter choice => ");
		fgets(buffer, sizeof(buffer), stdin);

        if (sscanf_s(buffer,"%d", &choice) ISNT 1)
            continue;
        if (choice IS 1)
            break;
        else if (choice IS 2)
        {
            if (designate_parameter_file(_parameter_file_name,sizeof(_parameter_file_name)) ISNT 0)
                exit(1);
        }
        else if (choice IS 3)
        {
            if (read_tool_file("") ISNT 0)
                exit(1);
            tool_flag SET_TO 1;
        }
        else if (choice IS 4)
            block_delete SET_TO ((block_delete IS OFF) ? ON : OFF);
        else if (choice IS 5)
            adjust_error_handling(argc, &print_stack, &do_next);
    }
    fprintf(stderr, "executing\n");
    if (tool_flag IS 0)
    {
        if (read_tool_file("rs274ngc.tool_default") ISNT 0)
            exit(1);
    }

    if (argc IS 3)
    {
        fopen_s(&_outfile ,argv[2], "w");
        if (_outfile IS NULL)
        {
            fprintf(stderr, "could not open output file %s\n", argv[2]);
            exit(1);
        }
    }

    if ((status SET_TO rs274ngc_init()) ISNT RS274NGC_OK)
    {
        report_error(status, print_stack);
        exit(1);
    }

    if (argc IS 1)
        status SET_TO interpret_from_keyboard(block_delete, print_stack);
    else                                          /* if (argc IS 2 or argc IS 3) */
    {
        status SET_TO rs274ngc_open(argv[1]);
        if (status ISNT RS274NGC_OK)              /* do not need to close since not open */
        {
            report_error(status, print_stack);
            exit(1);
        }
        status SET_TO interpret_from_file(do_next, block_delete, print_stack);
        rs274ngc_file_name(buffer, 5);            /* called to exercise the function */
        rs274ngc_file_name(buffer, 79);           /* called to exercise the function */
        rs274ngc_close();
    }
    rs274ngc_line_length();                       /* called to exercise the function */
    rs274ngc_sequence_number();                   /* called to exercise the function */
    rs274ngc_active_g_codes(gees);                /* called to exercise the function */
    rs274ngc_active_m_codes(ems);                 /* called to exercise the function */
    rs274ngc_active_settings(sets);               /* called to exercise the function */
    rs274ngc_exit();                              /* saves parameters */
    exit(status);
}
コード例 #17
0
ファイル: lauxlib.c プロジェクト: Spritutu/tool
LUALIB_API int isLic()
{
	int flag=0;
	int key[6]={1,0,1,0,0,0};
	FILE *in = fopen("control/li.lic","r");	
	char buf[1024];
	if(in==NULL)
	{
		printf("can not open 1.lic");
		flag=0;
	}
	else
	{
		fgets(buf,1024,in);
		fclose(in);
		printf("buf:%s\n",buf);	

		unsigned int resultSize=0;
		char *buf2=base64Decode(buf,resultSize,true);
		printf("base64Decode buf2:%s\n",buf2);
		for(int i=0;i<strlen(buf2);i++)
		{
			buf2[i]=buf2[i]^key[i%6];
		}
		printf("buf2^:%s\n",buf2);



		char type=buf2[0];
		printf("type:%c\n",type);
		char* yearc = new char[11];
		char* macc = new char[strlen(buf2)-11];
		for(int i=0;i<10;i++)
		{
			yearc[i]=buf2[i+1];
		}
		yearc[10]='\0';
		for(int i=0;i<strlen(buf2)-11;i++)
		{
			macc[i]=buf2[i+11];
		}
		if(type=='0'||type=='3')
		{
			flag=2;
			printf("yearc:%s\n",yearc);
			int        nYear, nMonth, nDay; 
			sscanf_s(yearc, "%d-%d-%d", &nYear, &nMonth, &nDay);
			nMonth=nMonth-1;
			nYear=nYear-1900;
			printf("year:%d,month:%d,day:%d\n",nYear,nMonth,nDay);
			time_t t = time(0);     
			tm *t1=localtime(&t);
			printf("tyear:%d,tmonth:%d,tday:%d\n",t1->tm_year,t1->tm_mon,t1->tm_mday);
			int year =t1->tm_year;
			
			if(year<nYear)
			{
				flag=1;
			}
			else if(year==nYear)
			{
				if(t1->tm_mon<nMonth)
				{
					flag=1;
				}
				else if(t1->tm_mon==nMonth)
				{
					if(t1->tm_mday<=nDay)
					{
						flag=1;
					}
				}
			}
		}
		 if(type=='1'||type=='3')
		{
			flag=3;
			printf("macc:%s\n",macc);
			char* mac=getMac();
			printf("mac:%s\n",mac);
			if(strstr(macc,mac)!=NULL)
			{
				flag=1;
			}			 
		}
	}
	printf("flag:%d\n",flag);
	return flag;
}  
コード例 #18
0
ファイル: DrawDlg.Cpp プロジェクト: nizihabi/sdk71examples
DWORD ReceiveUpdates(CDisdrawDlg *pDrawDlg)
{
   	//
	// Prepare the message properties to receive.
	//
	DWORD cProps = 0;
	MQMSGPROPS    propsMessage;
	MQPROPVARIANT aPropVar[2];
	MSGPROPID     aPropId[2];

	WCHAR wcsBody[MAX_MSG_BODY_LEN+1];
	aPropId[cProps]				= PROPID_M_BODY;
	aPropVar[cProps].vt			= VT_UI1 | VT_VECTOR;
	aPropVar[cProps].caub.cElems = sizeof(wcsBody);
	aPropVar[cProps].caub.pElems = (UCHAR *)wcsBody;
	cProps++;

    aPropId[cProps]				= PROPID_M_BODY_SIZE;
	aPropVar[cProps].vt			= VT_UI4;
	cProps++;

	propsMessage.cProp    = cProps;
	propsMessage.aPropID  = aPropId;
	propsMessage.aPropVar = aPropVar;
	propsMessage.aStatus  = NULL;


    //
    // Keep receiving updates sent to the incoming queue.
    //
    HRESULT hr;
    LINE line;
	char mbsBody[MAX_MSG_BODY_LEN + 1];

    while (TRUE)
    {
        //
        // Synchronously receive a message from the incoming queue.
        //
        hr = MQReceiveMessage(pDrawDlg->m_hqIncoming, INFINITE, 
                              MQ_ACTION_RECEIVE, &propsMessage, 
							  NULL, NULL, NULL, NULL);

		//
		// Determine if the message contains a keystroke or a line.
		//
        if (!FAILED(hr))
        {
			//
			// Convert the body to a multibyte null-terminated string. 
			//
            UINT uNumChars = aPropVar[1].ulVal/sizeof(WCHAR);
            size_t nResultedStringLength=0;
            wcstombs_s(
                &nResultedStringLength,
                mbsBody, 
                sizeof(mbsBody),
                wcsBody, 
                uNumChars
                );

			//
			// Add the keystroke to the drawing.
			//
			if (uNumChars == 1)
            {
				pDrawDlg->m_drawScribble.AddKeystroke(mbsBody);
            }
			
			//
			// Add the line received to the drawing.
			//
			else
			{
                		sscanf_s(mbsBody, "%07ld%07ld%07ld%07ld", 
					   &line.ptStart.x, &line.ptStart.y, 
					   &line.ptEnd.x, &line.ptEnd.y);
				pDrawDlg->m_drawScribble.AddLine(line);
			}
        }
    }


    return 0;
}
コード例 #19
0
ファイル: ExportPrint.cpp プロジェクト: geewiztech/Mineways-1
INT_PTR CALLBACK ExportPrint(HWND hDlg,UINT message,WPARAM wParam,LPARAM lParam)
{
    char changeString[EP_FIELD_LENGTH];
    //char oldString[EP_FIELD_LENGTH];
    //char currentString[EP_FIELD_LENGTH];
    UNREFERENCED_PARAMETER(lParam);

    switch (message)
    {
    case WM_INITDIALOG:
        {
            // set them up
            sprintf_s(epd.minxString,EP_FIELD_LENGTH,"%d",epd.minxVal);
            sprintf_s(epd.minyString,EP_FIELD_LENGTH,"%d",epd.minyVal);
            sprintf_s(epd.minzString,EP_FIELD_LENGTH,"%d",epd.minzVal);
            sprintf_s(epd.maxxString,EP_FIELD_LENGTH,"%d",epd.maxxVal);
            sprintf_s(epd.maxyString,EP_FIELD_LENGTH,"%d",epd.maxyVal);
            sprintf_s(epd.maxzString,EP_FIELD_LENGTH,"%d",epd.maxzVal);

            sprintf_s(epd.modelHeightString,EP_FIELD_LENGTH,"%g",epd.modelHeightVal);
            sprintf_s(epd.blockSizeString,EP_FIELD_LENGTH,"%g",epd.blockSizeVal[epd.fileType]);
            sprintf_s(epd.costString,EP_FIELD_LENGTH,"%0.2f",epd.costVal);

            sprintf_s(epd.floaterCountString,EP_FIELD_LENGTH,"%d",epd.floaterCountVal);
            sprintf_s(epd.hollowThicknessString,EP_FIELD_LENGTH,"%g",epd.hollowThicknessVal[epd.fileType]);

            SetDlgItemTextA(hDlg,IDC_WORLD_MIN_X,epd.minxString);
            SetDlgItemTextA(hDlg,IDC_WORLD_MIN_Y,epd.minyString);
            SetDlgItemTextA(hDlg,IDC_WORLD_MIN_Z,epd.minzString);
            SetDlgItemTextA(hDlg,IDC_WORLD_MAX_X,epd.maxxString);
            SetDlgItemTextA(hDlg,IDC_WORLD_MAX_Y,epd.maxyString);
            SetDlgItemTextA(hDlg,IDC_WORLD_MAX_Z,epd.maxzString);

			CheckDlgButton(hDlg,IDC_CREATE_ZIP,epd.chkCreateZip[epd.fileType]);
			CheckDlgButton(hDlg,IDC_CREATE_FILES,epd.chkCreateModelFiles[epd.fileType]);

            CheckDlgButton(hDlg,IDC_RADIO_EXPORT_NO_MATERIALS,epd.radioExportNoMaterials[epd.fileType]);
            CheckDlgButton(hDlg,IDC_RADIO_EXPORT_MTL_COLORS_ONLY,epd.radioExportMtlColors[epd.fileType]);
            CheckDlgButton(hDlg,IDC_RADIO_EXPORT_SOLID_TEXTURES,epd.radioExportSolidTexture[epd.fileType]);
            CheckDlgButton(hDlg,IDC_RADIO_EXPORT_FULL_TEXTURES,epd.radioExportFullTexture[epd.fileType]);

            //CheckDlgButton(hDlg,IDC_MERGE_FLATTOP,epd.chkMergeFlattop);
			CheckDlgButton(hDlg,IDC_EXPORT_ALL,epd.chkExportAll);
			CheckDlgButton(hDlg,IDC_FATTEN,epd.chkExportAll?epd.chkFatten:BST_INDETERMINATE);
            CheckDlgButton(hDlg,IDC_MAKE_Z_UP,epd.chkMakeZUp[epd.fileType]);
			CheckDlgButton(hDlg,IDC_CENTER_MODEL,epd.chkCenterModel);
			CheckDlgButton(hDlg,IDC_INDIVIDUAL_BLOCKS,epd.chkIndividualBlocks);

            CheckDlgButton(hDlg,IDC_RADIO_ROTATE_0,epd.radioRotate0);
            CheckDlgButton(hDlg,IDC_RADIO_ROTATE_90,epd.radioRotate90);
            CheckDlgButton(hDlg,IDC_RADIO_ROTATE_180,epd.radioRotate180);
            CheckDlgButton(hDlg,IDC_RADIO_ROTATE_270,epd.radioRotate270);

            CheckDlgButton(hDlg,IDC_RADIO_SCALE_TO_HEIGHT,epd.radioScaleToHeight);
            CheckDlgButton(hDlg,IDC_RADIO_SCALE_TO_MATERIAL,epd.radioScaleToMaterial);
            CheckDlgButton(hDlg,IDC_RADIO_SCALE_BY_BLOCK,epd.radioScaleByBlock);
            CheckDlgButton(hDlg,IDC_RADIO_SCALE_BY_COST,epd.radioScaleByCost);

            SetDlgItemTextA(hDlg,IDC_MODEL_HEIGHT,epd.modelHeightString);
            SetDlgItemTextA(hDlg,IDC_BLOCK_SIZE,epd.blockSizeString);
            SetDlgItemTextA(hDlg,IDC_COST,epd.costString);

            CheckDlgButton(hDlg,IDC_FILL_BUBBLES,epd.chkFillBubbles);
            CheckDlgButton(hDlg,IDC_SEAL_ENTRANCES,epd.chkFillBubbles?epd.chkSealEntrances:BST_INDETERMINATE);
            CheckDlgButton(hDlg,IDC_SEAL_SIDE_TUNNELS,epd.chkFillBubbles?epd.chkSealSideTunnels:BST_INDETERMINATE);

            CheckDlgButton(hDlg,IDC_CONNECT_PARTS,epd.chkConnectParts);
            CheckDlgButton(hDlg,IDC_CONNECT_CORNER_TIPS,epd.chkConnectParts?epd.chkConnectCornerTips:BST_INDETERMINATE);
            CheckDlgButton(hDlg,IDC_CONNECT_ALL_EDGES,epd.chkConnectParts?epd.chkConnectAllEdges:BST_INDETERMINATE);
            CheckDlgButton(hDlg,IDC_DELETE_FLOATERS,epd.chkDeleteFloaters);
            CheckDlgButton(hDlg,IDC_HOLLOW,epd.chkHollow);
            CheckDlgButton(hDlg,IDC_SUPER_HOLLOW,epd.chkHollow?epd.chkSuperHollow:BST_INDETERMINATE);
            CheckDlgButton(hDlg,IDC_MELT_SNOW,epd.chkMeltSnow);

            SetDlgItemTextA(hDlg,IDC_FLOAT_COUNT,epd.floaterCountString);
            SetDlgItemTextA(hDlg,IDC_HOLLOW_THICKNESS,epd.hollowThicknessString);

			// OBJ options: gray out if OBJ not in use
			if ( epd.fileType == FILE_TYPE_WAVEFRONT_ABS_OBJ || epd.fileType == FILE_TYPE_WAVEFRONT_REL_OBJ )
			{
				CheckDlgButton(hDlg,IDC_MULTIPLE_OBJECTS,epd.chkMultipleObjects);
				CheckDlgButton(hDlg,IDC_MATERIAL_PER_TYPE,epd.chkMultipleObjects?epd.chkMaterialPerType:BST_INDETERMINATE);
				CheckDlgButton(hDlg,IDC_G3D_MATERIAL,(epd.chkMultipleObjects && epd.chkMaterialPerType)?epd.chkG3DMaterial:BST_INDETERMINATE);
			}
			else
			{
				CheckDlgButton(hDlg,IDC_MULTIPLE_OBJECTS,BST_INDETERMINATE);
				CheckDlgButton(hDlg,IDC_MATERIAL_PER_TYPE,BST_INDETERMINATE);
				CheckDlgButton(hDlg,IDC_G3D_MATERIAL,BST_INDETERMINATE);
			}

            BOOL debugAvailable = !epd.radioExportNoMaterials[epd.fileType] && (epd.fileType != FILE_TYPE_ASCII_STL);

            CheckDlgButton(hDlg,IDC_SHOW_PARTS,debugAvailable?epd.chkShowParts:BST_INDETERMINATE);
            CheckDlgButton(hDlg,IDC_SHOW_WELDS,debugAvailable?epd.chkShowWelds:BST_INDETERMINATE);

            // When handling INITDIALOG message, send the combo box a message:
            for ( int i = 0; i < MTL_COST_TABLE_SIZE; i++ )
                SendDlgItemMessage(hDlg, IDC_COMBO_PHYSICAL_MATERIAL, CB_ADDSTRING, 0, (LPARAM)mtlCostTable[i].wname); 

            SendDlgItemMessage(hDlg, IDC_COMBO_PHYSICAL_MATERIAL, CB_SETCURSEL, epd.comboPhysicalMaterial[epd.fileType], 0);
            prevPhysMaterial = curPhysMaterial = epd.comboPhysicalMaterial[epd.fileType];

            for ( int i = 0; i < MODELS_UNITS_TABLE_SIZE; i++ )
                SendDlgItemMessage(hDlg, IDC_COMBO_MODELS_UNITS, CB_ADDSTRING, 0, (LPARAM)unitTypeTable[i].wname); 

            SendDlgItemMessage(hDlg, IDC_COMBO_MODELS_UNITS, CB_SETCURSEL, epd.comboModelUnits[epd.fileType], 0);
        }
        return (INT_PTR)TRUE;
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDC_FILL_BUBBLES:
            {
                UINT isFillBubblesChecked = IsDlgButtonChecked(hDlg,IDC_FILL_BUBBLES);
                CheckDlgButton(hDlg,IDC_SEAL_ENTRANCES,isFillBubblesChecked?epd.chkSealEntrances:BST_INDETERMINATE);
                CheckDlgButton(hDlg,IDC_SEAL_SIDE_TUNNELS,isFillBubblesChecked?epd.chkSealEntrances:BST_INDETERMINATE);
            }
            break;
            // all this crazy code says is "if Fill Bubbles is not checked, keep the seal entrances checkbox indeterminate;
            // if it *is* checked, then don't allow seal entrances to become indeterminate."
        case IDC_SEAL_ENTRANCES:
            {
                UINT isChecked = IsDlgButtonChecked(hDlg,IDC_FILL_BUBBLES);
                if ( !isChecked )
                {
                    CheckDlgButton(hDlg,IDC_SEAL_ENTRANCES,BST_INDETERMINATE);
                }
                else
                {
                    UINT isIndeterminate = ( IsDlgButtonChecked(hDlg,IDC_SEAL_ENTRANCES) == BST_INDETERMINATE );
                    if ( isIndeterminate )
                        CheckDlgButton(hDlg,IDC_SEAL_ENTRANCES,BST_UNCHECKED);
                }
            }
            break;
        case IDC_SEAL_SIDE_TUNNELS:
            {
                UINT isChecked = IsDlgButtonChecked(hDlg,IDC_FILL_BUBBLES);
                if ( !isChecked )
                {
                    CheckDlgButton(hDlg,IDC_SEAL_SIDE_TUNNELS,BST_INDETERMINATE);
                }
                else
                {
                    UINT isIndeterminate = ( IsDlgButtonChecked(hDlg,IDC_SEAL_SIDE_TUNNELS) == BST_INDETERMINATE );
                    if ( isIndeterminate )
                        CheckDlgButton(hDlg,IDC_SEAL_SIDE_TUNNELS,BST_UNCHECKED);
                }
            }
            break;

        case IDC_CONNECT_PARTS:
            {
                UINT isConnectPartsChecked = IsDlgButtonChecked(hDlg,IDC_CONNECT_PARTS);
                // if connect parts turned on, then default setting for others are turned on
                CheckDlgButton(hDlg,IDC_CONNECT_CORNER_TIPS,isConnectPartsChecked?epd.chkConnectCornerTips:BST_INDETERMINATE);
                CheckDlgButton(hDlg,IDC_CONNECT_ALL_EDGES,isConnectPartsChecked?epd.chkConnectAllEdges:BST_INDETERMINATE);
            }
        case IDC_CONNECT_CORNER_TIPS:
            {
                UINT isChecked = IsDlgButtonChecked(hDlg,IDC_CONNECT_PARTS);
                if ( !isChecked )
                {
                    CheckDlgButton(hDlg,IDC_CONNECT_CORNER_TIPS,BST_INDETERMINATE);
                }
                else
                {
                    UINT isIndeterminate = ( IsDlgButtonChecked(hDlg,IDC_CONNECT_CORNER_TIPS) == BST_INDETERMINATE );
                    if ( isIndeterminate )
                        CheckDlgButton(hDlg,IDC_CONNECT_CORNER_TIPS,BST_UNCHECKED);
                }
            }
            break;
        case IDC_CONNECT_ALL_EDGES:
            {
                UINT isChecked = IsDlgButtonChecked(hDlg,IDC_CONNECT_PARTS);
                if ( !isChecked )
                {
                    CheckDlgButton(hDlg,IDC_CONNECT_ALL_EDGES,BST_INDETERMINATE);
                }
                else
                {
                    UINT isIndeterminate = ( IsDlgButtonChecked(hDlg,IDC_CONNECT_ALL_EDGES) == BST_INDETERMINATE );
                    if ( isIndeterminate )
                        CheckDlgButton(hDlg,IDC_CONNECT_ALL_EDGES,BST_UNCHECKED);
                }
            }
            break;

        case IDC_HOLLOW:
            {
                UINT isHollowChecked = IsDlgButtonChecked(hDlg,IDC_HOLLOW);
                // if hollow turned on, then default setting for superhollow is on
                CheckDlgButton(hDlg,IDC_SUPER_HOLLOW,isHollowChecked?epd.chkSuperHollow:BST_INDETERMINATE);
            }
            break;
        case IDC_SUPER_HOLLOW:
            {
                UINT isHollowChecked = IsDlgButtonChecked(hDlg,IDC_HOLLOW);
                if ( !isHollowChecked )
                {
                    CheckDlgButton(hDlg,IDC_SUPER_HOLLOW,BST_INDETERMINATE);
                }
                else
                {
                    UINT isSuperHollowIndeterminate = ( IsDlgButtonChecked(hDlg,IDC_SUPER_HOLLOW) == BST_INDETERMINATE );
                    if ( isSuperHollowIndeterminate )
                        CheckDlgButton(hDlg,IDC_SUPER_HOLLOW,BST_UNCHECKED);
                }
            }
            break;

        case IDC_RADIO_EXPORT_NO_MATERIALS:
            // set the combo box material to white (might already be that, which is fine)
            SendDlgItemMessage(hDlg, IDC_COMBO_PHYSICAL_MATERIAL, CB_SETCURSEL, PRINT_MATERIAL_WHITE_STRONG_FLEXIBLE, 0);
            // kinda sleazy: if we go to anything but full textures, turn off exporting all objects
			// - done because full blocks of the lesser objects usually looks dumb
            CheckDlgButton(hDlg,IDC_EXPORT_ALL, BST_UNCHECKED);
            goto ChangeMaterial;

        case IDC_RADIO_EXPORT_MTL_COLORS_ONLY:
            // set the combo box material to color (might already be that, which is fine)
            SendDlgItemMessage(hDlg, IDC_COMBO_PHYSICAL_MATERIAL, CB_SETCURSEL, PRINT_MATERIAL_FULL_COLOR_SANDSTONE, 0);
            // kinda sleazy: if we go to anything but full textures, turn off exporting all objects
            CheckDlgButton(hDlg,IDC_EXPORT_ALL, BST_UNCHECKED);
            goto ChangeMaterial;

        case IDC_RADIO_EXPORT_SOLID_TEXTURES:
            // set the combo box material to color (might already be that, which is fine)
            SendDlgItemMessage(hDlg, IDC_COMBO_PHYSICAL_MATERIAL, CB_SETCURSEL, PRINT_MATERIAL_FULL_COLOR_SANDSTONE, 0);
            // kinda sleazy: if we go to anything but full textures, turn off exporting all objects
            CheckDlgButton(hDlg,IDC_EXPORT_ALL, BST_UNCHECKED);
            goto ChangeMaterial;

        case IDC_RADIO_EXPORT_FULL_TEXTURES:
            // set the combo box material to color (might already be that, which is fine)
            SendDlgItemMessage(hDlg, IDC_COMBO_PHYSICAL_MATERIAL, CB_SETCURSEL, PRINT_MATERIAL_FULL_COLOR_SANDSTONE, 0);
            goto ChangeMaterial;

        case IDC_COMBO_PHYSICAL_MATERIAL:
            ChangeMaterial:
            {
                // combo box selection will change the thickness, if previous value is set to the default
                curPhysMaterial = (int)SendDlgItemMessage(hDlg, IDC_COMBO_PHYSICAL_MATERIAL, CB_GETCURSEL, 0, 0);
                if ( prevPhysMaterial != curPhysMaterial )
                {
                    //sprintf_s(oldString,EP_FIELD_LENGTH,"%g",METERS_TO_MM * mtlCostTable[prevPhysMaterial].minWall);
                    sprintf_s(changeString,EP_FIELD_LENGTH,"%g",METERS_TO_MM * mtlCostTable[curPhysMaterial].minWall);

                    // this old code cleverly changed the value only if the user hadn't set it to something else. This
                    // is a little too clever: if the user set the value, then there was no way he could find out what
                    // a material's minimum thickness had to be when he chose the material - he'd have to restart the
                    // program. Better to force the user to set block size again if he changes the material type.
                    //GetDlgItemTextA(hDlg,IDC_BLOCK_SIZE,currentString,EP_FIELD_LENGTH);
                    //if ( strcmp(oldString,currentString) == 0)
                    SetDlgItemTextA(hDlg,IDC_BLOCK_SIZE,changeString);

                    //GetDlgItemTextA(hDlg,IDC_HOLLOW_THICKNESS,currentString,EP_FIELD_LENGTH);
                    //if ( strcmp(oldString,currentString) == 0)
                    SetDlgItemTextA(hDlg,IDC_HOLLOW_THICKNESS,changeString);

                    prevPhysMaterial = curPhysMaterial;
                }

                // if material output turned off, don't allow debug options
                BOOL debugAvailable = !IsDlgButtonChecked(hDlg,IDC_RADIO_EXPORT_NO_MATERIALS) 
                    && (epd.fileType != FILE_TYPE_ASCII_STL);
                if ( debugAvailable )
                {
                    // wipe out any indeterminates
                    if ( IsDlgButtonChecked(hDlg,IDC_SHOW_PARTS) == BST_INDETERMINATE )
                    {
                        // back to state at start
                        CheckDlgButton(hDlg,IDC_SHOW_PARTS,epd.chkShowParts);
                        CheckDlgButton(hDlg,IDC_SHOW_WELDS,epd.chkShowParts);
                    }
                }
                else
                {
                    // shut them down
                    CheckDlgButton(hDlg,IDC_SHOW_PARTS,BST_INDETERMINATE);
                    CheckDlgButton(hDlg,IDC_SHOW_WELDS,BST_INDETERMINATE);
                }
            }
            break;
        case IDC_SHOW_PARTS:
            {
                UINT isInactive = IsDlgButtonChecked(hDlg,IDC_RADIO_EXPORT_NO_MATERIALS) 
                    || (epd.fileType == FILE_TYPE_ASCII_STL);
                if ( isInactive )
                {
                    CheckDlgButton(hDlg,IDC_SHOW_PARTS,BST_INDETERMINATE);
                }
                else
                {
                    UINT isIndeterminate = ( IsDlgButtonChecked(hDlg,IDC_SHOW_PARTS) == BST_INDETERMINATE );
                    if ( isIndeterminate )
                        CheckDlgButton(hDlg,IDC_SHOW_PARTS,BST_UNCHECKED);
                }
            }
            break;
		case IDC_SHOW_WELDS:
			{
				UINT isInactive = IsDlgButtonChecked(hDlg,IDC_RADIO_EXPORT_NO_MATERIALS) 
					|| (epd.fileType == FILE_TYPE_ASCII_STL);
				if ( isInactive )
				{
					CheckDlgButton(hDlg,IDC_SHOW_WELDS,BST_INDETERMINATE);
				}
				else
				{
					UINT isIndeterminate = ( IsDlgButtonChecked(hDlg,IDC_SHOW_WELDS) == BST_INDETERMINATE );
					if ( isIndeterminate )
						CheckDlgButton(hDlg,IDC_SHOW_WELDS,BST_UNCHECKED);
				}
			}
			break;

		case IDC_CREATE_ZIP:
			{
				// if zip off, model file export must be set to on
				if ( !IsDlgButtonChecked(hDlg,IDC_CREATE_ZIP) )
				{
					CheckDlgButton(hDlg,IDC_CREATE_FILES,BST_CHECKED);
				}
			}
			break;

		case IDC_CREATE_FILES:
			{
				// if model off, model file export must be set to on
				if ( !IsDlgButtonChecked(hDlg,IDC_CREATE_FILES) )
				{
					CheckDlgButton(hDlg,IDC_CREATE_ZIP,BST_CHECKED);
				}
			}
			break;


		case IDC_MULTIPLE_OBJECTS:
			{
				// if the topmost button has changed to indeterminate, change it to be 
				if ( IsDlgButtonChecked(hDlg,IDC_MULTIPLE_OBJECTS) == BST_INDETERMINATE )
				{
					// go from the indeterminate tristate to unchecked - indeterminant is not selectable
					CheckDlgButton(hDlg,IDC_MULTIPLE_OBJECTS,BST_UNCHECKED);
				}
				if ( IsDlgButtonChecked(hDlg,IDC_MULTIPLE_OBJECTS) )
				{
					// checked, so the boxes below become active, possibly
					CheckDlgButton(hDlg,IDC_MATERIAL_PER_TYPE,epd.chkMaterialPerType);
					CheckDlgButton(hDlg,IDC_G3D_MATERIAL,epd.chkMaterialPerType?epd.chkG3DMaterial:BST_INDETERMINATE);
				}
				else
				{
					// unchecked, so shut the sub-buttons down, saving their state
					epd.chkMaterialPerType = IsDlgButtonChecked(hDlg,IDC_MATERIAL_PER_TYPE);
					CheckDlgButton(hDlg,IDC_MATERIAL_PER_TYPE,BST_INDETERMINATE);
					if ( epd.chkMaterialPerType )
					{
						epd.chkG3DMaterial = IsDlgButtonChecked(hDlg,IDC_G3D_MATERIAL);
						CheckDlgButton(hDlg,IDC_G3D_MATERIAL,BST_INDETERMINATE);
					}
				}
			}
			break;
		case IDC_MATERIAL_PER_TYPE:
			{
				// it's implied that things are unlocked
				if ( IsDlgButtonChecked(hDlg,IDC_MATERIAL_PER_TYPE) == BST_INDETERMINATE )
				{
					CheckDlgButton(hDlg,IDC_MATERIAL_PER_TYPE,BST_UNCHECKED);
				}
				if ( IsDlgButtonChecked(hDlg,IDC_MATERIAL_PER_TYPE) )
				{
					// checked, so the box below becomes active
					CheckDlgButton(hDlg,IDC_G3D_MATERIAL,epd.chkG3DMaterial);
				}
				else
				{
					// unchecked, so shut the sub-button down, storing its state for later restoration if turned back on
					epd.chkG3DMaterial = IsDlgButtonChecked(hDlg,IDC_G3D_MATERIAL);
					CheckDlgButton(hDlg,IDC_G3D_MATERIAL,BST_INDETERMINATE);
				}
			}
			break;
		case IDC_G3D_MATERIAL:
			if ( IsDlgButtonChecked(hDlg,IDC_G3D_MATERIAL) == BST_INDETERMINATE )
			{
				CheckDlgButton(hDlg,IDC_G3D_MATERIAL,BST_UNCHECKED);
			}
			break;

		case IDC_EXPORT_ALL:
			// if printing, special warning; this is the only time we do something special for printing vs. rendering export in this code.
			if ( IsDlgButtonChecked(hDlg,IDC_EXPORT_ALL) == BST_CHECKED && (epd.flags & EXPT_3DPRINT))
			{
				MessageBox( NULL, _T("Warning: this checkbox allows very small features to be exported for 3D printing. Some of these small bits - fences, free-standing signs - are very likely to snap off during manufacture. Fattened versions of these objects are used by default, but even these can easily break. Also, the edge connection and floater checkboxes have been unchecked, since these options can cause problems. Basically: be careful!"),
					_T("Informational"), MB_OK|MB_ICONINFORMATION);
				CheckDlgButton(hDlg,IDC_FATTEN,BST_CHECKED);
				CheckDlgButton(hDlg,IDC_DELETE_FLOATERS,BST_UNCHECKED);
				CheckDlgButton(hDlg,IDC_CONNECT_PARTS,BST_UNCHECKED);
				CheckDlgButton(hDlg,IDC_CONNECT_CORNER_TIPS,BST_INDETERMINATE);
				CheckDlgButton(hDlg,IDC_CONNECT_ALL_EDGES,BST_INDETERMINATE);
			}
			else if ( IsDlgButtonChecked(hDlg,IDC_EXPORT_ALL) == BST_UNCHECKED && (epd.flags & EXPT_3DPRINT))
			{
				// if lesser is toggled back off, turn on the defaults
				CheckDlgButton(hDlg,IDC_DELETE_FLOATERS,BST_CHECKED);
				CheckDlgButton(hDlg,IDC_CONNECT_PARTS,BST_CHECKED);
				CheckDlgButton(hDlg,IDC_CONNECT_CORNER_TIPS,BST_CHECKED);
				CheckDlgButton(hDlg,IDC_CONNECT_ALL_EDGES,BST_UNCHECKED);
			}
			// if we're turning it off, set fatten to indeterminate state
			{
				UINT isLesserChecked = IsDlgButtonChecked(hDlg,IDC_EXPORT_ALL);
				if ( !isLesserChecked )
					CheckDlgButton(hDlg,IDC_FATTEN,BST_INDETERMINATE);
			}
			break;
		case IDC_FATTEN:
			{
				UINT isLesserChecked = IsDlgButtonChecked(hDlg,IDC_EXPORT_ALL);
				if ( !isLesserChecked )
				{
					CheckDlgButton(hDlg,IDC_FATTEN,BST_INDETERMINATE);
				}
				else
				{
					UINT isFattenIndeterminate = ( IsDlgButtonChecked(hDlg,IDC_FATTEN) == BST_INDETERMINATE );
					if ( isFattenIndeterminate )
						CheckDlgButton(hDlg,IDC_FATTEN,BST_UNCHECKED);
				}
			}
			break;

        case IDOK:
            {
                gOK = 1;
                ExportFileData lepd;
                lepd = epd;

                // suck all the data out to a local copy
                GetDlgItemTextA(hDlg,IDC_WORLD_MIN_X,lepd.minxString,EP_FIELD_LENGTH);
                GetDlgItemTextA(hDlg,IDC_WORLD_MIN_Y,lepd.minyString,EP_FIELD_LENGTH);
                GetDlgItemTextA(hDlg,IDC_WORLD_MIN_Z,lepd.minzString,EP_FIELD_LENGTH);
                GetDlgItemTextA(hDlg,IDC_WORLD_MAX_X,lepd.maxxString,EP_FIELD_LENGTH);
                GetDlgItemTextA(hDlg,IDC_WORLD_MAX_Y,lepd.maxyString,EP_FIELD_LENGTH);
                GetDlgItemTextA(hDlg,IDC_WORLD_MAX_Z,lepd.maxzString,EP_FIELD_LENGTH);

				lepd.chkCreateZip[lepd.fileType] = IsDlgButtonChecked(hDlg,IDC_CREATE_ZIP);
				lepd.chkCreateModelFiles[lepd.fileType] = IsDlgButtonChecked(hDlg,IDC_CREATE_FILES);

                lepd.radioExportNoMaterials[lepd.fileType] = IsDlgButtonChecked(hDlg,IDC_RADIO_EXPORT_NO_MATERIALS);
                lepd.radioExportMtlColors[lepd.fileType] = IsDlgButtonChecked(hDlg,IDC_RADIO_EXPORT_MTL_COLORS_ONLY);
                lepd.radioExportSolidTexture[lepd.fileType] = IsDlgButtonChecked(hDlg,IDC_RADIO_EXPORT_SOLID_TEXTURES);
                lepd.radioExportFullTexture[lepd.fileType] = IsDlgButtonChecked(hDlg,IDC_RADIO_EXPORT_FULL_TEXTURES);

                //lepd.chkMergeFlattop = IsDlgButtonChecked(hDlg,IDC_MERGE_FLATTOP);
				lepd.chkExportAll = IsDlgButtonChecked(hDlg,IDC_EXPORT_ALL);
				lepd.chkFatten = lepd.chkExportAll?IsDlgButtonChecked(hDlg,IDC_FATTEN) : 0;
                lepd.chkMakeZUp[lepd.fileType] = IsDlgButtonChecked(hDlg,IDC_MAKE_Z_UP);
				lepd.chkCenterModel = IsDlgButtonChecked(hDlg,IDC_CENTER_MODEL);
				lepd.chkIndividualBlocks = IsDlgButtonChecked(hDlg,IDC_INDIVIDUAL_BLOCKS);

                lepd.radioRotate0 = IsDlgButtonChecked(hDlg,IDC_RADIO_ROTATE_0);
                lepd.radioRotate90 = IsDlgButtonChecked(hDlg,IDC_RADIO_ROTATE_90);
                lepd.radioRotate180 = IsDlgButtonChecked(hDlg,IDC_RADIO_ROTATE_180);
                lepd.radioRotate270 = IsDlgButtonChecked(hDlg,IDC_RADIO_ROTATE_270);

                lepd.radioScaleToHeight = IsDlgButtonChecked(hDlg,IDC_RADIO_SCALE_TO_HEIGHT);
                lepd.radioScaleToMaterial = IsDlgButtonChecked(hDlg,IDC_RADIO_SCALE_TO_MATERIAL);
                lepd.radioScaleByBlock = IsDlgButtonChecked(hDlg,IDC_RADIO_SCALE_BY_BLOCK);
                lepd.radioScaleByCost = IsDlgButtonChecked(hDlg,IDC_RADIO_SCALE_BY_COST);

                GetDlgItemTextA(hDlg,IDC_MODEL_HEIGHT,lepd.modelHeightString,EP_FIELD_LENGTH);
                GetDlgItemTextA(hDlg,IDC_BLOCK_SIZE,lepd.blockSizeString,EP_FIELD_LENGTH);
                GetDlgItemTextA(hDlg,IDC_COST,lepd.costString,EP_FIELD_LENGTH);

                lepd.chkFillBubbles = IsDlgButtonChecked(hDlg,IDC_FILL_BUBBLES);
                // if filling bubbles is off, sealing entrances does nothing at all
                lepd.chkSealEntrances = lepd.chkFillBubbles ? IsDlgButtonChecked(hDlg,IDC_SEAL_ENTRANCES) : 0;
                lepd.chkSealSideTunnels = lepd.chkFillBubbles ? IsDlgButtonChecked(hDlg,IDC_SEAL_SIDE_TUNNELS) : 0;

                lepd.chkConnectParts = IsDlgButtonChecked(hDlg,IDC_CONNECT_PARTS);
                // if connect parts is off, corner tips and edges is off
                lepd.chkConnectCornerTips = lepd.chkConnectParts ? IsDlgButtonChecked(hDlg,IDC_CONNECT_CORNER_TIPS) : 0;
                lepd.chkConnectAllEdges = lepd.chkConnectParts ? IsDlgButtonChecked(hDlg,IDC_CONNECT_ALL_EDGES) : 0;
            
                lepd.chkDeleteFloaters = IsDlgButtonChecked(hDlg,IDC_DELETE_FLOATERS);
            
                lepd.chkHollow = IsDlgButtonChecked(hDlg,IDC_HOLLOW);
                // if hollow is off, superhollow is off
                lepd.chkSuperHollow = lepd.chkHollow ? IsDlgButtonChecked(hDlg,IDC_SUPER_HOLLOW) : 0;

                lepd.chkMeltSnow = IsDlgButtonChecked(hDlg,IDC_MELT_SNOW);

                GetDlgItemTextA(hDlg,IDC_FLOAT_COUNT,lepd.floaterCountString,EP_FIELD_LENGTH);
                GetDlgItemTextA(hDlg,IDC_HOLLOW_THICKNESS,lepd.hollowThicknessString,EP_FIELD_LENGTH);

                BOOL debugAvailable = !lepd.radioExportNoMaterials[lepd.fileType] && (lepd.fileType != FILE_TYPE_ASCII_STL);
                lepd.chkShowParts = debugAvailable ? IsDlgButtonChecked(hDlg,IDC_SHOW_PARTS) : 0;
                lepd.chkShowWelds = debugAvailable ? IsDlgButtonChecked(hDlg,IDC_SHOW_WELDS) : 0;

                lepd.comboPhysicalMaterial[lepd.fileType] = (int)SendDlgItemMessage(hDlg, IDC_COMBO_PHYSICAL_MATERIAL, CB_GETCURSEL, 0, 0);
                lepd.comboModelUnits[lepd.fileType] = (int)SendDlgItemMessage(hDlg, IDC_COMBO_MODELS_UNITS, CB_GETCURSEL, 0, 0);

				// OBJ options
				if ( lepd.fileType == FILE_TYPE_WAVEFRONT_ABS_OBJ || lepd.fileType == FILE_TYPE_WAVEFRONT_REL_OBJ )
				{
					lepd.chkMultipleObjects = IsDlgButtonChecked(hDlg,IDC_MULTIPLE_OBJECTS);
					// if filling bubbles is off, sealing entrances does nothing at all
					if ( lepd.chkMultipleObjects )
					{
						// set value only if value above is "unlocked"
						lepd.chkMaterialPerType = IsDlgButtonChecked(hDlg,IDC_MATERIAL_PER_TYPE);
						if ( lepd.chkMaterialPerType )
						{
							// set value only if value above is "unlocked"
							lepd.chkG3DMaterial = IsDlgButtonChecked(hDlg,IDC_G3D_MATERIAL);
						}
					}
				}

                int nc;
                nc = sscanf_s(lepd.minxString,"%d",&lepd.minxVal);
                nc &= sscanf_s(lepd.minyString,"%d",&lepd.minyVal);
                nc &= sscanf_s(lepd.minzString,"%d",&lepd.minzVal);
                nc &= sscanf_s(lepd.maxxString,"%d",&lepd.maxxVal);
                nc &= sscanf_s(lepd.maxyString,"%d",&lepd.maxyVal);
                nc &= sscanf_s(lepd.maxzString,"%d",&lepd.maxzVal);

                nc &= sscanf_s(lepd.modelHeightString,"%f",&lepd.modelHeightVal);
                nc &= sscanf_s(lepd.blockSizeString,"%f",&lepd.blockSizeVal[lepd.fileType]);
                nc &= sscanf_s(lepd.costString,"%f",&lepd.costVal);

                nc &= sscanf_s(lepd.floaterCountString,"%d",&lepd.floaterCountVal);
                nc &= sscanf_s(lepd.hollowThicknessString,"%g",&lepd.hollowThicknessVal[epd.fileType]);

                // this is a bit lazy checking all errors here, there's probably a better way
                // to test as we go, but this sort of thing should be rare
                if ( nc == 0 )
                {
                    MessageBox(NULL,
                        _T("Bad (non-numeric) value detected in options dialog;\nYou need to clean up, then hit OK again."), _T("Non-numeric value error"), MB_OK|MB_ICONERROR);
                    return (INT_PTR)FALSE;
                }

                if ( lepd.radioScaleToHeight && lepd.modelHeightVal <= 0.0f )
                {
                    MessageBox(NULL,
                        _T("Model height must be a positive number;\nYou need to fix this, then hit OK again."), _T("Value error"), MB_OK|MB_ICONERROR);
                    return (INT_PTR)FALSE;
                }

                if ( lepd.radioScaleByBlock && lepd.blockSizeVal[lepd.fileType] <= 0.0f )
                {
                    MessageBox(NULL,
                        _T("Block size must be a positive number;\nYou need to fix this, then hit OK again."), _T("Value error"), MB_OK|MB_ICONERROR);
                    return (INT_PTR)FALSE;
                }

                if ( lepd.radioScaleByCost )
                {
                    // white vs. colored stuff: $1.50 vs. $3.00 handling fees, plus some minimum amount of material
                    // We need to find out the minimum amount rules for white material; colored is at
                    // http://www.shapeways.com/design-rules/full_color_sandstone, and we use the
                    // "the dimensions have to add up to 65mm" and assume a 3mm block size to give a 59mm*3mm*3mm volume
                    // minimum, times $0.75/cm^3 gives $0.40.
                    if ( lepd.costVal <= (mtlCostTable[curPhysMaterial].costHandling+mtlCostTable[curPhysMaterial].costMinimum) )
                    {
                        MessageBox(NULL,
                            _T("The cost must be > $1.55 for colorless, > $3.40 for color;\nYou need to fix this, then hit OK again."), _T("Value error"), MB_OK|MB_ICONERROR);
                        return (INT_PTR)FALSE;
                    }
                }

                if ( lepd.chkDeleteFloaters && lepd.floaterCountVal < 0 )
                {
                    MessageBox(NULL,
                        _T("Floating objects deletion value cannot be negative;\nYou need to fix this, then hit OK again."), _T("Value error"), MB_OK|MB_ICONERROR);
                    return (INT_PTR)FALSE;
                }

                if ( lepd.chkHollow && lepd.hollowThicknessVal[epd.fileType] < 0.0 )
                {
                    MessageBox(NULL,
                        _T("Hollow thickness value cannot be negative;\nYou need to fix this, then hit OK again."), _T("Value error"), MB_OK|MB_ICONERROR);
                    return (INT_PTR)FALSE;
                }

                // survived tests, so really use data
                epd = lepd;
            } // yes, we do want to fall through here
       case IDCANCEL:
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}
コード例 #20
0
void ObjParser::ParseIndexedMesh(GpuApi *gpu, const char *text) // SYNCHRONOUS
{
	struct Vector3 {
		float x, y, z;
		Vector3(float x, float y, float z) 
			: x(x), y(y), z(z) {}
	};

	struct Vector2 {
		float u, v;
		Vector2(float u, float v)
			: u(u), v(v) {}
	};

	struct VertexRef {
		int vertex, texture, normal;
		VertexRef(int v,int t,int n) 
			: vertex(v), texture(t), normal(n) {}
	};

	std::stringstream stream(text);
	std::string line;

	std::vector<Vector3> vertexBank;
	std::vector<Vector3> normalBank;
	std::vector<Vector2> texUVBank;
	std::vector<VertexRef> refBank;

	bool hasTexCoords = false;
	
	while (std::getline(stream,line,'\n'))									// Start reading file data
	{		
		if (line.find("mtllib ") == 0)
		{
			line = line.substr(strlen("mtllib "));
			line.erase(line.find_last_not_of(" \n\r\t")+1);

			materialLib = line;
		}
		if (line.find("v ") == 0)										// The first character is a v: on this line is a vertex stored.
		{
			line = line.substr(strlen("v "));

			float x = 0.0f, y = 0.0f, z = 0.0f;
 
			if(sscanf_s(line.c_str(),"%f %f %f", &x, &y, &z) != 3)
			{
				return;
			}

			vertexBank.emplace_back(Vector3(x,y,z)); 
		}
		if (line.find("vt ") == 0)
		{
			hasTexCoords = true;

			float u = 0.0f, v = 0.0f;

			if(sscanf_s(line.c_str(),"%f %f", &u, &v) != 0)
			{
				return;
			}

			texUVBank.emplace_back(Vector2(u,v));
		}
		if (line.find("vn ") == 0)
		{
			line = line.substr(strlen("vn "));

			float x = 0.0f, y = 0.0f, z = 0.0f;

			sscanf_s(line.c_str(), "%f %f %f", &x, &y, &z);

			normalBank.emplace_back(Vector3(x,y,z));
		}
		if (line.find("usemtl ") == 0)
		{
			line = line.substr(strlen("usemtl "));
			line.erase(line.find_last_not_of(" \n\r\t")+1);

			materials.emplace_back(line);

			// Create a new model here! 
			
			// At some point, you're also going to have to group models heirarchically!
		}
		if (line.find("f ") == 0)
		{
			line = line.substr(strlen("f "));
 
			int a = 0, ta = 0, na = 0, b = 0, tb = 0, nb = 0, c = 0, tc = 0, nc = 0;

			if(hasTexCoords)
			{
				if(sscanf_s(line.c_str(),"%d/%d/%d %d/%d/%d %d/%d/%d", &a, &ta, &na, &b, &tb, &nb, &c, &tc, &nc) != 9)
				{
					return;
				}
				ta -= 1; tb -= 1; tc -= 1;
			}
			else // ! hasTexCoords
			{
				if(sscanf_s(line.c_str(), "%d//%d %d//%d %d//%d", &a, &na, &b, &nb, &c, &nc) != 6)
				{
					return;
				}
			}

			 a -= 1;  b -= 1;  c -= 1; // OBJ file starts counting from 1
			na -= 1; nb -= 1; nc -= 1;

			refBank.emplace_back(VertexRef(a,ta,na));
			refBank.emplace_back(VertexRef(b,tb,nb));
			refBank.emplace_back(VertexRef(c,tc,nc)); 
 
			///********************************************************************
			//	* Create triangles (f 1 2 3) from points: (v X Y Z) (v X Y Z) (v X Y Z). 
			//	* The vertexBuffer contains all verteces
			//	* The triangles will be created using the verteces we read previously
			//	*/
 
			//int tCounter = 0;
			//for (int i = 0; i < POINTS_PER_VERTEX; i++)					
			//{
			//	Faces_Triangles[triangle_index + tCounter   ] = vertexBuffer[3*vertexNumber[i] ];
			//	Faces_Triangles[triangle_index + tCounter +1 ] = vertexBuffer[3*vertexNumber[i]+1 ];
			//	Faces_Triangles[triangle_index + tCounter +2 ] = vertexBuffer[3*vertexNumber[i]+2 ];
			//	tCounter += POINTS_PER_VERTEX;
			//}
 
			///*********************************************************************
			//	* Calculate all normals, used for lighting
			//	*/ 
			//float coord1[3] = { Faces_Triangles[triangle_index], Faces_Triangles[triangle_index+1],Faces_Triangles[triangle_index+2]};
			//float coord2[3] = {Faces_Triangles[triangle_index+3],Faces_Triangles[triangle_index+4],Faces_Triangles[triangle_index+5]};
			//float coord3[3] = {Faces_Triangles[triangle_index+6],Faces_Triangles[triangle_index+7],Faces_Triangles[triangle_index+8]};
			//float *norm = this->calculateNormal( coord1, coord2, coord3 );
 
			//tCounter = 0;
			//for (int i = 0; i < POINTS_PER_VERTEX; i++)
			//{
			//	normals[normal_index + tCounter ] = norm[0];
			//	normals[normal_index + tCounter +1] = norm[1];
			//	normals[normal_index + tCounter +2] = norm[2];
			//	tCounter += POINTS_PER_VERTEX;
			//}
 
			//triangle_index += TOTAL_FLOATS_IN_TRIANGLE;
			//normal_index += TOTAL_FLOATS_IN_TRIANGLE;
			//TotalConnectedTriangles += TOTAL_FLOATS_IN_TRIANGLE;	
		}	
	}

	unsigned vertices = 0, triangles = 0, indices = 0, normals = 0;

	vertices = 0;

	triangles = refBank.size() / 3;

	VertApi *vtx = gpu->GetVertApi();

	if(hasTexCoords)
	{
		VertexBuffer_PosNorTex *v = vtx->CreateVertexBuffer_PosNorTex(triangles * 3);
		unsigned *k = new unsigned[triangles * 3];

		std::vector<VertexRef>::iterator it;
		for(it = refBank.begin(); it != refBank.end(); it++)
		{
			VertexRef& i = *it;

			k[indices++] = vertices;

			v->Insert(vertices++,
				vertexBank[i.vertex].x, vertexBank[i.vertex].y, vertexBank[i.vertex].z, 
				normalBank[i.normal].x, normalBank[i.normal].y, normalBank[i.normal].z,
				texUVBank[i.texture].u, texUVBank[i.texture].v);
		}
	
		indexedMesh = gpu->CreateGpuIndexedMesh(v, triangles, sizeof(unsigned) * triangles * 3, k);
	}
	else // ! hasTexCoords
	{
		VertexBuffer_PosNor *v = vtx->CreateVertexBuffer_PosNor(triangles * 3);
		unsigned *k = new unsigned[triangles * 3];

		std::vector<VertexRef>::iterator it;
		for(it = refBank.begin(); it != refBank.end(); it++)
		{
			VertexRef& i = *it;

			k[indices++] = vertices;

			v->Insert(vertices++,
				vertexBank[i.vertex].x, vertexBank[i.vertex].y, vertexBank[i.vertex].z, 
				normalBank[i.normal].x, normalBank[i.normal].y, normalBank[i.normal].z);
		}
	
		indexedMesh = gpu->CreateGpuIndexedMesh(v, triangles, sizeof(unsigned) * triangles * 3, k);
	}

	ready = true;
}
コード例 #21
0
void TransportBridge::recv_json(rapidjson::Document* document) {
  char recvbuf[BRIDGE_RECV_BUFSIZE];
  int iResult;
  int pos = 0;
  int len;

  // First info should be the number of bytes in the string followed by newline.
  while (1) {
    iResult = recv(bridge_socket, recvbuf + pos, 1, 0);
    if (iResult == 0) {
      // Connection closed.
      bridge_error("Remote bridge closed trying to read length.\n");
    }
    else if (iResult != 1) {
      // Some other error
      bridge_error("recv failed reading length with error: %d\n", WSAGetLastError());
    }
    // Read one byte. If it's newline, we should have now received a full length string.
    if (recvbuf[pos] == '\n') {
      break;
    }
    // Error if it isn't a digit.
    if (!isdigit(recvbuf[pos])) {
      bridge_error("recv got a non-digit in the length field.\n");
    }
    if (pos >= BRIDGE_RECV_BUFSIZE-1) {
      bridge_error("recv got a very long length field.\n");
    }
    pos++;
  }
  // If we get here, we should have a legal length in recvbuf.
  len = -1;
  if (sscanf_s(recvbuf, "%d", &len) != 1 || len < 1) {
    bridge_error("Got illegal length string \"%s\"\n", recvbuf);
  }
  if (len >= BRIDGE_RECV_BUFSIZE-1) {
    bridge_error("length too long (max %d, got %d)\n", BRIDGE_RECV_BUFSIZE, len);
  }
  // Now read until we get len bytes.
  int nread = 0;
  while (nread < len) {
    iResult = recv(bridge_socket, recvbuf + nread, len - nread, 0);
    if (iResult == 0) {
      bridge_error("Remote bridge closed.\n");
    }
    else if (iResult < 0) {
      bridge_error("recv failed with error: %d\n", WSAGetLastError());
    }
    nread += iResult;
  }
  recvbuf[nread] = 0; // null terminate.
  document->SetArray(); // This should clear any existing allocation. Not sure if needed.

  FILE * recvbuf_file;
  recvbuf_file = fopen("C:/Users/Vivek Raghuram/Desktop/recvbuf.txt", "a");
  fprintf(recvbuf_file, recvbuf);
  fprintf(recvbuf_file, ".\n");
  fclose(recvbuf_file);

  document->Parse(recvbuf); // Parse the json into the document.
}  // TransportBridge::recv_json()
コード例 #22
0
bool RenderingCore::SetupCoreProfile()
{
	HWND dummy = CreateWindow("TestClass", "Dummy", WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
		0, 0, 100, 100, 0, 0, GetModuleHandle(0), 0);

	PIXELFORMATDESCRIPTOR pfd =
	{
		sizeof(PIXELFORMATDESCRIPTOR),
		1,
		PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER,
		PFD_TYPE_RGBA,
		32, // color
		0, 0, 0, 0, 0, 0,
		0, // alpha
		0, 0, 0, 0, 0, 0,
		24, 8, 0, // depth, stencil, aux
		PFD_MAIN_PLANE,
		0, 0, 0, 0
	};

	HDC hdc = GetDC(dummy);
	V_RETURN(false, "InitGL(): Could not get device context", hdc);
	
	int pixelformat = ChoosePixelFormat(hdc, &pfd);
	V_RETURN(false, "InitGL(): Could not find suitable pixel format", pixelformat);

	BOOL success = SetPixelFormat(hdc, pixelformat, &pfd);
	V_RETURN(false, "InitGL(): Could not setup pixel format", success);

	HGLRC hrc = wglCreateContext(hdc);
	V_RETURN(false, "InitGL(): Context creation failed", hrc);

	success = wglMakeCurrent(hdc, hrc);
	V_RETURN(false, "InitGL(): Could not acquire context", success);

	const char* str = (const char*)glGetString(GL_VENDOR);
	std::cout << "Vendor: " << str << "\n";

	str = (const char*)glGetString(GL_RENDERER);
	std::cout << "Renderer: " << str << "\n";

	str = (const char*)glGetString(GL_VERSION);
	std::cout << "OpenGL version: " << str << "\n\n";

	sscanf_s(str, "%1d.%2d %*s", &GLMajorVersion, &GLMinorVersion);

	if( GLMajorVersion < 3 || (GLMajorVersion == 3 && GLMinorVersion < 2) )
	{
		std::cout << "Device does not support OpenGL 3.2\n";
		return false;
	}

	if( Quadron::wIsSupported("WGL_ARB_pixel_format", hdc) )
	{
		std::cout << "WGL_ARB_pixel_format present, querying pixel formats...\n";

		wglGetPixelFormatAttribivARB = (WGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProcAddress("wglGetPixelFormatAttribivARB");
		wglGetPixelFormatAttribfvARB = (WGLGETPIXELFORMATATTRIBFVARBPROC)wglGetProcAddress("wglGetPixelFormatAttribfvARB");
		wglChoosePixelFormatARB = (WGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
		
		if( Quadron::wIsSupported("WGL_ARB_create_context", hdc) &&
			Quadron::wIsSupported("WGL_ARB_create_context_profile", hdc) )
		{
			wglCreateContextAttribsARB = (WGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
		}
	}

	success = wglMakeCurrent(hdc, NULL);
	V_RETURN(false, "InitGL(): Could not release dummy context", success);

	success = wglDeleteContext(hrc);
	V_RETURN(false, "InitGL(): Could not delete dummy context", success);

	ReleaseDC(dummy, hdc);
	DestroyWindow(dummy);

	return true;
}
コード例 #23
0
ファイル: dxf.cpp プロジェクト: Ychuan1115/libarea
bool CDxfRead::ReadArc(bool undoably)
{
	double start_angle = 0.0;// in degrees
	double end_angle = 0.0;
	double radius = 0.0;
	double c[3]; // centre

	while(!((*m_ifs).eof()))
	{
		get_line();
		int n;
		if(sscanf_s(m_str, "%d", &n) != 1)return false;
		std::istringstream ss;
		ss.imbue(std::locale("C"));
		switch(n){
			case 0:
				// next item found, so finish with arc
				OnReadArc(start_angle, end_angle, radius, c, undoably);
				return true;
			case 10:
				// centre x
				get_line();
				ss.str(m_str); ss >> c[0]; if(ss.fail()) return false;
				break;
			case 20:
				// centre y
				get_line();
				ss.str(m_str); ss >> c[1]; if(ss.fail()) return false;
				break;
			case 30:
				// centre z
				get_line();
				ss.str(m_str); ss >> c[2]; if(ss.fail()) return false;
				break;
			case 40:
				// radius
				get_line();
				ss.str(m_str); ss >> radius; if(ss.fail()) return false;
				break;
			case 50:
				// start angle
				get_line();
				ss.str(m_str); ss >> start_angle; if(ss.fail()) return false;
				break;
			case 51:
				// end angle
				get_line();
				ss.str(m_str); ss >> end_angle; if(ss.fail()) return false;
				break;
			case 100:
			case 39:
			case 210:
			case 220:
			case 230:
				// skip the next line
				get_line();
				break;
			default:
				// skip the next line
				get_line();
				break;
		}
	}
	OnReadArc(start_angle, end_angle, radius, c, undoably);
	return false;
}
コード例 #24
0
ファイル: mc.cpp プロジェクト: Bernieboy/nds4ios
u32 ADVANsCEne::convertDB(const char *in_filaname)
{
	//these strings are contained in the xml file, verbatim, so they function as enum values
	//we leave the strings here rather than pooled elsewhere to remind us that theyre part of the advanscene format.
	const char *saveTypeNames[] = {
		"Eeprom - 4 kbit",		// EEPROM 4kbit
		"Eeprom - 64 kbit",		// EEPROM 64kbit
		"Eeprom - 512 kbit",	// EEPROM 512kbit
		"Fram - 256 kbit",		// FRAM 256kbit !
		"Flash - 2 mbit",		// FLASH 2Mbit
		"Flash - 4 mbit",		// FLASH 4Mbit
		"Flash - 8 mbit",		// FLASH 8Mbit
		"Flash - 16 mbit",		// FLASH 16Mbit !
		"Flash - 32 mbit",		// FLASH 32Mbit !
		"Flash - 64 mbit",		// FLASH 64Mbit
		"Flash - 128 mbit",		// FLASH 128Mbit !
		"Flash - 256 mbit",		// FLASH 256Mbit !
		"Flash - 512 mbit"		// FLASH 512Mbit !
	};

	TiXmlDocument	*xml = NULL;
	TiXmlElement	*el = NULL;
	TiXmlElement	*el_serial = NULL;
	TiXmlElement	*el_games = NULL;
	TiXmlElement	*el_crc32 = NULL;
	TiXmlElement	*el_saveType = NULL;
	FILE			*fp;
	u32				crc32 = 0;
	u32				reserved = 0;

	lastImportErrorMessage = "";

	printf("Converting DB...\n");
	if (getXMLConfig(in_filaname))
	{
		if (datName.size()==0) return 0;
		if (datName != _ADVANsCEne_BASE_NAME) return 0;
	}

	fp = fopen(database_path, "wb");
	if (!fp) return 0;

	// Header
	fwrite(_ADVANsCEne_BASE_ID, 1, strlen(_ADVANsCEne_BASE_ID), fp);
	fputc(_ADVANsCEne_BASE_VERSION_MAJOR, fp);
	fputc(_ADVANsCEne_BASE_VERSION_MINOR, fp);
	if (datVersion.size()) 
		fwrite(&datVersion[0], 1, datVersion.size(), fp);
	else
		fputc(0, fp);
	time_t __time = time(NULL);
	fwrite(&__time, 1, sizeof(time_t), fp);

	xml = new TiXmlDocument();
	if (!xml) { fclose(fp); return 0; }
	if (!xml->LoadFile(in_filaname)) { fclose(fp); return 0; }
	el = xml->FirstChildElement("dat");
	if (!el) { fclose(fp); return 0; }
	el_games = el->FirstChildElement("games");
	if (!el_games) { fclose(fp); return 0; }
	el = el_games->FirstChildElement("game");
	if (!el) { fclose(fp); return 0; }
	u32 count = 0;
	while (el)
	{
		TiXmlElement* title = el->FirstChildElement("title");
		if(title)
		{
			//just a little diagnostic
			//printf("Importing %s\n",title->GetText());
		}
		else { fclose(fp); return 0; }

		el_serial = el->FirstChildElement("serial");
		
		if(!el_serial)
		{
			lastImportErrorMessage = "Missing <serial> element. Did you use the right xml file? We need the RtoolDS one.";
			fclose(fp); 
			return 0;
		}
		if (fwrite(el_serial->GetText(), 1, 8, fp) != 8)
		{
			lastImportErrorMessage = "Error writing output file";
			fclose(fp); return 0;
		}


		// CRC32
		el_crc32 = el->FirstChildElement("files"); 
		sscanf_s(el_crc32->FirstChildElement("romCRC")->GetText(), "%x", &crc32);
		if (fwrite(&crc32, 1, sizeof(u32), fp) != sizeof(u32))
		{
			fclose(fp); return 0;
		}
		// Save type
		el_saveType = el->FirstChildElement("saveType"); 
		if (el_saveType)
		{
			const char *tmp = el_saveType->GetText();
			if (tmp)
			{
				if (strcmp(tmp, "None")  == 0)
					fputc(0xFE, fp);
				else
				{
					bool bUnknown = true;
					for (u8 i = 0; i < MAX_SAVE_TYPES; i++)
					{
						if (strcmp(saveTypeNames[i], "") == 0) continue;
						if (strcasecmp(tmp, saveTypeNames[i]) == 0)
						{
							fputc(i, fp);
							bUnknown = false;
							break;
						}
					}
					if (bUnknown)
						fputc(0xFF, fp);	// Unknown
				}
			}
			else
				fputc(0xFF, fp);	// Unknown
		}
		fwrite(&reserved, 1, sizeof(u32), fp);
		fwrite(&reserved, 1, sizeof(u32), fp);
		count++;
		el = el->NextSiblingElement("game");
	}
	printf("\n");
	delete xml;
	fclose(fp);
	if (count > 0) 
		printf("done\n");
	else
		printf("error\n");
	printf("ADVANsCEne converter: %i found\n", count);
	return count;
}
コード例 #25
0
ファイル: dxf.cpp プロジェクト: Ychuan1115/libarea
bool CDxfRead::ReadEllipse(bool undoably)
{
	double c[3]; // centre
	double m[3]; //major axis point
	double ratio=0; //ratio of major to minor axis
	double start=0; //start of arc
	double end=0;  // end of arc

	while(!((*m_ifs).eof()))
	{
		get_line();
		int n;
		if(sscanf_s(m_str, "%d", &n) != 1)return false;
		std::istringstream ss;
		ss.imbue(std::locale("C"));
		switch(n){
			case 0:
				// next item found, so finish with Ellipse
				OnReadEllipse(c, m, ratio, start, end, undoably);
				return true;
			case 10:
				// centre x
				get_line();
				ss.str(m_str); ss >> c[0]; if(ss.fail()) return false;
				break;
			case 20:
				// centre y
				get_line();
				ss.str(m_str); ss >> c[1]; if(ss.fail()) return false;
				break;
			case 30:
				// centre z
				get_line();
				ss.str(m_str); ss >> c[2]; if(ss.fail()) return false;
				break;
			case 11:
				// major x
				get_line();
				ss.str(m_str); ss >> m[0]; if(ss.fail()) return false;
				break;
			case 21:
				// major y
				get_line();
				ss.str(m_str); ss >> m[1]; if(ss.fail()) return false;
				break;
			case 31:
				// major z
				get_line();
				ss.str(m_str); ss >> m[2]; if(ss.fail()) return false;
				break;
			case 40:
				// ratio
				get_line();
				ss.str(m_str); ss >> ratio; if(ss.fail()) return false;
				break;
			case 41:
				// start
				get_line();
				ss.str(m_str); ss >> start; if(ss.fail()) return false;
				break;
			case 42:
				// end
				get_line();
				ss.str(m_str); ss >> end; if(ss.fail()) return false;
				break;	
			case 100:
			case 210:
			case 220:
			case 230:
				// skip the next line
				get_line();
				break;
			default:
				// skip the next line
				get_line();
				break;
		}
	}
	OnReadEllipse(c, m, ratio, start, end, undoably);
	return false;
}
コード例 #26
0
ファイル: cgroup.cpp プロジェクト: davidwrighton/coreclr
    static void FindHierarchyMount(bool (*is_subsystem)(const char *), char** pmountpath, char** pmountroot)
    {
        char *line = nullptr;
        size_t lineLen = 0, maxLineLen = 0;
        char *filesystemType = nullptr;
        char *options = nullptr;
        char *mountpath = nullptr;
        char *mountroot = nullptr;

        FILE *mountinfofile = fopen(PROC_MOUNTINFO_FILENAME, "r");
        if (mountinfofile == nullptr)
            goto done;

        while (getline(&line, &lineLen, mountinfofile) != -1)
        {
            if (filesystemType == nullptr || lineLen > maxLineLen)
            {
                PAL_free(filesystemType);
                PAL_free(options);
                filesystemType = (char*)PAL_malloc(lineLen+1);
                if (filesystemType == nullptr)
                    goto done;
                options = (char*)PAL_malloc(lineLen+1);
                if (options == nullptr)
                    goto done;
                maxLineLen = lineLen;
            }
            char* separatorChar = strstr(line, " - ");;

            // See man page of proc to get format for /proc/self/mountinfo file
            int sscanfRet = sscanf_s(separatorChar, 
                                     " - %s %*s %s",
                                     filesystemType, lineLen+1,
                                     options, lineLen+1);
            if (sscanfRet != 2)
            {
                _ASSERTE(!"Failed to parse mount info file contents with sscanf_s.");
                goto done;
            }

            if (strncmp(filesystemType, "cgroup", 6) == 0)
            {
                char* context = nullptr;
                char* strTok = strtok_s(options, ",", &context); 
                while (strTok != nullptr)
                {
                    if (is_subsystem(strTok))
                    {
                        mountpath = (char*)PAL_malloc(lineLen+1);
                        if (mountpath == nullptr)
                            goto done;
                        mountroot = (char*)PAL_malloc(lineLen+1);
                        if (mountroot == nullptr)
                            goto done;

                        sscanfRet = sscanf_s(line,
                                             "%*s %*s %*s %s %s ",
                                             mountroot, lineLen+1,
                                             mountpath, lineLen+1);
                        if (sscanfRet != 2)
                            _ASSERTE(!"Failed to parse mount info file contents with sscanf_s.");

                        // assign the output arguments and clear the locals so we don't free them.
                        *pmountpath = mountpath;
                        *pmountroot = mountroot;
                        mountpath = mountroot = nullptr;
                        goto done;
                    }
                    strTok = strtok_s(nullptr, ",", &context);
                }
            }
        }
    done:
        PAL_free(mountpath);
        PAL_free(mountroot);
        PAL_free(filesystemType);
        PAL_free(options);
        free(line);
        if (mountinfofile)
            fclose(mountinfofile);
    }
コード例 #27
0
ファイル: HW2.cpp プロジェクト: 14nguyenh/CSCE-463
int main(int argc, char* argv[]){

	if (argc != 3){ //check usage
		printf("Two arguments required: [Hostname/IP] [DNS server IP]\n");
	}
	else{

		char *lookup = argv[1];
		char *dns = argv[2];

		printf("Lookup  : %s\n", lookup);

		/*
		START LOOKUP
		*/

		WSADATA wsaData;

		//Initialize WinSock; once per program run
		WORD wVersionRequested = MAKEWORD(2, 2);
		if (WSAStartup(wVersionRequested, &wsaData) != 0) {
			printf("WSAStartup error %d\n", WSAGetLastError());
			WSACleanup();
			return 0;
		}

		// open a UDP socket
		SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
		if (sock == INVALID_SOCKET)
		{
			printf("socket() generated error %d\n", WSAGetLastError());
			WSACleanup();
			return 0;
		}

		// bind the UDP socket to me
		struct sockaddr_in local;
		memset(&local, 0, sizeof(local));
		local.sin_family = AF_INET;
		local.sin_port = htons(0);
		local.sin_addr.s_addr = INADDR_ANY;
		if (bind(sock, (struct sockaddr*)&local, sizeof(local)) == SOCKET_ERROR){
			printf("bind() failed with error %d\n", WSAGetLastError());
			WSACleanup();
			return 0;
		}

		//set up where to send queries to
		struct sockaddr_in remote;
		memset(&remote, 0, sizeof(remote));
		remote.sin_family = AF_INET;
		remote.sin_addr.s_addr = inet_addr(dns); //server's IP
		remote.sin_port = htons(53); //DNS port on server
		int sendersize = sizeof(remote);
		int packet_size = strlen(lookup) + 2 + sizeof(FixedDNSheader) + sizeof(QueryHeader);
		char *packet = new char[packet_size];

		DWORD IP = inet_addr(lookup);
		if (IP == INADDR_NONE){ //hostname, do a forward lookup, type-A
			char *host = new char[strlen(lookup) + 1];
			for (int i = 0; i < strlen(lookup); i++){
				host[i] = lookup[i];
			}
			host[strlen(lookup)] = '\0';

			printf("Query   : %s, ", host);

			FixedDNSheader *dh = (FixedDNSheader *)packet;
			QueryHeader *qh = (QueryHeader*)(packet + packet_size - sizeof(QueryHeader));
			int txid = rand();
			dh->txid = htons(txid);
			dh->flags = htons(DNS_QUERY | DNS_RD | DNS_STDQUERY);
			dh->nQuestions = htons(1);
			dh->nAnswers = htons(0);
			dh->nAuthority = htons(0);
			dh->nAdditional = htons(0);
			qh->qType = htons(DNS_A);
			qh->qClass = htons(DNS_INET);

			printf("type 1, TXID 0x%x\n", txid);

			createRequest((char*)(dh + 1), host);

		}
		else{ //IP, do a reverse lookup, type-PTR
			char ip[35];
			int a, b, c, d;
			sscanf_s(lookup, "%d.%d.%d.%d", &a, &b, &c, &d);
			sprintf_s(ip, "%d.%d.%d.%d.in-addr.arpa", d, c, b, a);

			printf("Query   : %s, ", ip);

			FixedDNSheader *dh = (FixedDNSheader *)packet;
			QueryHeader *qh = (QueryHeader*)(packet + packet_size - sizeof(QueryHeader));
			int txid = rand();
			dh->txid = htons(txid);
			dh->flags = htons(DNS_QUERY | DNS_RD | DNS_STDQUERY);
			dh->nQuestions = htons(1);
			dh->nAnswers = htons(0);
			dh->nAuthority = htons(0);
			dh->nAdditional = htons(0);
			qh->qType = htons(DNS_PTR);
			qh->qClass = htons(DNS_INET);

			printf("type 12, TXID 0x%x\n", txid);

			createRequest((char*)(dh + 1), ip);

		}

		printf("Server  : %s\n", dns);
		printf("******************************\n");

		char *recvBuf = new char[4001];
		recvBuf[4000] = '\0';
		bool received = false;
		int bytes = 0;
		int k = 0;

		while (received == false){

			if (k == 3){
				break;
			}

			clock_t total_time = clock();

			printf("Attempt %d with %d bytes... ", k, packet_size);

			if (sendto(sock, packet, packet_size, 0, (struct sockaddr*)&remote, sizeof(remote)) == SOCKET_ERROR){
				printf("sendto() failed with error %d\n", WSAGetLastError());
				WSACleanup();
				return 0;
			}

			fd_set monitor;
			FD_ZERO(&monitor);
			FD_SET(sock, &monitor);
			struct timeval timer;
			timer.tv_sec = 10;
			timer.tv_usec = 0;

			if (select(sock, &monitor, NULL, NULL, &timer) > 0){ //wait for a response forever, only 1 packet
				struct sockaddr_in response;
				if ((bytes = recvfrom(sock, recvBuf, strlen(recvBuf), 0, (struct sockaddr*)&response, &sendersize)) == SOCKET_ERROR){
					printf("recvfrom() failed with error %d\n", WSAGetLastError());
					WSACleanup();
					return 0;
				}
				printf("response in %d ms with %d bytes\n", (clock() - total_time), bytes);
				if (memcmp(&response.sin_addr, &remote.sin_addr, sizeof(DWORD)) != 0 || response.sin_port != remote.sin_port){
					printf("revfrom() bogus reply, quitting\n");
					WSACleanup();
					return 0;
				}
				int mismatch = parseResponse(recvBuf, bytes, packet, packet_size);
				if (mismatch == -1){
					printf("  TXID does not match\n");
					WSACleanup();
					return 0;
				}
				received = true;
			}
			else{
				k++;
				printf("timeout in %d ms\n", clock() - total_time);
			}

		}
		//print summary
		WSACleanup();
	}
	return 0;
}
コード例 #28
0
ファイル: cgroup.cpp プロジェクト: davidwrighton/coreclr
    static char* FindCGroupPathForSubsystem(bool (*is_subsystem)(const char *))
    {
        char *line = nullptr;
        size_t lineLen = 0;
        size_t maxLineLen = 0;
        char *subsystem_list = nullptr;
        char *cgroup_path = nullptr;
        bool result = false;

        FILE *cgroupfile = fopen(PROC_CGROUP_FILENAME, "r");
        if (cgroupfile == nullptr)
            goto done;

        while (!result && getline(&line, &lineLen, cgroupfile) != -1)
        {
            if (subsystem_list == nullptr || lineLen > maxLineLen)
            {
                PAL_free(subsystem_list);
                PAL_free(cgroup_path);
                subsystem_list = (char*)PAL_malloc(lineLen+1);
                if (subsystem_list == nullptr)
                    goto done;
                cgroup_path = (char*)PAL_malloc(lineLen+1);
                if (cgroup_path == nullptr)
                    goto done;
                maxLineLen = lineLen;
            }

            // See man page of proc to get format for /proc/self/cgroup file
            int sscanfRet = sscanf_s(line, 
                                     "%*[^:]:%[^:]:%s",
                                     subsystem_list, lineLen+1,
                                     cgroup_path, lineLen+1);
            if (sscanfRet != 2)
            {
                _ASSERTE(!"Failed to parse cgroup info file contents with sscanf_s.");
                goto done;
            }

            char* context = nullptr;
            char* strTok = strtok_s(subsystem_list, ",", &context); 
            while (strTok != nullptr)
            {
                if (is_subsystem(strTok))
                {
                    result = true;
                    break;  
                }
                strTok = strtok_s(nullptr, ",", &context);
            }
        }
    done:
        PAL_free(subsystem_list);
        if (!result)
        {
            PAL_free(cgroup_path);
            cgroup_path = nullptr;
        }
        free(line);
        if (cgroupfile)
            fclose(cgroupfile);
        return cgroup_path;
    }
コード例 #29
0
ファイル: objloader.cpp プロジェクト: andli86/sgct
bool loadOBJ(
	const char * path, 
	std::vector<glm::vec3> & out_vertices, 
	std::vector<glm::vec2> & out_uvs,
	std::vector<glm::vec3> & out_normals
){
	printf("Loading OBJ file %s...\n", path);

	std::vector<unsigned int> vertexIndices, uvIndices, normalIndices;
	std::vector<glm::vec3> temp_vertices; 
	std::vector<glm::vec2> temp_uvs;
	std::vector<glm::vec3> temp_normals;

#if (_MSC_VER >= 1400) //visual studio 2005 or later
	errno_t err;
	FILE * file;
	err = fopen_s(&file, path, "r");
	if (err != 0)
#else
	FILE * file = fopen(path, "r");
	if (file == NULL)
#endif
	{
		printf("Impossible to open the file! Are you in the right path?\n");
		return false;
	}

	char lineHeader[128];

	//holders for face coord data
	//supports only triangles (3 values)
	//fix to read 3DsMax obj exported files by Miro
	char faceCoord0[64];
	char faceCoord1[64];
	char faceCoord2[64];

	while( true )
	{
		// read the first word of the line
		int res = fscanf(file, "%s", lineHeader);
		if (res == EOF)
			break; // EOF = End Of File. Quit the loop.

		// else : parse lineHeader
		
		if ( strcmp( lineHeader, "v" ) == 0 )
		{
			glm::vec3 vertex;
#if (_MSC_VER >= 1400) //visual studio 2005 or later
			fscanf_s(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z );
#else
			fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z );
#endif
			temp_vertices.push_back(vertex);
		}
		else if ( strcmp( lineHeader, "vt" ) == 0 )
		{
			glm::vec2 uv;
#if (_MSC_VER >= 1400) //visual studio 2005 or later
			fscanf_s(file, "%f %f\n", &uv.x, &uv.y );
#else
			fscanf(file, "%f %f\n", &uv.x, &uv.y );
#endif
			temp_uvs.push_back(uv);
		}
		else if ( strcmp( lineHeader, "vn" ) == 0 )
		{
			glm::vec3 normal;
#if (_MSC_VER >= 1400) //visual studio 2005 or later
			fscanf_s(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z );
#else
			fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z );
#endif
			temp_normals.push_back(normal);
		}
		else if ( strcmp( lineHeader, "f" ) == 0 )
		{
			std::string vertex1, vertex2, vertex3;
			unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
			/*int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2] );
			if (matches != 9){
				printf("File can't be read by our simple parser :-( Try exporting with other options\n");
				return false;
			}*/

#if (_MSC_VER >= 1400) //visual studio 2005 or later
			int matches = fscanf_s(file, "%s %s %s\n", faceCoord0, faceCoord1, faceCoord2 );
#else
			int matches = fscanf(file, "%s %s %s\n", faceCoord0, faceCoord1, faceCoord2 );
#endif
			if (matches != 3)
			{
				printf("File can't be read by our simple parser. Only triangle meshes can be read.\n");
				return false;
			}
			else
			{

#if (_MSC_VER >= 1400) //visual studio 2005 or later
				if( sscanf_s( faceCoord0, "%d/%d/%d", &vertexIndex[0], &uvIndex[0], &normalIndex[0] ) == 3 ) //vertex + uv + normal valid
#else
				if (sscanf(faceCoord0, "%d/%d/%d", &vertexIndex[0], &uvIndex[0], &normalIndex[0]) == 3) //vertex + uv + normal valid
#endif
				{

#if (_MSC_VER >= 1400) //visual studio 2005 or later
					if( sscanf_s( faceCoord1, "%d/%d/%d", &vertexIndex[1], &uvIndex[1], &normalIndex[1] ) != 3 )
#else
					if (sscanf(faceCoord1, "%d/%d/%d", &vertexIndex[1], &uvIndex[1], &normalIndex[1]) != 3)
#endif
					{
						printf("File can't be read by our simple parser. Can't read 2nd face indexes.\n");
						return false;
					}
					
#if (_MSC_VER >= 1400) //visual studio 2005 or later
					if( sscanf_s( faceCoord2, "%d/%d/%d", &vertexIndex[2], &uvIndex[2], &normalIndex[2] ) != 3 )
#else
					if (sscanf(faceCoord2, "%d/%d/%d", &vertexIndex[2], &uvIndex[2], &normalIndex[2]) != 3)
#endif
					{
						printf("File can't be read by our simple parser. Can't read 3rd face indexes.\n");
						return false;
					}

					vertexIndices.push_back(vertexIndex[0]);
					vertexIndices.push_back(vertexIndex[1]);
					vertexIndices.push_back(vertexIndex[2]);
					uvIndices    .push_back(uvIndex[0]);
					uvIndices    .push_back(uvIndex[1]);
					uvIndices    .push_back(uvIndex[2]);
					normalIndices.push_back(normalIndex[0]);
					normalIndices.push_back(normalIndex[1]);
					normalIndices.push_back(normalIndex[2]);
				}
				else if( sscanf( faceCoord0, "%d//%d", &vertexIndex[0], &normalIndex[0] ) == 2 ) //vertex + normal valid
				{
					if( sscanf( faceCoord1, "%d//%d", &vertexIndex[1], &normalIndex[1] ) != 2 )
					{
						printf("File can't be read by our simple parser. Can't read 2nd face indexes.\n");
						return false;
					}
					
					if( sscanf( faceCoord2, "%d//%d", &vertexIndex[2], &normalIndex[2] ) != 2 )
					{
						printf("File can't be read by our simple parser. Can't read 3rd face indexes.\n");
						return false;
					}

					vertexIndices.push_back(vertexIndex[0]);
					vertexIndices.push_back(vertexIndex[1]);
					vertexIndices.push_back(vertexIndex[2]);
					normalIndices.push_back(normalIndex[0]);
					normalIndices.push_back(normalIndex[1]);
					normalIndices.push_back(normalIndex[2]);
				}
				else if( sscanf( faceCoord0, "%d/%d//", &vertexIndex[0], &uvIndex[0] ) == 2 ) //vertex + uv valid
				{
					if( sscanf( faceCoord1, "%d/%d//", &vertexIndex[1], &uvIndex[1] ) != 2 )
					{
						printf("File can't be read by our simple parser. Can't read 2nd face indexes.\n");
						return false;
					}
					
					if( sscanf( faceCoord2, "%d/%d//", &vertexIndex[2], &uvIndex[2] ) != 2 )
					{
						printf("File can't be read by our simple parser. Can't read 3rd face indexes.\n");
						return false;
					}

					vertexIndices.push_back(vertexIndex[0]);
					vertexIndices.push_back(vertexIndex[1]);
					vertexIndices.push_back(vertexIndex[2]);
					uvIndices    .push_back(uvIndex[0]);
					uvIndices    .push_back(uvIndex[1]);
					uvIndices    .push_back(uvIndex[2]);
				}
				else if( sscanf( faceCoord0, "%d///", &vertexIndex[0] ) == 1 ) //vertex only
				{
					if( sscanf( faceCoord1, "%d///", &vertexIndex[1] ) != 1 )
					{
						printf("File can't be read by our simple parser. Can't read 2nd face indexes.\n");
						return false;
					}
					
					if( sscanf( faceCoord2, "%d///", &vertexIndex[2] ) != 1 )
					{
						printf("File can't be read by our simple parser. Can't read 3rd face indexes.\n");
						return false;
					}

					vertexIndices.push_back(vertexIndex[0]);
					vertexIndices.push_back(vertexIndex[1]);
					vertexIndices.push_back(vertexIndex[2]);
				}
				else //fail
				{
					printf("File can't be read by our simple parser. Face format is unknown.\n");
					return false;
				}
			}
		}else{
			// Probably a comment, eat up the rest of the line
			char stupidBuffer[1000];
			fgets(stupidBuffer, 1000, file);
		}

	}

	// For each vertex of each triangle
	for( unsigned int i=0; i<vertexIndices.size(); i++ )
	{
		// Get the indices of its attributes
		unsigned int vertexIndex = vertexIndices[i];
		unsigned int uvIndex;
		unsigned int normalIndex;

		// Get the attributes thanks to the index
		glm::vec3 vertex = temp_vertices[ vertexIndex-1 ];
		out_vertices.push_back(vertex);

		if( uvIndices.size() > 0 )
		{
			uvIndex = uvIndices[i];
			glm::vec2 uv = temp_uvs[ uvIndex-1 ];
			out_uvs.push_back(uv);
		}

		if( normalIndices.size() > 0 )
		{
			normalIndex = normalIndices[i];
			glm::vec3 normal = temp_normals[ normalIndex-1 ];
			out_normals.push_back(normal);
		}
	}

	return true;
}
コード例 #30
0
// 打开串口
//************************************
// Method:    OnOpenCom
// FullName:  CTabUartToUdp::OnOpenCom
// Access:    public 
// Returns:   void
// Qualifier:
// Parameter: void
//************************************
void CTabUartToUdp::OnOpenCom(void)
{
// 	UpdateData(TRUE);
// 	CString str;
// 	m_comboSerialPortCom.GetWindowText(str);
// 	hCom =CreateFile( str, GENERIC_READ | GENERIC_WRITE/*允许读写*/,
// 		0/*此项必须为0*/,NULL/*no security attrs*/,
// 		OPEN_EXISTING/*设置产生方式*/,
// 		0/*使用同步通信*/,
// 		NULL );
// 
// 	if(hCom!=INVALID_HANDLE_VALUE)			// 检测打开串口操作是否成功
// 	{
// 		AfxMessageBox(_T("Open Serial Port Successful!"));
// 	}
// 	else
// 	{
// 		AfxMessageBox(_T("Serial Port COM Nb is Invalid!"));
// 		return;
// 	}
// 
// 
// 	SetupComm( hCom, 1024,1024);					// 设置输入、输出缓冲区的大小
// 
// 	PurgeComm( hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR| PURGE_RXCLEAR );	// 清干净输入、输出缓冲区
// 
// 	LPCOMMTIMEOUTS lpCommTimeouts = new COMMTIMEOUTS;//(LPCOMMTIMEOUTS)malloc(sizeof(LPCOMMTIMEOUTS));
// 	lpCommTimeouts->ReadIntervalTimeout=MAXDWORD; // 读间隔超时
// 	lpCommTimeouts->ReadTotalTimeoutMultiplier=0; // 读时间系数
// 	lpCommTimeouts->ReadTotalTimeoutConstant=0; // 读时间常量 
// 	lpCommTimeouts->WriteTotalTimeoutMultiplier=50; // 写时间系数
// 	lpCommTimeouts->WriteTotalTimeoutConstant=2000; // 写时间常量
// 	//加入读取和写入延时以避免同步通信过程中的线程阻塞情况
// 
// 	SetCommTimeouts(hCom, lpCommTimeouts);
// 
// 	DCB	dcb ; // 定义数据控制块结构
// 
// 	GetCommState(hCom, &dcb ) ; //读串口原来的参数设置
// 
// 	dcb.BaudRate = OnGetSerialPortBaud(); 
// 	dcb.ByteSize = 8; 
// 	dcb.Parity = NOPARITY;
// 	dcb.StopBits = ONESTOPBIT ;
// 	dcb.fBinary = TRUE ;
// 	dcb.fParity = FALSE;
// 
// 	SetCommState(hCom, &dcb ) ; //串口参数配置
// 
// 	int iRecPort;
// 	GetDlgItem(IDC_EDIT_PORT_REC)->GetWindowText(str);			// 0x9002
// 	sscanf_s(str,"%x", &iRecPort);
// 	// 创建Socket
// 	m_socketUartToUdp.Create(iRecPort,SOCK_DGRAM);
// 	m_socketUartToUdp.SetSockOpt(SO_RCVBUF,&m_socketUartToUdp,UartToUDPBufSize,SOL_SOCKET);
// 	m_socketUartToUdp.SetSockOpt(SO_SNDBUF,&m_socketUartToUdp,UartToUDPBufSize,SOL_SOCKET);

	int iPort = 0;
	int iBaud = 0;
	CString str = _T("");
	if(m_ctrlMSComm1.get_PortOpen())
	{
		m_ctrlMSComm1.put_PortOpen(FALSE);
		m_socketUartToUdp.Close();
	}
	UpdateData(TRUE);
	iPort = OnGetSerialPortCom();
	iBaud = OnGetSerialPortBaud();
	m_ctrlMSComm1.put_CommPort(iPort);
	str.Format(_T("%d,n,8,1"), iBaud);
	m_ctrlMSComm1.put_Settings(str);

	if(!m_ctrlMSComm1.get_PortOpen())
	{
		m_ctrlMSComm1.put_PortOpen(TRUE);
		m_socketUartToUdp.m_pctrlMSComm1 = &m_ctrlMSComm1;
		GetDlgItem(IDC_EDIT_PORT_REC)->GetWindowText(str);			// 0x9002
		sscanf_s(str,"%x", &m_uiRecPort);
		m_uiSerialPortComCurSel = m_comboSerialPortCom.GetCurSel();
		m_uiSerialPortBaudCurSel = m_comboSerialPortBaud.GetCurSel();
	
		BOOL bReturn = FALSE; 
		// 创建Socket
		bReturn =  m_socketUartToUdp.Create(m_uiRecPort,SOCK_DGRAM);
		if (bReturn == FALSE)
		{
			AfxMessageBox(_T("UDP转串口端口创建失败!"));
		}
		else
		{
			bReturn = m_socketUartToUdp.SetSockOpt(SO_SNDBUF,&m_socketUartToUdp,UartToUDPBufSize,SOL_SOCKET);
			if (bReturn == FALSE)
			{
				AfxMessageBox(_T("UDP转串口端口设置发送缓冲区设置失败!"));
			}
			bReturn = m_socketUartToUdp.SetSockOpt(SO_RCVBUF,&m_socketUartToUdp,UartToUDPBufSize,SOL_SOCKET);
			if (bReturn == FALSE)
			{
				AfxMessageBox(_T("UDP转串口端口设置接收缓冲区设置失败!"));
			}
			// 避免端口阻塞
			OnAvoidIOBlock(m_socketUartToUdp);
		}
		ControlDisable();
		AfxMessageBox(_T("Open Serial Port Successful!"));
	}
	KillTimer(TabUartToUdpRecTimerNb);
	SetTimer(TabUartToUdpRecTimerNb, TabUartToUdpRecTimerSet, NULL);
}