// Dump the orbit, etc information to the given output stream. // @throw Invalid Request if the required data has not been stored. void GalEphemeris::dumpBody(std::ostream& os) const { try { OrbitEph::dumpBody(os); os << " Galileo-SPECIFIC PARAMETERS\n" << scientific << setprecision(8) << "Tgd (E5a/E1) : " << setw(16) << Tgda << " meters" << endl << "Tgd (E5b/E1) : " << setw(16) << Tgdb << " meters" << endl << "HOW time : " << setw(6) << HOWtime << " (sec of GAL week " << setw(4) << static_cast<GALWeekSecond>(ctToe).getWeek() << ")" << endl << "TransmitTime : " << OrbitEph::timeDisplay(transmitTime) << endl << "IODNav: " << IODnav << fixed << setprecision(2) << " Accuracy : " << getAccuracy() << " meters" << " fitDuration: " << setw(2) << fitDuration << " hours" << endl << "Healthy? : 0x" << hex << setw(2) << health << dec << " :" << " [E1b_D " << ((health & 0x1) ? "N":"Y") << "]" << " [E1b_H " << ((health & 0x2) ? "N":"Y") << "]" << " [E5a_D " << ((health & 0x4) ? "N":"Y") << "]" << " [E5a_H " << ((health & 0x18) ? "N":"Y") << "]" << " [E5b_D " << ((health & 0x20) ? "N":"Y") << "]" << " [E5b_H " << ((health & 0xC0) ? "N":"Y") << "]" << endl << "Datasources : " << setw(3) << datasources << " :" << ((datasources & 0x1) ? " [I/NAV E1-B]" : "") << ((datasources & 0x2) ? " [F/NAV E5a-I]" : "") << ((datasources & 0x4) ? " [I/NAV E5b-I]" : "") << ((datasources & 0x8) ? " [bit 3 reserved]" : "") << ((datasources & 0x10) ? " [bit 4 reserved]" : "") << ((datasources & 0x100) ? " [set clk/Toc/acc for E5a,E1]" : "") << ((datasources & 0x200) ? " [set clk/Toc/acc for E5b,E1]" : "") << endl; } catch(Exception& e) { GPSTK_RETHROW(e); } }
void LightService::handleEvent(bps_event_t *event) { uint16_t code = bps_event_get_code(event); if (code == SENSOR_LIGHT_READING) { float illuminance = sensor_event_get_illuminance(event); unsigned long long timestamp = getTimestamp(event); SensorAccuracy accuracy = getAccuracy(event); Q_EMIT illuminanceData(illuminance, timestamp, accuracy); } }
void AccelerometerService::handleEvent(bps_event_t *event) { uint16_t code = bps_event_get_code(event); if (code == SENSOR_ACCELEROMETER_READING) { float x, y, z; sensor_event_get_xyz(event, &x, &y, &z); unsigned long long timestamp = getTimestamp(event); SensorAccuracy accuracy = getAccuracy(event); Q_EMIT accelerometerData(x, y, z, timestamp, accuracy); } }
int BaseCostFunction::forwardUpdate(int timestep){ Activation::forwardUpdate(timestep); //timestep + 2 to keep stats until writePeriod if((timestep + 2) % writePeriod == 0){ //reset counts reset(); } //Move device est and gt activity to host updateHostData(); //Calculate costs and accuracy currCost = calcCost(); currCorrect = calcCorrect(); sumCost += currCost; numCorrect += currCorrect; numTests += bSize; if(estFilename != ""){ writeEst(); } //timestep + 1 to skip timestep 0 if((timestep+1) % writePeriod == 0){ if(costFilename != ""){ costFile << timestep << "," << getAverageCost() << std::endl; } if(accuracyFilename != ""){ accuracyFile << timestep << "," << getAccuracy() << std::endl; std::cout << "Timestep: " << timestep << " accuracy " << getAccuracy() << "\n"; } } return SUCCESS; }
void BDSEphemeris::dumpTerse(std::ostream& os) const { string tform = "%03j %02H:%02M:%02S"; try { os << " " << setw(3) << satID.id << " ! "; os << printTime(transmitTime,tform) << " ! " << printTime(ctToe,tform) << " ! " << printTime(endValid,tform) << " !" << fixed << setprecision(2) << setw(6) << getAccuracy() << "!" << setw(4) << IODC << "!" << setw(4) << IODE << "!" << setw(6) << health << "!" << endl; } catch(Exception& e) { GPSTK_RETHROW(e); } }
QMap<QString, pokemonStruct> accessAllCaughtPokemon(QString trainerName) { QMap<QString, pokemonStruct> data; QSqlQuery query(Dynamic); QString statement = "SELECT * FROM CaughtPokemon WHERE trainer='" + trainerName + "'"; if( !query.exec(statement) ) { qDebug() << query.lastError().databaseText(); return data; } while( query.next() ) { pokemonStruct saved; saved.PID = query.record().field("PID").value().toInt(); saved.attEV = query.record().field("AtEV").value().toInt(); saved.CPID = query.record().field("CPID").value().toInt(); saved.defEV = query.record().field("DefEV").value().toInt(); saved.EXP = query.record().field("EXP").value().toInt(); saved.HPEV = query.record().field("HPEV").value().toInt(); saved.speedEV = query.record().field("speedEV").value().toInt(); saved.HP = query.record().field("HP").value().toInt(); saved.level = getLevel(saved.EXP); saved.name = getPokemonName(QString::number(saved.PID)); saved.attack = getStat(saved.attEV, getBaseAtt(saved.name), saved.level); saved.defense = getStat(saved.defEV, getBaseDef(saved.name), saved.level); saved.speed = getStat(saved.speedEV, getBaseSpeed(saved.name), saved.level); saved.HP = getHP(saved.HPEV, getBaseHP(saved.name), saved.level); QString moves = query.record().field("Moves").value().toString(); QStringList l = moves.split("|"); for(int i = 0; i < l.size(); i++) { QStringList m = l[i].split("."); moveStruct move; move.name = m[0]; move.pp = m[1].toInt(); move.accuracy = getAccuracy(move.name); move.damage = getDamage(move.name); move.type = getMoveType(move.name); saved.moves.append(move); } data.insert(saved.name, saved); } return data; }
// Dump the orbit, etc information to the given output stream. // @throw Invalid Request if the required data has not been stored. void GPSEphemeris::dumpBody(std::ostream& os) const { try { OrbitEph::dumpBody(os); os << " GPS-SPECIFIC PARAMETERS\n" << scientific << setprecision(8) << "Tgd (L1/L2) : " << setw(16) << Tgd << " meters" << endl << "HOW time : " << setw(6) << HOWtime << " (sec of GPS week " << setw(4) << static_cast<GPSWeekSecond>(ctToe).getWeek() << ")" << " fitDuration: " << setw(2) << fitDuration << " hours" << endl << "TransmitTime: " << OrbitEph::timeDisplay(transmitTime) << endl << "Accuracy : flag(URA): " << accuracyFlag << " => " << fixed << setprecision(2) << getAccuracy() << " meters" << endl << "IODC: " << IODC << " IODE: " << IODE << " health: " << health << " (0=good) codeflags: " << codeflags << " L2Pdata: " << L2Pdata << endl; } catch(Exception& e) { GPSTK_RETHROW(e); } }
// Dump the orbit, etc information to the given output stream. // @throw Invalid Request if the required data has not been stored. void BDSEphemeris::dumpBody(std::ostream& os) const { try { OrbitEph::dumpBody(os); os << " BeiDou-SPECIFIC PARAMETERS\n" << scientific << setprecision(8) << "Tgd (B1/B3) : " << setw(16) << Tgd13 << " meters" << endl << "Tgd (B2/B3) : " << setw(16) << Tgd23 << " meters" << endl << "HOW time : " << setw(6) << HOWtime << " (sec of BDS week " << setw(4) << static_cast<BDSWeekSecond>(ctToe).getWeek() << ")" << " fitDuration: " << setw(2) << fitDuration << " hours" << endl << "TransmitTime: " << OrbitEph::timeDisplay(transmitTime) << endl << "Accuracy : " << fixed << setprecision(2) << getAccuracy() << " meters" << endl << "IODC: " << IODC << " IODE: " << IODE << " health: " << health << endl; } catch(Exception& e) { GPSTK_RETHROW(e); } }
string itsProblem::getInformations_XML() { // put all in the stream stringstream msg; msg << "<problem>" << endl; msg << "<key>" << getKey() << "</key>" << endl; msg << "<name>" << getName() << "</name>" << endl; msg << "<description>" << getDescription() << "</description>" << endl; msg << "<formula>" << getFormula() << "</formula>" << endl; msg << "<dimension>" << getDimension() << "</dimension>" << endl; msg << "<accuracy>" << getAccuracy() << "</accuracy>" << endl; msg << "<optimums>" << endl; if ( getOptima().size() <= 0 ) { msg << "Unknown"; } else { // print vectors of the optimums for(unsigned int i=0;i<getOptima().size();i++) { if(getOptima().size()>1) { msg << "<point id=\"" << i << "\">" << "<values>"; } else { msg << "<point>" << "<values>"; } msg << print(getOptima()[i].getValues()," "); msg << "</values>" << "<solution>"; msg << print(getOptima()[i].getSolution()," "); msg << "</solution>" << "</point>" << endl; } } msg << "</optimums>" << endl; // print vectors of bounds msg << "<bounds>" << endl; msg << "<minimums>"; msg << "<point>" << "<solution>"; msg << print( getBoundsMinima(), " "); msg << "</solution>" << "</point>"; msg << "</minimums>" << endl; msg << "<maximums>"; msg << "<point>" << "<solution>"; msg << print( getBoundsMaxima(), " "); msg << "</solution>" << "</point>"; msg << "</maximums>" << endl; msg << "</bounds>" << endl; // references msg << "<reference>" << getCitation() << "</reference>" << endl; msg << "</problem>" << endl; // return only the string return msg.str(); }
AnimalMovesWindow::AnimalMovesWindow(const std::map<QString, std::shared_ptr<db::Database>> & map, db::Database & db, const Animal & animal, QWidget * parent) : QWidget(), ui(new Ui::AnimalMovesWindow), m_parent(parent), m_db(db), m_dbMap(map), m_animal(animal) { ui->setupUi(this); ui->label_Name->setText(m_animal.getName()); QStringList horizontalHeader; horizontalHeader.append("Level"); horizontalHeader.append("Move"); horizontalHeader.append("Type"); horizontalHeader.append("Category"); horizontalHeader.append("Dmg"); horizontalHeader.append("Acc"); horizontalHeader.append("Prio"); m_movesModel.setHorizontalHeaderLabels(horizontalHeader); ComboBoxDelegate * delegate = new ComboBoxDelegate(this); std::vector<QString> vec; for (const auto & move : m_db.getMovesByID()) { vec.emplace_back(move.second.getName()); } delegate->setItems(vec); ui->tableView_Moves->setItemDelegateForColumn(1, delegate); QSortFilterProxyModel * proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(&m_movesModel); proxyModel->setSortRole(NumericModel::SortRole); ui->tableView_Moves->setModel(proxyModel); ui->tableView_Moves->resizeColumnsToContents(); ui->tableView_Moves->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed); // calculate max move name size int size = 20; QFont font; QFontMetrics fm(font); for (const auto & move : m_db.getMoves()) { size = std::max(size, fm.width(move.first)); } ui->tableView_Moves->horizontalHeader()->resizeSection(1, size + 30); // calculate max type name size size = 20; for (const auto & type : m_db.getTypes()) { size = std::max(size, fm.width(type.first)); } ui->tableView_Moves->horizontalHeader()->resizeSection(2, size + 30); // fill moves for (const auto & p : m_animal.moves()) { assert(m_db.getMoves().count(p.second) != 0); const auto move = m_db.getMoves().at(p.second); QList<QStandardItem *> itemList; itemList.append(new QStandardItem(QString::number(p.first))); itemList.append(new QStandardItem(move.getName())); itemList.append(new QStandardItem(move.getType())); itemList.back()->setEditable(false); itemList.append(new QStandardItem(move.getCategory())); itemList.back()->setEditable(false); itemList.append(new QStandardItem(QString::number(move.getBaseDamage()))); itemList.back()->setEditable(false); itemList.append(new QStandardItem(QString::number(move.getAccuracy()))); itemList.back()->setEditable(false); itemList.append(new QStandardItem(QString::number(move.getPriority()))); itemList.back()->setEditable(false); m_movesModel.appendRow(itemList); } connect(&m_movesModel, &QStandardItemModel::itemChanged, [&](QStandardItem * item){ const auto col = item->column(); if (col == 0) { // lvl changed ui->tableView_Moves->sortByColumn(0, Qt::AscendingOrder); } else if (col == 1) { // move changed const auto move = m_db.getMoves().at(item->text()); m_movesModel.setItem(item->row(), 2, new QStandardItem(move.getType())); m_movesModel.setItem(item->row(), 3, new QStandardItem(move.getCategory())); m_movesModel.setItem(item->row(), 4, new QStandardItem(QString::number(move.getBaseDamage()))); m_movesModel.setItem(item->row(), 5, new QStandardItem(QString::number(move.getAccuracy()))); m_movesModel.setItem(item->row(), 6, new QStandardItem(QString::number(move.getPriority()))); } }); }
uint8_t Clock::get(uint8_t * buffer, uint8_t size){ float f = getAccuracy(); memcpy(buffer, &f, sizeof(float)); return sizeof(float); }
void VEquipScreen::Render() { this->equippedItems.clear(); this->inventoryItems.clear(); fw().Stage_GetPrevious(this->shared_from_this())->Render(); fw().renderer->setPalette(this->pal); fw().renderer->drawFilledRect({0, 0}, fw().Display_GetSize(), Colour{0, 0, 0, 128}); // The labels/values in the stats column are used for lots of different things, so keep them // around clear them and keep them around in a vector so we don't have 5 copies of the same // "reset unused entries" code around std::vector<sp<Label>> statsLabels; std::vector<sp<Label>> statsValues; for (int i = 0; i < 9; i++) { auto labelName = UString::format("LABEL_%d", i + 1); auto label = form->FindControlTyped<Label>(labelName); if (!label) { LogError("Failed to find UI control matching \"%s\"", labelName.c_str()); } label->SetText(""); statsLabels.push_back(label); auto valueName = UString::format("VALUE_%d", i + 1); auto value = form->FindControlTyped<Label>(valueName); if (!value) { LogError("Failed to find UI control matching \"%s\"", valueName.c_str()); } value->SetText(""); statsValues.push_back(value); } auto nameLabel = form->FindControlTyped<Label>("NAME"); auto iconGraphic = form->FindControlTyped<Graphic>("SELECTED_ICON"); // If no vehicle/equipment is highlighted (mouse-over), or if we're dragging equipment around // show the currently selected vehicle stats. // // Otherwise we show the stats of the vehicle/equipment highlighted. if (highlightedEquipment) { iconGraphic->SetImage(highlightedEquipment->equipscreen_sprite); nameLabel->SetText(tr(highlightedEquipment->name)); int statsCount = 0; // All equipment has a weight statsLabels[statsCount]->SetText(tr("Weight")); statsValues[statsCount]->SetText(UString::format("%d", highlightedEquipment->weight)); statsCount++; // Draw equipment stats switch (highlightedEquipment->type) { case VEquipmentType::Type::Engine: { auto &engineType = static_cast<const VEngineType &>(*highlightedEquipment); statsLabels[statsCount]->SetText(tr("Top Speed")); statsValues[statsCount]->SetText(UString::format("%d", engineType.top_speed)); statsCount++; statsLabels[statsCount]->SetText(tr("Power")); statsValues[statsCount]->SetText(UString::format("%d", engineType.power)); break; } case VEquipmentType::Type::Weapon: { auto &weaponType = static_cast<const VWeaponType &>(*highlightedEquipment); statsLabels[statsCount]->SetText(tr("Damage")); statsValues[statsCount]->SetText(UString::format("%d", weaponType.damage)); statsCount++; statsLabels[statsCount]->SetText(tr("Range")); statsValues[statsCount]->SetText(UString::format("%d", weaponType.range)); statsCount++; statsLabels[statsCount]->SetText(tr("Accuracy")); statsValues[statsCount]->SetText(UString::format("%d", weaponType.accuracy)); statsCount++; // Only show rounds if non-zero (IE not infinite ammo) if (highlightedEquipment->max_ammo) { statsLabels[statsCount]->SetText(tr("Rounds")); statsValues[statsCount]->SetText( UString::format("%d", highlightedEquipment->max_ammo)); statsCount++; } break; } case VEquipmentType::Type::General: { auto &generalType = static_cast<const VGeneralEquipmentType &>(*highlightedEquipment); if (generalType.accuracy_modifier) { statsLabels[statsCount]->SetText(tr("Accuracy")); statsValues[statsCount]->SetText( UString::format("%d", generalType.accuracy_modifier)); statsCount++; } if (generalType.cargo_space) { statsLabels[statsCount]->SetText(tr("Cargo")); statsValues[statsCount]->SetText( UString::format("%d", generalType.cargo_space)); statsCount++; } if (generalType.passengers) { statsLabels[statsCount]->SetText(tr("Passengers")); statsValues[statsCount]->SetText(UString::format("%d", generalType.passengers)); statsCount++; } if (generalType.alien_space) { statsLabels[statsCount]->SetText(tr("Aliens Held")); statsValues[statsCount]->SetText( UString::format("%d", generalType.alien_space)); statsCount++; } if (generalType.missile_jamming) { statsLabels[statsCount]->SetText(tr("Jamming")); statsValues[statsCount]->SetText( UString::format("%d", generalType.missile_jamming)); statsCount++; } if (generalType.shielding) { statsLabels[statsCount]->SetText(tr("Shielding")); statsValues[statsCount]->SetText(UString::format("%d", generalType.shielding)); statsCount++; } if (generalType.cloaking) { statsLabels[statsCount]->SetText(tr("Cloaks Craft")); statsCount++; } if (generalType.teleporting) { statsLabels[statsCount]->SetText(tr("Teleports")); statsCount++; } break; } } } else { auto vehicle = this->highlightedVehicle; if (!vehicle) vehicle = this->selected; nameLabel->SetText(vehicle->name); // FIXME: These stats would be great to have a generic (string?) referenced list statsLabels[0]->SetText(tr("Constitution")); if (vehicle->getConstitution() == vehicle->getMaxConstitution()) { statsValues[0]->SetText(UString::format("%d", vehicle->getConstitution())); } else { statsValues[0]->SetText(UString::format("%d/%d", vehicle->getConstitution(), vehicle->getMaxConstitution())); } statsLabels[1]->SetText(tr("Armor")); statsValues[1]->SetText(UString::format("%d", vehicle->getArmor())); // FIXME: This value doesn't seem to be the same as the %age shown in the ui? statsLabels[2]->SetText(tr("Accuracy")); statsValues[2]->SetText(UString::format("%d", vehicle->getAccuracy())); statsLabels[3]->SetText(tr("Top Speed")); statsValues[3]->SetText(UString::format("%d", vehicle->getTopSpeed())); statsLabels[4]->SetText(tr("Acceleration")); statsValues[4]->SetText(UString::format("%d", vehicle->getAcceleration())); statsLabels[5]->SetText(tr("Weight")); statsValues[5]->SetText(UString::format("%d", vehicle->getWeight())); statsLabels[6]->SetText(tr("Fuel")); statsValues[6]->SetText(UString::format("%d", vehicle->getFuel())); statsLabels[7]->SetText(tr("Passengers")); statsValues[7]->SetText( UString::format("%d/%d", vehicle->getPassengers(), vehicle->getMaxPassengers())); statsLabels[8]->SetText(tr("Cargo")); statsValues[8]->SetText( UString::format("%d/%d", vehicle->getCargo(), vehicle->getMaxCargo())); iconGraphic->SetImage(vehicle->type.equip_icon_small); } // Now draw the form, the actual equipment is then drawn on top form->Render(); auto paperDollControl = form->FindControlTyped<Graphic>("PAPER_DOLL"); Vec2<int> equipOffset = paperDollControl->Location + form->Location; // Draw the equipment grid { for (auto &slot : selected->type.equipment_layout_slots) { Vec2<int> p00 = (slot.bounds.p0 * EQUIP_GRID_SLOT_SIZE) + equipOffset; Vec2<int> p11 = (slot.bounds.p1 * EQUIP_GRID_SLOT_SIZE) + equipOffset; Vec2<int> p01 = {p00.x, p11.y}; Vec2<int> p10 = {p11.x, p00.y}; if (slot.type == selectionType) { // Scale the sin curve from (-1, 1) to (0, 1) float glowFactor = (sin(this->glowCounter) + 1.0f) / 2.0f; Colour equipColour; switch (selectionType) { case VEquipmentType::Type::Engine: equipColour = EQUIP_GRID_COLOUR_ENGINE; break; case VEquipmentType::Type::Weapon: equipColour = EQUIP_GRID_COLOUR_WEAPON; break; case VEquipmentType::Type::General: equipColour = EQUIP_GRID_COLOUR_GENERAL; break; } Colour selectedColour; selectedColour.r = mix(equipColour.r, EQUIP_GRID_COLOUR.r, glowFactor); selectedColour.g = mix(equipColour.g, EQUIP_GRID_COLOUR.g, glowFactor); selectedColour.b = mix(equipColour.b, EQUIP_GRID_COLOUR.b, glowFactor); selectedColour.a = 255; fw().renderer->drawLine(p00, p01, selectedColour, 2); fw().renderer->drawLine(p01, p11, selectedColour, 2); fw().renderer->drawLine(p11, p10, selectedColour, 2); fw().renderer->drawLine(p10, p00, selectedColour, 2); } else { fw().renderer->drawLine(p00, p01, EQUIP_GRID_COLOUR, 2); fw().renderer->drawLine(p01, p11, EQUIP_GRID_COLOUR, 2); fw().renderer->drawLine(p11, p10, EQUIP_GRID_COLOUR, 2); fw().renderer->drawLine(p10, p00, EQUIP_GRID_COLOUR, 2); } } } // Draw the equipped stuff for (auto &e : selected->equipment) { auto pos = e->equippedPosition; VehicleType::AlignmentX alignX = VehicleType::AlignmentX::Left; VehicleType::AlignmentY alignY = VehicleType::AlignmentY::Top; Rect<int> slotBounds; bool slotFound = false; for (auto &slot : this->selected->type.equipment_layout_slots) { if (slot.bounds.p0 == pos) { alignX = slot.align_x; alignY = slot.align_y; slotBounds = slot.bounds; slotFound = true; break; } } if (!slotFound) { LogError("No matching slot for equipment at {%d,%d}", pos.x, pos.y); } if (pos.x >= EQUIP_GRID_SLOTS.x || pos.y >= EQUIP_GRID_SLOTS.y) { LogError("Equipment at {%d,%d} outside grid", pos.x, pos.y); } pos *= EQUIP_GRID_SLOT_SIZE; pos += equipOffset; int diffX = slotBounds.getWidth() - e->type.equipscreen_size.x; int diffY = slotBounds.getHeight() - e->type.equipscreen_size.y; switch (alignX) { case VehicleType::AlignmentX::Left: pos.x += 0; break; case VehicleType::AlignmentX::Right: pos.x += diffX * EQUIP_GRID_SLOT_SIZE.x; break; case VehicleType::AlignmentX::Centre: pos.x += (diffX * EQUIP_GRID_SLOT_SIZE.x) / 2; break; } switch (alignY) { case VehicleType::AlignmentY::Top: pos.y += 0; break; case VehicleType::AlignmentY::Bottom: pos.y += diffY * EQUIP_GRID_SLOT_SIZE.y; break; case VehicleType::AlignmentY::Centre: pos.y += (diffY * EQUIP_GRID_SLOT_SIZE.y) / 2; break; } fw().renderer->draw(e->type.equipscreen_sprite, pos); Vec2<int> endPos = pos; endPos.x += e->type.equipscreen_sprite->size.x; endPos.y += e->type.equipscreen_sprite->size.y; this->equippedItems.emplace_back(std::make_pair(Rect<int>{pos, endPos}, e)); } // Only draw inventory that can be used by this type of craft VEquipmentType::User allowedEquipmentUser; switch (this->selected->type.type) { case VehicleType::Type::Flying: allowedEquipmentUser = VEquipmentType::User::Air; break; case VehicleType::Type::Ground: allowedEquipmentUser = VEquipmentType::User::Ground; break; default: LogError( "Trying to draw equipment screen of unsupported vehicle type for vehicle \"%s\"", this->selected->name.c_str()); allowedEquipmentUser = VEquipmentType::User::Air; } // Draw the inventory if the selected is in a building, and that is a base auto bld = this->selected->building.lock(); sp<Base> base; if (bld) { base = bld->base; } if (base) { auto inventoryControl = form->FindControlTyped<Graphic>("INVENTORY"); Vec2<int> inventoryPosition = inventoryControl->Location + form->Location; for (auto &invPair : base->inventory) { // The gap between the bottom of the inventory image and the count label static const int INVENTORY_COUNT_Y_GAP = 4; // The gap between the end of one inventory image and the start of the next static const int INVENTORY_IMAGE_X_GAP = 4; auto equipIt = state->getRules().getVehicleEquipmentTypes().find(invPair.first); if (equipIt == state->getRules().getVehicleEquipmentTypes().end()) { // It's not vehicle equipment, skip continue; } auto &equipmentType = *equipIt->second; if (equipmentType.type != this->selectionType) { // Skip equipment of different types continue; } if (!equipmentType.users.count(allowedEquipmentUser)) { // The selected vehicle is not a valid user of the equipment, don't draw continue; } int count = invPair.second; if (count == 0) { // Not in stock continue; } auto countImage = labelFont->getString(UString::format("%d", count)); auto &equipmentImage = equipmentType.equipscreen_sprite; fw().renderer->draw(equipmentImage, inventoryPosition); Vec2<int> countLabelPosition = inventoryPosition; countLabelPosition.y += INVENTORY_COUNT_Y_GAP + equipmentImage->size.y; // FIXME: Center in X? fw().renderer->draw(countImage, countLabelPosition); Vec2<int> inventoryEndPosition = inventoryPosition; inventoryEndPosition.x += equipmentImage->size.x; inventoryEndPosition.y += equipmentImage->size.y; this->inventoryItems.emplace_back(Rect<int>{inventoryPosition, inventoryEndPosition}, equipmentType); // Progress inventory offset by width of image + gap inventoryPosition.x += INVENTORY_IMAGE_X_GAP + equipmentImage->size.x; } } if (this->drawHighlightBox) { Vec2<int> p00 = highlightBox.p0; Vec2<int> p11 = highlightBox.p1; Vec2<int> p01 = {p00.x, p11.y}; Vec2<int> p10 = {p11.x, p00.y}; fw().renderer->drawLine(p00, p01, highlightBoxColour, 1); fw().renderer->drawLine(p01, p11, highlightBoxColour, 1); fw().renderer->drawLine(p11, p10, highlightBoxColour, 1); fw().renderer->drawLine(p10, p00, highlightBoxColour, 1); } if (this->draggedEquipment) { // Draw equipment we're currently dragging (snapping to the grid if possible) Vec2<int> equipmentPos = fw().gamecore->MouseCursor->getPosition() + this->draggedEquipmentOffset; // If this is within the grid try to snap it Vec2<int> equipmentGridPos = equipmentPos - equipOffset; equipmentGridPos /= EQUIP_GRID_SLOT_SIZE; if (equipmentGridPos.x < 0 || equipmentGridPos.x >= EQUIP_GRID_SLOTS.x || equipmentGridPos.y < 0 || equipmentGridPos.y >= EQUIP_GRID_SLOTS.y) { // This is outside thge grid } else { // Inside the grid, snap equipmentPos = equipmentGridPos * EQUIP_GRID_SLOT_SIZE; equipmentPos += equipOffset; } fw().renderer->draw(this->draggedEquipment->equipscreen_sprite, equipmentPos); } fw().gamecore->MouseCursor->Render(); }
int main (int argc, char** argv) { char *kfile, *tfile, *cfile, *tafile, *lfile; size_t ksize, tsize, iter, depth; // FILE *kout, *tout; char opt; graph_t **gtrain; int* target; FILE* fileTrain, *fileResult, *fileTarget; core_t core; gtrain = NULL; lfile = tafile = cfile = kfile = NULL; depth = 3; CLEAR_FLAGS(); SET_RUNNABLE(); ksize = tsize = 0; core = TanimotoCore; while((opt = getopt(argc, argv, "mvihd:k:t:c:a:l:")) != -1) { switch(opt){ case 'v': SET_VERBOSE(); break; case 'i': SET_INFO(); break; case 'd': depth = strtol((const char*) optarg, 0, 10); break; case 'k': SET_K_FILE(); kfile = optarg; break; case 't': SET_T_FILE(); tfile = optarg; break; case 'c': SET_C_FILE(); cfile = optarg; break; case 'a': SET_TA_FILE(); tafile = optarg; break; case 'l': SET_L_FILE(); lfile = optarg; break; case 'h': SET_HELP(); break; case 'm': SET_PROVA_MINMAX(); break; default: SET_HELP(); } } if(HELP()) { usage(); CLEAR_FLAGS(); } if(INFO()) { info(); CLEAR_FLAGS(); } if(optind < argc) { if(!strcmp(argv[optind], "tanimoto")) { printf("tanimoto kernel\n"); } else if(!strcmp(argv[optind], "minmax")) { printf("minmax kernel\n"); core = MinMaxCore; } else printf("unavailable core ...\ndefault core: tanimoto\n"); } //else //printf("default core: tanimoto\n"); if(RUNNABLE()) { if(K_FILE() && T_FILE()) { if((fileTrain = fopen(kfile, "r")) && (fileTarget = fopen(tfile, "r"))) { gtrain = parse(fileTrain, &ksize); fclose(fileTrain); target=parseTarget(fileTarget, ksize); fclose(fileTarget); if(target==0) printf("\ncheck training file and target file"); else FoldCrossValidation(core, gtrain, target, ksize, depth); for(iter = 0; iter < ksize; iter++) free_graph(gtrain[iter]); XFREE(gtrain); XFREE(target); }else fatal("unable to open training file"); } if(TA_FILE() && C_FILE()) { fileResult = fopen(cfile, "r"); fileTarget = fopen(tafile, "r"); printf("\nAccuratezza: %f\n", getAccuracy(fileTarget, fileResult)); fclose(fileResult); fclose(fileTarget); } /* if(L_FILE()) { file = fopen(lfile, "r"); printf("\nLeaveOneOut: %f\n", getLeaveOneOut(file)); fclose(file); } */ if(K_FILE() && !T_FILE()) { if((fileTrain = fopen(kfile, "r"))) { gtrain = parse(fileTrain, &ksize); fclose(fileTrain); print_graph(gtrain[0]); print_graph(gtrain[1]); if(gtrain==0) printf("\ncheck training file"); else WriteKernelMatrix(core, gtrain, ksize, depth); for(iter = 0; iter < ksize; iter++) free_graph(gtrain[iter]); XFREE(gtrain); }else fatal("unable to open training file"); } if(PROVA_MINMAX()) { printf("\nPROVA MIN MAX\n"); fileTrain = fopen("./minmax.mol2", "r"); gtrain = parse(fileTrain, &ksize); //print_graph(gtrain[0]); //print_graph(gtrain[1]); print_graph(gtrain[0]); print_graph(gtrain[1]); printf("\nMinMax: %f", MinMaxCore(gtrain[0], gtrain[1], 3)); //printf("\nTanimoto: %f", TanimotoCore(gtrain[0], gtrain[1], 3)); fclose(fileTrain); } } //else usage(); return EXIT_SUCCESS; }
int annTrain::train(std::string imagesDir, int networkInputSize, float testRatio) { std::cout << "Reading training set..." << std::endl; uint64 start = ofGetElapsedTimeMillis(); std::vector<std::string> files = getFilesInDirectory(imagesDir); std::random_shuffle(files.begin(), files.end()); cv::Mat img; for (auto it = files.begin(); it != files.end(); ++it) { std::string filename = *it; //std::cout << "Reading image " << filename << "..." << std::endl; img = cv::imread(filename, 0); if (img.empty()) { std::cerr << "WARNING: Could not read image." << std::endl; continue; } std::string classname = getClassName(filename); cv::Mat descriptors = getDescriptors(img); processClassAndDesc(classname, descriptors); } std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl; std::cout << "Creating vocabulary..." << std::endl; start = ofGetElapsedTimeMillis(); cv::Mat labels; cv::Mat vocabulary; // Use k-means to find k centroids (the words of our vocabulary) cv::kmeans(descriptorsSet, networkInputSize, labels, cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::MAX_ITER, 10, 0.01), 1, cv::KMEANS_PP_CENTERS, vocabulary); // No need to keep it on memory anymore descriptorsSet.release(); std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl; // Convert a set of local features for each image in a single descriptors // using the bag of words technique std::cout << "Getting histograms of visual words..." << std::endl; int* ptrLabels = (int*)(labels.data); int size = labels.rows * labels.cols; for (int i = 0; i < size; i++) { int label = *ptrLabels++; ImageData* data = descriptorsMetadata[i]; data->bowFeatures.at<float>(label)++; } // Filling matrixes to be used by the neural network std::cout << "Preparing neural network..." << std::endl; std::set<ImageData*> uniqueMetadata(descriptorsMetadata.begin(), descriptorsMetadata.end()); for (auto it = uniqueMetadata.begin(); it != uniqueMetadata.end(); ) { ImageData* data = *it; cv::Mat normalizedHist; cv::normalize(data->bowFeatures, normalizedHist, 0, data->bowFeatures.rows, cv::NORM_MINMAX, -1, cv::Mat()); trainSamples.push_back(normalizedHist); trainResponses.push_back(getClassCode(classes, data->classname)); delete *it; // clear memory it++; } descriptorsMetadata.clear(); // Training neural network std::cout << "Training neural network..." << std::endl; start = ofGetElapsedTimeMillis(); mlp = getTrainedNeuralNetwork(trainSamples, trainResponses); std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl; // We can clear memory now trainSamples.release(); trainResponses.release(); // Train FLANN std::cout << "Training FLANN..." << std::endl; start = ofGetElapsedTimeMillis(); flann = cv::Ptr<cv::FlannBasedMatcher>(new cv::FlannBasedMatcher()); flann->add(vocabulary); flann->train(); std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl; // Reading test set std::cout << "Reading test set..." << std::endl; start = ofGetElapsedTimeMillis(); readImagesToTest(files.begin() + (size_t)(files.size() * testRatio), files.end()); std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl; // Get confusion matrix of the test set std::vector<std::vector<int> > confusionMatrix = getConfusionMatrix(); // how accurate is our model std::cout << "Confusion matrix " << std::endl; printConfusionMatrix(confusionMatrix, classes); std::cout << "Accuracy " << getAccuracy(confusionMatrix) << std::endl; // now save everything std::cout << "saving models" << std::endl; saveModels(vocabulary, classes); return 0; }