blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
cff02f555c920980bc66ddd55c06b6a28e01623d
7708ac67fc92f247ec5a99ed058554d642ca3aa5
/zone/doors.cpp
c0dea06b116f2e3bf2f6409ffc10e8a7d2ace607
[]
no_license
SecretsOTheP/classless3
8b59d37e1ef5a2aad30603dd63791146879db180
5de515f238ea09cbd4beaa24b14a746cc652523c
refs/heads/main
2023-08-11T13:58:23.498199
2021-09-21T18:45:20
2021-09-21T18:45:20
408,935,794
1
1
null
null
null
null
UTF-8
C++
false
false
24,509
cpp
/* EQEMu: Everquest Server Emulator Copyright (C) 2001-2002 EQEMu Development Team (http://eqemu.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY except by those people which sell it, which are required to give you total support for your newly bought product; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "../common/global_define.h" #include "../common/eqemu_logsys.h" #include "../common/string_util.h" #include "client.h" #include "doors.h" #include "entity.h" #include "guild_mgr.h" #include "mob.h" #include "string_ids.h" #include "worldserver.h" #include "zonedb.h" #include <iostream> #include <string.h> #define OPEN_DOOR 0x02 #define CLOSE_DOOR 0x03 #define OPEN_INVDOOR 0x03 #define CLOSE_INVDOOR 0x02 extern EntityList entity_list; extern WorldServer worldserver; Doors::Doors(const Door *door) : close_timer(5000), m_Position(door->pos_x, door->pos_y, door->pos_z, door->heading), m_Destination(door->dest_x, door->dest_y, door->dest_z, door->dest_heading) { strn0cpy(zone_name, door->zone_name, 32); strn0cpy(door_name, door->door_name, 32); strn0cpy(destination_zone_name, door->dest_zone, 16); this->database_id = door->db_id; this->door_id = door->door_id; this->incline = door->incline; this->open_type = door->opentype; this->guild_id = door->guild_id; this->lockpick = door->lock_pick; this->key_item_id = door->keyitem; this->no_key_ring = door->nokeyring; this->trigger_door = door->trigger_door; this->trigger_type = door->trigger_type; this->triggered = false; this->door_param = door->door_param; this->size = door->size; this->invert_state = door->invert_state; this->destination_instance_id = door->dest_instance_id; this->is_ldon_door = door->is_ldon_door; this->client_version_mask = door->client_version_mask; SetOpenState(false); close_timer.Disable(); disable_timer = (door->disable_timer == 1 ? true : false); } Doors::Doors(const char *model, const glm::vec4 &position, uint8 open_type, uint16 size) : close_timer(5000), m_Position(position), m_Destination(glm::vec4()){ strn0cpy(zone_name, zone->GetShortName(), 32); strn0cpy(door_name, model, 32); strn0cpy(destination_zone_name, "NONE", 32); this->database_id = (uint32) database.GetDoorsCountPlusOne(zone->GetShortName(), zone->GetInstanceVersion()); this->door_id = (uint8) database.GetDoorsDBCountPlusOne(zone->GetShortName(), zone->GetInstanceVersion()); this->open_type = open_type; this->size = size; this->incline = 0; this->guild_id = 0; this->lockpick = 0; this->key_item_id = 0; this->no_key_ring = 0; this->trigger_door = 0; this->trigger_type = 0; this->triggered = false; this->door_param = 0; this->invert_state = 0; this->is_ldon_door = 0; this->client_version_mask = 4294967295u; this->disable_timer = 0; this->destination_instance_id = 0; SetOpenState(false); close_timer.Disable(); } Doors::~Doors() { } bool Doors::Process() { if (close_timer.Enabled() && close_timer.Check() && IsDoorOpen()) { if (open_type == 40 || GetTriggerType() == 1) { auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct)); MoveDoor_Struct *md = (MoveDoor_Struct *) outapp->pBuffer; md->doorid = door_id; md->action = invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR; entity_list.QueueClients(0, outapp); safe_delete(outapp); } triggered = false; close_timer.Disable(); SetOpenState(false); } return true; } void Doors::HandleClick(Client* sender, uint8 trigger) { Log(Logs::Detail, Logs::Doors, "%s clicked door %s (dbid %d, eqid %d) at %s", sender->GetName(), this->door_name, this->database_id, this->door_id, to_string(m_Position).c_str() ); Log(Logs::Detail, Logs::Doors, "incline %d, open_type %d, lockpick %d, key %d, nokeyring %d, trigger %d type %d, param %d", this->incline, this->open_type, this->lockpick, this->key_item_id, this->no_key_ring, this->trigger_door, this->trigger_type, this->door_param ); Log(Logs::Detail, Logs::Doors, "disable_timer '%s',size %d, invert %d, dest: %s %s", (this->disable_timer ? "true" : "false"), this->size, this->invert_state, this->destination_zone_name, to_string(m_Destination).c_str() ); auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct)); auto *move_door_packet = (MoveDoor_Struct *) outapp->pBuffer; move_door_packet->doorid = door_id; if (this->IsLDoNDoor()) { if (sender) { if (RuleI(Adventure, ItemIDToEnablePorts) != 0) { if (!sender->KeyRingCheck(RuleI(Adventure, ItemIDToEnablePorts))) { if (sender->GetInv().HasItem(RuleI(Adventure, ItemIDToEnablePorts)) == INVALID_INDEX) { sender->MessageString(Chat::Red, DUNGEON_SEALED); safe_delete(outapp); return; } else { sender->KeyRingAdd(RuleI(Adventure, ItemIDToEnablePorts)); } } } if (!sender->GetPendingAdventureDoorClick()) { sender->PendingAdventureDoorClick(); auto pack = new ServerPacket( ServerOP_AdventureClickDoor, sizeof(ServerPlayerClickedAdventureDoor_Struct) ); /** * Adventure door */ ServerPlayerClickedAdventureDoor_Struct *adventure_door_click; adventure_door_click = (ServerPlayerClickedAdventureDoor_Struct *) pack->pBuffer; strcpy(adventure_door_click->player, sender->GetName()); adventure_door_click->zone_id = zone->GetZoneID(); adventure_door_click->id = this->GetDoorDBID(); worldserver.SendPacket(pack); safe_delete(pack); } safe_delete(outapp); return; } } uint32 required_key_item = GetKeyItem(); uint8 disable_add_to_key_ring = GetNoKeyring(); uint32 player_has_key = 0; uint32 player_key = 0; const EQ::ItemInstance *lock_pick_item = sender->GetInv().GetItem(EQ::invslot::slotCursor); player_has_key = static_cast<uint32>(sender->GetInv().HasItem(required_key_item, 1)); if (player_has_key != INVALID_INDEX) { player_key = required_key_item; } /** * Object is not triggered */ if (this->GetTriggerType() == 255) { /** * Door is only triggered by an object */ if (trigger == 1) { if (!this->IsDoorOpen() || (open_type == 58)) { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR); } else { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR); } } else { safe_delete(outapp); return; } } /** * Guild Doors * * Door is not locked */ bool is_guild_door = (this->GetGuildID() > 0) && (this->GetGuildID() == sender->GuildID()); bool is_door_not_locked = ((required_key_item == 0) && (this->GetLockpick() == 0) && (this->GetGuildID() == 0)); bool is_door_open_and_open_able = (this->IsDoorOpen() && (open_type == 58)); if (is_door_not_locked || is_door_open_and_open_able || is_guild_door) { if (!this->IsDoorOpen() || (this->GetOpenType() == 58)) { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR); } else { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR); } } else { /** * Guild Doors */ if ((this->GetGuildID() > 0) && !sender->GetGM()) { std::string guild_name; char door_message[240]; if (guild_mgr.GetGuildNameByID(guild_id, guild_name)) { sprintf(door_message, "Only members of the <%s> guild may enter here", guild_name.c_str()); } else { strcpy(door_message, "Door is locked by an unknown guild"); } sender->Message(Chat::LightBlue, door_message); safe_delete(outapp); return; } /** * Key required */ sender->Message(Chat::LightBlue, "This is locked..."); /** * GM can always open locks */ if (sender->GetGM()) { sender->MessageString(Chat::LightBlue, DOORS_GM); if (!IsDoorOpen() || (open_type == 58)) { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR); } else { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR); } } /** * Player has something they are trying to open it with */ else if (player_key) { /** * Key required and client is using the right key */ if (required_key_item && (required_key_item == player_key)) { if (!disable_add_to_key_ring) { sender->KeyRingAdd(player_key); } sender->Message(Chat::LightBlue, "You got it open!"); if (!IsDoorOpen() || (open_type == 58)) { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR); } else { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR); } } } /** * Try Lock pick */ else if (lock_pick_item != nullptr) { if (lock_pick_item->GetItem()->ItemType == EQ::item::ItemTypeLockPick) { if (sender->GetSkill(EQ::skills::SkillPickLock)) { if (lock_pick_item->GetItem()->ItemType == EQ::item::ItemTypeLockPick) { float player_pick_lock_skill = sender->GetSkill(EQ::skills::SkillPickLock); sender->CheckIncreaseSkill(EQ::skills::SkillPickLock, nullptr, 1); LogSkills("Client has lockpicks: skill=[{}]", player_pick_lock_skill); if (GetLockpick() <= player_pick_lock_skill) { if (!IsDoorOpen()) { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR); } else { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR); } sender->MessageString(Chat::LightBlue, DOORS_SUCCESSFUL_PICK); } else { sender->MessageString(Chat::LightBlue, DOORS_INSUFFICIENT_SKILL); safe_delete(outapp); return; } } else { sender->MessageString(Chat::LightBlue, DOORS_NO_PICK); safe_delete(outapp); return; } } else { sender->MessageString(Chat::LightBlue, DOORS_CANT_PICK); safe_delete(outapp); return; } } } /** * Locked door and nothing to open it with */ else { /** * Search for key on keyring */ if (sender->KeyRingCheck(required_key_item)) { player_key = required_key_item; sender->Message(Chat::LightBlue, "You got it open!"); // more debug spam if (!IsDoorOpen() || (open_type == 58)) { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR); } else { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR); } } else { sender->MessageString(Chat::LightBlue, DOORS_LOCKED); safe_delete(outapp); return; } } } entity_list.QueueClients(sender, outapp, false); if (!IsDoorOpen() || (open_type == 58)) { if (!disable_timer) close_timer.Start(); SetOpenState(true); } else { close_timer.Disable(); if (!disable_timer) SetOpenState(false); } /* * Everything past this point assumes we opened the door * and met all the requirements for opening * everything to do with closed doors has already been taken care of * we return because we don't want people using teleports on an unlocked door (exploit!) */ if ((move_door_packet->action == CLOSE_DOOR && invert_state == 0) || (move_door_packet->action == CLOSE_INVDOOR && invert_state == 1)) { safe_delete(outapp); return; } safe_delete(outapp); if ((GetTriggerDoorID() != 0) && (GetTriggerType() == 1)) { Doors *trigger_door_entity = entity_list.FindDoor(GetTriggerDoorID()); if (trigger_door_entity && !trigger_door_entity->triggered) { triggered = true; trigger_door_entity->HandleClick(sender, 1); } else { triggered = false; } } else if ((GetTriggerDoorID() != 0) && (GetTriggerType() != 1)) { Doors *trigger_door_entity = entity_list.FindDoor(GetTriggerDoorID()); if (trigger_door_entity && !trigger_door_entity->triggered) { triggered = true; trigger_door_entity->HandleClick(sender, 0); } else { triggered = false; } } /** * Teleport door */ if (((open_type == 57) || (open_type == 58)) && (strncmp(destination_zone_name, "NONE", strlen("NONE")) != 0)) { /** * If click destination is same zone and doesn't require a key */ if ((strncmp(destination_zone_name, zone_name, strlen(zone_name)) == 0) && (!required_key_item)) { if (!disable_add_to_key_ring) { sender->KeyRingAdd(player_key); } sender->MovePC( zone->GetZoneID(), zone->GetInstanceID(), m_Destination.x, m_Destination.y, m_Destination.z, m_Destination.w ); } /** * If requires a key */ else if ( (!IsDoorOpen() || open_type == 58) && (required_key_item && ((required_key_item == player_key) || sender->GetGM())) ) { if (!disable_add_to_key_ring) { sender->KeyRingAdd(player_key); } if (database.GetZoneID(destination_zone_name) == zone->GetZoneID()) { sender->MovePC( zone->GetZoneID(), zone->GetInstanceID(), m_Destination.x, m_Destination.y, m_Destination.z, m_Destination.w ); } else { sender->MovePC( database.GetZoneID(destination_zone_name), static_cast<uint32>(destination_instance_id), m_Destination.x, m_Destination.y, m_Destination.z, m_Destination.w ); } } if ((!IsDoorOpen() || open_type == 58) && (!required_key_item)) { if (database.GetZoneID(destination_zone_name) == zone->GetZoneID()) { sender->MovePC( zone->GetZoneID(), zone->GetInstanceID(), m_Destination.x, m_Destination.y, m_Destination.z, m_Destination.w ); } else { sender->MovePC( database.GetZoneID(destination_zone_name), static_cast<uint32>(this->destination_instance_id), m_Destination.x, m_Destination.y, m_Destination.z, m_Destination.w ); } } } } void Doors::Open(Mob* sender, bool alt_mode) { if (sender) { if (GetTriggerType() == 255 || GetTriggerDoorID() > 0 || GetLockpick() != 0 || GetKeyItem() != 0 || open_type == 59 || open_type == 58 || !sender->IsNPC()) { // this object isnt triggered or door is locked - NPCs should not open locked doors! return; } auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct)); MoveDoor_Struct* md = (MoveDoor_Struct*)outapp->pBuffer; md->doorid = door_id; md->action = invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR; entity_list.QueueCloseClients(sender, outapp, false, 200); safe_delete(outapp); if (!alt_mode) { // original function if (!is_open) { if (!disable_timer) close_timer.Start(); is_open = true; } else { close_timer.Disable(); if (!disable_timer) is_open = false; } } else { // alternative function if (!disable_timer) close_timer.Start(); is_open = true; } } } void Doors::ForceOpen(Mob *sender, bool alt_mode) { auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct)); MoveDoor_Struct* md = (MoveDoor_Struct*)outapp->pBuffer; md->doorid = door_id; md->action = invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR; entity_list.QueueClients(sender, outapp, false); safe_delete(outapp); if (!alt_mode) { // original function if (!is_open) { if (!disable_timer) close_timer.Start(); is_open = true; } else { close_timer.Disable(); if (!disable_timer) is_open = false; } } else { // alternative function if (!disable_timer) close_timer.Start(); is_open = true; } } void Doors::ForceClose(Mob *sender, bool alt_mode) { auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct)); MoveDoor_Struct *move_door_packet; move_door_packet = (MoveDoor_Struct *) outapp->pBuffer; move_door_packet->doorid = door_id; move_door_packet->action = invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR; // change from original (open to close) entity_list.QueueClients(sender, outapp, false); safe_delete(outapp); if (!alt_mode) { // original function if (!is_open) { if (!disable_timer) close_timer.Start(); is_open = true; } else { close_timer.Disable(); is_open = false; } } else { // alternative function if (is_open) close_timer.Trigger(); } } void Doors::ToggleState(Mob *sender) { if(GetTriggerDoorID() > 0 || GetLockpick() != 0 || GetKeyItem() != 0 || open_type == 58 || open_type == 40) { // borrowed some NPCOpen criteria return; } auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct)); MoveDoor_Struct* move_door_packet; move_door_packet = (MoveDoor_Struct*)outapp->pBuffer; move_door_packet->doorid = door_id; if(!is_open) { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR); is_open=true; } else { move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR); is_open=false; } entity_list.QueueClients(sender,outapp,false); safe_delete(outapp); } int32 ZoneDatabase::GetDoorsCount(uint32* oMaxID, const char *zone_name, int16 version) { std::string query = StringFormat("SELECT MAX(id), count(*) FROM doors " "WHERE zone = '%s' AND (version = %u OR version = -1)", zone_name, version); auto results = QueryDatabase(query); if (!results.Success()) { return -1; } if (results.RowCount() != 1) return -1; auto row = results.begin(); if (!oMaxID) return atoi(row[1]); if (row[0]) *oMaxID = atoi(row[0]); else *oMaxID = 0; return atoi(row[1]); } int32 ZoneDatabase::GetDoorsCountPlusOne(const char *zone_name, int16 version) { std::string query = StringFormat( "SELECT MAX(id) FROM doors WHERE zone = '%s' AND version = %u", zone_name, version ); auto results = QueryDatabase(query); if (!results.Success()) { return -1; } if (results.RowCount() != 1) return -1; auto row = results.begin(); if (!row[0]) return 0; return atoi(row[0]) + 1; } int32 ZoneDatabase::GetDoorsDBCountPlusOne(const char *zone_name, int16 version) { uint32 oMaxID = 0; std::string query = StringFormat("SELECT MAX(doorid) FROM doors " "WHERE zone = '%s' AND (version = %u OR version = -1)", zone_name, version); auto results = QueryDatabase(query); if (!results.Success()) { return -1; } if (results.RowCount() != 1) return -1; auto row = results.begin(); if (!row[0]) return 0; return atoi(row[0]) + 1; } bool ZoneDatabase::LoadDoors(int32 door_count, Door *into, const char *zone_name, int16 version) { LogInfo("Loading Doors from database"); std::string query = StringFormat( " SELECT " " id, " " doorid, " " zone, " " NAME, " " pos_x, " " pos_y, " " pos_z, " " heading, " " opentype, " " guild, " " lockpick, " " keyitem, " " nokeyring, " " triggerdoor, " " triggertype, " " dest_zone, " " dest_instance, " " dest_x, " " dest_y, " " dest_z, " " dest_heading, " " door_param, " " invert_state, " " incline, " " size, " " is_ldon_door, " " client_version_mask, " " disable_timer " " FROM " " doors " " WHERE " " zone = '%s' " " AND ( version = % u OR version = - 1 ) " " ORDER BY " " doorid ASC ", zone_name, version ); auto results = QueryDatabase(query); if (!results.Success()) { return false; } int32 row_index = 0; for (auto row = results.begin(); row != results.end(); ++row, ++row_index) { if (row_index >= door_count) { std::cerr << "Error, Door Count of " << door_count << " exceeded." << std::endl; break; } memset(&into[row_index], 0, sizeof(Door)); strn0cpy(into[row_index].zone_name, row[2], 32); strn0cpy(into[row_index].door_name, row[3], 32); strn0cpy(into[row_index].dest_zone, row[15], 32); into[row_index].db_id = static_cast<uint32>(atoi(row[0])); into[row_index].door_id = static_cast<uint8>(atoi(row[1])); into[row_index].pos_x = (float) atof(row[4]); into[row_index].pos_y = (float) atof(row[5]); into[row_index].pos_z = (float) atof(row[6]); into[row_index].heading = (float) atof(row[7]); into[row_index].opentype = static_cast<uint8>(atoi(row[8])); into[row_index].guild_id = static_cast<uint32>(atoi(row[9])); into[row_index].lock_pick = static_cast<uint16>(atoi(row[10])); into[row_index].keyitem = static_cast<uint32>(atoi(row[11])); into[row_index].nokeyring = static_cast<uint8>(atoi(row[12])); into[row_index].trigger_door = static_cast<uint8>(atoi(row[13])); into[row_index].trigger_type = static_cast<uint8>(atoi(row[14])); into[row_index].dest_instance_id = static_cast<uint32>(atoi(row[16])); into[row_index].dest_x = (float) atof(row[17]); into[row_index].dest_y = (float) atof(row[18]); into[row_index].dest_z = (float) atof(row[19]); into[row_index].dest_heading = (float) atof(row[20]); into[row_index].door_param = static_cast<uint32>(atoi(row[21])); into[row_index].invert_state = atoi(row[22]); into[row_index].incline = atoi(row[23]); into[row_index].size = static_cast<uint16>(atoi(row[24])); into[row_index].is_ldon_door = static_cast<uint8>(atoi(row[25])); into[row_index].client_version_mask = (uint32) strtoul(row[26], nullptr, 10); into[row_index].disable_timer = static_cast<uint8>(atoi(row[27])); Log(Logs::Detail, Logs::Doors, "Door Load: db id: %u, door_id %u disable_timer: %i", into[row_index].db_id, into[row_index].door_id, into[row_index].disable_timer ); } return true; } void Doors::SetLocation(float x, float y, float z) { entity_list.DespawnAllDoors(); m_Position = glm::vec4(x, y, z, m_Position.w); entity_list.RespawnAllDoors(); } void Doors::SetPosition(const glm::vec4& position) { entity_list.DespawnAllDoors(); m_Position = position; entity_list.RespawnAllDoors(); } void Doors::SetIncline(int in) { entity_list.DespawnAllDoors(); incline = in; entity_list.RespawnAllDoors(); } void Doors::SetOpenType(uint8 in) { entity_list.DespawnAllDoors(); open_type = in; entity_list.RespawnAllDoors(); } void Doors::SetDoorName(const char* name) { entity_list.DespawnAllDoors(); memset(door_name, 0, sizeof(door_name)); strncpy(door_name, name, sizeof(door_name)); entity_list.RespawnAllDoors(); } void Doors::SetSize(uint16 in) { entity_list.DespawnAllDoors(); size = in; entity_list.RespawnAllDoors(); } void Doors::SetDisableTimer(bool flag) { disable_timer = flag; } void Doors::CreateDatabaseEntry() { if (database.GetDoorsDBCountPlusOne(zone->GetShortName(), zone->GetInstanceVersion()) - 1 >= 255) { return; } /** * Persist */ database.InsertDoor( GetDoorDBID(), GetDoorID(), GetDoorName(), m_Position, GetOpenType(), static_cast<uint16>(GetGuildID()), GetLockpick(), GetKeyItem(), static_cast<uint8>(GetDoorParam()), static_cast<uint8>(GetInvertState()), GetIncline(), GetSize() ); } float Doors::GetX() { return m_Position.x; } float Doors::GetY() { return m_Position.y; } float Doors::GetZ() { return m_Position.z; }
[ "90209350+hackermangunz@users.noreply.github.com" ]
90209350+hackermangunz@users.noreply.github.com
c44e161af16ba0e4e975baf2b084a81c0d24e5e4
df67f4a2f3bb3f4bb78951e88ecab90955ff5c8a
/branch/ATSarf/src/case/hadith_general.cpp
68f3b4ebf01d26fcc1a081058accc1f78717f799
[]
no_license
sakrsamir/atmine
8268b8ebaa3cf00d01b57761c4ed6c09b5a46728
74c71bd09021d14c982da3a5d0d28f05b0361e49
refs/heads/master
2020-05-01T07:03:47.547064
2018-09-10T06:09:41
2018-09-10T06:09:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
37,306
cpp
#include "hadith.h" #ifdef GENERAL_HADITH #include <QFile> #include <QRegExp> #include <QString> #include <QStringList> #include "stemmer.h" #include "letters.h" #include "text_handling.h" #include "diacritics.h" #include "narrator_abstraction.h" #include "common.h" #include "ATMProgressIFC.h" #include "Math_functions.h" #include "sql_queries.h" #include "Retrieve_Template.h" #include "Search_by_item_locally.h" #include "chain_graph.h" #include <assert.h> enum wordType { NAME, NRC,NMC}; enum stateType { TEXT_S , NAME_S, NMC_S , NRC_S}; QStringList compound_words; QString hadath; long abstract_NAME, abstract_POSSESSIVE, abstract_PLACE, abstract_CITY,abstract_COUNTRY; int bit_NAME, bit_POSSESSIVE, bit_PLACE,bit_CITY,bit_COUNTRY; #ifdef PREPROCESS_DESCRIPTIONS QHash<long,bool> NMC_descriptions; QHash<long,bool> NRC_descriptions; #endif #ifdef COMPARE_TO_BUCKWALTER QTextStream * myoutPtr; #endif #ifdef COUNT_AVERAGE_SOLUTIONS long long total_solutions=0; long stemmings=0; #endif #ifdef HADITHDEBUG inline QString type_to_text(wordType t) { switch(t) { case NAME: return "NAME"; case NRC: return "NRC"; case NMC: return "NMC"; default: return "UNDEFINED-TYPE"; } } inline QString type_to_text(stateType t) { switch(t) { case TEXT_S: return "TEXT_S"; case NAME_S: return "NAME_S"; case NMC_S: return "NMC_S"; case NRC_S: return "NRC_S"; default: return "UNDEFINED-TYPE"; } } inline void display(wordType t) { out<<type_to_text(t)<<" "; //qDebug() <<type_to_text(t)<<" "; } inline void display(stateType t) { out<<type_to_text(t)<<endl; //qDebug() <<type_to_text(t); } inline void display(QString t) { out<<t; //qDebug() <<t; } #else #define display(c) ; #endif typedef QList<NameConnectorPrim *> TempConnectorPrimList; #define display_letters 30 typedef struct chainData_ { NamePrim *namePrim; NameConnectorPrim *nameConnectorPrim; NarratorConnectorPrim *narratorConnectorPrim; TempConnectorPrimList * temp_nameConnectors; Narrator *narrator; Chain *chain; } chainData; typedef struct stateData_ { long long sanadStartIndex,nmcThreshold, narratorCount,nrcThreshold,narratorStartIndex,narratorEndIndex,nrcStartIndex,nrcEndIndex,narratorThreshold,; long long nmcCount, nrcCount,nameStartIndex,nmcStartIndex; bool nmcValid; } stateData; #ifdef STATS typedef struct map_entry_ { int frequency; QString exact; QString stem; } map_entry; typedef struct statistics_{ int names_in, names_out, chains, narrators; QVector<int> narrator_per_chain, name_per_narrator; QHash <QString, map_entry*> nrc_exact, nmc_exact; QHash <QString, int> nrc_stem,nmc_stem; } statistics; QVector<map_entry*> temp_nrc_s, temp_nmc_s; int temp_nrc_count,temp_nmc_count; statistics stat; int temp_names_per_narrator; QString current_exact,current_stem; #endif stateData currentData; QString * text; long current_pos; #ifdef CHAIN_BUILDING void initializeChainData(chainData *currentChain) { delete currentChain->namePrim; delete currentChain->nameConnectorPrim; delete currentChain->narratorConnectorPrim; delete currentChain->narrator; delete currentChain->chain; /*for (int i=0;i<currentChain->temp_nameConnectors->count()-1;i++) delete (*currentChain->temp_nameConnectors)[i];*/ delete currentChain->temp_nameConnectors; currentChain-> namePrim=new NamePrim(text); currentChain-> nameConnectorPrim=new NameConnectorPrim(text); currentChain->narratorConnectorPrim=new NarratorConnectorPrim(text) ; currentChain-> narrator=new Narrator (text); currentChain-> chain=new Chain(text); currentChain->temp_nameConnectors=new TempConnectorPrimList(); display(QString("\ninit%1\n").arg(currentChain->narrator->m_narrator.size())); } #endif void hadith_initialize() { hadath.append(_7a2).append(dal).append(tha2); #if defined(REFINEMENTS) && !defined(JUST_BUCKWALTER) abstract_NAME=get_abstractCategory_id("Male Names"); #elif defined(JUST_BUCKWALTER) abstract_NAME=get_abstractCategory_id("NOUN_PROP"); #else abstract_NAME=get_abstractCategory_id("Name of Person"); #endif #ifndef JUST_BUCKWALTER abstract_POSSESSIVE=get_abstractCategory_id("POSSESSIVE"); abstract_PLACE=get_abstractCategory_id("Name of Place"); abstract_CITY=get_abstractCategory_id("City/Town"); abstract_COUNTRY=get_abstractCategory_id("Country"); bit_POSSESSIVE=get_bitindex(abstract_POSSESSIVE,abstract_category_ids); bit_PLACE=get_bitindex(abstract_PLACE,abstract_category_ids); bit_CITY=get_bitindex(abstract_CITY,abstract_category_ids); bit_COUNTRY=get_bitindex(abstract_COUNTRY,abstract_category_ids); #else abstract_POSSESSIVE=-1; abstract_PLACE=-1; abstract_CITY=-1; abstract_COUNTRY=-1; #endif bit_NAME=get_bitindex(abstract_NAME,abstract_category_ids); #ifdef REFINEMENTS QFile input("../src/case/phrases"); //contains compound words or phrases //maybe if later number of words becomes larger we save it into a trie and thus make their finding in a text faster if (!input.open(QIODevice::ReadOnly)) return; QTextStream file(&input); file.setCodec("utf-8"); QString phrases=file.readAll(); if (phrases.isNull() || phrases.isEmpty()) return; compound_words=phrases.split("\n",QString::SkipEmptyParts); #endif #ifdef STATS stat.chains=0; stat.names_in=0; stat.names_out=0; stat.narrators=0; stat.name_per_narrator.clear(); stat.narrator_per_chain.clear(); #endif #ifdef PREPROCESS_DESCRIPTIONS //preprocessing descriptions: Retrieve_Template nrc_s("description","id","name='said' OR name='say' OR name='notify/communicate' OR name LIKE '%/listen' OR name LIKE 'listen/%' OR name LIKE 'listen %' OR name LIKE '% listen' OR name = 'listen' OR name LIKE '%from/about%' OR name LIKE '%narrate%'"); while (nrc_s.retrieve()) NRC_descriptions.insert(nrc_s.get(0).toULongLong(),true); Retrieve_Template nmc_s("description","id","name='son'"); while (nmc_s.retrieve()) NMC_descriptions.insert(nmc_s.get(0).toULongLong(),true); #endif } inline void initializeStateData() { currentData.nmcThreshold=3; currentData.nmcCount=0; currentData.narratorCount=0; currentData.nrcThreshold=5; currentData.nrcCount=0; currentData.narratorStartIndex=0; currentData.narratorEndIndex=0; currentData.nrcStartIndex=0; currentData.nrcEndIndex=0; currentData.narratorThreshold=3; currentData.nmcValid=false; currentData.nameStartIndex=0; currentData.nmcStartIndex=0; } class hadith_stemmer: public Stemmer { private: bool place; #ifdef TEST_WITHOUT_SKIPPING bool finished; #endif public: bool name, nrc, nmc,possessive; long long finish_pos; #ifdef STATS QString stem; QList<QString> stems; #endif hadith_stemmer(QString * word, int start) #ifndef COMPARE_TO_BUCKWALTER :Stemmer(word,start,false) #else :Stemmer(word,start,true) #endif { name=false; nmc=false; nrc=false; possessive=false; place=false; finish_pos=start; setSolutionSettings(M_ALL); #ifdef STATS stem=""; stems.clear(); #endif #ifdef TEST_WITHOUT_SKIPPING finished=false; #endif #ifdef COUNT_AVERAGE_SOLUTIONS stemmings++; #endif } #ifndef COMPARE_TO_BUCKWALTER bool on_match() { #if 0 Search_by_item_locally s(STEM,Stem->id_of_currentmatch,Stem->category_of_currentmatch,Stem->raw_data_of_currentmatch); if (!called_everything) info.finish=Stem->currentMatchPos; stem_info=new minimal_item_info; while(s.retrieve(*stem_info)) { if (!analyze()) return false; } return true; #else solution_position * S_inf=Stem->computeFirstSolution(); do { stem_info=Stem->solution; #ifdef GET_AFFIXES_ALSO solution_position * p_inf=Prefix->computeFirstSolution(); do { prefix_infos=Prefix->affix_info; solution_position * s_inf=Suffix->computeFirstSolution(); do { suffix_infos=Suffix->affix_info; #endif #ifdef COUNT_AVERAGE_SOLUTIONS total_solutions++; #endif #ifndef TEST_WITHOUT_SKIPPING if (!analyze()) return false; #else if (!finished && !analyze()) finished=true; #endif #ifdef GET_AFFIXES_ALSO }while (Suffix->computeNextSolution(s_inf)); delete s_inf; }while (Prefix->computeNextSolution(p_inf)); delete p_inf; #endif }while (Stem->computeNextSolution(S_inf)); delete S_inf; return true; #endif } bool analyze() { #ifdef STATS QString temp_stem=removeDiacritics(info.text->mid(Stem->starting_pos, Suffix->info.start-Stem->starting_pos));//removeDiacritics(stem_info->raw_data); #endif #ifndef PREPROCESS_DESCRIPTIONS QString description=stem_info->description(); #endif if (equal_ignore_diacritics(stem_info->raw_data,hadath)) { #ifdef STATS stem=temp_stem; #endif nrc=true; finish_pos=info.finish; return false; } #ifndef PREPROCESS_DESCRIPTIONS else if (description=="son") #else else if (NMC_descriptions.contains(stem_info->description_id)) #endif { #ifdef STATS stem=temp_stem; #endif nmc=true; finish_pos=info.finish; return false; } #ifndef PREPROCESS_DESCRIPTIONS else if (description=="said" || description=="say" || description=="notify/communicate" || description.split(QRegExp("[ /]")).contains("listen") || description.contains("from/about") || description.contains("narrate")) #else else if (NRC_descriptions.contains(stem_info->description_id)) #endif { #ifdef STATS stem=temp_stem; #endif nrc=true; finish_pos=info.finish; return false; } if (stem_info->abstract_categories.getBit(bit_NAME)) { name=true; if (info.finish>finish_pos) { finish_pos=info.finish; #ifdef STATS stem=temp_stem; #endif } return true; } #ifndef JUST_BUCKWALTER if (stem_info->abstract_categories.getBit(bit_POSSESSIVE)) { possessive=true; if (place) { #ifdef STATS stem=temp_stem; #endif nmc=true; finish_pos=info.finish; return false; } } if (stem_info->abstract_categories.getBit(bit_PLACE)) { #ifdef STATS stem=temp_stem; #endif place=true; if (possessive) { nmc=true; finish_pos=info.finish; return false; } } #endif #ifdef STATS stems.append(temp_stem); #endif return true; } #else bool on_match() { QTextStream & myout=*myoutPtr; myout <<"( "<<prefix_infos->at(0).description()<<" )-" <<"-("<<stem_info->description() <<" [ "; #ifndef COMPARE_WITHOUT_ABSCAT for (int i=0;i<abstract_category_ids[max_sources]/*stem_info->abstract_categories.length()*/;i++) if (stem_info->abstract_categories[i]) myout<<database_info.comp_rules->getCategoryName(get_abstractCategory_id(i))<<"/"; myout <<" ][ "; #endif myout <<stem_info->POS <<"])--("<< suffix_infos->at(0).description()<<")" <<" "<<prefix_infos->at(0).raw_data<<stem_info->raw_data<<suffix_infos->at(0).raw_data<<" " <<" "<<info.finish+1-info.start<<"\n"; return true; } #endif }; inline long long next_positon(long long finish) { finish++; while(finish<text->length() && delimiters.contains(text->at(finish))) finish++; return finish; } inline long long getLastLetter_IN_previousWord(long long start_letter_current_word) { start_letter_current_word--; while(start_letter_current_word>=0 && delimiters.contains(text->at(start_letter_current_word))) start_letter_current_word--; return start_letter_current_word; } inline long long getLastLetter_IN_currentWord(long long start_letter_current_word) { int size=text->length(); while(start_letter_current_word<size && !delimiters.contains(text->at(start_letter_current_word))) start_letter_current_word++; return start_letter_current_word; } inline wordType result(wordType t){display(t); return t;} inline QString choose_stem(QList<QString> stems) //rule can be modified later { if (stems.size()==0) return ""; QString result=stems[0]; for (int i=1;i<stems.size();i++) if (result.length()>stems[i].length()) result=stems[i]; return result; } #ifndef BUCKWALTER_INTERFACE wordType getWordType(bool & isBinOrPossessive,bool & possessive, long long &next_pos) { long long finish; isBinOrPossessive=false; hadith_stemmer s(text,current_pos); #ifdef REFINEMENTS QString c; bool found,phrase=false; foreach (c, compound_words) { found=true; int pos=current_pos; for (int i=0;i<c.length();) { if (!isDiacritic(text->at(pos))) { if (!equal(c[i],text->at(pos))) { found=false; break; } i++; } pos++; } if (found) { phrase=true; finish=pos-1; #ifdef STATS current_stem=c; current_exact=c; #endif break; } } if (!phrase) { #endif s(); finish=max(s.info.finish,s.finish_pos); if (finish==current_pos) finish=getLastLetter_IN_currentWord(current_pos); #ifdef STATS current_exact=removeDiacritics(s.info.text->mid(current_pos,finish-current_pos+1)); current_stem=s.stem; if (current_stem=="") current_stem=choose_stem(s.stems); if (current_stem=="") current_stem=current_exact; #endif #ifdef REFINEMENTS } #endif next_pos=next_positon(finish); display(text->mid(current_pos,finish-current_pos+1)+":"); #ifdef REFINEMENTS if (phrase) { display("PHRASE"); //isBinOrPossessive=true; //same behaviour as Bin return NMC; } #endif possessive=s.possessive; if (s.nrc ) return result(NRC); else if (s.nmc) { display("NMC-Bin/Pos "); isBinOrPossessive=true; return NMC; } else if (s.name) return result(NAME); else return result(NMC); } #endif bool getNextState(stateType currentState,wordType currentType,stateType & nextState,long long start_index,bool isBinOrPossessive,bool possessive,chainData *currentChain) { display(QString(" nmcsize: %1 ").arg(currentData.nmcCount)); display(QString(" nrcsize: %1 ").arg(currentData.nrcCount)); display(currentState); switch(currentState) { case TEXT_S: if(currentType==NAME) { initializeStateData(); nextState=NAME_S; currentData.sanadStartIndex=start_index; currentData.narratorStartIndex=start_index; #ifdef CHAIN_BUILDING initializeChainData(currentChain); currentChain->namePrim=new NamePrim(text,start_index); #endif #ifdef STATS temp_names_per_narrator=1; #endif } else if (currentType==NRC) { initializeStateData(); currentData.sanadStartIndex=start_index; currentData.nrcStartIndex=start_index; nextState=NRC_S; #ifdef CHAIN_BUILDING initializeChainData(currentChain); currentChain->narratorConnectorPrim=new NarratorConnectorPrim(text,start_index); #endif #ifdef STATS temp_nrc_s.clear(); map_entry * entry=new map_entry; entry->exact=current_exact; entry->stem=current_stem; entry->frequency=1; temp_nrc_s.append(entry); temp_nrc_count=1; #endif } #ifdef TENTATIVE//needed in case a hadith starts by ibn such as "ibn yousef qal..." else if (currentType==NMC && isBinOrPossessive) { initializeStateData(currentData); initializeChainData(currentChain); currentData.narratorStartIndex=start_index; currentData.sanadStartIndex=start_index; currentData.nmcStartIndex=start_index; currentChain->nameConnectorPrim=new NameConnectorPrim(text,start_index); nextState=NAME_S; } #endif else { nextState=TEXT_S; } return true; case NAME_S: if(currentType==NMC) { nextState=NMC_S; currentData.nmcValid=isBinOrPossessive; currentData.nmcCount=1; currentData.nmcStartIndex=start_index; #ifdef CHAIN_BUILDING currentChain->namePrim->m_end=getLastLetter_IN_previousWord(start_index); currentChain->narrator->m_narrator.append(currentChain->namePrim); currentChain->nameConnectorPrim=new NameConnectorPrim(text,start_index); /*for (int i=0;i<currentChain->temp_nameConnectors->count()-1;i++) delete (*currentChain->temp_nameConnectors)[i];*/ delete currentChain->temp_nameConnectors; currentChain->temp_nameConnectors= new TempConnectorPrimList(); #endif #ifdef STATS map_entry * entry=new map_entry; entry->exact=current_exact; entry->stem=current_stem; entry->frequency=1; temp_nmc_s.append(entry); temp_nmc_count++; #endif } else if (currentType==NRC) { nextState=NRC_S; currentData.narratorCount++; #ifdef STATS stat.name_per_narrator.append(temp_names_per_narrator);//found 1 name temp_names_per_narrator=0; map_entry * entry=new map_entry; entry->exact=current_exact; entry->stem=current_stem; entry->frequency=1; temp_nrc_s.append(entry); temp_nrc_count=1; temp_nmc_count=0; #endif display(QString("counter%1\n").arg(currentData.narratorCount)); currentData.nrcCount=1; currentData.narratorEndIndex=getLastLetter_IN_previousWord(start_index); currentData.nrcStartIndex=start_index; #ifdef CHAIN_BUILDING currentChain->namePrim->m_end=getLastLetter_IN_previousWord(start_index); currentChain->narrator->m_narrator.append(currentChain->namePrim); currentChain->narratorConnectorPrim=new NarratorConnectorPrim(text,start_index); currentChain->chain->m_chain.append(currentChain->narrator); currentChain->narrator=new Narrator(text); #endif } else { if (currentType==NAME) { #ifdef STATS temp_names_per_narrator++;//found another name name #endif } nextState=NAME_S; } return true; case NMC_S: if (currentType==NRC) { currentData.narratorCount++; #ifdef STATS stat.name_per_narrator.append(temp_names_per_narrator);//found 1 name temp_names_per_narrator=0; map_entry * entry=new map_entry; entry->exact=current_exact; entry->stem=current_stem; entry->frequency=1; temp_nrc_s.append(entry); temp_nrc_count=1; temp_nmc_count=0; #endif display(QString("counter%1\n").arg(currentData.narratorCount)); currentData.nrcCount=1; nextState=NRC_S; currentData.narratorEndIndex=getLastLetter_IN_previousWord(start_index); currentData.nrcStartIndex=start_index; #ifdef CHAIN_BUILDING currentChain->nameConnectorPrim->m_end=getLastLetter_IN_previousWord(start_index); currentChain->temp_nameConnectors->append(currentChain->nameConnectorPrim); for (int i=0;i<currentChain->temp_nameConnectors->count();i++) currentChain->narrator->m_narrator.append(currentChain->temp_nameConnectors->at(i)); currentChain->narratorConnectorPrim=new NarratorConnectorPrim(text,start_index); currentChain->chain->m_chain.append(currentChain->narrator); currentChain->narrator=new Narrator(text); #endif } else if(currentType==NAME) { nextState=NAME_S; #ifdef CHAIN_BUILDING currentChain->nameConnectorPrim->m_end=getLastLetter_IN_previousWord(start_index); currentChain->temp_nameConnectors->append(currentChain->nameConnectorPrim); for (int i=0;i<currentChain->temp_nameConnectors->count();i++) currentChain->narrator->m_narrator.append(currentChain->temp_nameConnectors->at(i)); currentChain->namePrim=new NamePrim(text,start_index); #endif #ifdef STATS temp_names_per_narrator++;//found another name name #endif } else if (currentData.nmcCount>currentData.nmcThreshold) { if (currentData.nmcValid) { currentData.nmcValid=false; nextState=NMC_S; currentData.nmcCount=0; } else { nextState=TEXT_S; #ifdef CHAIN_BUILDING currentChain->nameConnectorPrim->m_end=getLastLetter_IN_previousWord(start_index);//later check for out of bounds currentChain->temp_nameConnectors->append(currentChain->nameConnectorPrim); for (int i=0;i<currentChain->temp_nameConnectors->count();i++) currentChain->narrator->m_narrator.append(currentChain->temp_nameConnectors->at(i));//check to see if we should also add the narrator to chain currentChain->chain->m_chain.append(currentChain->narrator); #endif currentData.narratorEndIndex=getLastLetter_IN_previousWord(start_index); //check this case return false; } //currentData.narratorEndIndex=getLastLetter_IN_previousWord(start_index); check this case } else if (currentType==NMC) { currentChain->nameConnectorPrim->m_end=getLastLetter_IN_previousWord(start_index); currentChain->temp_nameConnectors->append(currentChain->nameConnectorPrim); currentChain->nameConnectorPrim=new NameConnectorPrim(text,start_index); currentData.nmcCount++; if (isBinOrPossessive) currentData.nmcValid=true; nextState=NMC_S; #ifdef STATS map_entry * entry=new map_entry; entry->exact=current_exact; entry->stem=current_stem; entry->frequency=1; temp_nmc_s.append(entry); temp_nmc_count++; #endif } else { nextState=NMC_S; //maybe modify later currentChain->nameConnectorPrim->m_end=getLastLetter_IN_previousWord(start_index); currentChain->temp_nameConnectors->append(currentChain->nameConnectorPrim); currentChain->nameConnectorPrim=new NameConnectorPrim(text,start_index); #ifdef STATS map_entry * entry=new map_entry; entry->exact=current_exact; entry->stem=current_stem; entry->frequency=1; temp_nmc_s.append(entry); temp_nmc_count++; #endif } return true; case NRC_S: #ifdef REFINEMENTS if (currentType==NAME || possessive) #else if (currentType==NAME) #endif { nextState=NAME_S; //currentData.nameStartIndex=start_index; #ifdef CHAIN_BUILDING //currentChain->namePrim->m_start=start_index; currentChain->narratorConnectorPrim->m_end=getLastLetter_IN_previousWord(start_index); currentChain->chain->m_chain.append(currentChain->narratorConnectorPrim); currentChain->namePrim=new NamePrim(text,start_index); #endif currentData.nrcEndIndex=getLastLetter_IN_previousWord(start_index); #ifdef STATS temp_names_per_narrator++;//found another name name #endif } else if (currentData.nrcCount>=currentData.nrcThreshold) { nextState=TEXT_S; #ifdef STATS for (int i=temp_nmc_s.count()-temp_nmc_count;i<temp_nmc_s.count();i++) { delete temp_nmc_s[i]; temp_nmc_s.remove(i); } for (int i=temp_nrc_s.count()-temp_nrc_count;i<temp_nrc_s.count();i++) { delete temp_nrc_s[i]; temp_nrc_s.remove(i); } temp_nmc_count=0; temp_nrc_count=0; #endif //currentData.nrcEndIndex=getLastLetter_IN_previousWord(start_index); //currentChain->narratorConnectorPrim->m_end=getLastLetter_IN_previousWord(start_index); //currentChain->chain->m_chain.append(currentChain->narratorConnectorPrim); //currentData.narratorEndIndex=getLastLetter_IN_previousWord(start_index); //check this case return false; } #ifdef TENTATIVE ////needed in case 2 3an's appear after each other intervened by a name which is unknown else if (currentType==NRC) { if(currentData.nrcCount>1) //in order not to have two NRCs without a name suspect between them { currentData.narratorCount++; display(QString("counter%1\n").arg(currentData.narratorCount)); currentData.nrcCount=1; nextState=NRC_S; currentData.narratorEndIndex=getLastLetter_IN_previousWord(start_index); currentData.nrcStartIndex=start_index; currentChain->narratorConnectorPrim->m_end=getLastLetter_IN_previousWord(start_index); currentChain->chain->m_chain.append(currentChain->narratorConnectorPrim); currentChain->narratorConnectorPrim=new NarratorConnectorPrim(text,start_index); } } #endif else { nextState=NRC_S; currentData.nrcCount++; #ifdef STATS map_entry * entry=new map_entry; entry->exact=current_exact; entry->stem=current_stem; entry->frequency=1; temp_nrc_s.append(entry); temp_nrc_count++; #endif } return true; default: return true; } } #ifdef STATS void show_according_to_frequency(QList<int> freq,QList<QString> words) { QList<QPair<int, QString> > l; for (int i=0;i<freq.size() && i<words.size();i++) l.append(QPair<int,QString>(freq[i],words[i])); qSort(l.begin(),l.end()); for (int i=l.size()-1;i>=0;i--) displayed_error <<"("<<l[i].first<<") "<<l[i].second<<"\n"; } #endif #ifdef IMAN_CODE class adjective_stemmer: public Stemmer { public: bool adj ; long long finish_pos; adjective_stemmer(QString * word, int start):Stemmer(word,start/*,false*/) { adj=false; finish_pos=start; } bool on_match() { for (unsigned int i=0;i<stem_info->abstract_categories.length();i++) if (stem_info->abstract_categories[i] && get_abstractCategory_id(i)>=0) { if (getColumn("category","name",get_abstractCategory_id(i))=="ADJ") { adj=true; finish_pos=info.finish; return false; } } return true; } }; int adjective_detector(QString input_str) { QFile input(input_str.split("\n")[0]); if (!input.open(QIODevice::ReadWrite)) { out << "File not found\n"; return 1; } QTextStream file(&input); file.setCodec("utf-8"); text=new QString(file.readAll()); if (text->isNull()) { out<<"file error:"<<input.errorString()<<"\n"; return 1; } if (text->isEmpty()) //ignore empty files { out<<"empty file\n"; return 0; } long long text_size=text->size(); while(current_pos<text->length() && delimiters.contains(text->at(current_pos))) current_pos++; for (;current_pos<text_size;) { adjective_stemmer s(text,current_pos); s(); long long finish=max(s.info.finish,s.finish_pos); if (s.adj ) out <<text->mid(current_pos,finish-current_pos+1)+":ADJECTIVE\n"; current_pos=next_positon(finish);;//here current_pos is changed } return 0; } #endif #ifdef BUCKWALTER_INTERFACE class machine_info { public: bool name:1; bool nrc:1; bool nmc:1; machine_info() { name=false; nrc=false; nmc=false; } }; inline QString getnext() { long next_pos=text->indexOf('\n',current_pos); QString line=text->mid(current_pos,next_pos-current_pos); current_pos=next_pos+1; //qDebug()<<line; return line; } #ifdef OPTIMIZED_BUCKWALTER_TEST_CASE #define check(n) ; #else #define check(n) assert(n) #endif machine_info readNextWord() { machine_info info; QString line; line=getnext(); if (line=="") { current_pos=text->size(); return info; } check(line.contains("INPUT STRING")); line=getnext(); if (line.contains("Non-Alphabetic Data")) { line=getnext(); check (line==""); return info; } check(line.contains("LOOK-UP WORD")); while(1) { line=getnext(); if (line=="") break; while (line.contains("NOT FOUND")) { line=getnext(); if (line=="") return info; else if (line.contains("ALTERNATIVE")) { line=getnext(); if (line=="") return info; } } check(line.contains("SOLUTION")); QString raw_data=line.split('(').at(1).split(')').at(0); /*line=getnext(); check(line.startsWith(']'));*/ if (line.contains("NOUN_PROP")) info.name=true; line=getnext(); check(line.contains("(GLOSS)")); QString description=line.split(" + ").at(1); if (raw_data.contains("Hdv")) info.nrc=true; else if (description=="son") info.nmc=true; else if (description=="said" || description=="say" || description=="notify/communicate" || description.split(QRegExp("[ /]")).contains("listen") || description.contains("from/about") || description.contains("narrate")) info.nrc=true; } return info; } wordType getWordType(bool & isBinOrPossessive,bool & possessive, long long &next_pos) { isBinOrPossessive=false; possessive=false; machine_info s=readNextWord(); next_pos=current_pos; if (s.nrc ) return result(NRC); else if (s.nmc) { display("NMC-Bin/Pos "); isBinOrPossessive=true; return NMC; } else if (s.name) return result(NAME); else return result(NMC); } #ifdef OPTIMIZED_BUCKWALTER_TEST_CASE #undef check #endif #include <sys/time.h> #endif int hadith(QString input_str,ATMProgressIFC *prg) { #ifdef IMAN_CODE return adjective_detector(input_str); #endif #ifdef COMPARE_TO_BUCKWALTER QFile myfile("output"); myfile.remove(); if (!myfile.open(QIODevice::ReadWrite)) return 1; QByteArray output_to_file; myoutPtr= new QTextStream(&output_to_file); #else QFile chainOutput("chainOutput"); chainOutput.remove(); if (!chainOutput.open(QIODevice::ReadWrite)) return 1; QDataStream chainOut(&chainOutput); #endif #ifdef BUCKWALTER_INTERFACE timeval tim; gettimeofday(&tim,NULL); double t1=tim.tv_sec+(tim.tv_usec/1000000.0); #endif QFile input(input_str.split("\n")[0]); if (!input.open(QIODevice::ReadWrite)) { out << "File not found\n"; return 1; } QTextStream file(&input); file.setCodec("utf-8"); text=new QString(file.readAll()); if (text->isNull()) { out<<"file error:"<<input.errorString()<<"\n"; return 1; } if (text->isEmpty()) //ignore empty files { out<<"empty file\n"; return 0; } long long text_size=text->size(); #ifdef BUCKWALTER_INTERFACE gettimeofday(&tim,NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); out <<"="<<t2-t1<<"-"; #endif #ifdef COUNT_AVERAGE_SOLUTIONS total_solutions=0; stemmings=0; #endif #ifndef COMPARE_TO_BUCKWALTER stateType currentState=TEXT_S; stateType nextState=TEXT_S; wordType currentType; long long newHadithStart=-1; initializeStateData(); #ifdef CHAIN_BUILDING chainData *currentChain=new chainData(); initializeChainData(currentChain); #else chainData *currentChain=NULL; #endif long long sanadEnd; int hadith_Counter=1; #endif current_pos=0; #ifndef BUCKWALTER_INTERFACE while(current_pos<text->length() && delimiters.contains(text->at(current_pos))) current_pos++; #else QString line =getnext();//just for first line assert(line==""); #endif for (;current_pos<text_size;) { #ifndef COMPARE_TO_BUCKWALTER long long start=current_pos; long long next; bool isBinOrPossessive=false,possessive=false; currentType=getWordType(isBinOrPossessive,possessive,next); current_pos=next;//here current_pos is changed if((getNextState(currentState,currentType,nextState,start,isBinOrPossessive,possessive,currentChain)==false)) { if (currentData.narratorCount>=currentData.narratorThreshold) { sanadEnd=currentData.narratorEndIndex; #ifdef DISPLAY_HADITH_OVERVIEW newHadithStart=currentData.sanadStartIndex; long long end=text->indexOf(QRegExp(delimiters),sanadEnd);//sanadEnd is first letter of last word in sanad out<<"\n"<<hadith_Counter<<" new hadith start: "<<text->mid(newHadithStart,display_letters)<<endl; out<<"sanad end: "<<text->mid(end-display_letters,display_letters)<<endl<<endl; #ifdef CHAIN_BUILDING currentChain->chain->serialize(chainOut); //currentChain->chain->serialize(displayed_error); #endif #endif hadith_Counter++; #ifdef STATS int additional_names=temp_names_per_narrator; temp_names_per_narrator=0; for (int i=1;i<=currentData.narratorCount;i++) additional_names+=stat.name_per_narrator[stat.name_per_narrator.size()-i];//we are sure names found are in narrators stat.names_in+=additional_names; stat.chains++; stat.narrator_per_chain.append(currentData.narratorCount); stat.narrators+=currentData.narratorCount; display(QString("narrator_per_chain=")+QString::number(currentData.narratorCount)+", names="+QString::number(additional_names)+"\n"); for (int i=0;i<temp_nmc_s.count();i++) { if (!stat.nmc_stem.contains(temp_nmc_s[i]->stem)) stat.nmc_stem[temp_nmc_s[i]->stem]=1; else stat.nmc_stem[temp_nmc_s[i]->stem]++; if (!stat.nmc_exact.contains(temp_nmc_s[i]->exact)) stat.nmc_exact.insert(temp_nmc_s[i]->exact,temp_nmc_s[i]); else { map_entry * entry=stat.nmc_exact.value(temp_nmc_s[i]->exact); assert (entry->stem==temp_nmc_s[i]->stem); entry->frequency++; delete temp_nmc_s[i]; } } temp_nmc_s.clear(); temp_nmc_count=0; for (int i=0;i<temp_nrc_s.count();i++) { if (!stat.nrc_stem.contains(temp_nrc_s[i]->stem)) stat.nrc_stem[temp_nrc_s[i]->stem]=1; else stat.nrc_stem[temp_nrc_s[i]->stem]++; if (!stat.nrc_exact.contains(temp_nrc_s[i]->exact)) stat.nrc_exact.insert(temp_nrc_s[i]->exact,temp_nrc_s[i]); else { map_entry * entry=stat.nrc_exact.value(temp_nrc_s[i]->exact); assert (entry->stem==temp_nrc_s[i]->stem); entry->frequency++; delete temp_nrc_s[i]; } } temp_nrc_s.clear(); temp_nrc_count=0; #endif } else { #ifdef STATS int additional_names=temp_names_per_narrator; temp_names_per_narrator=0; for (int i=1;i<=currentData.narratorCount;i++) additional_names+=stat.name_per_narrator[stat.name_per_narrator.size()-i];//we are sure names found are in not inside valid narrators stat.names_out+=additional_names; stat.name_per_narrator.remove(stat.name_per_narrator.size()-currentData.narratorCount,currentData.narratorCount); display(QString("additional names out names =")+QString::number(additional_names)+"\n"); for (int i=0;i<temp_nmc_s.count();i++) delete temp_nmc_s[i]; temp_nmc_s.clear(); for (int i=0;i<temp_nrc_s.count();i++) delete temp_nrc_s[i]; temp_nrc_s.clear(); temp_nmc_count=0; temp_nrc_count=0; #endif } } currentState=nextState; #else hadith_stemmer s(text,current_pos); s(); long long finish=max(s.info.finish,s.finish_pos); if (finish==current_pos) finish=getLastLetter_IN_currentWord(current_pos); current_pos=next_positon(finish); #endif #ifdef PROGRESSBAR prg->report((double)current_pos/text_size*100+0.5); if (current_pos==text_size-1) break; #endif } #if !defined(COMPARE_TO_BUCKWALTER) && defined(DISPLAY_HADITH_OVERVIEW) if (newHadithStart<0) { out<<"no hadith found\n"; chainOutput.close(); return 0; } chainOutput.close(); #endif #ifdef CHAIN_BUILDING //just for testing deserialize QFile f("hadith_chains.txt"); if (!f.open(QIODevice::WriteOnly)) return 1; QTextStream file_hadith(&f); file_hadith.setCodec("utf-8"); if (!chainOutput.open(QIODevice::ReadWrite)) return 1; QDataStream tester(&chainOutput); int tester_Counter=1; #ifdef TEST_EQUAL_NARRATORS #if 0 QList<QList<Narrator *> > all_narrators; #endif #endif chains.clear(); while (!tester.atEnd()) { Chain * s=new Chain(text); s->deserialize(tester); #ifdef TEST_EQUAL_NARRATORS #if 0 QList<Narrator*> chain_narrators; for (int i=0;i<s->m_chain.count();i++) if (s->m_chain[i]->isNarrator()) chain_narrators.append((Narrator*)s->m_chain[i]); all_narrators.append(chain_narrators); #endif chains.append(s); #endif hadith_out<<tester_Counter<<" "; s->serialize(hadith_out); tester_Counter++; s->serialize(file_hadith); #ifndef TEST_EQUAL_NARRATORS delete s; #endif } chainOutput.close(); f.close(); #ifdef TEST_EQUAL_NARRATORS #if 0 QList <QList< QList< QList<double> > > > equality_value; for (int c1=0;c1<all_narrators.count();c1++) { QList< QList< QList<double> > > e1; for (int c2=0;c2<all_narrators.count();c2++) { QList< QList<double> > e2; for(int n1=0;n1<all_narrators[c1].count();n1++) { QList<double> e3; for(int n2=0;n2<all_narrators[c2].count();n2++) { e3.push_back(0); } e2.push_back(e3); } e1.push_back(e2); } equality_value.push_back(e1); } for (int c1=0;c1<all_narrators.count();c1++) for (int c2=0;c2<all_narrators.count();c2++) for(int n1=0;n1<all_narrators[c1].count();n1++) for(int n2=0;n2<all_narrators[c2].count();n2++) equality_value[c1][c2][n1][n2]=equal(*all_narrators[c1][n1],*all_narrators[c2][n2]); //just dis[lay values for first 2 chains for(int n1=0;n1<all_narrators[0].count();n1++) { for(int n2=0;n2<all_narrators[1].count();n2++) out <<equality_value[0][1][n1][n2]<<" "; out<<"\n"; } #else test_NarratorEquality(""); #endif #endif #endif #ifdef STATS double avg_narrators_per_chain=average(stat.narrator_per_chain); double avg_names_per_narrator=average(stat.name_per_narrator); displayed_error <<"Chains=\t\t"<<stat.chains<<"\n" <<"Narrators=\t\t"<<stat.narrators<<"\n" <<"Names IN=\t\t"<<stat.names_in<<"\n" <<"Names OUT=\t\t"<<stat.names_out<<"\n" <<"Avg Names/Narr=\t"<<avg_names_per_narrator<<"\n" <<"Avg Narr/Chain=\t"<<avg_narrators_per_chain<<"\n" <<"Median Names/Narr=\t"<<median(stat.name_per_narrator)<<"\n" <<"Median Narr/Chain=\t"<<median(stat.narrator_per_chain)<<"\n" <<"St Dev Names/Narr=\t"<<standard_deviation(stat.name_per_narrator,avg_names_per_narrator)<<"\n" <<"St Dev Narr/Chain=\t"<<standard_deviation(stat.narrator_per_chain,avg_narrators_per_chain)<<"\n"; displayed_error <<"\nNMC:\n"; show_according_to_frequency(stat.nmc_stem.values(),stat.nmc_stem.keys()); displayed_error <<"\nNRC:\n"; show_according_to_frequency(stat.nrc_stem.values(),stat.nrc_stem.keys()); displayed_error <<"\n\nNMC-exact:\n"; QList<int> freq; QList<map_entry *> temp=stat.nmc_exact.values(); for (int i=0;i<temp.size();i++) freq.append(temp[i]->frequency); show_according_to_frequency(freq,stat.nmc_exact.keys()); displayed_error <<"\nNRC-exact:\n"; freq.clear(); temp=stat.nrc_exact.values(); for (int i=0;i<temp.size();i++) freq.append(temp[i]->frequency); show_according_to_frequency(freq,stat.nrc_exact.keys()); displayed_error <<"\n"; temp=stat.nmc_exact.values(); for (int i=0;i<temp.size();i++) delete temp[i]; temp=stat.nrc_exact.values(); for (int i=0;i<temp.size();i++) delete temp[i]; #endif #ifdef COMPARE_TO_BUCKWALTER myfile.write(output_to_file); #endif #ifdef COUNT_AVERAGE_SOLUTIONS displayed_error << (double)(total_solutions/(long double)stemmings)<<"\n" <<stemmings<<"\n"; #endif return 0; } #endif
[ "jadothebest@6ae2aee6-be38-11de-869a-473eb4776397" ]
jadothebest@6ae2aee6-be38-11de-869a-473eb4776397
7c3fa479768682e89aa671eab6bebb4c2d8cacda
594d098f296cbb1633474972ad48ebbe9fd5254d
/ReactCommon/fabric/uimanager/ContextContainer.h
8c0819c85326af3a2810b605f03c63c015764834
[ "MIT", "CC-BY-SA-4.0", "CC-BY-4.0", "CC-BY-NC-SA-4.0" ]
permissive
Sid-ah/react-native
2616bebac1a1bbc835549ebf83af1665d2a7840c
5d06c7495d8e58543610da66f4b2aed7ea6f1386
refs/heads/master
2023-03-07T02:14:19.758351
2018-12-20T12:39:37
2018-12-20T12:42:34
162,590,749
1
0
MIT
2023-03-01T03:51:38
2018-12-20T14:32:13
JavaScript
UTF-8
C++
false
false
1,636
h
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #pragma once #include <memory> #include <mutex> #include <string> #include <typeindex> #include <typeinfo> #include <unordered_map> #include <utility> namespace facebook { namespace react { class ContextContainer; using SharedContextContainer = std::shared_ptr<ContextContainer>; /* * General purpose dependecy injection container. * Instance types must be copyable. */ class ContextContainer final { public: /* * Registers an instance of the particular type `T` in the container. * If `key` parameter is specified, the instance is registered * by `{type, key}` pair. */ template <typename T> void registerInstance(const T &instance, const std::string &key = {}) { std::lock_guard<std::mutex> lock(mutex_); instances_.insert( {{std::type_index(typeid(T)), key}, std::make_shared<T>(instance)}); } /* * Returns a previously registered instance of the particular type `T`. * If `key` parameter is specified, the lookup will be performed * by {type, key} pair. */ template <typename T> T getInstance(const std::string &key = {}) const { std::lock_guard<std::mutex> lock(mutex_); return *std::static_pointer_cast<T>( instances_.at({std::type_index(typeid(T)), key})); } private: std::unordered_map< std::pair<std::type_index, std::string>, std::shared_ptr<void>> instances_; mutable std::mutex mutex_; }; } // namespace react } // namespace facebook
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
2cea858ede1c6c06bc9ee64e89fe4ab188ded39e
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir521/dir522/dir572/dir1838/dir1839/dir2183/file2365.cpp
088d33a17aad08244ac264d8d90889ba684e6ac1
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
111
cpp
#ifndef file2365 #error "macro file2365 must be defined" #endif static const char* file2365String = "file2365";
[ "tgeng@google.com" ]
tgeng@google.com
b686031aca7d5c6df45868d57581a71e30266884
f3e19c7d2dfcabc69c1b4fbcb37cf7041684965f
/keyvi/bin/keyvi_c/c_api.cpp
d0450685849d7e6736764c6e96ba6cb635e635be
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
jsdelivrbot/keyvi
f7eeac6b74eee3f58b16691dd81f212e6c728e62
0feccb289de018505870833d36f5004539b32f9a
refs/heads/master
2020-04-10T02:12:26.393634
2018-12-06T14:43:26
2018-12-06T14:43:26
160,738,250
0
0
null
2018-12-06T22:05:13
2018-12-06T22:05:13
null
UTF-8
C++
false
false
4,817
cpp
/* * keyvi - A key value store. * * Copyright 2015, 2016 Narek Gharibyan <narekgharibyan@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * c_api.cpp * * Created on: September 4, 2017 * Author: Narek Gharibyan <narekgharibyan@gmail.com> */ #include <cstring> #include <iostream> #include "c_api/c_api.h" #include "dictionary/completion/multiword_completion.h" #include "dictionary/completion/prefix_completion.h" #include "dictionary/dictionary.h" using keyvi::dictionary::Dictionary; using keyvi::dictionary::Match; using keyvi::dictionary::MatchIterator; using keyvi::dictionary::completion::MultiWordCompletion; using keyvi::dictionary::completion::PrefixCompletion; using keyvi::dictionary::dictionary_t; namespace { char* std_2_c_string(const std::string& str) { const size_t c_str_length = str.size() + 1; auto result = static_cast<char*>(malloc(c_str_length)); strncpy(result, str.c_str(), c_str_length); return result; } } // namespace struct keyvi_dictionary { explicit keyvi_dictionary(const Dictionary& dictionary) : obj_(new Dictionary(dictionary)) {} dictionary_t obj_; }; struct keyvi_match { explicit keyvi_match(const Match& obj) : obj_(obj) {} Match obj_; }; struct keyvi_match_iterator { explicit keyvi_match_iterator(const MatchIterator::MatchIteratorPair& obj) : current_(obj.begin()), end_(obj.end()) {} MatchIterator current_; const MatchIterator end_; }; ////////////////////// //// String ////////////////////// void keyvi_string_destroy(char* str) { free(str); } ////////////////////// //// Dictionary ////////////////////// keyvi_dictionary* keyvi_create_dictionary(const char* filename) { try { return new keyvi_dictionary(Dictionary(filename)); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return nullptr; } } void keyvi_dictionary_destroy(const keyvi_dictionary* dict) { delete dict; } size_t keyvi_dictionary_get_size(const keyvi_dictionary* dict) { return dict->obj_->GetSize(); } char* keyvi_dictionary_get_statistics(const keyvi_dictionary* dict) { return std_2_c_string(dict->obj_->GetStatistics()); } keyvi_match* keyvi_dictionary_get(const keyvi_dictionary* dict, const char* key) { return new keyvi_match(dict->obj_->operator[](key)); } keyvi_match_iterator* keyvi_dictionary_get_prefix_completions(const keyvi_dictionary* dict, const char* key, size_t cutoff) { PrefixCompletion prefixCompletion(dict->obj_); return new keyvi_match_iterator(prefixCompletion.GetCompletions(key, cutoff)); } keyvi_match_iterator* keyvi_dictionary_get_fuzzy(const keyvi_dictionary* dict, const char* key, size_t max_edit_distance) { return new keyvi_match_iterator(dict->obj_->GetFuzzy(key, max_edit_distance)); } keyvi_match_iterator* keyvi_dictionary_get_multi_word_completions(const keyvi_dictionary* dict, const char* key, size_t cutoff) { MultiWordCompletion multiWordCompletion(dict->obj_); return new keyvi_match_iterator(multiWordCompletion.GetCompletions(key, cutoff)); } ////////////////////// //// Match ////////////////////// void keyvi_match_destroy(const keyvi_match* match) { delete match; } bool keyvi_match_is_empty(const keyvi_match* match) { return match->obj_.IsEmpty(); } double keyvi_match_get_score(const keyvi_match* match) { return match->obj_.GetScore(); } char* keyvi_match_get_value_as_string(const keyvi_match* match) { return std_2_c_string(match->obj_.GetValueAsString()); } char* keyvi_match_get_matched_string(const keyvi_match* match) { return std_2_c_string(match->obj_.GetMatchedString()); } ////////////////////// //// Match Iterator ////////////////////// void keyvi_match_iterator_destroy(const keyvi_match_iterator* iterator) { delete iterator; } bool keyvi_match_iterator_empty(const keyvi_match_iterator* iterator) { return iterator->current_ == iterator->end_; } keyvi_match* keyvi_match_iterator_dereference(const keyvi_match_iterator* iterator) { return new keyvi_match(*iterator->current_); } void keyvi_match_iterator_increment(keyvi_match_iterator* iterator) { iterator->current_.operator++(); }
[ "narekgharibyan@gmail.com" ]
narekgharibyan@gmail.com
42d2d3010173c4b4f9028b1567d13ead315a65ac
1497386b0fe450e6c3881c8c6d52d9e6ad9117ab
/trunk/CrypTool/DlgMac.cpp
51c9d8f21bffde9bb25f97b94ce7a7e6bc052856
[ "Apache-2.0" ]
permissive
flomar/CrypTool-VS2015
403f538d6cad9b2f16fbf8846d94456c0944569b
6468257af2e1002418882f22a9ed9fabddde096d
refs/heads/master
2021-01-21T14:39:58.113648
2017-02-22T14:10:19
2017-02-22T14:10:19
57,972,666
0
5
null
null
null
null
ISO-8859-1
C++
false
false
8,799
cpp
/************************************************************************** Copyright [2009] [CrypTool Team] This file is part of CrypTool. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************/ #include "stdafx.h" #include "CrypToolApp.h" #include "DlgMac.h" #include "SecudeCryptography.h" #include "CrypToolTools.h" #include "FileTools.h" #include ".\dlgmac.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // CDlgMac-Dialogfeld CDlgMac::CDlgMac(CWnd* pParent /*=NULL*/) : CDialog(CDlgMac::IDD, pParent) { //{{AFX_DATA_INIT(CDlgMac) m_alg = 0; m_position = 0; m_str_mac = _T(""); m_key = _T(""); m_secondkey = _T(""); //}}AFX_DATA_INIT } /*CDlgMac::~CDlgMac() { }*/ /*Aufruf nach Konstruktion, jedoch vor Anzeige des Dialogfeldes Anzeige der Datei im Dialog*/ BOOL CDlgMac::OnInitDialog() { CDialog::OnInitDialog(); UpdateData(true); m_text.SetWindowText(strText); UpdateData(false); return TRUE; } void CDlgMac::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlgMac) DDX_Radio(pDX, IDC_RADIO1, m_alg); DDX_Radio(pDX, IDC_RADIO7, m_position); DDX_Control(pDX, IDC_SHOW_TEXT, m_text); DDX_Control(pDX, IDC_SHOW_MAC, m_mac); DDX_Control(pDX, IDC_EDIT_KEY, m_ctrl_key); DDX_Text(pDX, IDC_SHOW_MAC, m_str_mac); DDX_Text(pDX, IDC_EDIT_KEY, m_key); DDX_Text(pDX, IDC_EDIT_KEY2, m_secondkey); DDX_Control(pDX, IDC_EDIT_KEY2, m_ctrl_secondkey); DDX_Control(pDX, IDOK, m_create_mac); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlgMac, CDialog) //{{AFX_MSG_MAP(CDlgMac) ON_BN_CLICKED(IDC_RADIO11, OnBUTTONSecondKey) ON_EN_CHANGE(IDC_SHOW_TEXT, OnEditText) ON_EN_CHANGE(IDC_EDIT_KEY, OnEditKey) ON_BN_CLICKED(IDC_RADIO7, OnBUTTONFront) ON_BN_CLICKED(IDC_RADIO8, OnBUTTONBack) ON_BN_CLICKED(IDC_RADIO9, OnBUTTONBoth) ON_BN_CLICKED(IDC_RADIO10, OnBUTTONDouble) ON_EN_CHANGE(IDC_EDIT_KEY2, OnEditSecondKey) ON_BN_CLICKED(IDOK, OnOK) ON_BN_CLICKED(IDC_RADIO1, OnBUTTONHashFunction) ON_BN_CLICKED(IDC_RADIO2, OnBUTTONHashFunction) ON_BN_CLICKED(IDC_RADIO3, OnBUTTONHashFunction) ON_BN_CLICKED(IDC_RADIO4, OnBUTTONHashFunction) ON_BN_CLICKED(IDC_RADIO5, OnBUTTONHashFunction) ON_BN_CLICKED(IDC_RADIO6, OnBUTTONHashFunction) //}}AFX_MSG_MAP END_MESSAGE_MAP() void CDlgMac::OnOK() { UpdateData(true); CString tempRes; switch (m_position) { case 0: if (m_key == "") { LoadString(AfxGetInstanceHandle(), IDS_STRING_MAC_NoKey, pc_str, 100); AfxMessageBox(pc_str, MB_ICONINFORMATION|MB_OK); } strText = m_key + strText; break;//Schlüssel vorne case 1: if (m_key == "") { LoadString(AfxGetInstanceHandle(), IDS_STRING_MAC_NoKey, pc_str, 100); AfxMessageBox(pc_str, MB_ICONINFORMATION|MB_OK); } strText += m_key; break;//Schlüssel hinten case 2: if (m_key == "") { LoadString(AfxGetInstanceHandle(), IDS_STRING_MAC_NoKey, pc_str, 100); AfxMessageBox(pc_str, MB_ICONINFORMATION|MB_OK); } strText = m_key + strText + m_key; break;//Schlüssel vorne und hinten case 3: if (m_key == "") { LoadString(AfxGetInstanceHandle(), IDS_STRING_MAC_Double, pc_str, 150); AfxMessageBox(pc_str, MB_ICONINFORMATION|MB_OK); } tempRes = m_key + strText; strText = m_key + CalculateMac(tempRes); break;//doppelte Ausführung der Hashfunktion case 4: if ((m_key == "") && (m_secondkey == "")) { LoadString(AfxGetInstanceHandle(), IDS_STRING_MAC_NoKey, pc_str, 100); AfxMessageBox(pc_str, MB_ICONINFORMATION|MB_OK); } else if ((m_key == "") && (m_secondkey != "")) { LoadString(AfxGetInstanceHandle(), IDS_STRING_MAC_OnlyOneKey, pc_str, 150); AfxMessageBox(pc_str, MB_ICONINFORMATION|MB_OK); } else if ((m_key != "") && (m_secondkey == "")) { LoadString(AfxGetInstanceHandle(), IDS_STRING_MAC_OnlyOneKey, pc_str, 150); AfxMessageBox(pc_str, MB_ICONINFORMATION|MB_OK); } strText = m_key + strText + m_secondkey; break;//zwei Schlüssel } SetMac(strText); m_text.SetWindowText(strText); UpdateData(false); } void CDlgMac::SetMac(CString input) { //Umwandeln in OctetString OctetString os, macHash; os.octets = 0x00000000; os.noctets = 0; const char* None = new char[0]; macHash.octets = 0x000000000; macHash.noctets = 0; String2Octets(&os, LPCSTR(input), input.GetLength()); String2Octets(&macHash, None, 0); //hashen mit dem gewählten Algorithmus switch (m_alg) { case 0: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.md2_aid, NULL); break;//MD2 case 1: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.md4_aid, NULL); break;//MD4 case 2: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.md5_aid, NULL); break;//MD5 case 3: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.sha_aid, NULL); break;//SHA case 4: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.sha1_aid, NULL); break;//SHA1 case 5: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.ripemd160_aid, NULL); break;//RIPEMD 160 } m_str_mac = MacToHex(&macHash); m_create_mac.EnableWindow(FALSE); UpdateData(false); theApp.SecudeLib.aux_free(macHash.octets); } CString CDlgMac::CalculateMac(CString tmpStr) { OctetString os, macHash; os.octets = 0x00000000; os.noctets = 0; const char* None = new char[0]; macHash.octets = 0x000000000; macHash.noctets = 0; String2Octets(&macHash, None, 0); String2Octets(&os, LPCSTR(tmpStr), tmpStr.GetLength()); //hashen mit dem gewählten Algorithmus macHash.noctets = 0; switch (m_alg) { case 0: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.md2_aid, NULL); break;//MD2 case 1: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.md4_aid, NULL); break;//MD4 case 2: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.md5_aid, NULL); break;//MD5 case 3: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.sha_aid, NULL); break;//SHA case 4: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.sha1_aid, NULL); break;//SHA1 case 5: theApp.SecudeLib.sec_hash_all(&os, &macHash, theApp.SecudeLib.ripemd160_aid, NULL); break;//RIPEMD 160 } CString tmpRes = MacToHex(&macHash); return tmpRes; } void CDlgMac::String2Octets(OctetString* osTarget, const char* Source, const int Length) { osTarget->noctets = Length; char* Buffer = new char[Length]; for(int i=0; i<Length; i++) Buffer[i] = Source[i]; delete[] osTarget->octets; osTarget->octets = Buffer; } CString CDlgMac::MacToHex(OctetString* hash) { CString hexaString; for (unsigned int i=0; i<hash->noctets; i++) { unsigned char x = hash->octets[i]; char c1, c2; if (( x % 16 ) < 10 ) { c2 = '0' + (x % 16); } else { c2 = 'A' + (x % 16) -10; } x /= 16; if ( x < 10 ) { c1 = '0' + x; } else { c1 = 'A' + x -10; } hexaString += c1; hexaString += c2; if (i < hash->noctets+1) { hexaString += ' '; } } return hexaString; } void CDlgMac::OnEditText() { UpdateData(true); m_create_mac.EnableWindow(TRUE); m_text.GetWindowText(strText); UpdateData(false); } void CDlgMac::OnEditKey() { UpdateData(true); m_create_mac.EnableWindow(TRUE); UpdateData(false); } void CDlgMac::OnEditSecondKey() { UpdateData(true); m_create_mac.EnableWindow(TRUE); UpdateData(false); } void CDlgMac::OnBUTTONFront() { UpdateData(true); m_ctrl_secondkey.EnableWindow(FALSE); m_create_mac.EnableWindow(TRUE); UpdateData(false); } void CDlgMac::OnBUTTONBack() { UpdateData(true); m_ctrl_secondkey.EnableWindow(FALSE); m_create_mac.EnableWindow(TRUE); UpdateData(false); } void CDlgMac::OnBUTTONBoth() { UpdateData(true); m_ctrl_secondkey.EnableWindow(FALSE); m_create_mac.EnableWindow(TRUE); UpdateData(false); } void CDlgMac::OnBUTTONDouble() { UpdateData(true); m_ctrl_secondkey.EnableWindow(FALSE); m_create_mac.EnableWindow(TRUE); UpdateData(false); } void CDlgMac::OnBUTTONSecondKey() { UpdateData(true); m_ctrl_secondkey.EnableWindow(TRUE); m_create_mac.EnableWindow(TRUE); UpdateData(false); } void CDlgMac::OnBUTTONHashFunction() { UpdateData(true); m_create_mac.EnableWindow(TRUE); UpdateData(false); }
[ "florian@marchal.de" ]
florian@marchal.de
b74d7fff52b2b4a29d7a34a08b4754b2a42c0881
70dc7fea5eb14bf53fceaa8ac021afe247adf1cf
/047 - Feof.cpp
f5923943347987f8c7f8c2ae84d2672389433f9d
[]
no_license
Horckun/Ejercicios-programacion-Cplusplus
aa20b30673df9dc6ef635d6a20fb070a443712f9
9dd267b66e632a3b957dcd9b8e372b285f1e2180
refs/heads/master
2020-03-09T17:28:47.668789
2019-03-14T17:05:12
2019-03-14T17:05:12
128,909,431
0
0
null
null
null
null
ISO-8859-1
C++
false
false
617
cpp
// Feof // Librería #include <iostream> using namespace std; // Función principal int main() { // Archivo *variable FILE *archivo; // Variable = abrir archivo archivo = fopen("archivo.txt","rt"); // Comprobar si se abre if(archivo == NULL) { cout << "No se ha podido abrir el archivo." << endl; } // Variable char letra; // Leer un carácter letra = fgetc(archivo); // Mostrar carácter por caracter while(feof(archivo) == 0) { cout << letra; letra = fgetc(archivo); } // Cerrar archivo fclose(archivo); // Cierre cout << "Presiona Intro para terminar..."; cin.get(); return 0; }
[ "horckun@gmail.com" ]
horckun@gmail.com
3507091e6107d33edec7904a147e2ce395ee270e
f030f192bf9926b3777da3d1f68d5028c7421435
/arm_compute/runtime/CL/functions/CLSpaceToDepthLayer.h
5a4bf1ed038ea6e821cd3f436f01a1ad78bec76f
[ "MIT" ]
permissive
nugabom/ACL-lowp
2253575f24f7c550d7cf35ce840ec0b2542b85af
98d8f013ef1bd31d17e29c66531146d6ef1c92fe
refs/heads/master
2023-04-02T11:04:18.653748
2020-11-28T06:58:19
2020-11-28T06:58:19
567,345,360
1
0
MIT
2022-11-17T15:39:31
2022-11-17T15:39:30
null
UTF-8
C++
false
false
2,799
h
/* * Copyright (c) 2019 ARM Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __ARM_COMPUTE_CLSPACETODEPTHLAYER_H__ #define __ARM_COMPUTE_CLSPACETODEPTHLAYER_H__ #include "arm_compute/runtime/IFunction.h" #include "arm_compute/core/CL/kernels/CLSpaceToDepthLayerKernel.h" #include "arm_compute/core/Types.h" namespace arm_compute { class ICLTensor; /** Basic function to run @ref CLSpaceToDepthLayerKernel. */ class CLSpaceToDepthLayer : public IFunction { public: /** Default constructor */ CLSpaceToDepthLayer(); /** Set the input and output tensors. * * @param[in] input Tensor input. Supported tensor rank: 4. Data types supported: U8/S8/QASYMM8/U16/S16/F16/U32/S32/F32. * @param[out] output Tensor output. Data types supported: same as @p input * @param[in] block_shape Block shape value. */ void configure(const ICLTensor *input, ICLTensor *output, int32_t block_shape); /** Static function to check if given info will lead to a valid configuration of @ref CLSpaceToDepthLayer. * * @param[in] input Tensor input info. Supported tensor rank: 4. Data types supported: U8/S8/QASYMM8/U16/S16/F16/U32/S32/F32. * @param[in] output Tensor output info. Data types supported: same as @p input * @param[in] block_shape Block shape value. * * @return a status */ static Status validate(const ITensorInfo *input, const ITensorInfo *output, int32_t block_shape); // Inherited methods overridden: void run() override; private: CLSpaceToDepthLayerKernel _space_to_depth_kernel; /**< CLSpaceToDepthLayerKernel to run */ }; } // namespace arm_compute #endif /* __ARM_COMPUTE_CLSPACETODEPTHLAYER_H__ */
[ "bsgcomp@arm.com" ]
bsgcomp@arm.com
41c64173a338e814573c9b5490a74a445f996cb9
5a97be73f3c6e2987480194a791675259f8d7edf
/BZOJ/3052/make.cpp
34e9ab118c2a0a00b7bced049a0402eda1c55cb4
[ "MIT" ]
permissive
sjj118/OI-Code
1d33d2a7a6eeba2ed16692d663e1b81cdc1341fd
964ea6e799d14010f305c7e4aee269d860a781f7
refs/heads/master
2022-02-21T17:54:14.764880
2019-09-05T07:16:27
2019-09-05T07:16:27
65,370,460
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
#include<iostream> #include<cstdio> #include<cstdlib> #define rg register #define rep(i,x,y) for(rg int i=(x);i<=(y);++i) #define per(i,x,y) for(rg int i=(x);i>=(y);--i) using namespace std; const int inf=1e6; int main(){ freopen("code.in","w",stdout); int n=1e5,m=1e5,q=1e5; printf("%d %d %d\n",n,m,q); rep(i,1,m)printf("%d ",rand()%inf+1);puts(""); rep(i,1,n)printf("%d ",rand()%inf+1);puts(""); rep(i,1,n-1)printf("%d %d\n",i+1,i); rep(i,1,n)printf("%d ",rand()%m+1);puts(""); rep(i,1,q)printf("%d %d %d\n",rand()&1,rand()%n+1,rand()%n+1); }
[ "sjj118@sjj118.com" ]
sjj118@sjj118.com
653903e69141a69a51cb7c31490b0afa9ed56bf0
8f796a14f2f3a8c3596cb1dc7d111cc773fa94e8
/roomba/src/RobotLogic.cpp
e012e95d292d76a42474ba3744097d83a9c73c87
[]
no_license
fraggytheundead/OC-Praktikum
a9663394db27826a75549e5c7dc2b3d6c04f784c
723649a67ee8b9019c37a3dce5fdb007b6e70619
refs/heads/master
2021-01-18T10:47:24.536241
2009-11-12T19:52:44
2009-11-12T19:52:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,006
cpp
/* ---------------------------------------------------------------------- * This file is part of the WISEBED project. * Copyright (C) 2009 by the Institute of Telematics, University of Luebeck * This is free software; you can redistribute it and/or modify it * under the terms of the BSD License. Refer to bsd-licence.txt * file in the root of the source tree for further details. ------------------------------------------------------------------------*/ /* * RobotLogic.cpp * * Created on: Jun 4, 2009 * Author: Alexander Böcken, Michael Brehler, Stephan Lohse, Tobias Witt */ #include "RobotLogic.h" #include "roombatest.h" #define DEBUG_GET_CAPABILITIES //#define DEBUG_DOTASK RobotLogic::RobotLogic(Os& os, Uart *pUart, Communication *pCommunication) : m_pOs(os), m_Robot(os), m_neighborhoodMonitor(os, 1800), neighbors(NULL) { m_Robot.initialize(pUart); m_Robot.setRobotHandler(this); int c=0; for (c=0; c<20; c++) { centerQualityID[c]=BROADCAST; } m_randOmat.srand((uint32) (m_pOs.time()).ms()); m_pCommunication = pCommunication; lastAction = Time(0,0); m_pOs.add_timeout_in(Time(MILLISECONDS), this, NULL); noNeighborsDetected = false; bumpsAndWheeldrop = 0; } RobotLogic::~RobotLogic() { // TODO Auto-generated destructor stub } void RobotLogic::doTask(const char* taskName, uint8 paramLength, const uint16 *parameters) { #ifdef DEBUG_DOTASK m_pOs.debug("doTask STRING, ID: %s, paramLength: %i", taskName, paramLength); #endif if(strcmp(taskName, "drive") == 0) { if(paramLength == 2) { lastAction = m_pOs.time(); #ifdef DEBUG_DOTASK m_pOs.debug("doTask: drive Param0:%i Param1:%i",parameters[0],parameters[1]); #endif m_Robot.drive((uint16) parameters[0], (uint16) parameters[1]); } } if(strcmp(taskName, "turn") == 0) { if(paramLength == 2) { activeTask=-1; #ifdef DEBUG_DOTASK m_pOs.debug("doTask: turnParam0:%i Param1:%i",parameters[0],parameters[1]); #endif turn((int16) parameters[0], (uint8) (parameters[1] & 0xff)); } } if(strcmp(taskName, "turnInfinite") == 0) { if(paramLength == 1) { activeTask=-1; #ifdef DEBUG_DOTASK m_pOs.debug("doTask: turnInfinite"); turnInfinite((int16) parameters[0]); #endif } } if(strcmp(taskName, "stop") == 0) { activeTask=-1; #ifdef DEBUG_DOTASK m_pOs.debug("doTask: stop"); #endif stop(); } if(strcmp(taskName, "driveDistance") == 0) { if(paramLength == 3) { activeTask=-1; #ifdef DEBUG_DOTASK m_pOs.debug("doTask: drveDist Param0: %i Param1: %i Param2: %i",parameters[0],parameters[1],parameters[2]); #endif driveDistance((uint16) parameters[0], (uint16) parameters[1], (uint16) parameters[2]); } } if (strcmp(taskName, "spread") == 0) { #ifdef DEBUG_DOTASK m_pOs.debug("doTask: spread"); #endif spread(parameters[0],parameters[1]); } if (strcmp(taskName, "gather") == 0) { gather(parameters[0],parameters[1]); } if (strcmp(taskName, "randomDrive") == 0) { randomDrive(); } if (strcmp(taskName, "patapatapata") == 0) { //m_pOs.debug("patapatapata erhalten in ID: %i",m_pOs.id()); m_pCommunication->sendMessage(m_pOs.id(),BROADCAST,"pon",0,NULL); } if (strcmp(taskName, "pon") == 0) { //m_pCommunication->sendMessage(0,"pon",0,NULL); m_pOs.debug("pon erhalten in ID: %i",m_pOs.id()); } if (strcmp(taskName, "cquality") == 0) { //m_pOs.debug("Centerquality Msgtest von %x ist %i %i",parameters[0],parameters[1],parameters[2]); uint16 tempID; tempID=parameters[0]; int i=0; for (i=0; i<20; i++) { if (centerQualityID[i]==tempID) { //m_pOs.debug("Centerquality[%i] von %x ist %i %i",i,tempID,parameters[1],parameters[2]); centerConnected[i]=parameters[1]; centerQuality[i]=parameters[2]; centerTimeoutCounter[i]=0; return; } if (centerQualityID[i]==BROADCAST) { centerQualityID[i]=tempID; centerConnected[i]=parameters[1]; centerQuality[i]=parameters[2]; //m_pOs.debug("Centerquality[%i] von %x ist %i %i ",i,tempID,parameters[1],parameters[2]); break; } } } if (strcmp(taskName, "usedemo") == 0) { activeTask=-1; usedemo(parameters[0]); } if(strcmp(taskName, "mitheme") == 0) { miTheme(); } if(strcmp(taskName, "driveStraight") == 0) { if(paramLength == 1) { activeTask=-1; m_Robot.driveStraight(parameters[0]); } } if(strcmp(taskName, "driveStraightDistance") == 0) { if(paramLength == 1) { activeTask=-1; driveStraightDistance(parameters[0], parameters[1]); } } if(strcmp(taskName, "led") == 0) { m_Robot.setLeds(parameters[0], parameters[1], parameters[2]); } // m_pOs.debug("ActionTime: %i s %i ms", lastAction.sec(), lastAction.ms()); } void RobotLogic::getCapabilities() { #ifdef DEBUG_GET_CAPABILITIES m_pOs.debug("getCapabilities start"); #endif //uint8 taskListLength = 12; uint8 taskListLength=10; //const char* taskList[]={"drive","turn","driveDistance","turnInfinite","stop","spread","gather","randomDrive","mitheme","usedemo", "driveStraight", "driveStraightDistance"}; const char* taskList[]={"drive","turn","driveDistance","turnInfinite","stop","spread","gather","randomDrive","mitheme","usedemo"}; const char*** paramList; //const uint8 paramListLength[]={2,2,3,1,0,2,2,0,0,1,1,2}; const uint8 paramListLength[]={2,2,3,1,0,2,2,0,0,1,3}; // TODO uint8 sensorLength = 3; char* sensors[]={"battery", "bumperLeft", "bumperRight"}; uint8 sensorRange[]={0,100,0,1,0,1}; paramList = ((const char ***)isense::malloc(sizeof (const char **) * taskListLength)); for (int i = 0; i < taskListLength; ++i) { int bytesNeeded = (sizeof (const char *) * paramListLength[i]); // m_pOs.debug("multiplikation: %i, sizeof (const char **): %i, paramListLength: %i", bytesNeeded, sizeof (const char *), paramListLength[i]); if(bytesNeeded > 0) { paramList[i] = ((const char **)isense::malloc(bytesNeeded)); } } #ifdef DEBUG_GET_CAPABILITIES m_pOs.debug("getCapabilities after mallocs"); #endif paramList[0][0] = "speed"; paramList[0][1] = "radius"; paramList[1][0] = "angle"; paramList[1][1] = "random"; paramList[2][0] = "speed"; paramList[2][1] = "radius"; paramList[2][2] = "distance"; paramList[3][0] = "direction"; paramList[5][0] = "centerID"; paramList[5][1] = "threshold"; paramList[6][0] = "centerID"; paramList[6][1] = "threshold"; paramList[9][0] = "number"; /*paramList[10][0] = "speed"; paramList[11][0] = "speed"; paramList[11][1] = "distance";*/ uint16 nodeID = m_pOs.id(); #ifdef DEBUG_GET_CAPABILITIES m_pOs.debug("getCapabilities after assigning paramlist members"); #endif Communication *m_pComm; m_pComm = ((roombatest *) m_pOs.application())->getCommunication(); #ifdef DEBUG_GET_CAPABILITIES m_pOs.debug("getCapabilities after getting communication"); #endif // uint8 buf[128]; m_pComm->sendFeatures(nodeID, taskListLength, taskList, paramListLength, paramList, sensorLength, sensors, sensorRange); for (int i = 0; i < taskListLength; ++i) { // m_pOs.debug("getCapabilities: freeing paramlist[%i]", i); isense::free (paramList[i]); } #ifdef DEBUG_GET_CAPABILITIES m_pOs.debug("getCapabilities after freeing paramlist members"); #endif isense::free (paramList); #ifdef DEBUG_GET_CAPABILITIES m_pOs.debug("getCapabilities end"); m_Robot.setLeds(0x0A, 16, 255); #endif } void RobotLogic::turn(int16 angle, uint8 randomComponent) { // 206mm/s == 90° / s uint16 turnSpeed = 206; Time actionTime = m_pOs.time(); lastAction = actionTime; if(randomComponent > 0) { int8 random = (int8) (m_randOmat.rand(randomComponent) & 0xff); angle += (int16) random; } uint16 turnDirection = 0x0001; if(angle < 0) { turnDirection = 0xffff; angle = angle * -1; } m_Robot.drive(turnSpeed, turnDirection); taskStruct *task = new taskStruct(); (*task).id = ROBOT_ACTION_STOP; (*task).time = actionTime; uint32 seconds = angle / 90; uint16 msecs = (1000 * angle / 90) - 1000 * seconds; Time turnTime = Time(seconds, msecs); // m_pOs.debug("RobotLogic turn, angle: %i, seconds: %i, msecs: %i", angle, seconds, msecs); // m_pOs.debug("RobotLogic turn, taskID: %i, TaskTime: %i s %i ms", (*task).id, (*task).time.sec(), (*task).time.ms()); m_pOs.add_timeout_in(turnTime, this,(void*) task); // m_pOs.debug("RobotLogic turn, taskadresse %x", task); } void RobotLogic::turnInfinite(int16 turnVelocity) { m_Robot.driveDirect(turnVelocity,-turnVelocity); } void RobotLogic::stop() { lastAction = m_pOs.time(); // m_pOs.debug("RobotLogic stop"); m_Robot.driveDirect(0,0); } void RobotLogic::usedemo(int demoNr) { m_Robot.startDemo(demoNr); } void RobotLogic::spread(uint16 tempID,uint8 tempThreshold) { activeTask=cSPREAD; hops=255; centerID = tempID; centerThreshold=tempThreshold; noNeighborsDetected=false; for (int i=0; i<20; i++) { centerQualityID[i] = BROADCAST; centerQuality[i] = 0; centerConnected[i] = 0; } } void RobotLogic::gather(uint16 tempID,uint8 tempThreshold) { activeTask = cGATHER; centerID = tempID; centerThreshold=tempThreshold; gatherDistance=100; for (int i = 0; i<20; i++) { centerQualityID[i] = BROADCAST; centerQuality[i] = 0; } centerCounter=0; if (centerID!=m_pOs.id()) { uint16 temp[] = {200,32768}; doTask("drive",2,temp); } oldGatherSum=0; gatherSum=0; timeoutCounter=0; } void RobotLogic::randomDrive() { activeTask=cRANDOMDRIVE; uint8 linkQuality; NeighborhoodMonitor::neighbor* neighbors; neighbors = m_neighborhoodMonitor.get_neighbors( m_neighborhoodMonitor.SIGNAL_STRENGTH); while (neighbors->addr != 0xFFFF) { linkQuality = neighbors->value; m_pOs.debug("randomDrive, linkQuality: %i", linkQuality); *(neighbors++); } turn(1,180); uint16 temp[] = {200,32768}; doTask("drive",2,temp); } void RobotLogic::miTheme() { activeTask = cMITHEME; uint8 song1[]={88,8,1,8,88,8,91,8,90,8,88,8,86,16,88,32,1,8,86,8,1,8,86,8,84,8,83,8,86,8,84,8}; m_Robot.setSong(0,song1,16); uint8 song2[]={1,8,84,8,1,8,83,8,83,8,1,8,1,8,88,8,1,8,88,24,91,8,90,8,88,8,86,8,86,8,88,24}; m_Robot.setSong(1,song2,16); uint8 song3[]={88,8,1,8,90,8,91,8,1,8,91,8,1,8,93,8,93,8,1,8,1,8,90,8,89,8,1,8,91,8,89,8}; m_Robot.setSong(2,song3,16); uint8 song4[]={88,8,86,8,90,8,91,8,1,8,91,8,1,8,89,8,89,8,1,8,1,16,1,32}; m_Robot.setSong(3,song4,12); songNumber=0; m_Robot.playSong(songNumber); } void RobotLogic::driveDistance(uint16 speed, uint16 radius, uint16 distance) { Time actionTime = m_pOs.time(); lastAction = actionTime; taskStruct *task = new taskStruct(); (*task).id = ROBOT_ACTION_STOP; (*task).time = actionTime; uint32 seconds = distance / speed; uint16 msecs = ((1000 * distance) / speed) - 1000 * seconds; // m_pOs.debug("RobotLogic driveDistance, distance: %i, speed: %i, seconds: %i, msecs: %i", distance, speed, seconds, msecs); // m_pOs.debug("RobotLogic turn, taskID: %i, TaskTime: %i s %i ms", (*task).id, (*task).time.sec(), (*task).time.ms()); Time distanceTime = Time(seconds, msecs); m_Robot.drive(speed, radius); m_pOs.add_timeout_in(distanceTime, this, (void*) task); // m_pOs.debug("RobotLogic turn, taskadresse %x", task); } void RobotLogic::driveStraightDistance(uint16 speed, uint16 distance) { Time actionTime = m_pOs.time(); lastAction = actionTime; taskStruct *task = new taskStruct(); (*task).id = ROBOT_ACTION_STOP; (*task).time = actionTime; uint32 seconds = distance / speed; uint16 msecs = ((1000 * distance) / speed) - 1000 * seconds; Time distanceTime = Time(seconds, msecs); m_Robot.driveStraight(speed); m_pOs.add_timeout_in(distanceTime, this, (void*) task); } void RobotLogic::timeout(void *userdata) { // m_pOs.debug("RobotLogic timeout, ID: %i", *(uint8*) userdata); if(userdata != NULL) { m_pOs.add_task(this, userdata); } else { taskBool=m_pOs.add_task(this, NULL); //m_pOs.debug("ROBOTLOGIC taskbool:%i",taskBool); //m_pOs.debug("ROBOTLOGIC timeoutbool:%i",timeoutBool); timeoutCounter++; //m_pOs.debug("TimeoutCounter:%i",timeoutCounter); } } void RobotLogic::execute(void *userdata) { if(userdata!=NULL) { taskStruct *task = (taskStruct*) userdata; // m_pOs.debug("RobotLogic turn, taskadresse %x", task); // m_pOs.debug("RobotLogic execute, taskID: %i, time: %i s %i ms", (*task).id, (*task).time.sec(), (*task).time.ms()); if((*task).id == ROBOT_ACTION_STOP && (*task).time.sec() == lastAction.sec() && (*task).time.ms() == lastAction.ms()) { stop(); } delete (taskStruct*) userdata; } else { //m_pOs.debug("TIMEOUT ROBOTLOGIC"); if (activeTask==cSPREAD) { bool bcenterConnected; uint8 linkQuality; uint8 neighborCount = 0; uint8 ownCenterQuality = 0; m_pOs.debug("spread: GetNeighbors ID: %x",m_pOs.id()); neighbors = m_neighborhoodMonitor.get_neighbors(m_neighborhoodMonitor.SIGNAL_STRENGTH); neighborsCopy=neighbors; if (neighbors!=NULL) { while (neighbors->addr != 0xFFFF) { linkQuality = neighbors->value; //m_pOs.debug("spread, Nachbar addr: %x linkQuality: %i", neighbors->addr, linkQuality); neighborCount++; linkQualityArray[neighborCount]=linkQuality; linkQualityID[neighborCount]=neighbors->addr; if (neighbors->addr == centerID) { ownCenterQuality=linkQuality; } *(neighbors++); } isense::free(neighborsCopy); } else { neighborCount=0; } for (int i=0; i<20; i++) { centerTimeoutCounter[i]++; if (centerTimeoutCounter[i]>maxTimeout) { centerQualityID[i]=BROADCAST; centerQuality[i]=0; centerConnected[i]=0; } } if (m_pOs.id()!=centerID) { bcenterConnected=true; uint16 templinkQuality=0; if (ownCenterQuality<centerThreshold) { stop(); bcenterConnected=false; for (int i=0; i<20; i++) { for (int n=0; n<20; n++) { if (centerQualityID[i]==linkQualityID[n]) { templinkQuality=linkQualityArray[n]; } } if ((centerConnected[i]>0)&&(templinkQuality>centerThreshold)) { if ((centerConnected[i]<=hops+1))//||(hops==0)) { m_pOs.debug("Connected over ID:%x Hop:%i",centerQualityID[i],centerConnected[i]); bcenterConnected=true; hops=centerConnected[i]; } else { m_pOs.debug("Illegaler Hop ID:%x Hops:%i",centerQualityID[i],centerConnected[i]); bcenterConnected=false; } } } } else { hops=0; m_pOs.debug("Directly Connected:%i",ownCenterQuality); } uint16 temp[3]; temp[0]=m_pOs.id(); if (bcenterConnected) { temp[1]=hops+1; } else { m_pOs.debug("Not Connected"); temp[1]=0; } m_pOs.debug("Hops:%i",hops); temp[2]=ownCenterQuality; m_pCommunication->sendMessage(m_pOs.id(),BROADCAST,"cquality",3,temp); //TODO richtige Bezeichnung if (bumpsAndWheeldrop&1) { turn(90,10); } else if (bumpsAndWheeldrop&2) { turn(-90,10); } else if (bcenterConnected) { if (noNeighborsDetected) { uint8 turnscript[] = {137, 0, 200, 0, 0, 157, 0, 180}; m_Robot.setScript(turnscript, 8); m_Robot.executeScript(); uint16 temp[] = {200,32768}; doTask("drive",2,temp); noNeighborsDetected = false; } else { uint16 temp[] = {200,32768}; doTask("drive",2,temp); } } //TODO was sinnvolleres als umzudrehen else if ((!bcenterConnected)&&(!noNeighborsDetected)) { uint8 turnscript[] = {137, 0, 200, 0, 0, 157, 0, 180}; m_Robot.setScript(turnscript, 8); m_Robot.executeScript(); uint16 temp[] = {200,32768}; doTask("drive",2,temp); noNeighborsDetected = true; } } m_pOs.debug("Ende von spread"); } if (activeTask==cGATHER) { m_pOs.debug("cGATHER"); uint8 linkQuality; timeoutCounter=((timeoutCounter+1)%10); if (timeoutCounter==0) { neighbors = m_neighborhoodMonitor.get_neighbors(m_neighborhoodMonitor.SIGNAL_STRENGTH); neighborsCopy=neighbors; if (neighbors!=NULL) { while (neighbors->addr != 0xFFFF) { linkQuality = neighbors->value; //m_pOs.debug("Nachbar addr: %x",neighbors->addr); //m_pOs.debug("gather, linkQuality: %i", linkQuality); if (neighbors->addr == centerID) { centerQuality[centerCounter]=linkQuality; m_pOs.debug("centerQuality[%i]: %i",centerCounter,centerQuality[centerCounter]); centerCounter=(centerCounter+1)%maxCenterCounter; } *(neighbors++); } isense::free(neighborsCopy); //m_pCommunication->sendMessage(m_pOs.id(),BROADCAST,"dummytraffic",0,NULL); if (m_pOs.id()!=centerID) { if (centerCounter==0) { oldGatherSum=gatherSum; gatherSum=0; for (int i=0;i<maxCenterCounter;i++) { gatherSum=gatherSum+centerQuality[centerCounter]; } if (gatherSum/maxCenterCounter>centerThreshold) { m_Robot.setLeds(0, 0, 0); m_pOs.debug("Center erreicht"); stop(); activeTask=0; } if ((oldGatherSum/maxCenterCounter)>(gatherSum/maxCenterCounter)+5) { m_Robot.setLeds(2, 255, 255); m_pOs.debug("Gather moved away from %i to %i",(oldGatherSum/maxCenterCounter),(gatherSum/maxCenterCounter)); uint8 turnscript[] = {137, 0, 200, 0, 0, 157, 0, 90}; m_Robot.setScript(turnscript, 8); m_Robot.executeScript(); gatherDistance=500; driveDistance(200,32768,gatherDistance); /*uint8 movescript[] = {137, 1, 44, 128, 0, 156, uint8(gatherDistance>>8), uint8(gatherDistance&0xff), 137, 0, 0, 0, 0}; m_Robot.setScript(movescript, 13); m_Robot.executeScript();*/ } else { m_Robot.setLeds(8, 16, 255); gatherDistance=gatherDistance-10; if (gatherDistance<200) { gatherDistance=200; } uint8 movescript[] = {137, 1, 44, 128, 0, 156, uint8(gatherDistance>>8), uint8(gatherDistance&0xff), 137, 0, 0, 0, 0}; m_Robot.setScript(movescript, 13); m_Robot.executeScript(); } } } } } } if (activeTask==cRANDOMDRIVE) { m_pOs.debug("cRANDOMDRIVE"); uint8 linkQuality; uint8 neighborCount = 0; m_pOs.debug("randomDrive: GetNeighbors ID: %x",m_pOs.id()); neighbors = m_neighborhoodMonitor.get_neighbors(m_neighborhoodMonitor.SIGNAL_STRENGTH); neighborsCopy=neighbors; if (neighbors!=NULL) { while (neighbors->addr != 0xFFFF) { linkQuality = neighbors->value; m_pOs.debug("Nachbar addr: %x",neighbors->addr); m_pOs.debug("randomDrive, linkQuality: %i", linkQuality); if (linkQuality > 50) { neighborCount++; } *(neighbors++); } isense::free(neighborsCopy); } if (neighborCount==0) { uint8 turnscript[] = {137, 0, 200, 0, 0, 157, 0, 180}; m_Robot.setScript(turnscript, 8); m_Robot.executeScript(); uint16 temp[] = {200,32768}; doTask("drive",2,temp); } if (bumpsAndWheeldrop&1) { uint8 turnscript[] = {137, 0, 200, 0, 0, 157, 0, 90}; m_Robot.setScript(turnscript, 8); m_Robot.executeScript(); uint16 temp[] = {200,32768}; doTask("drive",2,temp); } } timeoutBool=m_pOs.add_timeout_in(Time(MILLISECONDS/10), this, NULL); } } void RobotLogic::onIoModeChanged(uint8 ioMode) { } void RobotLogic::onPowerStateChanged(PCPOWERSTATE pState) { } void RobotLogic::onCliffStateChanged(PCCLIFFSTATE pState) { } void RobotLogic::onMovementStateChanged(PCMOVEMENTSTATE pState) { } void RobotLogic::onButtonChanged(uint8 buttons) { m_pOs.debug("Button changed: %d", buttons); } void RobotLogic::onWallSensorChanged(uint8 wall, uint8 virtualWall) { } void RobotLogic::onBumpAndWheelDrop(uint8 bumpsAndWheelDrop) { m_pOs.debug("Bump and wheel drop: %d", bumpsAndWheelDrop); bumpsAndWheeldrop = bumpsAndWheelDrop; } void RobotLogic::onSongStateChanged(uint8 songNumber, uint8 songPlaying) { if (activeTask==cMITHEME) { if (songPlaying==0) { songNumber=songNumber+1; m_pOs.debug("MITHEME %i",songNumber); m_Robot.playSong(songNumber); } if (songNumber>3) { activeTask=-1; } } }
[ "lohse@informatik.uni-luebeck.de" ]
lohse@informatik.uni-luebeck.de
6f779113e397cd05f06b3cde1e2979a53ed9f195
19be686d8ad49f37f1c73a1f66d75a647ccdb214
/DelaunayGridGenerator/nodewrapper.h
60c4d56ef2a94f214f5b6fb21484633f80eb3b5f
[]
no_license
NazariyJaworskiGitHub/physicalenvironmentdesign
fba9195fd9410a2846433a72fa8312b222506582
e7d119725c206c3cbb1aeb537e7e29bd4cf24d10
refs/heads/master
2022-04-12T01:25:34.129952
2020-02-24T08:27:42
2020-02-24T08:27:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,488
h
#ifndef NODEWRAPPER_H #define NODEWRAPPER_H #include <limits> #include "listwrapperinterface.h" #include "mathutils.h" #include "node.h" namespace DelaunayGridGenerator { /// Wraps Node class adding the self-pointrer storage for O(1) deletion from lists; /// Note, that QList is not the "real" list with O(1) insertion complexyty, when /// QLinkedList is. But index-search for QList is O(1) and for QLinkedList is O(N), /// that's why one need to use wrapped objects with self-pointers to achieve O(1) in /// both cases. See help references or /// http://qt-project.org/doc/qt-5.1/qtcore/containers.html#algorithmic-complexity /// \todo add Node-stole constructor, do not copy Nodes template< typename _NodeType_, typename _DimType_ = MathUtils::Real> class NodeWrapper : public _NodeType_ { LIST_WRAPPED_INTERFACE(NodeWrapper) /// Use it to know the global index of current node, whatever it means; /// \todo don't use indexes, remake all to pointers; private: int _myGlobalIndex = -1; public : int getGlobalIndex() const noexcept { return _myGlobalIndex; } /// \todo it makes copy, avoid that public : NodeWrapper(const _NodeType_ &target, int globalIndex = -1) noexcept: _NodeType_(target), _myState(UNKNOWN), _myGlobalIndex(globalIndex) { } public : NodeWrapper(const NodeWrapper &target, int globalIndex = -1) noexcept: _NodeType_(target), _ptrToMyself(target._ptrToMyself), _myState(target._myState), _myGlobalIndex(globalIndex) { } public : NodeWrapper() noexcept: _NodeType_(), _myState(UNKNOWN), _myGlobalIndex(-1) { } /// \todo test this, make shure that you need this void roundToDiscreteSpace(_DimType_ discretizationStep = std::numeric_limits<_DimType_>::epsilon()) noexcept { for(_DimType_ &c : this->_coord) c = MathUtils::round<_DimType_>(c,discretizationStep); } public : ~NodeWrapper() noexcept {} }; typedef NodeWrapper<FEM::Node2D> WrappedNode2D; typedef NodeWrapper<FEM::Node3D> WrappedNode3D; typedef NodeWrapper<FEM::Node4D> WrappedNode4D; } #endif // NODEWRAPPER_H
[ "Passazhur@gmail.com@fbf05d7f-0995-0f14-e1a3-7aaf52e8406a" ]
Passazhur@gmail.com@fbf05d7f-0995-0f14-e1a3-7aaf52e8406a
676bfb3338f8e0360f36a00df66488f4457ff0fb
da3c0a0937900e28cbe40e0323192e093af592d4
/src/misc/Headers/auto_correlation.hpp
7af6ddba116b0114126a12faafd240f661dbe13a
[]
no_license
ElliotEklund/MAVARIC_v2.0
a8d4ebc5614c3e56583a7698bc7e0de37a21ac2a
25b213b3954f479fd2d2c1e82ad5a567267f6940
refs/heads/master
2023-06-28T11:00:20.550305
2021-07-22T03:12:31
2021-07-22T03:12:31
387,864,745
0
0
null
null
null
null
UTF-8
C++
false
false
2,094
hpp
#ifndef auto_correlation_hpp #define auto_correlation_hpp #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <string> #include <fstream> #include "mpi.h" #include "M_Matrix.h" #include "C_Matrix.h" #include "dM_Matrix_dQ.hpp" #include "theta_mixed.hpp" #include "theta_mixed_dQ.hpp" #include "theta_mixed_dElec.hpp" #include "Forces_MTS.hpp" #include "mvrpmd_mixed_forces.hpp" #include "ABM_MVRPMD.hpp" #include "aggregate.hpp" #include "pop_estimators.hpp" #include "trajs_io.hpp" using namespace boost::numeric::ublas; class auto_correlation{ public: auto_correlation(int my_id,int nun_procs, int root_proc); int compute(unsigned long long num_trajs_global, unsigned long long num_trajs_local, std::string input_dir,std::string output_dir, int num_samples, int num_errors); /* Mutators */ /* All variables corresponding to those in set_system arguement are set after function call. is_sys_set = true after call */ void set_system(int nuc_beadsIN, int elec_beadsIN, int num_statesIN, double massIN, double beta_nuc_beadsIN, double beta_elec_beadsIN, double alphaIN); void request_calcs(bool pac, int pac_stride, bool bp, int bp_stride, bool sp, int sp_stride, bool wp, int wp_stride); void set_time(double dtIN, double total_timeIN); private: /* Data */ int my_id, num_procs, root_proc; //mpi data double dt, total_time; int nuc_beads, elec_beads, num_states; //system information double mass, beta_nuc_beads, beta_elec_beads; //system information double alpha; //mapping variable pre-factor bool pac, bp, wp, sp; int pac_stride, bp_stride, sp_stride, wp_stride; bool is_sys_set, is_time_set, is_req_set; /* Functions*/ double compute_centroid(const vector<double> &Q); }; #endif
[ "ece52@cornell.edu" ]
ece52@cornell.edu
8e33ab7c09b9f3005652b08766f5cf8951092518
79ae8fba040157a6c31a4fc11c4b0dea8700840b
/simon.cpp
d2f6bd7647a2516cc5cfc838b6d0cd1e36aaa782
[]
no_license
sautmanurung1/Kumpulan-Program-C-
381e866704bb989a965be53b04cb8a7abd4020ee
88ccd3a1ca77ae56d90c5294272e6e94c4ca911b
refs/heads/master
2023-08-26T17:52:37.991687
2021-10-28T11:42:14
2021-10-28T11:42:14
422,181,158
1
0
null
null
null
null
UTF-8
C++
false
false
802
cpp
#include <iostream> #include <string.h> using namespace std; int main( ){ char kode,kodeDiskon,namaBuku[30]; long harga=0; cout<<"Kode Buku : ";cin>>kode; cout<<"Kode Diskon : ";cin>>kodeDiskon; if (kode == '1') { strcpy(namaBuku,"Belajarcpp.com"); if (kodeDiskon=='S' || kodeDiskon =='s'){ harga=45000; } else { harga = 50000; } } else if (kode=='2') { strcpy(namaBuku,"Belajar C++"); if (kodeDiskon=='S' || kodeDiskon=='s'){ harga=65000; } else { harga = 70000; } } else { cout<<"Salah Kode Buku"<<endl; } cout<<"----------------------"<<endl; cout<<"Judul Buku : "<<namaBuku<<endl; cout<<"Harga Buku : "<<harga<<endl; return 0; }
[ "smanurung360@gmail.com" ]
smanurung360@gmail.com
a2941face2076356fd0b2eb4512eea6423d496f8
66f66b77fe04b6ee816bb5b395ac98776da40a61
/src/gpucf/common/DataSet.h
5ba2af379670b897fbae31ac695916ad0af9918d
[]
no_license
fweig/gpucf
dfa278388043665f13cc6010754d62f0539342d1
83389c7df28d92303e21a47f73bd41bb3241390f
refs/heads/master
2020-07-08T22:10:13.960899
2019-09-24T22:39:41
2019-09-24T22:39:41
203,793,366
0
0
null
null
null
null
UTF-8
C++
false
false
1,368
h
// Copyright CERN and copyright holders of ALICE O2. This software is // distributed under the terms of the GNU General Public License v3 (GPL // Version 3), copied verbatim in the file "COPYING". // // See http://alice-o2.web.cern.ch/license for full licensing information. // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. #pragma once #include <gpucf/common/Object.h> #include <filesystem/path.h> #include <string> #include <vector> namespace gpucf { class DataSet { public: void read(const filesystem::path &); void write(const filesystem::path &) const; std::vector<Object> get() const; template<class T> void serialize(const std::vector<T> &in) { objs.clear(); objs.reserve(in.size()); for (const T &o : in) { objs.push_back(o.serialize()); } } template<class T> std::vector<T> deserialize() const { std::vector<T> out; out.reserve(objs.size()); for (const Object &o : objs) { out.emplace_back(); out.back().deserialize(o); } return out; } private: std::vector<Object> objs; }; } // vim: set ts=4 sw=4 sts=4 expandtab:
[ "felix.weiglhofer@gmail.com" ]
felix.weiglhofer@gmail.com
b3276a5bbd9f5d4e443ea719952e1824daf4a211
04854e7dc859870baa887c2a20f6bc90d741774a
/StructuredScript/StructuredScript/scanner/Wells/StringCharacterWell.h
5b8272fd86d42a29a3165d7de3b6e85c181c719b
[]
no_license
benbraide/StructuredScript
6d0445876d7b76ee8fbad4b332488de7369ec11e
fdc12fd2a9e40c3dbdca0f9024ac79b7695dbe46
refs/heads/master
2016-09-14T10:16:58.379091
2016-05-27T16:18:47
2016-05-27T16:18:47
57,159,990
1
0
null
null
null
null
UTF-8
C++
false
false
1,359
h
#pragma once #ifndef STRUCTURED_SCRIPT_STRING_CHARACTER_WELL_H #define STRUCTURED_SCRIPT_STRING_CHARACTER_WELL_H #include <list> #include "../../Interfaces/ICharacterWell.h" namespace StructuredScript{ namespace Scanner{ class StringCharacterWell : public ICharacterWell{ public: typedef std::list<unsigned int> ForkListType; explicit StringCharacterWell(const std::string &value) : value_(value){} virtual char peek() override; virtual std::string peek(unsigned int length) override; virtual std::string get() override; virtual char next() override; virtual char prev() override; virtual void step(int steps) override; virtual void stepToEnd() override; virtual bool stepTo(char target) override; virtual void collapse() override; virtual void commit() override; virtual void fork() override; virtual void revert() override; virtual void discard() override; virtual void merge() override; virtual std::string dump() override; virtual bool load() override; virtual bool empty() const override; virtual unsigned int getStartIndex() const override; virtual unsigned int getEndIndex() const override; protected: ForkListType forks_; std::string value_; unsigned int start_ = 0, end_ = 0; }; } } #endif /* !STRUCTURED_SCRIPT_STRING_CHARACTER_WELL_H */
[ "benbraide@yahoo.com" ]
benbraide@yahoo.com
15b92205c37ead34909d69c691efa390d5f604e2
093aac4ab40bcd785533b7cae21a986eaf917711
/C++/105 복사 생성자.cpp
6d9b497008239a9a6c7e59810565456fa28359a7
[]
no_license
Fox-Rain/C_Plus_Plus
42408fb9a338b198ac6f16d8be44f5a7ba8bb716
736656e82606e861b1eb5efafa3a9063faf8318b
refs/heads/main
2023-06-14T20:43:04.195482
2021-07-14T07:26:14
2021-07-14T07:26:14
376,890,743
0
0
null
null
null
null
UHC
C++
false
false
1,186
cpp
#include<iostream> #include<cassert> using namespace std; class Fraction { private: int m_numerator; int m_denominator; public: Fraction(int num = 0, int den = 1) // Fraction 생성자 :m_numerator(num), m_denominator(den) { assert(den != 0); } Fraction(const Fraction &fraction) // 복사 생성자 (매개변수로 원래 생겨있는 Fraction객체를 참조로 받음) :m_numerator(fraction.m_numerator), m_denominator(fraction.m_denominator) { cout << "Copy constructor" << endl; } friend std::ostream &operator<<(std::ostream &out, const Fraction &f) // 연산자 << 오버로딩 { cout << f.m_numerator << " / " << f.m_denominator; return out; } }; int main() { Fraction frac(3, 5); // 클래스 객체를 그냥 생성하므로 생성자가 실행됨 Fraction frac_copy(frac); // 클래스 객체를 복사하여 생성하므로 복사 생성자가 실행됨 // Fraction frac_copy=frac; <- 이런식으로 타이핑해도 복사생성자가 실행된다. (=등호로도 복사생성자가 호출됨) cout << frac << " " << frac_copy << endl; // 둘다 같은 값이 출력된다. 3/5 3/5 return 0; }
[ "noreply@github.com" ]
Fox-Rain.noreply@github.com
d4aaa45cc3ab3b04b5b075b9a1670db73f370a91
001eef3e7d1f5a240fde31ca4818524ab67288dc
/inst/include/libshogun/shogun/kernel/CombinedKernel.h
946b97511f8ca028a9a774b09cac53fae6ff9331
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
JMR-b/shikken
76ff3e30e52100df8ed019e9158057249437e717
99999cf7c90d27773ae9d7ea000cd509a7e09666
refs/heads/master
2021-01-16T19:22:11.200229
2011-09-23T04:48:07
2011-09-23T04:48:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,366
h
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 1999-2009 Soeren Sonnenburg * Written (W) 1999-2008 Gunnar Raetsch * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #ifndef _COMBINEDKERNEL_H___ #define _COMBINEDKERNEL_H___ #include <shogun/lib/List.h> #include <shogun/lib/io.h> #include <shogun/kernel/Kernel.h> #include <shogun/features/Features.h> #include <shogun/features/CombinedFeatures.h> namespace shogun { class CFeatures; class CCombinedFeatures; class CList; class CListElement; /** * @brief The Combined kernel is used to combine a number of kernels into a * single CombinedKernel object by linear combination. * * It keeps pointers to the added sub-kernels \f$k_m({\bf x}, {\bf x'})\f$ and * for each sub-kernel - a kernel specific weight \f$\beta_m\f$. * * It is especially useful to combine kernels working on different domains and * to combine kernels looking at independent features and requires * CCombinedFeatures to be used. * * It is defined as: * * \f[ * k_{combined}({\bf x}, {\bf x'}) = \sum_{m=1}^M \beta_m k_m({\bf x}, {\bf x'}) * \f] * */ class CCombinedKernel : public CKernel { public: /** constructor * * @param size cache size * @param append_subkernel_weights if subkernel weights shall be * appended */ CCombinedKernel(int32_t size=10, bool append_subkernel_weights=false); virtual ~CCombinedKernel(); /** initialize kernel * * @param lhs features of left-hand side * @param rhs features of right-hand side * @return if initializing was successful */ virtual bool init(CFeatures* lhs, CFeatures* rhs); /** clean up kernel */ virtual void cleanup(); /** return what type of kernel we are * * @return kernel type COMBINED */ virtual EKernelType get_kernel_type() { return K_COMBINED; } /** return feature type the kernel can deal with * * @return feature type UNKNOWN */ virtual EFeatureType get_feature_type() { return F_UNKNOWN; } /** return feature class the kernel can deal with * * @return feature class COMBINED */ virtual EFeatureClass get_feature_class() { return C_COMBINED; } /** return the kernel's name * * @return name Combined */ virtual const char* get_name() const { return "CombinedKernel"; } /** list kernels */ void list_kernels(); /** get first kernel * * @return first kernel */ inline CKernel* get_first_kernel() { return (CKernel*) kernel_list->get_first_element(); } /** get first kernel * * @param current * @return first kernel */ inline CKernel* get_first_kernel(CListElement*& current) { return (CKernel*) kernel_list->get_first_element(current); } /** get kernel * * @param idx index of kernel * @return kernel at index idx */ inline CKernel* get_kernel(int32_t idx) { CKernel * k = get_first_kernel(); for (int32_t i=0; i<idx; i++) { SG_UNREF(k); k = get_next_kernel(); } return k; } /** get last kernel * * @return last kernel */ inline CKernel* get_last_kernel() { return (CKernel*) kernel_list->get_last_element(); } /** get next kernel * * @return next kernel */ inline CKernel* get_next_kernel() { return (CKernel*) kernel_list->get_next_element(); } /** get next kernel multi-thread safe * * @param current * @return next kernel */ inline CKernel* get_next_kernel(CListElement*& current) { return (CKernel*) kernel_list->get_next_element(current); } /** insert kernel * * @param k kernel * @return if inserting was successful */ inline bool insert_kernel(CKernel* k) { ASSERT(k); adjust_num_lhs_rhs_initialized(k); if (!(k->has_property(KP_LINADD))) unset_property(KP_LINADD); return kernel_list->insert_element(k); } /** append kernel * * @param k kernel * @return if appending was successful */ inline bool append_kernel(CKernel* k) { ASSERT(k); adjust_num_lhs_rhs_initialized(k); if (!(k->has_property(KP_LINADD))) unset_property(KP_LINADD); return kernel_list->append_element(k); } /** delete kernel * * @return if deleting was successful */ inline bool delete_kernel() { CKernel* k=(CKernel*) kernel_list->delete_element(); SG_UNREF(k); if (!k) { num_lhs=0; num_rhs=0; } return (k!=NULL); } /** check if subkernel weights are appended * * @return if subkernel weigths are appended */ inline bool get_append_subkernel_weights() { return append_subkernel_weights; } /** get number of subkernels * * @return number of subkernels */ inline int32_t get_num_subkernels() { if (append_subkernel_weights) { int32_t num_subkernels = 0 ; CListElement* current = NULL ; CKernel * k = get_first_kernel(current) ; while(k) { num_subkernels += k->get_num_subkernels() ; SG_UNREF(k); k = get_next_kernel(current) ; } return num_subkernels ; } else return kernel_list->get_num_elements(); } /** test whether features have been assigned to lhs and rhs * * @return true if features are assigned */ virtual inline bool has_features() { return initialized; } /** remove lhs from kernel */ virtual void remove_lhs(); /** remove rhs from kernel */ virtual void remove_rhs(); /** remove lhs and rhs from kernel */ virtual void remove_lhs_and_rhs(); /** initialize optimization * * @param count count * @param IDX index * @param weights weights * @return if initializing was successful */ virtual bool init_optimization( int32_t count, int32_t *IDX, float64_t * weights); /** delete optimization * * @return if deleting was successful */ virtual bool delete_optimization(); /** compute optimized * * @param idx index to compute * @return optimized value at given index */ virtual float64_t compute_optimized(int32_t idx); /** computes output for a batch of examples in an optimized fashion (favorable if kernel supports it, * i.e. has KP_BATCHEVALUATION. * to the outputvector target (of length num_vec elements) the output for the examples enumerated * in vec_idx are added. therefore make sure that it is initialized with ZERO. the following num_suppvec, * IDX, alphas arguments are the number of support vectors, their indices and weights */ virtual void compute_batch( int32_t num_vec, int32_t* vec_idx, float64_t* target, int32_t num_suppvec, int32_t* IDX, float64_t* alphas, float64_t factor=1.0); /** helper for compute optimized kernel * * @param p thread parameter */ static void* compute_optimized_kernel_helper(void* p); /** helper for compute kernel * * @param p thread parameter */ static void* compute_kernel_helper(void* p); /** emulates batch computation, via linadd optimization w^t x or even down to sum_i alpha_i K(x_i,x) * * @param k kernel * @param num_vec number of vectors * @param vec_idx vector index * @param target target * @param num_suppvec number of support vectors * @param IDX IDX * @param weights weights */ void emulate_compute_batch( CKernel* k, int32_t num_vec, int32_t* vec_idx, float64_t* target, int32_t num_suppvec, int32_t* IDX, float64_t* weights); /** add to normal vector * * @param idx where to add * @param weight what to add */ virtual void add_to_normal(int32_t idx, float64_t weight); /** clear normal vector */ virtual void clear_normal(); /** compute by subkernel * * @param idx index * @param subkernel_contrib subkernel contribution */ virtual void compute_by_subkernel( int32_t idx, float64_t * subkernel_contrib); /** get subkernel weights * * @param num_weights where number of weights is stored * @return subkernel weights */ virtual const float64_t* get_subkernel_weights(int32_t& num_weights); /** get subkernel weights (swig compatible) * * @param weights subkernel weights * @param num_weights number of weights */ virtual void get_subkernel_weights(float64_t** weights, int32_t* num_weights); /** set subkernel weights * * @param weights new subkernel weights * @param num_weights number of subkernel weights */ virtual void set_subkernel_weights( float64_t* weights, int32_t num_weights); /** set optimization type * * @param t optimization type */ virtual void set_optimization_type(EOptimizationType t); /** precompute all sub-kernels */ bool precompute_subkernels(); protected: /** compute kernel function * * @param x x * @param y y * @return computed kernel function */ virtual float64_t compute(int32_t x, int32_t y); /** adjust the variables num_lhs, num_rhs and initialized * based on the kernel to be appended/inserted * * @param k kernel */ inline void adjust_num_lhs_rhs_initialized(CKernel* k) { ASSERT(k); if (k->get_num_vec_lhs()) { if (num_lhs) ASSERT(num_lhs==k->get_num_vec_lhs()); num_lhs=k->get_num_vec_lhs(); if (!get_num_subkernels()) { initialized=true; #ifdef USE_SVMLIGHT cache_reset(); #endif //USE_SVMLIGHT } } else initialized=false; if (k->get_num_vec_rhs()) { if (num_rhs) ASSERT(num_rhs==k->get_num_vec_rhs()); num_rhs=k->get_num_vec_rhs(); if (!get_num_subkernels()) { initialized=true; #ifdef USE_SVMLIGHT cache_reset(); #endif //USE_SVMLIGHT } } else initialized=false; } private: void init(); protected: /** list of kernels */ CList* kernel_list; /** support vector count */ int32_t sv_count; /** support vector index */ int32_t* sv_idx; /** support vector weights */ float64_t* sv_weight; /** subkernel weights buffers */ float64_t* subkernel_weights_buffer; /** if subkernel weights are appended */ bool append_subkernel_weights; /** whether kernel is ready to be used */ bool initialized; }; } #endif /* _COMBINEDKERNEL_H__ */
[ "slianoglou@gmail.com" ]
slianoglou@gmail.com
325b187a6432e39eccc54fa087eea4f9f7dbc385
2a92aec751149ac301bf0d13fa14677841dd24fb
/src/Utility.cpp
978893dd556037fd9d572a378f4bdca2a5068cc5
[]
no_license
mhayashi/worldclock
469a9e26113b0870b99b178db50fe2e4a6f913a5
6d7e49df874e24058f1d7065b206d1db13ea22dd
refs/heads/master
2021-01-21T12:40:54.064182
2010-10-29T09:39:52
2010-10-29T09:39:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,607
cpp
#include <iostream> #include <curl/curl.h> #import <GLUT/GLUT.h> #include "Utility.h" using std::cout; using std::endl; char errorBuffer[CURL_ERROR_SIZE]; string curlBuffer = ""; // This is the writer call back function used by curl static int writer(char *data, size_t size, size_t nmemb, string *buffer) { // What we will return int result = 0; // Is there anything in the buffer? if (buffer != NULL) { // Append the data to the buffer buffer->append(data, size * nmemb); // How much did we write? result = size * nmemb; } return result; } bool curl(string url) { cout << "Retrieving " << url << endl; curlBuffer = ""; // Our curl objects CURL *curl; CURLcode result; // Create our curl handle curl = curl_easy_init(); if (curl) { // Now set up all of the curl options curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HEADER, 0); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &curlBuffer); // Attempt to retrieve the remote page result = curl_easy_perform(curl); // Always cleanup curl_easy_cleanup(curl); // Did we succeed? if (result == CURLE_OK) { cout << curlBuffer << endl; return true; } else { cout << "Error: [" << result << "] - " << errorBuffer; return false; } } } double radian(double angle) { return angle / 180.0 * M_PI; } void drawCircle(float radius, int slice, int type = 0) { static const float PI_OVER_180 = 0.0174532925; static float angle, step, startAngle; step = 360.0 / slice; switch(type) { case 0: glBegin(GL_TRIANGLE_FAN); break; case 1: glBegin(GL_LINES); break; case 2: glBegin(GL_LINE_STRIP); break; } for (angle = 0; angle <= 360.0; angle += step) { startAngle = angle * PI_OVER_180; glVertex2f(radius * cos(startAngle), radius * sin(startAngle)); } glEnd(); } string replace_all(const string &source, const string &pattern, const string &placement) { string result; string::size_type pos_before = 0; string::size_type pos = 0; string::size_type len = pattern.size(); while ((pos = source.find(pattern, pos)) != string::npos) { result.append(source, pos_before, pos - pos_before); result.append(placement); pos += len; pos_before = pos; } result.append(source, pos_before, source.size() - pos_before); return result; }
[ "hayashi.masahiro@gmail.com" ]
hayashi.masahiro@gmail.com
2a47192e6f040c928ced2b8c6ce56bd7a4e9134c
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-chime/source/model/UpdateAccountSettingsRequest.cpp
efd9825624b7ef0b24bc83007a4f312df80f050d
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
1,196
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/chime/model/UpdateAccountSettingsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Chime::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateAccountSettingsRequest::UpdateAccountSettingsRequest() : m_accountIdHasBeenSet(false), m_accountSettingsHasBeenSet(false) { } Aws::String UpdateAccountSettingsRequest::SerializePayload() const { JsonValue payload; if(m_accountSettingsHasBeenSet) { payload.WithObject("AccountSettings", m_accountSettings.Jsonize()); } return payload.View().WriteReadable(); }
[ "magmarco@amazon.com" ]
magmarco@amazon.com
bb66ef20efd4494779a6ea8579a829fa5e344d7f
bf0a83ddda776ad9bb7e7dd59272366d1498632d
/week1/build_the_sum/build_the_sum.cpp
3d8bb42586ed22ab22b313f6b0e8a2d4f5c88a71
[]
no_license
marbaga/algolab
e4f41c95ec3665e18d0a7acfde74cf454d4d8bbf
3a683919969a27f6daa0a7b76777e6f518370624
refs/heads/master
2022-05-01T12:56:33.494577
2020-02-16T23:19:24
2020-02-16T23:19:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
434
cpp
//Implementation by marcobaga //This solution achieves 100 points #include <iostream> int main(){ std::ios_base::sync_with_stdio(false); int t; std::cin >> t; for(int i=0; i<t; ++i){ int n = 0; std::cin >> n; int sum=0; for(int i=0; i<n; ++i){ int x; std::cin>>x; sum += x; } std::cout << sum << std::endl; } return 0; }
[ "bagatella.marco@libero.it" ]
bagatella.marco@libero.it
4b7797c9401d142f38311742f13ff8f782f8ce9f
f540f6e63fd9efa69a38d88ab1f435f589d15d3b
/inexlib/ourex/SOPHYA/include/randr48.h
1166ef1426d1001607e0962ed2318d96811764ea
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
gbarrand/ioda
a43aab4548d36074dc49c3924b6826aff8446ad8
bf569f61703cf25e60145d0a28b947937cf40fe4
refs/heads/master
2021-07-09T02:51:58.267796
2018-12-20T13:56:04
2018-12-20T13:56:04
135,979,262
0
0
null
null
null
null
UTF-8
C++
false
false
3,067
h
#ifndef RANDR48_H_SEEN #define RANDR48_H_SEEN // Classes DR48RandGen // Generateur aleatoire utilisant l'aleatoire drand48() // // R. Ansari (C) UPS+LAL IN2P3/CNRS 2009 // C. Magneville (C) DAPNIA/SPP CEA 2009 #include "machdefs.h" #include "objfio.h" #include "ndatablock.h" #include "randinterf.h" namespace SOPHYA { // Implementation de RandomGeneratorInterface avec drand48() class DR48RandGen : public RandomGeneratorInterface { public: DR48RandGen(); DR48RandGen(long int seed); virtual ~DR48RandGen(); virtual void SetSeed(long int seed); virtual void SetSeed(uint_2 seed[3]); virtual void GetSeed(uint_2 seed[3]); virtual void AutoInit(int lp=0); virtual void ShowRandom(); friend class ObjFileIO<DR48RandGen> ; protected: virtual r_8 Next(); }; //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Version thread-safe de DR48RandGen class ThSDR48RandGen : public DR48RandGen { public: ThSDR48RandGen(size_t n=1024,bool tsafe=true); ThSDR48RandGen(ThSDR48RandGen const & rg); virtual ~ThSDR48RandGen(); void SetBuffSize(size_t n); virtual void SetSeed(long int seed); virtual void SetSeed(uint_2 seed[3]); virtual void GetSeed(uint_2 seed[3]); virtual void AutoInit(int lp=0); virtual void ShowRandom(); friend class ObjFileIO<ThSDR48RandGen> ; protected: // ---- protected data members NDataBlock<r_8> rseq_; size_t idx_; bool fg_nothrsafe; // if true --> NOT thread-safe // ---- protected methods void GenSeq(); virtual r_8 Next(); //! For PPF handler use inline void GetSeed_P(uint_2 seed[3]) { return DR48RandGen::GetSeed(seed); } //! For PPF handler use inline void SetSeed_P(uint_2 seed[3]) { return DR48RandGen::SetSeed(seed); } }; // Classe pour la gestion de persistance PPF : ObjFileIO<ThSDR48RandGen> /*! Writes the random generator object state in the POutPersist stream \b os */ inline POutPersist& operator << (POutPersist& os, ThSDR48RandGen & obj) { ObjFileIO<ThSDR48RandGen> fio(&obj); fio.Write(os); return(os); } /*! Reads the random generator object state from the PInPersist stream \b is */ inline PInPersist& operator >> (PInPersist& is, ThSDR48RandGen & obj) { ObjFileIO<ThSDR48RandGen> fio(&obj); is.SkipToNextObject(); fio.Read(is); return(is); } // Classe pour la gestion de persistance PPF : ObjFileIO<DR48RandGen> /*! Writes the random generator object state in the POutPersist stream \b os */ inline POutPersist& operator << (POutPersist& os, DR48RandGen & obj) { ObjFileIO<DR48RandGen> fio(&obj); fio.Write(os); return(os); } /*! Reads the random generator object state from the PInPersist stream \b is */ inline PInPersist& operator >> (PInPersist& is, DR48RandGen & obj) { ObjFileIO<DR48RandGen> fio(&obj); is.SkipToNextObject(); fio.Read(is); return(is); } } /* namespace SOPHYA */ #endif
[ "guy.barrand@gmail.com" ]
guy.barrand@gmail.com
462ff4a493ab9fcc4a3dedd217122ba025fe8b2c
a40855e50548436cff096c10ab963bcadce7125a
/CSCE4550p1(BellLapudula)/SecureSystem.cpp
b7952af00a143e87850d0273532fd0f8c3c79a35
[]
no_license
travisleeallan/Cpp-Projects
4f994a06b72c9bf955a5f7c2f726f412bfb75a40
82a841093cc5ab32e0bc31e819e138db5f25c45a
refs/heads/master
2021-01-24T07:34:32.745146
2017-06-04T23:13:41
2017-06-04T23:13:41
93,347,056
0
0
null
null
null
null
UTF-8
C++
false
false
4,794
cpp
/* *Travis Allan *11/10/2016 *CSCE 4550.001 *Project 1 *Description: This project is an implementation of the Bell-LaPadula security model. */ #include <iostream> #include <fstream> #include <cstring> #include <string> //#include "Subject.h" //#include "Object.h" #include "RefMon.h" using namespace std; int main(int argc, char* argv[]) { //declarations char command[10]; char sName[20]; char oName[20]; char fileName[20]; string line; int inputVal; ReferenceMonitor RefMon; //initiallization //cout << argc << endl; strcpy(fileName, argv[argc-1]); //cout << fileName << endl; RefMon.setCount(); RefMon.createSubject("adam", 1); RefMon.createSubject("james", 2); RefMon.createSubject("tim", 3); RefMon.createSubject("sara", 1); RefMon.createSubject("kristy", 2); RefMon.createSubject("liz", 3); RefMon.createObject("aobj", 1); RefMon.createObject("jobj", 2); RefMon.createObject("tobj", 3); RefMon.createObject("sobj", 1); RefMon.createObject("kobj", 2); RefMon.createObject("lobj", 3); //input ifstream file (fileName); if (file.is_open()) { while (getline(file, line)) { //cout << line << endl;; //test //line parsing using strtok char * cline = new char[line.size() + 1]; copy(line.begin(), line.end(), cline); cline[line.size()] = '\0'; char * cline2 = new char[line.size() + 1]; strcpy(cline2, cline); //this is used to check the number of params in line for error handling char * lengthCheck = strtok(cline2, " "); //cout << lengthCheck << endl; int len = 0; //length of line counter while (lengthCheck != NULL) { len++; //cout << lengthCheck << endl; //cout << "len = " << len << endl; lengthCheck = strtok(NULL, " "); } delete [] cline2; //line parsing strcpy(command, strtok (cline, " ")); if ((strcmp(command, "READ") == 0) || (strcmp(command, "read") == 0)) { int returnVal; if (len == 3) { strcpy(sName, strtok (NULL, " ")); strcpy(oName, strtok (NULL, " ")); //test //cout << sName << endl; //cout << oName << endl; //call read function returnVal = RefMon.executeRead(sName, oName); if (returnVal == 0) cout << "Bad Instruction : " << line << endl; else if (returnVal == 1){ cout << line << endl; //print the state RefMon.printState(); } else cout << line << endl; } else { cout << "Bad Instruction : " << line << endl; //RefMon.printState(); } } else if ((strcmp(command, "WRITE") == 0) || (strcmp(command, "write") == 0)) { int returnVal; if (len==4) { strcpy(sName, strtok (NULL, " ")); strcpy(oName, strtok (NULL, " ")); char* temp = (strtok (NULL, " ")); //cout << temp << endl; //test inputVal = atoi (temp); //test //cout << sName << endl; //cout << oName << endl; //cout << inputVal << endl; //call write function returnVal = RefMon.executeWrite(sName, oName, inputVal); if (returnVal == 0) cout << "Bad Instruction : " << line << endl; else if (returnVal == 1){ cout << line << endl; //print the state RefMon.printState(); } else cout << line << endl; } else { cout << "Bad Instruction : " << line << endl; //RefMon.printState(); } } else { cout << "Bad Instruction : " << line << endl; //RefMon.printState(); } //method calls delete[] cline; } file.close(); } else cout << "File not opened" << endl; return 0; }
[ "travisallan@Traviss-Mac-mini.local" ]
travisallan@Traviss-Mac-mini.local
d10b17551936846406543e9561eb7b6cbcee56d9
2bc835b044f306fca1affd1c61b8650b06751756
/outlookexpress/mailnews/shell/multiusr.cpp
e217af1413e1cf7ec0b673a4b9201939c11d0852
[]
no_license
KernelPanic-OpenSource/Win2K3_NT_inetcore
bbb2354d95a51a75ce2dfd67b18cfb6b21c94939
75f614d008bfce1ea71e4a727205f46b0de8e1c3
refs/heads/master
2023-04-04T02:55:25.139618
2021-04-14T05:25:01
2021-04-14T05:25:01
357,780,123
1
0
null
null
null
null
UTF-8
C++
false
false
27,898
cpp
/******************************************************* MultiUsr.cpp Code for handling multiple user functionality in Outlook Express. Initially by Christopher Evans (cevans) 4/28/98 ********************************************************/ #include "pch.hxx" #include "multiusr.h" #include "demand.h" #include "instance.h" #include "acctutil.h" #include "options.h" #include "conman.h" #include <..\help\mailnews.h> #include "msident.h" #include "menures.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #ifndef THOR_SETUP #include <shlwapi.h> #define strstr StrStr #define RegDeleteKeyRecursive SHDeleteKey #endif // THOR_SETUP TCHAR g_szRegRoot[MAX_PATH] = ""; static TCHAR g_szCharsetRegRoot[MAX_PATH] = ""; static TCHAR g_szIdentityName[CCH_USERNAME_MAX_LENGTH+1]; static BOOL g_fUsingDefaultId = FALSE; static IUserIdentityManager *g_pIdMan = NULL; static HKEY g_hkeyIdentity = HKEY_CURRENT_USER; static BOOL g_fIdentitiesDisabled = FALSE; extern DWORD g_dwIcwFlags; GUID *PGUIDCurrentOrDefault(void) { return (g_fUsingDefaultId ? (GUID *)&UID_GIBC_DEFAULT_USER : (GUID *)&UID_GIBC_CURRENT_USER); } static void SafeIdentityRelease() { if (g_pIdMan && 0 == (g_pIdMan)->Release()) { g_pIdMan = NULL; RegCloseKey(g_hkeyIdentity); g_hkeyIdentity = HKEY_CURRENT_USER; } } /* MU_RegisterIdentityNotifier Handles the dirty work of registering an identity notifier. Caller needs to hold on to dwCookie and use it to unadvise. */ HRESULT MU_RegisterIdentityNotifier(IUnknown *punk, DWORD *pdwCookie) { IConnectionPoint *pConnectPt = NULL; HRESULT hr = S_OK; Assert(pdwCookie); Assert(punk); Assert(g_pIdMan); if (SUCCEEDED(hr = g_pIdMan->QueryInterface(IID_IConnectionPoint, (void **)&pConnectPt))) { Assert(pConnectPt); SideAssert(SUCCEEDED(hr = pConnectPt->Advise(punk, pdwCookie))); SafeRelease(pConnectPt); g_pIdMan->AddRef(); } return hr; } /* MU_RegisterIdentityNotifier Handles the dirty work of unregistering an identity notifier. dwCookie is the cookie returned from MU_RegisterIdentityNotifier. */ HRESULT MU_UnregisterIdentityNotifier(DWORD dwCookie) { IConnectionPoint *pConnectPt = NULL; HRESULT hr = S_OK; Assert(g_pIdMan); if (SUCCEEDED(hr = g_pIdMan->QueryInterface(IID_IConnectionPoint, (void **)&pConnectPt))) { Assert(pConnectPt); SideAssert(SUCCEEDED(hr = pConnectPt->Unadvise(dwCookie))); SafeRelease(pConnectPt); SafeIdentityRelease(); } return hr; } /* MU_CheckForIdentitySwitch Check to see if the switch is actually a logout, or just a switch. Then tell the COutlookExpress object so that it can restart if necessary */ BOOL MU_CheckForIdentityLogout() { HRESULT hr; IUserIdentity *pIdentity = NULL; BOOL fIsLogout = TRUE; GUID uidCookie; Assert(g_pIdMan); if (SUCCEEDED(hr = g_pIdMan->GetIdentityByCookie((GUID *)&UID_GIBC_INCOMING_USER, &pIdentity))) { if (pIdentity) { pIdentity->GetCookie(&uidCookie); fIsLogout = (uidCookie == GUID_NULL); pIdentity->Release(); } } return fIsLogout; } /* MU_ShowErrorMessage Simple wrapper around resource string table based call to MessageBox */ void MU_ShowErrorMessage(HINSTANCE hInst, HWND hwnd, UINT iMsgID, UINT iTitleID) { char szMsg[255], szTitle[63]; LoadString(g_hLocRes, iMsgID, szMsg, sizeof(szMsg)); LoadString(g_hLocRes, iTitleID, szTitle, sizeof(szTitle)); MessageBox(hwnd, szMsg, szTitle, MB_OK); } // -------------------------------------------------------------------------------- // Functions to convert GUIDs to ascii strings // -------------------------------------------------------------------------------- static int AStringFromGUID(GUID *puid, TCHAR *lpsz, int cch) { WCHAR wsz[255]; int i; i = StringFromGUID2(*puid, wsz, 255); if (WideCharToMultiByte(CP_ACP, 0, wsz, -1, lpsz, cch, NULL, NULL) == 0) return 0; return (lstrlen(lpsz) + 1); } static HRESULT GUIDFromAString(TCHAR *lpsz, GUID *puid) { WCHAR wsz[255]; HRESULT hr; if (MultiByteToWideChar(CP_ACP, 0, lpsz, -1, wsz, 255) == 0) return GetLastError(); hr = CLSIDFromString(wsz, puid); return hr; } /* MU_GetCurrentUserInfo return the current user's id (guid) and username as strings */ HRESULT MU_GetCurrentUserInfo(LPSTR pszId, UINT cchId, LPSTR pszName, UINT cchName) { HRESULT hr = E_UNEXPECTED; IUserIdentity *pIdentity = NULL; GUID uidUserId; WCHAR szwName[CCH_USERNAME_MAX_LENGTH+1]; Assert(g_pIdMan); // we have to have the IUserIdentityManager if (!g_pIdMan) goto exit; // Get the current user if (FAILED(hr = g_pIdMan->GetIdentityByCookie(PGUIDCurrentOrDefault(), &pIdentity))) goto exit; // if the caller wants the id if (pszId) { // get the cookie (id) as a guid if (FAILED(hr = pIdentity->GetCookie(&uidUserId))) goto exit; // turn it into a string if (0 == AStringFromGUID(&uidUserId, pszId, cchId)) hr = E_OUTOFMEMORY; else hr = S_OK; } // if the caller wants the user's name if (pszName) { // get the name as a wide string if (FAILED(hr = pIdentity->GetName(szwName, cchName))) goto exit; // convert it to an ascii string if (WideCharToMultiByte(CP_ACP, 0, szwName, -1, pszName, cchName, NULL, NULL) == 0) hr = GetLastError(); } exit: // clean up SafeRelease(pIdentity); return hr; } /* MU_GetCurrentUserHKey Return the current user's HKEY. If no one has logged on yet (this happens when coming in from SMAPI) then do the login first. If the user cancels the login, just return the hkey for the default user. Caller should not close this key. It is a common key. If it is going to be passed out to another library or something, caller should call MU_OpenCurrentUserHkey. */ HKEY MU_GetCurrentUserHKey() { IUserIdentity *pIdentity = NULL; HRESULT hr; HKEY hkey; // g_hkeyIdentity is initialized to HKEY_CURRENT_USER if (g_hkeyIdentity == HKEY_CURRENT_USER) { // we haven't logged in yet. Lets try now if (!MU_Login(GetDesktopWindow(), FALSE, "")) { Assert(g_pIdMan); if (NULL == g_pIdMan) goto exit; // if they cancelled or whatever, try to get the // default user if (FAILED(hr = g_pIdMan->GetIdentityByCookie((GUID *)&UID_GIBC_DEFAULT_USER, &pIdentity))) goto exit; } else { // login succeeded, get the current identity Assert(g_pIdMan); if (NULL == g_pIdMan) goto exit; if (FAILED(hr = g_pIdMan->GetIdentityByCookie(PGUIDCurrentOrDefault(), &pIdentity))) goto exit; } if (g_hkeyIdentity != HKEY_CURRENT_USER) RegCloseKey(g_hkeyIdentity); // open a new all access reg key. Caller must close it if (pIdentity && SUCCEEDED(hr = pIdentity->OpenIdentityRegKey(KEY_ALL_ACCESS, &hkey))) g_hkeyIdentity = hkey; else g_hkeyIdentity = HKEY_CURRENT_USER; } exit: // Clean up SafeRelease(pIdentity); return g_hkeyIdentity; } /* MU_OpenCurrentUserHkey Open a new reg key for the current user. */ HRESULT MU_OpenCurrentUserHkey(HKEY *pHkey) { HRESULT hr = E_UNEXPECTED; IUserIdentity *pIdentity = NULL; GUID uidUserId; Assert(g_pIdMan); // we have to have the IUserIdentityManager if (!g_pIdMan) goto exit; // Get the current identity. If we can't get it, bail. if (FAILED(hr = g_pIdMan->GetIdentityByCookie(PGUIDCurrentOrDefault(), &pIdentity))) goto exit; // If passed in an hkey pointer, open a new all access key if (pHkey) hr = pIdentity->OpenIdentityRegKey(KEY_ALL_ACCESS, pHkey); exit: // Clean up SafeRelease(pIdentity); return hr; } /* MU_GetCurrentUserDirectoryRoot Return the path to the top of the current user's root directory. This is the directory where the mail store should be located. It is in a subfolder the App Data folder. lpszUserRoot is a pointer to a character buffer that is cch chars in size. */ HRESULT MU_GetCurrentUserDirectoryRoot(TCHAR *lpszUserRoot, int cch) { HRESULT hr = E_FAIL; IUserIdentity *pIdentity = NULL; Assert(g_pIdMan); Assert(lpszUserRoot != NULL); Assert(cch >= MAX_PATH); if (g_pIdMan == NULL) goto exit; if (FAILED(hr = g_pIdMan->GetIdentityByCookie(PGUIDCurrentOrDefault(), &pIdentity))) goto exit; hr = MU_GetIdentityDirectoryRoot(pIdentity, lpszUserRoot, cch); exit: SafeRelease(pIdentity); return hr; } HRESULT MU_GetIdentityDirectoryRoot(IUserIdentity *pIdentity, LPSTR lpszUserRoot, int cch) { HRESULT hr; TCHAR szSubDir[MAX_PATH], *psz; WCHAR szwUserRoot[MAX_PATH]; int cb; Assert(pIdentity); Assert(lpszUserRoot != NULL); Assert(cch >= MAX_PATH); hr = pIdentity->GetIdentityFolder(GIF_NON_ROAMING_FOLDER, szwUserRoot, MAX_PATH); if (FAILED(hr)) return(hr); if (WideCharToMultiByte(CP_ACP, 0, szwUserRoot, -1, lpszUserRoot, cch, NULL, NULL) == 0) return(E_FAIL); AthLoadString(idsMicrosoft, szSubDir, ARRAYSIZE(szSubDir)); psz = PathAddBackslash(szSubDir); AthLoadString(idsAthena, psz, ARRAYSIZE(szSubDir)-(DWORD)(psz-szSubDir)); cb = lstrlen(lpszUserRoot) + lstrlen(szSubDir) + 3; if (cb < cch) { psz = PathAddBackslash(lpszUserRoot); if (psz) { StrCpyN(psz, szSubDir, cch - (DWORD)(psz-lpszUserRoot)); psz = PathAddBackslash(lpszUserRoot); } hr = S_OK; } return(hr); } DWORD MU_CountUsers() { IEnumUserIdentity *pEnum = NULL; HRESULT hr; ULONG cUsers = 0; Assert(g_pIdMan); if (SUCCEEDED(hr = g_pIdMan->EnumIdentities(&pEnum)) && pEnum) { pEnum->GetCount(&cUsers); SafeRelease(pEnum); } return cUsers; } /* MU_Login Wrapper routine for logging in to OE. Asks the user to choose a username and, if necessary, enter the password for that user. The user can also create an account at this point. lpszUsername should contain the name of the person who should be the default selection in the list. If the name is empty ("") then it will look up the default from the registry. Returns the username that was selected in lpszUsername. Returns true if that username is valid. */ BOOL MU_Login(HWND hwnd, BOOL fForceUI, char *lpszUsername) { HRESULT hr = S_OK; IUserIdentity *pIdentity = NULL; if (g_fUsingDefaultId) goto exit; if (NULL == g_pIdMan) { hr = MU_Init(FALSE); if (FAILED(hr)) goto exit; } #pragma prefast(suppress:11, "noise") g_pIdMan->AddRef(); #pragma prefast(suppress:11, "noise") hr = g_pIdMan->Logon(hwnd, (fForceUI ? UIL_FORCE_UI : 0), &pIdentity); if (SUCCEEDED(hr)) { g_fIdentitiesDisabled = (hr == S_IDENTITIES_DISABLED); if (!fForceUI) { if (g_hkeyIdentity != HKEY_CURRENT_USER) RegCloseKey(g_hkeyIdentity); hr = pIdentity->OpenIdentityRegKey(KEY_ALL_ACCESS,&g_hkeyIdentity); } SafeRelease(pIdentity); } SafeIdentityRelease(); exit: return SUCCEEDED(hr); } BOOL MU_Logoff(HWND hwnd) { HRESULT hr=E_FAIL; Assert(g_pIdMan); if (g_pIdMan) hr = g_pIdMan->Logoff(hwnd); return SUCCEEDED(hr); } /* MU_MigrateFirstUserSettings This should only be called once, when there are no users configured yet. */ #define MAXDATA_LENGTH 16L*1024L void MU_MigrateFirstUserSettings(void) { /* OEUSERINFO vCurrentUser; TCHAR szLM[255]; HKEY hDestinationKey = NULL; HKEY hSourceKey = NULL; FILETIME ftCU = {0,1}, ftLM = {0,0}; //default CU to just later than LM DWORD dwType, dwSize, dwStatus; if (MU_GetCurrentUserInfo(&vCurrentUser)) { TCHAR szRegPath[MAX_PATH], szAcctPath[MAX_PATH]; Assert(vCurrentUser.idUserID != -1); MU_GetRegRootForUserID(vCurrentUser.idUserID, szRegPath); Assert(*szRegPath); MU_GetAccountRegRootForUserID(vCurrentUser.idUserID, szAcctPath); Assert(*szAcctPath); hDestinationKey = NULL; if (RegCreateKey(HKEY_CURRENT_USER, szAcctPath, &hDestinationKey) == ERROR_SUCCESS) { if (RegOpenKey(HKEY_CURRENT_USER, c_szInetAcctMgrRegKey, &hSourceKey) == ERROR_SUCCESS) { CopyRegistry(hSourceKey, hDestinationKey); RegCloseKey(hSourceKey); } RegCloseKey(hDestinationKey); } if (RegCreateKey(HKEY_CURRENT_USER, szRegPath, &hDestinationKey) == ERROR_SUCCESS) { if (RegOpenKey(HKEY_CURRENT_USER, c_szRegRoot, &hSourceKey) == ERROR_SUCCESS) { DWORD EnumIndex; DWORD cbValueName; DWORD cbValueData; DWORD Type; CHAR ValueNameBuffer[MAXKEYNAME]; BYTE ValueDataBuffer[MAXDATA_LENGTH]; // // Copy all of the value names and their data. // EnumIndex = 0; while (TRUE) { cbValueName = sizeof(ValueNameBuffer); cbValueData = MAXDATA_LENGTH; if (RegEnumValue(hSourceKey, EnumIndex++, ValueNameBuffer, &cbValueName, NULL, &Type, ValueDataBuffer, &cbValueData) != ERROR_SUCCESS) break; RegSetValueEx(hDestinationKey, ValueNameBuffer, 0, Type, ValueDataBuffer, cbValueData); } RegSetValueEx(hDestinationKey, c_szUserID, 0, REG_DWORD, (BYTE *)&vCurrentUser.idUserID, sizeof(DWORD)); // // Copy all of the subkeys and recurse into them. // EnumIndex = 0; while (TRUE) { HKEY hSourceSubKey, hDestinationSubKey; if (RegEnumKey(hSourceKey, EnumIndex++, ValueNameBuffer, MAXKEYNAME) != ERROR_SUCCESS) break; // don't recursively copy the Profiles key into the profiles key. if (lstrcmpi(ValueNameBuffer, "Profiles") != 0) { if (RegOpenKey(hSourceKey, ValueNameBuffer, &hSourceSubKey) == ERROR_SUCCESS) { if (RegCreateKey(hDestinationKey, ValueNameBuffer, &hDestinationSubKey) == ERROR_SUCCESS) { CopyRegistry(hSourceSubKey, hDestinationSubKey); RegCloseKey(hDestinationSubKey); } RegCloseKey(hSourceSubKey); } } } RegCloseKey(hSourceKey); } RegCloseKey(hDestinationKey); } } */ } /* MU_ShutdownCurrentUser Do everything necessary to get the app to the point where calling CoDecrementInit will tear everything else down. */ BOOL MU_ShutdownCurrentUser(void) { HWND hWnd, hNextWnd = NULL; BOOL bResult = true; LRESULT lResult; DWORD dwProcessId, dwWndProcessId; HINITREF hInitRef; /* g_pInstance->SetSwitchingUsers(true); dwProcessId = GetCurrentProcessId(); g_pInstance->CoIncrementInit(0, "", &hInitRef); hWnd = GetTopWindow(NULL); if (g_pConMan->IsConnected()) { if (IDNO == AthMessageBoxW(hWnd, MAKEINTRESOURCEW(idsSwitchUser),MAKEINTRESOURCEW(idsMaintainConnection), NULL, MB_ICONEXCLAMATION | MB_YESNO | MB_DEFBUTTON1 | MB_APPLMODAL)) g_pConMan->Disconnect(hWnd, TRUE, FALSE, FALSE ); } while (hWnd) { hNextWnd = GetNextWindow(hWnd, GW_HWNDNEXT); GetWindowThreadProcessId(hWnd,&dwWndProcessId); if (dwProcessId == dwWndProcessId && IsWindowVisible(hWnd)) { TCHAR szWndClassName[255]; GetClassName( hWnd, szWndClassName, sizeof(szWndClassName)); if (lstrcmp(szWndClassName, g_szDBNotifyWndProc) != 0 && lstrcmp(szWndClassName, g_szDBListenWndProc) != 0) { lResult = SendMessage(hWnd, WM_CLOSE, 0, 0); // if the window is still there, something is wrong if(lResult != ERROR_SUCCESS || GetTopWindow(NULL) == hWnd) { Assert(GetTopWindow(NULL) != hWnd); return false; } } } hWnd = hNextWnd; } g_pInstance->CoDecrementInit(&hInitRef); */ return bResult; } /* _GetRegRootForUserID HACK ALERT The proper way to store registry things with identities is to use the HKEY that is returned from IUserIdentity::OpenIdentityRegKey. This is here only because some old interfaces assume HKEY_CURRENT_USER. Those that do, need to be fixed. In the meantime, we have this */ HRESULT _GetRegRootForUserID(GUID *puidUserId, LPSTR pszPath, DWORD cch) { HRESULT hr = S_OK; IUserIdentity *pIdentity = NULL; TCHAR szPath[MAX_PATH]; HKEY hkey; TCHAR szUid[255]; GUID uidIdentityId; Assert(pszPath); Assert(g_pIdMan); Assert(puidUserId); if (g_pIdMan == NULL) { hr = E_FAIL; goto exit; } if (FAILED(hr = g_pIdMan->GetIdentityByCookie(puidUserId, &pIdentity))) goto exit; if (FAILED(hr = pIdentity->GetCookie(&uidIdentityId))) goto exit; AStringFromGUID(&uidIdentityId, szUid, 255); wnsprintf(pszPath, cch, "%s\\%s\\%s", "Identities", szUid, c_szRegRoot); exit: SafeRelease(pIdentity); return hr; } LPCTSTR MU_GetRegRoot() { if (*g_szRegRoot) return g_szRegRoot; if (FAILED(_GetRegRootForUserID(PGUIDCurrentOrDefault(), g_szRegRoot, ARRAYSIZE(g_szRegRoot)))) _GetRegRootForUserID((GUID *)&UID_GIBC_DEFAULT_USER, g_szRegRoot, ARRAYSIZE(g_szRegRoot)); return g_szRegRoot; } LPCSTR MU_GetCurrentIdentityName() { HRESULT hr; IUserIdentity *pIdentity = NULL; WCHAR szwName[CCH_USERNAME_MAX_LENGTH+1]; Assert(g_pIdMan); if (g_pIdMan == NULL) return NULL; if (*g_szIdentityName) return g_szIdentityName; if (MU_CountUsers() == 1) g_szIdentityName[0] = 0; else { if (FAILED(hr = g_pIdMan->GetIdentityByCookie(PGUIDCurrentOrDefault(), &pIdentity))) goto exit; if (!pIdentity) goto exit; if (FAILED(hr = pIdentity->GetName(szwName, CCH_USERNAME_MAX_LENGTH))) goto exit; if (WideCharToMultiByte(CP_ACP, 0, szwName, -1, g_szIdentityName, CCH_USERNAME_MAX_LENGTH, NULL, NULL) == 0) { g_szIdentityName[0] = 0; goto exit; } } exit: SafeRelease(pIdentity); return g_szIdentityName; } void MU_ResetRegRoot() { RegCloseKey(g_hkeyIdentity); g_hkeyIdentity = HKEY_CURRENT_USER; g_szRegRoot[0] = 0; g_szIdentityName[0] = 0; g_dwIcwFlags = 0; } void MigrateOEMultiUserToIdentities(void) { TCHAR szProfilesPath[] = "Software\\Microsoft\\Outlook Express\\5.0\\Profiles"; TCHAR szCheckKeyPath[] = "Software\\Microsoft\\Outlook Express\\5.0\\Shared Settings\\Setup"; TCHAR szPath[MAX_PATH], szProfilePath[MAX_PATH]; HKEY hOldKey, hOldSubkey, hNewTopKey, hNewOEKey, hNewIAMKey, hCheckKey = NULL; DWORD EnumIndex; DWORD cbKeyName, cUsers; DWORD dwType, dwValue, dwStatus, dwSize; CHAR KeyNameBuffer[1024]; IPrivateIdentityManager *pPrivIdMgr; HRESULT hr; if (NULL == g_pIdMan) { hr = CoCreateInstance(CLSID_UserIdentityManager, NULL, CLSCTX_INPROC_SERVER, IID_IUserIdentityManager, (LPVOID *)&g_pIdMan); if (FAILED(hr)) return; } Assert(g_pIdMan); if (FAILED(g_pIdMan->QueryInterface(IID_IPrivateIdentityManager, (void **)&pPrivIdMgr))) return; if (RegOpenKey(HKEY_CURRENT_USER, szProfilesPath, &hOldKey) == ERROR_SUCCESS) { dwStatus = RegCreateKey(HKEY_CURRENT_USER, szCheckKeyPath, &hCheckKey); dwSize = sizeof(dwValue); if (dwStatus != ERROR_SUCCESS || (dwStatus = RegQueryValueEx(hCheckKey, "MigToLWP", NULL, &dwType, (LPBYTE)&dwValue, &dwSize)) != ERROR_SUCCESS || (1 != dwValue)) { // // Copy all of the value names and their data. // dwStatus = RegQueryInfoKey(hOldKey, NULL, NULL, 0, &cUsers, NULL, NULL, NULL, NULL, NULL, NULL, NULL); EnumIndex = 0; while (TRUE && cUsers > 0) { cbKeyName = sizeof(KeyNameBuffer); if (RegEnumKey(hOldKey, EnumIndex++, KeyNameBuffer, cbKeyName) != ERROR_SUCCESS) break; wnsprintf(szProfilePath, ARRAYSIZE(szProfilePath), "%s\\Application Data", KeyNameBuffer); if (ERROR_SUCCESS == RegOpenKey(hOldKey, szProfilePath, &hOldSubkey)) { TCHAR szUserName[CCH_USERNAME_MAX_LENGTH+1]; WCHAR szwUserName[CCH_USERNAME_MAX_LENGTH+1]; IUserIdentity *pIdentity = NULL; dwSize = sizeof(szUserName); if ((dwStatus = RegQueryValueEx(hOldSubkey, "Current Username", NULL, &dwType, (LPBYTE)szUserName, &dwSize)) == ERROR_SUCCESS && (0 != *szUserName)) { if (MultiByteToWideChar(CP_ACP, 0, szUserName, -1, szwUserName, CCH_USERNAME_MAX_LENGTH) == 0) goto UserFailed; if (cUsers == 1) { if (FAILED(g_pIdMan->GetIdentityByCookie((GUID *)&UID_GIBC_DEFAULT_USER, &pIdentity)) || !pIdentity) goto UserFailed; } else { if (FAILED(pPrivIdMgr->CreateIdentity(szwUserName, &pIdentity)) || !pIdentity) goto UserFailed; } if (FAILED(pIdentity->OpenIdentityRegKey(KEY_ALL_ACCESS, &hNewTopKey))) goto UserFailed; if (ERROR_SUCCESS == RegCreateKey(hNewTopKey, c_szRegRoot, &hNewOEKey)) { CopyRegistry(hOldSubkey, hNewOEKey); RegCloseKey(hNewOEKey); } // now copy the IAM settings wnsprintf(szProfilePath, ARRAYSIZE(szProfilePath), "%s\\Internet Accounts", KeyNameBuffer); RegCloseKey(hOldSubkey); hOldSubkey = NULL; if (ERROR_SUCCESS == RegOpenKey(hOldKey, szProfilePath, &hOldSubkey)) { if (ERROR_SUCCESS == RegCreateKey(hNewTopKey, c_szInetAcctMgrRegKey, &hNewIAMKey)) { CopyRegistry(hOldSubkey, hNewIAMKey); RegCloseKey(hNewIAMKey); } } UserFailed: RegCloseKey(hNewTopKey); SafeRelease(pIdentity); if (hOldSubkey) { RegCloseKey(hOldSubkey); hOldSubkey = NULL; } } } } dwValue = 1; RegSetValueEx(hCheckKey, "MigToLWP", 0, REG_DWORD, (BYTE *)&dwValue, sizeof(DWORD)); } if (hCheckKey != NULL) RegCloseKey(hCheckKey); RegCloseKey(hOldKey); } pPrivIdMgr->Release(); } BOOL MU_IdentitiesDisabled() { return g_fIdentitiesDisabled || (g_dwAthenaMode & MODE_NOIDENTITIES && !g_fPluralIDs); } void MU_UpdateIdentityMenus(HMENU hMenu) { DWORD cItems, dwIndex; MENUITEMINFO mii; TCHAR szLogoffString[255]; TCHAR szRes[255]; if (MU_IdentitiesDisabled()) { // Delete the switch identity menu DeleteMenu(hMenu, ID_SWITCH_IDENTITY, MF_BYCOMMAND); DeleteMenu(hMenu, ID_EXIT_LOGOFF, MF_BYCOMMAND); // loop through the other menu items looking for logoff cItems = GetMenuItemCount(hMenu); mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_ID; for (dwIndex = cItems; dwIndex > 0; --dwIndex) { GetMenuItemInfo(hMenu, dwIndex, TRUE, &mii); // if this is the logoff item, delete it and the separator // line that follows if (mii.wID == ID_IDENTITIES) { DeleteMenu(hMenu, ID_IDENTITIES, MF_BYCOMMAND); DeleteMenu(hMenu, dwIndex, MF_BYPOSITION); break; } } } else { // Load a new menu string from the resources AthLoadString(idsLogoffFormat, szRes, ARRAYSIZE(szRes)); // Format it wnsprintf(szLogoffString, ARRAYSIZE(szLogoffString), szRes, MU_GetCurrentIdentityName()); // Splat it on the menu ModifyMenu(hMenu, ID_LOGOFF_IDENTITY, MF_BYCOMMAND | MF_STRING, ID_LOGOFF_IDENTITY, szLogoffString); } } void MU_NewIdentity(HWND hwnd) { if (g_pIdMan) { g_pIdMan->ManageIdentities(hwnd, UIMI_CREATE_NEW_IDENTITY); } } void MU_ManageIdentities(HWND hwnd) { if (g_pIdMan) { g_pIdMan->ManageIdentities(hwnd, 0); } } void MU_IdentityChanged() { // flush the cached name so we reload it *g_szIdentityName = 0; } HRESULT MU_Init(BOOL fDefaultId) { HRESULT hr = S_OK; g_fUsingDefaultId = fDefaultId; if (NULL == g_pIdMan) { hr = CoCreateInstance(CLSID_UserIdentityManager, NULL, CLSCTX_INPROC_SERVER, IID_IUserIdentityManager, (LPVOID *)&g_pIdMan); if (FAILED(hr)) MU_ShowErrorMessage(g_hLocRes, GetDesktopWindow(), idsCantLoadMsident,idsAthenaTitle); } else g_pIdMan->AddRef(); return hr; } void MU_Shutdown() { Assert(g_pIdMan); if (g_pIdMan == NULL) return; SafeIdentityRelease(); }
[ "polarisdp@gmail.com" ]
polarisdp@gmail.com
f402311ae6f2a62d5e7aae6255de6d8a603c4805
8bd6ed7ce9811e2c8682e057e906780834e825a5
/SimpleObjectTableModel.h
4a5fe27735be94726633bbaec68c2e038b71ac46
[]
no_license
deepaksamuel/simple
5a20651dc243ffe9638b48d91904b36cdc309689
5f88639bd81bfcdad1fb8b87f2c345388877baf2
refs/heads/master
2023-01-28T23:47:22.947569
2023-01-13T12:50:09
2023-01-13T12:50:09
210,591,616
20
4
null
null
null
null
UTF-8
C++
false
false
1,249
h
#ifndef SIMPLEOBJECTTABLEMODEL_H #define SIMPLEOBJECTTABLEMODEL_H // File modified by Deepak Samuel on 25 Sep 2019 #include <QAbstractTableModel> #include <SimpleObject.h> class SimpleObjectTableModel : public QAbstractTableModel { Q_OBJECT public: SimpleObjectTableModel(); public: int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index,const QVariant &value, int role); G4ThreeVector GetVector(QString string); QStringList GetStringList(QString string, QString sep="'"){return string.split(sep);} void setObject(SimpleObject* o, int index){obj=o; obj_index=index;emit layoutChanged();} void setMaterialList(QStringList l){materials=l;} SimpleObject *obj; int obj_index; // this contains the original index of the object in the main QList QStringList materials; signals: void objectUpdated(SimpleObject *obj, int newValue); }; #endif // SIMPLEOBJECTTABLEMODEL_H
[ "deepaksamuel@gmail.com" ]
deepaksamuel@gmail.com
8af3cdb33af45342a3cb9437e1c3d4fd34a63f4d
46bb27d865f4a736631f2cb12de7bbd0b7c4a467
/oxygine/src/core/logging.h
b4018157134f47918f019c884ec49d8bf3f8668b
[ "MIT" ]
permissive
cnsoft/oxygine-framework
e5b105efc062865c4ed76f26c1ac953d0a0beef8
f31ac9cafaa5dc372659501594964830d7c51bac
refs/heads/master
2020-12-25T00:04:34.194530
2013-08-23T16:39:44
2013-08-23T16:39:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
689
h
#pragma once #include <stdarg.h> namespace oxygine { /***/ namespace log { void enable(); void disable(); void out(const char *str); //outputs message without end line void message(const char *format, ...); void message_va(const char *format, va_list args); //outputs message with end line void messageln(const char *format, ...); void messageln_va(const char *format, va_list args); //outputs message as warning, has end line void warning(const char *format, ...); void warning_va(const char *format, va_list args); //outputs message as error, has end line void error(const char *format, ...); void error_va(const char *format, va_list args); } }
[ "frankinshtein85@gmail.com" ]
frankinshtein85@gmail.com
45c322206a33873d1ec6c591b9b6c270bb7752f4
64320add7a21fba99a724256fe3b5506d0590248
/MasterDeck.cpp
f8a124c6276e31acccc29e0a14e63a92741b4e77
[ "MIT" ]
permissive
ROpsal/qt-topaz31
c580369e1602541780c941f0d1058a577f2eac7e
ae9d1a6a27a83ffd7edcf52059ee98689132bfce
refs/heads/master
2021-01-11T22:27:07.584957
2019-03-11T15:58:48
2019-03-11T15:58:48
78,964,448
0
0
null
null
null
null
UTF-8
C++
false
false
2,425
cpp
/// // Author: Richard Opsal // // Purpose: Implementation of MasterDeck for game of "31". // // Location: Qt.Demo/Topaz31 // $RCSfile$ // // Started: 2009/12/13 // $Revision$ // $Date$ /// /// // Qt includes. /// #include <QList> #include <QGraphicsScene> #include <QSvgRenderer> /// // Local includes. /// #include "Card.h" #include "CardDeck.h" #include "MasterDeck.h" /// // Constructor MasterDeck() : /// MasterDeck:: MasterDeck(QObject *pparent) : QObject(pparent), psvgRenderer(new QSvgRenderer(QLatin1String(":/images/svg-cards.svg"))) { createCardList() ; } /// // Destructor ~MasterDeck() : // // Delete allocated card objects. /// MasterDeck:: ~MasterDeck() { while (!cardList.isEmpty()) { // List holds pointers to Card objects. // Delete card object and remove entry from list. Card * pcard = cardList.back() ; delete pcard ; cardList.pop_back() ; } // Remove renderer. delete psvgRenderer ; } /// // Routine MasterDeck:: createCardList() : /// void MasterDeck:: createCardList() { const char * ACPSZ_RANKS [] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king"} ; const char * ACPSZ_SUITES[] = { "spade", "club", "diamond", "heart"} ; const Card::Suite ASUITES[] = {Card::Spade, Card::Club, Card::Diamond, Card::Heart} ; QString qstr ; for (unsigned s = 0 ; s < sizeof(ACPSZ_SUITES) / sizeof(const char *); s++ ) { for (unsigned r = 0 ; r < sizeof(ACPSZ_RANKS) / sizeof(const char *); r++ ) { qstr = ACPSZ_RANKS[r] ; qstr += '_' ; qstr += ACPSZ_SUITES[s] ; cardList.push_back( new Card(psvgRenderer, qstr, r+1, ASUITES[s] )); } } } /// // Routine MasterDeck:: initCardDeck() : // // Basically, copy cards from our "master" list to target list. /// void MasterDeck:: initCardDeck( CardDeck & rcardDeck ) { rcardDeck.cardList = MasterDeck::cardList ; } /// // Routine MasterDeck:: removeCardsFromScene() : // // Removes all the cards from the passed scene. // Assumes all cards have placed on the Topaz board. /// void MasterDeck:: removeCardsFromScene(QGraphicsScene & rscene) { foreach(Card * pcard, cardList) rscene.removeItem(pcard) ; }
[ "gegenteil@fastmail.com" ]
gegenteil@fastmail.com
47f580694fca2f1439ab72f25e308953efbef3a5
82640e6ce47bd93e6be4141585de8f4880dcc3c7
/src/soft.cpp
e924ac51c0330d2caa9a1804d56fbfe8d7e08a5e
[ "MIT" ]
permissive
miuho/Hadoop-YARN
43e5f581cb991050b6a346d93a4c08f04c318373
4ef10c656169763422f3815ebc9599eeb1a28689
refs/heads/master
2020-03-19T13:43:01.742072
2018-06-08T09:32:46
2018-06-08T09:32:46
136,591,968
1
0
null
null
null
null
UTF-8
C++
false
false
25,123
cpp
#include "TetrischedService.h" #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/server/TSimpleServer.h> #include <thrift/transport/TServerSocket.h> #include <thrift/transport/TBufferTransports.h> #include "YARNTetrischedService.h" #include <thrift/transport/TSocket.h> #include <thrift/transport/TTransportUtils.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <time.h> #include <ctype.h> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstring> #include <vector> #include <queue> #include <set> #include <unordered_map> #include <mutex> #define NONE 1 #define HARD 2 #define SOFT 3 #define MAX_WAIT_TIME 1200 using namespace ::apache::thrift; using namespace ::apache::thrift::protocol; using namespace ::apache::thrift::transport; using namespace ::apache::thrift::server; //using boost::shared_ptr; using namespace std; using namespace alsched; struct Job_S { JobID jobId; job_t::type jobType; int32_t k; int32_t priority; double duration; double slowDuration; double chosen_duration; time_t added_time; int32_t *machines; }; class TetrischedServiceHandler : virtual public TetrischedServiceIf { private: int free_machines; int mode; // 1 = none, 2 = hard, 3 = soft vector<vector<int32_t>> free_racks; vector<vector<int32_t>> used_racks; unordered_map<int32_t, time_t> free_times; set<Job_S *> jobs; mutex mtx; Job_S *get_random_job(void) { // find the earliest added job (fifo) int earliest_time = INT_MAX; Job_S *earliest_job = NULL; for (std::set<Job_S *>::iterator it = jobs.begin(); it != jobs.end(); ++it) { Job_S *job = *it; if (job->added_time < earliest_time) { earliest_time = job->added_time; earliest_job = job; } } // check if possible to allocate at all if (free_machines < earliest_job->k) return NULL; // randomly allocate machines srand (time(NULL)); int j = 0; while (j < earliest_job->k) { int rand_i = rand() % free_racks.size(); if (free_racks[rand_i].empty()) continue; used_racks[rand_i].push_back(free_racks[rand_i].back()); (earliest_job->machines)[j] = free_racks[rand_i].back(); // overwrite each check free_racks[rand_i].pop_back(); j++; } return earliest_job; } time_t get_waiting_time_gpu(time_t cur_time, int32_t k) { if (k > (int32_t)(free_racks[0].size() + used_racks[0].size())) { cout << "Invalid GPU rack\n"; return cur_time; } // compute the minimum waiting time for gpu rack int32_t require = k - free_racks[0].size(); vector<time_t> times; for (int32_t j = 0; j < (int32_t)used_racks[0].size(); j++) { time_t t = free_times[used_racks[0][j]]; time_t diff = (t > cur_time) ? (t - cur_time) : 0; times.push_back(diff); } // sort the waiting time sort(times.begin(), times.end()); time_t rack_min = times[require - 1]; return rack_min; } time_t get_waiting_time_mpi(time_t cur_time, int32_t k) { time_t global_rack_min = cur_time; // traverse all racks for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { // skips those small racks if (k > (int32_t)(free_racks[i].size() + used_racks[i].size())) continue; // compute the minimum waiting time for this rack int32_t require = k - free_racks[i].size(); if (require <= 0) { cout << "ERROR: Found full rack to allocate\n"; continue; } vector<time_t> times; for (int32_t j = 0; j < (int32_t)used_racks[i].size(); j++) { time_t t = free_times[used_racks[i][j]]; time_t diff = (t > cur_time) ? (t - cur_time) : 0; times.push_back(diff); } // sort the waiting time sort(times.begin(), times.end()); time_t rack_min = times[require - 1]; if (rack_min < global_rack_min) global_rack_min = rack_min; } return global_rack_min; } int get_utility(Job_S *job, bool preferred) { int utility = 1200; int waited_time = (int)(job->added_time - time(NULL)); if (preferred) utility -= (waited_time + job->duration); else utility -= (waited_time + job->slowDuration); return (utility < 0) ? 0 : utility; } Job_S *get_max_utility_job(time_t cur_time) { int max_utility = -1; Job_S *max_utility_job = NULL; cout << "Traverse all jobs\n"; for (std::set<Job_S *>::iterator it = jobs.begin(); it != jobs.end(); ++it) { Job_S *job = *it; // check if possible to allocate at all if (free_machines < job->k) continue; bool preferred = false; if (job->jobType == 0) { // JOB_MPI cout << "Looking at MPI job " << job->jobId << "\n"; // check for available non-gpu racks to place all k containers for (int32_t i = 1; i < (int32_t)free_racks.size(); i++) { if ((int32_t)free_racks[i].size() >= job->k) { preferred = true; cout << "Found full rack: "; for (int32_t j = 0; j < job->k; j++) { //used_racks[i].push_back(free_racks[i].back()); //(job->machines)[j] = free_racks[i].back(); // overwrite each check //cout << j << ":" << free_racks[i].back() << ","; //free_racks[i].pop_back(); (job->machines)[j] = free_racks[i][j]; cout << free_racks[i][j] << ","; } cout << "\n"; // fast duration job->chosen_duration = job->duration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } break; } } // check if gpu rack is available if (!preferred) { // try to place k containers into gpu machines if ((int32_t)free_racks[0].size() >= job->k) { preferred = true; cout << "Finding in GPU rack: "; for (int i = 0; i < job->k; i++) { //used_racks[0].push_back(free_racks[0].back()); //(job->machines)[i] = free_racks[0].back(); // overwrite each check //cout << i << ":" << free_racks[0].back() << ","; //free_racks[0].pop_back(); (job->machines)[i] = free_racks[0][i]; cout << free_racks[0][i] << ","; } cout << "\n"; // fast duration job->chosen_duration = job->duration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } } } // no availble full rack if (!preferred && mode == SOFT) { cout << "Cannot find full rack\n"; if ((cur_time + get_waiting_time_mpi(cur_time, job->k) + job->duration) < (cur_time + job->slowDuration)) { // wait for free rack //cout << "Delay for free rack\n"; continue; } cout << "Finding in other racks: "; int32_t m = 0; for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { //while(!free_racks[i].empty()) { for (int32_t j = 0; j < (int32_t)free_racks[i].size(); j++) { //used_racks[i].push_back(free_racks[i].back()); //(job->machines)[m] = free_racks[i].back(); // overwrite each check //cout << m << ":" << free_racks[i].back() << ","; //free_racks[i].pop_back(); (job->machines)[m] = free_racks[i][j]; cout << free_racks[i][j] << ","; m++; if (m >= job->k) break; } if (m >= job->k) break; } cout << "\n"; // slow duration job->chosen_duration = job->slowDuration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } } } else if (job->jobType == 2) { // JOB_GPU cout << "Looking at GPU job " << job->jobId << "\n"; // try to place k containers into gpu machines if ((int32_t)free_racks[0].size() >= job->k) { preferred = true; cout << "Finding in GPU rack: "; for (int i = 0; i < job->k; i++) { //used_racks[0].push_back(free_racks[0].back()); //(job->machines)[i] = free_racks[0].back(); // overwrite each check //cout << i << ":" << free_racks[0].back() << ","; //free_racks[0].pop_back(); (job->machines)[i] = free_racks[0][i]; cout << free_racks[0][i] << ","; } cout << "\n"; // fast duration job->chosen_duration = job->duration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } } // not enough gpu machines if (!preferred && mode == SOFT) { if ((cur_time + get_waiting_time_gpu(cur_time, job->k) + job->duration) < (cur_time + job->slowDuration)) { // wait for free gpu rack //cout << "Delay for free gpu rack\n"; continue; } cout << "Finding in other racks: "; int32_t m = 0; for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { //while(!free_racks[i].empty()) { for (int32_t j = 0; j < (int32_t)free_racks[i].size(); j++) { //used_racks[i].push_back(free_racks[i].back()); //(job->machines)[m] = free_racks[i].back(); // overwrite each check //cout << m << ":" << free_racks[i].back() << ","; //free_racks[i].pop_back(); (job->machines)[m] = free_racks[i][j]; cout << free_racks[i][j] << ","; m++; if (m >= job->k) break; } if (m >= job->k) break; } cout << "\n"; // slow duration job->chosen_duration = job->slowDuration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } } } else { cout << "Invalid jobType\n"; } } if (max_utility_job != NULL) { for (int32_t i = 0; i < max_utility_job->k; i++) { int32_t machine = (max_utility_job->machines)[i]; int32_t j = 0; for (int32_t k = 0; k < (int32_t)free_racks.size(); k++) { j += (int32_t)(free_racks[k].size() + used_racks[k].size()); if (machine < j) { vector<int32_t>::iterator it2 = find(free_racks[k].begin(), free_racks[k].end(), machine); if (it2 == free_racks[k].end()) cout << "ERROR: Trying to allocate resource that is already allocated\n"; else { free_racks[k].erase(it2); used_racks[k].push_back(machine); } break; } } } } return max_utility_job; } void TryToAllocate() { cout << "TryToAllocate\n"; // remove jobs that waited too long time_t cur_time = time(NULL); for (std::set<Job_S *>::iterator it = jobs.begin(); it != jobs.end(); ) { Job_S *job = *it; cout << "job " << job->jobId << " waited for " << (cur_time - job->added_time) << " seconds\n"; // max allowable waiting time in job list < already waited time in job list if ((MAX_WAIT_TIME - job->duration) < (cur_time - job->added_time)) { cout << "Removed timeout job: " << job->jobId << "\n"; it = jobs.erase(it); delete [] (job->machines); delete job; } else { ++it; } } int yarnport = 9090; boost::shared_ptr<TTransport> socket(new TSocket("localhost", yarnport)); boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); YARNTetrischedServiceClient client(protocol); set<int32_t> machines; // try to allocate some nodes try { transport->open(); // keep allocating resources for as many jobs as possible while (!jobs.empty()) { cout << "Begin to find a job...\n"; cur_time = time(NULL); machines.clear(); Job_S *head = NULL; if (mode == NONE) head = get_random_job(); else head = get_max_utility_job(cur_time); // not enough resources to allocate to head if (head == NULL) { cout << "Not enough resources\n"; break; } cout << "Got resources\n"; cout << "Handling job " << head->jobId << "\n"; // allocate resources cout << "Prepare to allocate slaves: "; for (int i = 0; i < (head->k); i++) { int32_t machine = (head->machines)[i]; cout << machine << ", "; machines.insert(machine); } cout << "\n"; free_machines -= (head->k); // allocate machines client.AllocResources(head->jobId, machines); cout << "Successfully handled job " << head->jobId << "\n"; cout << "k: " << head->k << " chosen_duration: " << head->chosen_duration << "\n"; // store free time for (std::set<int32_t>::iterator it = machines.begin(); it != machines.end(); ++it) free_times[*it] = cur_time + (head->chosen_duration); // free job info delete [] (head->machines); jobs.erase(jobs.find(head)); delete head; } transport->close(); } catch (TException& tx) { printf("ERROR calling YARN : %s\n", tx.what()); // recover printf("Recover: \n"); for (std::set<int32_t>::iterator it = machines.begin(); it != machines.end(); ++it) { int32_t j = 0; for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { j += (int32_t)(free_racks[i].size() + used_racks[i].size()); if (*it < j) { vector<int32_t>::iterator it2 = find(used_racks[i].begin(), used_racks[i].end(), *it); if (it2 == used_racks[i].end()) cout << "ERROR: Trying to free resource that isnt allocated\n"; else { used_racks[i].erase(it2); free_racks[i].push_back(*it); free_machines++; } break; } } cout << *it << ", "; } cout << "\n"; } } public: TetrischedServiceHandler(char *config_file) { // Your initialization goes here printf("init\n"); free_machines = 0; mode = 0; // 1 = none, 2 = hard, 3 = soft if (config_file != NULL) { ifstream in(config_file); if (!in) printf("ERROR: cannot find config file\n"); else { string line; string topology = ""; while (getline(in, line)) { if (line.empty()) continue; else { size_t found = line.find("simtype"); if (found != string::npos) { string tmp = line.substr(found + 8); found = tmp.find("\""); if (found != string::npos) { tmp = tmp.substr(found + 1); found = tmp.find("\""); if (found != string::npos) { tmp = tmp.substr(0, found); cout << tmp << "\n"; if (!tmp.compare("none")) mode = NONE; else if (!tmp.compare("hard")) mode = HARD; else if (!tmp.compare("soft")) mode = SOFT; else cout << "Invalid simtype\n"; cout << "mode: " << mode << "\n"; } } } found = line.find("rack_cap"); if (found != string::npos) { string tmp = line.substr(found); topology.append(tmp); if (tmp.find("]") != string::npos) break; while (getline(in, line)) { if (line.empty()) continue; else { topology.append(line); if (line.find("]") != string::npos) break; } } } } } in.close(); if (!mode) { printf("No specified policy: using SOFT as default\n"); mode = SOFT; // default is soft } if (topology == "" || topology.find("[") == string::npos || topology.find("]") == string::npos || topology.find("[") > topology.find("]")) { printf("ERROR: invalid config file\n"); return; } topology = topology.substr(topology.find("["), topology.find("]")); cout << topology << "\n"; for (unsigned int i = 0; i < topology.length(); i++) { char c = topology.at(i); if (isdigit(c)) { int num = c - '0'; vector<int32_t> tmp1; used_racks.push_back(tmp1); vector<int32_t> tmp2; // all slaves in a rack are initially free for (int i = free_machines; i < (free_machines + num); i++) { tmp2.push_back(i); cout << i << ","; } cout << "\n"; free_racks.push_back(tmp2); free_machines += num; } } } } else { printf("ERROR: no input config file\n"); } } void AddJob(const JobID jobId, const job_t::type jobType, const int32_t k, const int32_t priority, const double duration, const double slowDuration) { mtx.lock(); cout << "AddJob\n"; cout << "jobId: " << jobId << ", jobType: " << jobType << ", k: " << k << ", priority: " << priority << ", duration: " << duration << ", slowDuration: " << slowDuration << "\n"; // create Job_S structure to store job info Job_S *job = new Job_S; job->jobId = jobId; job->jobType = jobType; job->k = k; job->priority = priority; job->duration = duration; job->slowDuration = slowDuration; job->added_time = time(NULL); job->machines = new int32_t[k]; jobs.insert(job); TryToAllocate(); mtx.unlock(); } void FreeResources(const std::set<int32_t> & machines) { mtx.lock(); cout << "FreeResources\n"; // free resources cout << "Free slaves: "; for (std::set<int32_t>::iterator it = machines.begin(); it != machines.end(); ++it) { int32_t j = 0; for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { j += (int32_t)(free_racks[i].size() + used_racks[i].size()); if (*it < j) { vector<int32_t>::iterator it2 = find(used_racks[i].begin(), used_racks[i].end(), *it); if (it2 == used_racks[i].end()) cout << "ERROR: Trying to free resource that isnt allocated\n"; else { used_racks[i].erase(it2); free_racks[i].push_back(*it); free_machines++; } break; } } cout << *it << ", "; } cout << "\n"; TryToAllocate(); mtx.unlock(); } }; int main(int argc, char **argv) { //create a listening server socket int alschedport = 9091; char *config_file = NULL; if (argc == 2) config_file = argv[1]; else if (argc == 3) config_file = argv[2]; else printf("ERROR: no config file\n"); boost::shared_ptr<TetrischedServiceHandler> handler(new TetrischedServiceHandler(config_file)); boost::shared_ptr<TProcessor> processor(new TetrischedServiceProcessor(handler)); boost::shared_ptr<TServerTransport> serverTransport(new TServerSocket(alschedport)); boost::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory()); boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory()); TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory); server.serve(); return 0; }
[ "miuhingon@hotmail.com" ]
miuhingon@hotmail.com
d7b7b90e4c7ccf07c286c46a4a9a1aa216bee0c1
48d89625161f93c614de2eb53630345091a7428e
/day15/task1.cpp
b555661b751af46b23931a5d0438f52310b93dd2
[]
no_license
kpyrkosz/advent_of_code_2020
030875cd1aeefd877fa4ed95360e1ed611a77a9b
faa6d59cb3a83fd08937273cb8ef468ee9dd73d2
refs/heads/master
2023-02-03T00:59:42.264978
2020-12-18T14:02:15
2020-12-18T14:02:15
318,219,319
0
0
null
null
null
null
UTF-8
C++
false
false
802
cpp
#include <iostream> #include <unordered_map> int main() { unsigned last_spoken; unsigned current_turn = 1; std::unordered_map<unsigned, unsigned> val_to_last_spoken; std::cin >> last_spoken; while (!std::cin.eof()) { val_to_last_spoken[last_spoken] = current_turn++; std::cin >> last_spoken; std::cin >> std::ws; } while (current_turn < 2020) { if (val_to_last_spoken.count(last_spoken) == 0) { val_to_last_spoken[last_spoken] = current_turn++; last_spoken = 0; } else { unsigned dist = current_turn - val_to_last_spoken[last_spoken]; val_to_last_spoken[last_spoken] = current_turn; last_spoken = dist; ++current_turn; } std::cout << "Turn\t" << current_turn << " last spoken\t" << last_spoken << '\n'; } }
[ "krzpyrkosz@gmail.com" ]
krzpyrkosz@gmail.com
ded503ce4867aeaa77295147cd39407adf5706e2
7c6fcad6575682d11e7f2d0a67203d33c5f7e556
/game1/game1.cpp
69fcab05cef6a09e119fe7a8128a7170f117623c
[]
no_license
hchencn/first-c-game
261d27f94b550c01a73b57b0481aa43385ae744f
692d917b6a926fd106f2a4acf78125681a33d634
refs/heads/master
2021-05-28T13:05:02.398826
2014-08-14T01:56:09
2014-08-14T01:56:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,008
cpp
#include "stdafx.h" #include <iostream> void pre_game(void); int num = 1, w = 30, h = 20, type = 0; int main(int argc, char argv[]) { pre_game(); system("cls"); Game newgame(num, w ,h, type); newgame.run(); system("pause"); return 0; } void pre_game(void) { std::cout << "Game Start" << std::endl << "Your mission is to kill all the enemies. You can be a mage or a warrior:" << std::endl << "Mage has 3 lives and use fireball(need 2 hits to kill the enemy)." << std::endl << "Warrior has 4 lives and use sword (only 1 hit can kill the enemy)." << std::endl << "'a, s, d, w' for moving, 'j' for attacking" << std::endl; std::cout << "Please enter the number of enemy:" << std::endl; std::cin >> num; std::cout << "Please enter the width of map (more than 10):" << std::endl; std::cin >> w; std::cout << "Please enter the height of map (more than 10):" << std::endl; std::cin >> h; std::cout << "Please select your class (0 for mage, 1 for warrior):" << std::endl; std::cin >> type; }
[ "chenhan728@gmail.com" ]
chenhan728@gmail.com
696489e8ff264aa874f02589954d979d33fa1576
bf38cf48cbebf0b077234519876b5940fda0c99a
/src/libconex/ternary_tree/tst_detail/new_iterator_base.ipp
39e00e89119f68bbde1c21d2818010086fbb8e81
[]
no_license
guangyixiao/stextedit
ace36a5fa446d8f2500253b9d91cd6b6213b83b1
eb52358a6dc9d398e28444825917ccecdbac3a9c
refs/heads/master
2021-01-18T22:10:47.763184
2016-05-27T08:54:54
2016-05-27T08:54:54
33,931,696
0
0
null
null
null
null
UTF-8
C++
false
false
7,031
ipp
// block direct use #ifndef TERNARY_TREE_INCLUDE_GUARD # error This is a dependent header file, included by ternary_tree.hpp - DO NOT USE DIRECTLY #endif #include "iteration_impl.hpp" namespace containers { namespace tst_detail { //--------------------------------------------------------------------------------------- // ternary_tree::tst_iterator_base class // 0.685: prepare for different iterator types; now uses iteration policy class: // - insert-order iterator (= vector::iterator but only at end nodes) // - subkey iterator: can visit any non-erased node //--------------------------------------------------------------------------------------- /** Implements forward and backward iteration in lexical order. * Iteration is slightly expensive as it needs to walk nodes, and backtrack to find next value. * Complexity of increment is amortized constant time. Actual time taken is O(n) in average length * of strings minus string common prefixes. * * tst_iterator_base is constructible from a node list and a node index; this is used * with values returned from wildcard-match and neighbour-match searches. * * iteration_policy defines methods: * - find_first_endnode - seek forward to the lowest/leftmost terminal node * - find_last_endnode - backward, ditto * - find_forward_path - seek towards trunk for forward/higher branch * - find_backward_path - backward, ditto * */ template<class NodeListT, class StringT, class TraitsT = inorder_seek<NodeListT, StringT> > class tst_iterator_base { private: typedef NodeListT NodeList; typedef TraitsT iter_traits; typedef key_access<NodeListT, StringT> t_key_access; public: typedef typename NodeListT::value_type node; typedef typename NodeListT::size_type node_index; typedef StringT string_type; typedef typename node::value_type value_type; typedef value_type& reference; typedef const value_type& const_reference; tst_iterator_base() : m_nodes(0), m_current_node(node::invalid_index) {} explicit tst_iterator_base(const NodeList& nodes) : m_nodes(&nodes), m_current_node(node::invalid_index) {} // ! Pre: key represents the key part at node index nid. Used internally by eg prefix_match etc; \n // ! Pre: This may not be used with user keys, only with keys extracted from the tree! // ! (since comparator doesn't enforce identity) /* tst_iterator_base(const NodeList& nodes, node_index nid, const StringT& key) : m_nodes(&nodes), m_current_node(nid), m_current_key(key.begin(), key.end()) { if (nid == node::invalid_index) { assert(m_current_key.empty()); return; } m_current_node = iter_traits::find_first_endnode(*m_nodes, m_current_node, m_current_key); string_type tmp; assert(m_current_key == t_key_access::retrieve_key_string(*m_nodes, m_current_node, tmp)); } */ tst_iterator_base(const NodeList& nodes, node_index index) : m_nodes(&nodes), m_current_node(index) { if (index == node::invalid_index) return; if (m_nodes->empty()) m_current_node = node::invalid_index; else { m_current_node = iter_traits::find_first_endnode(*m_nodes, m_current_node, m_current_key); if (index != 0) t_key_access::retrieve_key_string(*m_nodes, m_current_node, m_current_key); else { string_type tmp; assert(m_current_key == t_key_access::retrieve_key_string(*m_nodes, m_current_node, tmp)); } } } public: /** @name publicly usable interface * @{ */ /** Returns the key at current iterator position - this value changes when iterator * is incremented or decremented. */ const string_type& key() const { return m_current_key; } /** Returns a mutable reference to the value associated with current key. */ reference value() { return dereference(); } /** Returns a const reference to the value associated with current key. */ const_reference value() const { return dereference(); } /* @{ */ /** @name iterator_wrapper interface * @{ */ /** Called from iterator wrappers - note that mutable reference is returned even though * method is const: the iterator wrapper const_traits policy must manage client access rights. */ reference dereference() const { return (const_cast<NodeList&>(*m_nodes)[m_current_node].value()); } /** Seek to next end-of-string node (or set to invalid node) * Precondition: current node is at_end() */ void increment() { node_index nid = m_current_node; assert( nid >= (*m_nodes).size() || (current_node().at_end() && current_node().at_end() != node::erased)); // step forward, or back off from endnode m_current_node = iter_traits::find_forward_path(*m_nodes, m_current_node, m_current_key); { string_type tmp; assert( (m_current_node == node::invalid_index && m_current_key.empty()) || m_current_key == t_key_access::retrieve_key_string(*m_nodes, m_current_node, tmp)); } // go left/down to next m_current_node = iter_traits::find_first_endnode(*m_nodes, m_current_node, m_current_key); { string_type tmp; assert( (m_current_node == node::invalid_index && m_current_key.empty()) || m_current_key == t_key_access::retrieve_key_string(*m_nodes, m_current_node, tmp)); } } /** Seek to next end-of-string node (or set to invalid node) * Precondition: current node is at_end() */ void decrement() // Always true: bool endcheck) { node_index nid = m_current_node; assert(nid >= (*m_nodes).size() || (current_node().at_end() && current_node().at_end() != node::erased)); // special case for decrementing from end-node: back up to last element if (nid >= (*m_nodes).size()) { m_current_key.clear(); if ((*m_nodes).empty()) m_current_node = node::invalid_index; else m_current_node = iter_traits::find_last_endnode(*m_nodes, 0, m_current_key); return; } // back up from endnode - handles full iteration m_current_node = iter_traits::find_backward_path(*m_nodes, m_current_node, m_current_key); } bool equal(const tst_iterator_base& other) const { assert(!m_nodes || !other.m_nodes || m_nodes == other.m_nodes); return tree_position() == other.tree_position(); } void swap(tst_iterator_base& rhs) { std::swap(m_nodes, rhs.m_nodes); std::swap(m_current_node, rhs.m_current_node); std::swap(m_current_key, rhs.m_current_key); } bool empty() const { return m_nodes? ((*m_nodes).size() == 0) : true; } node_index tree_position() const { return m_current_node; } /* @} */ private: const node& current_node() const { return nodes()[m_current_node]; } const NodeList& nodes() const { return *m_nodes; } private: const NodeList* m_nodes; node_index m_current_node; string_type m_current_key; }; } } // end namespace containers::tst_detail
[ "guangyi_xiao@163.com" ]
guangyi_xiao@163.com
bdb3420649eb9e2723bd182eea968928654a4c31
0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd
/ash/app_list/views/suggestion_chip_container_view.cc
fa2cb268e6f58e1e8a7ff48f3aade5feb5881114
[ "BSD-3-Clause" ]
permissive
yachtcaptain23/browser-android-tabs
e5144cee9141890590d6d6faeb1bdc5d58a6cbf1
a016aade8f8333c822d00d62738a922671a52b85
refs/heads/master
2021-04-28T17:07:06.955483
2018-09-26T06:22:11
2018-09-26T06:22:11
122,005,560
0
0
NOASSERTION
2019-05-17T19:37:59
2018-02-19T01:00:10
null
UTF-8
C++
false
false
3,286
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/app_list/views/suggestion_chip_container_view.h" #include <memory> #include "ash/app_list/views/app_list_main_view.h" #include "ash/app_list/views/contents_view.h" #include "ash/app_list/views/search_result_suggestion_chip_view.h" #include "ash/public/cpp/app_list/app_list_config.h" #include "ash/public/cpp/app_list/app_list_constants.h" #include "ash/public/cpp/app_list/app_list_features.h" #include "ui/views/layout/box_layout.h" namespace app_list { namespace { // The spacing between chips. constexpr int kChipSpacing = 8; } // namespace SuggestionChipContainerView::SuggestionChipContainerView( ContentsView* contents_view) : contents_view_(contents_view) { SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); DCHECK(contents_view); view_delegate_ = contents_view_->GetAppListMainView()->view_delegate(); views::BoxLayout* layout_manager = SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(), kChipSpacing)); layout_manager->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::MAIN_AXIS_ALIGNMENT_CENTER); } SuggestionChipContainerView::~SuggestionChipContainerView() = default; int SuggestionChipContainerView::DoUpdate() { if (IgnoreUpdateAndLayout()) return num_results(); // Clear all current suggestion chips. for (size_t i = 0; i < suggestion_chip_views.size(); ++i) delete suggestion_chip_views[i]; suggestion_chip_views.clear(); std::vector<SearchResult*> display_results = SearchModel::FilterSearchResultsByDisplayType( results(), ash::SearchResultDisplayType::kRecommendation, kNumStartPageTiles); // Create a suggestion chip for each search result, but wait until layout to // add them as child views when we know this view's bounds. for (auto* result : display_results) { SearchResultSuggestionChipView* chip = new SearchResultSuggestionChipView(view_delegate_); chip->SetSearchResult(result); suggestion_chip_views.emplace_back(chip); } return num_results(); } const char* SuggestionChipContainerView::GetClassName() const { return "SuggestionChipContainerView"; } void SuggestionChipContainerView::Layout() { if (IgnoreUpdateAndLayout()) return; // Only show the chips that fit in this view's contents bounds. RemoveAllChildViews(false /* delete_children */); int total_width = 0; const int max_width = GetContentsBounds().width(); for (auto* chip : suggestion_chip_views) { const int chip_width = chip->GetPreferredSize().width(); if (chip_width + total_width > max_width) break; AddChildView(chip); total_width += (total_width == 0 ? 0 : kChipSpacing) + chip_width; } views::View::Layout(); } bool SuggestionChipContainerView::IgnoreUpdateAndLayout() const { // Ignore update and layout when this view is not shown. const ash::AppListState state = contents_view_->GetActiveState(); return state != ash::AppListState::kStateStart && state != ash::AppListState::kStateApps; } } // namespace app_list
[ "artem@brave.com" ]
artem@brave.com
22d2293ecf314913d8c68b2aaee14e881e05c431
b3017c05b608961a8d3a6ebc58cce50c1349291a
/ZGeom/include/ZGeom/Quadric.h
ae5541f04922b222436201c493b0247d51d7b6b1
[]
no_license
sunyzm/ZGeometry
c3db5a4d1287855fab050446124264dd92018ff6
65baecab370760df37192765120c22d1eaaa7af8
refs/heads/master
2021-01-23T17:30:42.889280
2016-12-03T17:51:22
2016-12-03T17:51:22
5,421,261
0
0
null
null
null
null
UTF-8
C++
false
false
933
h
#ifndef ZGEOM_QUADRIC_H #define ZGEOM_QUADRIC_H #include "Vec3.h" class Quadric { public: Quadric(); Quadric(double a, double b, double c, double d, double r); Quadric(const Quadric& q); Quadric& operator =(const Quadric& q); double eval(const ZGeom::Vec3d& v); ZGeom::Matrix3 getTensor() const; ZGeom::Vec3d getVector() const; double getOffset() const {return d2;} double getArea() const {return area;} Quadric& operator +=(const Quadric& q1); Quadric& operator -=(const Quadric& q1); Quadric& operator *=(double coeff); friend Quadric operator +(const Quadric& q1, const Quadric& q2); friend Quadric operator -(const Quadric& q1, const Quadric& q2); friend Quadric operator *(const Quadric& q1, double coeff); private: void initInternal(); // Attributes double a2, ab, ac, ad; double b2, bc, bd; double c2, cd; double d2; double area; double* pData[11]; }; #endif
[ "mzhong@cs.stonybrook.edu" ]
mzhong@cs.stonybrook.edu
4d0ac72278f78083b52c5bfd7dda07239c4c3f7f
52d9ae18b0ff40050caf4b98bd3244d5bd320851
/BattleTanks/Source/BattleTanks/MainMenuGameMode.cpp
ee342b68f45ef94e74d2e69b789e7da89dc008c0
[]
no_license
kensai01/02_battletanks
868c68ce11ce8200c0f9ca141e1e16ca7e69a425
e20cc877904ddfbedbee48ce9bac3066c0312be4
refs/heads/master
2022-01-07T02:56:58.687428
2019-05-01T05:08:52
2019-05-01T05:08:52
74,416,709
1
0
null
null
null
null
UTF-8
C++
false
false
5,269
cpp
// Copyright MB #include "BattleTanks.h" #include "MainMenuGameMode.h" #include "UI/MainMenuHUD.h" #include "Player/TankPlayerController.h" #include "Player/Tank.h" AMainMenuGameMode::AMainMenuGameMode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { //PlayerControllerClass = ATankPlayerController::StaticClass(); DefaultPawnClass = ATank::StaticClass(); HUDClass = AMainMenuHUD::StaticClass(); //static ConstructorHelpers::FClassFinder<AStrategyBuilding> EmptyWallSlotHelper(TEXT("/Game/Buildings/Wall/Wall_EmptySlot")); //EmptyWallSlotClass = EmptyWallSlotHelper.Class; if ((GEngine != nullptr) && (GEngine->GameViewport != nullptr)) { GEngine->GameViewport->SetSuppressTransitionMessage(true); } } //// internal //EGameplayState::Type AMainMenuGameMode::GetGameplayState() const //{ // return GetGameState<AStrategyGameState>()->GameplayState; //} // //const FString AMainMenuGameMode::DifficultyOptionName(TEXT("Difficulty")); // // //void AMainMenuGameMode::InitGameState() //{ // Super::InitGameState(); // // AStrategyGameState* const StrategyGameState = GetGameState<AStrategyGameState>(); // if (StrategyGameState) // { // EGameDifficulty::Type const NewDifficulty = (EGameDifficulty::Type) UGameplayStatics::GetIntOption(OptionsString, DifficultyOptionName, 0); // StrategyGameState->SetGameDifficulty(NewDifficulty); // // // start the game! // StrategyGameState->StartGameplayStateMachine(); // } //} // //void AMainMenuGameMode::RestartPlayer(AController* NewPlayer) //{ // AActor* const StartSpot = FindPlayerStart(NewPlayer); // if (StartSpot != nullptr) // { // // initialize and start it up // InitStartSpot(StartSpot, NewPlayer); // // AStrategyPlayerController* const NewPC = Cast<AStrategyPlayerController>(NewPlayer); // if (NewPC != nullptr) // { // NewPC->SetInitialLocationAndRotation(StartSpot->GetActorLocation(), StartSpot->GetActorRotation()); // } // } // else // { // UE_LOG(LogGame, Warning, TEXT("Player start not found, failed to restart player")); // } //} // //float AMainMenuGameMode::ModifyDamage(float Damage, AActor* DamagedActor, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) const //{ // // no health changes after game is finished // if (GetGameplayState() == EGameplayState::Finished) // { // return 0.0f; // } // // if (Damage > 0.f) // { // const IStrategyTeamInterface* VictimTeam = Cast<IStrategyTeamInterface>(DamagedActor); // IStrategyTeamInterface* InstigatorTeam = Cast<IStrategyTeamInterface>(EventInstigator); // if (InstigatorTeam == nullptr) // { // InstigatorTeam = Cast<IStrategyTeamInterface>(DamageCauser); // } // // // skip friendly fire // if (InstigatorTeam && VictimTeam && InstigatorTeam->GetTeamNum() == VictimTeam->GetTeamNum()) // { // return 0.0f; // } // // // pawn's damage reduction // const AStrategyChar* DamagedChar = Cast<AStrategyChar>(DamagedActor); // if (DamagedChar) // { // Damage -= DamagedChar->GetPawnData()->DamageReduction; // } // } // // return Damage; //} // //void AMainMenuGameMode::FinishGame(EStrategyTeam::Type InWinningTeam) //{ // AStrategyGameState* CurrentGameState = GetGameState<AStrategyGameState>(); // // If the game state is valid and we are still playing // if ((CurrentGameState != nullptr) && (CurrentGameState->GameplayState != EGameplayState::Finished)) // { // // tell the gamestate to wrap it up // CurrentGameState->FinishGame(InWinningTeam); // // } // // Add a timer to return to main if one does not already exist. // if (GetWorldTimerManager().GetTimerRate(TimerHandle_ReturnToMenu) == -1.0f) // { // // set timer to return to the main menu // GetWorldTimerManager().SetTimer(TimerHandle_ReturnToMenu, this, &AMainMenuGameMode::ReturnToMenu, TimeBeforeReturnToMenu, false); // } //} void AMainMenuGameMode::ReturnToMenu() { GetWorld()->ServerTravel(FString("/Game/_Levels/MainMenu")); } //bool AMainMenuGameMode::OnFriendlyTeam(const AActor* ActorA, const AActor* ActorB) //{ // const IStrategyTeamInterface* TeamA = Cast<const IStrategyTeamInterface>(ActorA); // const IStrategyTeamInterface* TeamB = Cast<const IStrategyTeamInterface>(ActorB); // // if ((TeamA != nullptr && TeamA->GetTeamNum() == EStrategyTeam::Unknown) || (TeamB != nullptr && TeamB->GetTeamNum() == EStrategyTeam::Unknown)) // return true; // // return (TeamA != nullptr) && (TeamB != nullptr) && (TeamA->GetTeamNum() == TeamB->GetTeamNum()); //} // //bool AMainMenuGameMode::OnEnemyTeam(const AActor* ActorA, const AActor* ActorB) //{ // const IStrategyTeamInterface* TeamA = Cast<const IStrategyTeamInterface>(ActorA); // const IStrategyTeamInterface* TeamB = Cast<const IStrategyTeamInterface>(ActorB); // // if ((TeamA != nullptr && TeamA->GetTeamNum() == EStrategyTeam::Unknown) || (TeamB != nullptr && TeamB->GetTeamNum() == EStrategyTeam::Unknown)) // return false; // // return (TeamA != nullptr) && (TeamB != nullptr) && (TeamA->GetTeamNum() != TeamB->GetTeamNum()); //} void AMainMenuGameMode::ExitGame() { ATankPlayerController* PlayerController = nullptr; if (GEngine) { PlayerController = Cast<ATankPlayerController>(GEngine->GetFirstLocalPlayerController(GetWorld())); PlayerController->ConsoleCommand(TEXT("quit")); } }
[ "br9975@wayne.edu" ]
br9975@wayne.edu
3f7f717146d00fa57e1f5cb75874069947b667fc
ebe68bb8d78481b8143f5abc00790077f327c6b6
/3_24Text3/MainFrm.cpp
d0ff29b647a1354bc4504350f3d38d03bf49472a
[]
no_license
WangPW915/VC-work
37b26978921f760993fefefda8399367bbec9c4e
5253082c556d0865070be8e88de418ddcfc0b570
refs/heads/master
2022-11-15T18:07:19.851559
2020-07-05T15:37:14
2020-07-05T15:37:14
255,224,886
0
0
null
null
null
null
GB18030
C++
false
false
1,773
cpp
// MainFrm.cpp : CMainFrame 类的实现 // #include "stdafx.h" #include "3_24Text3.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // 状态行指示器 ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame 构造/析构 CMainFrame::CMainFrame() { // TODO: 在此添加成员初始化代码 } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("未能创建工具栏\n"); return -1; // 未能创建 } if (!m_wndStatusBar.Create(this)) { TRACE0("未能创建状态栏\n"); return -1; // 未能创建 } m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT)); // TODO: 如果不需要可停靠工具栏,则删除这三行 m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: 在此处通过修改 // CREATESTRUCT cs 来修改窗口类或样式 return TRUE; } // CMainFrame 诊断 #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG // CMainFrame 消息处理程序
[ "1832738390@qq.com" ]
1832738390@qq.com
315ef309308a2af6f980432c2f9ce4e459451d74
2464de739ea08991fc4af8dcb96211ed37de708b
/MasteringQt5/gallery-core/gallery-desktop/AlbumListWidget.cpp
5ee31304ad4072640095aa0c61884394663bc92d
[]
no_license
KyleBeebe/MasteringQt5
62b1e31c701a7717347d74ec5335ccad409b58a3
6149c8f297645314c6908a8f5523a9d932eb443a
refs/heads/master
2020-07-01T10:43:06.690899
2019-08-27T04:40:57
2019-08-27T04:40:57
201,147,538
0
0
null
null
null
null
UTF-8
C++
false
false
1,209
cpp
#include "AlbumListWidget.h" #include "ui_AlbumListWidget.h" #include <QInputDialog> #include "AlbumModel.h" AlbumListWidget::AlbumListWidget(QWidget *parent) : QWidget(parent), ui(new Ui::AlbumListWidget), mAlbumModel(nullptr) { ui->setupUi(this); connect(ui->createAlbumButton, &QPushButton::clicked,this, &AlbumListWidget::createAlbum); } AlbumListWidget::~AlbumListWidget() { delete ui; } //set albumlist model void AlbumListWidget::setModel(AlbumModel* model){ mAlbumModel = model; ui->albumList->setModel(mAlbumModel); } //set albumlist selection model void AlbumListWidget::setSelectionModel(QItemSelectionModel *selectionModel){ ui->albumList->setSelectionModel(selectionModel); } void AlbumListWidget::createAlbum(){ if(!mAlbumModel){ return; } bool ok; //ask user to enter album name QString albumName = QInputDialog::getText(this,"Create a new Album", "Choose a name",QLineEdit::Normal,"New Album",&ok); if(ok && !albumName.isEmpty()){ Album album(albumName); QModelIndex createdIndex = mAlbumModel->addAlbum(album); ui->albumList->setCurrentIndex(createdIndex); } }
[ "kyle.t.beebe@gmail.com" ]
kyle.t.beebe@gmail.com
d25a4346a3667e1df1fbd23a0db3208841208f8a
bdd9f3cdabe0c768641cf61855a6f24174735410
/src/external/3rd/library/libMozilla/include/private/include/necko/nsIHttpProtocolHandler.h
ef62f589b2ef7d65d0f747bc217d355a8819c36f
[]
no_license
SWG-Source/client-tools
4452209136b376ab369b979e5c4a3464be28257b
30ec3031184243154c3ba99cedffb2603d005343
refs/heads/master
2023-08-31T07:44:22.692402
2023-08-28T04:34:07
2023-08-28T04:34:07
159,086,319
15
47
null
2022-04-15T16:20:34
2018-11-25T23:57:31
C++
UTF-8
C++
false
false
15,164
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM c:/mozilla/netwerk/protocol/http/public/nsIHttpProtocolHandler.idl */ #ifndef __gen_nsIHttpProtocolHandler_h__ #define __gen_nsIHttpProtocolHandler_h__ #ifndef __gen_nsIProxiedProtocolHandler_h__ #include "nsIProxiedProtocolHandler.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIHttpProtocolHandler */ #define NS_IHTTPPROTOCOLHANDLER_IID_STR "122c91c0-2485-40ba-89c9-b895934921bc" #define NS_IHTTPPROTOCOLHANDLER_IID \ {0x122c91c0, 0x2485, 0x40ba, \ { 0x89, 0xc9, 0xb8, 0x95, 0x93, 0x49, 0x21, 0xbc }} class NS_NO_VTABLE nsIHttpProtocolHandler : public nsIProxiedProtocolHandler { public: NS_DEFINE_STATIC_IID_ACCESSOR(NS_IHTTPPROTOCOLHANDLER_IID) /** * Get the HTTP advertised user agent string. */ /* readonly attribute ACString userAgent; */ NS_IMETHOD GetUserAgent(nsACString & aUserAgent) = 0; /** * Get the application name. * * @return The name of this application (eg. "Mozilla"). */ /* readonly attribute ACString appName; */ NS_IMETHOD GetAppName(nsACString & aAppName) = 0; /** * Get the application version string. * * @return The complete version (major and minor) string. (eg. "5.0") */ /* readonly attribute ACString appVersion; */ NS_IMETHOD GetAppVersion(nsACString & aAppVersion) = 0; /** * @return The vendor name. */ /* attribute ACString vendor; */ NS_IMETHOD GetVendor(nsACString & aVendor) = 0; NS_IMETHOD SetVendor(const nsACString & aVendor) = 0; /** * @return The vendor sub string. */ /* attribute ACString vendorSub; */ NS_IMETHOD GetVendorSub(nsACString & aVendorSub) = 0; NS_IMETHOD SetVendorSub(const nsACString & aVendorSub) = 0; /** * @return The vendor comment. */ /* attribute ACString vendorComment; */ NS_IMETHOD GetVendorComment(nsACString & aVendorComment) = 0; NS_IMETHOD SetVendorComment(const nsACString & aVendorComment) = 0; /** * @return The product name. */ /* attribute ACString product; */ NS_IMETHOD GetProduct(nsACString & aProduct) = 0; NS_IMETHOD SetProduct(const nsACString & aProduct) = 0; /** * @return A product sub string. */ /* attribute ACString productSub; */ NS_IMETHOD GetProductSub(nsACString & aProductSub) = 0; NS_IMETHOD SetProductSub(const nsACString & aProductSub) = 0; /** * @return A product comment. */ /* attribute ACString productComment; */ NS_IMETHOD GetProductComment(nsACString & aProductComment) = 0; NS_IMETHOD SetProductComment(const nsACString & aProductComment) = 0; /** * Get the current platform. * * @return The platform this application is running on * (eg. "Windows", "Macintosh", "X11") */ /* readonly attribute ACString platform; */ NS_IMETHOD GetPlatform(nsACString & aPlatform) = 0; /** * Get the current oscpu. * * @return The oscpu this application is running on */ /* readonly attribute ACString oscpu; */ NS_IMETHOD GetOscpu(nsACString & aOscpu) = 0; /** * Get the translation of the application. The value for language * is usually a 2-letter code such as "en" and occasionally a * five-character code to indicate a language subtype, such as "zh_CN". */ /* attribute ACString language; */ NS_IMETHOD GetLanguage(nsACString & aLanguage) = 0; NS_IMETHOD SetLanguage(const nsACString & aLanguage) = 0; /** * Get/Set the application comment misc portion. */ /* attribute ACString misc; */ NS_IMETHOD GetMisc(nsACString & aMisc) = 0; NS_IMETHOD SetMisc(const nsACString & aMisc) = 0; }; /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIHTTPPROTOCOLHANDLER \ NS_IMETHOD GetUserAgent(nsACString & aUserAgent); \ NS_IMETHOD GetAppName(nsACString & aAppName); \ NS_IMETHOD GetAppVersion(nsACString & aAppVersion); \ NS_IMETHOD GetVendor(nsACString & aVendor); \ NS_IMETHOD SetVendor(const nsACString & aVendor); \ NS_IMETHOD GetVendorSub(nsACString & aVendorSub); \ NS_IMETHOD SetVendorSub(const nsACString & aVendorSub); \ NS_IMETHOD GetVendorComment(nsACString & aVendorComment); \ NS_IMETHOD SetVendorComment(const nsACString & aVendorComment); \ NS_IMETHOD GetProduct(nsACString & aProduct); \ NS_IMETHOD SetProduct(const nsACString & aProduct); \ NS_IMETHOD GetProductSub(nsACString & aProductSub); \ NS_IMETHOD SetProductSub(const nsACString & aProductSub); \ NS_IMETHOD GetProductComment(nsACString & aProductComment); \ NS_IMETHOD SetProductComment(const nsACString & aProductComment); \ NS_IMETHOD GetPlatform(nsACString & aPlatform); \ NS_IMETHOD GetOscpu(nsACString & aOscpu); \ NS_IMETHOD GetLanguage(nsACString & aLanguage); \ NS_IMETHOD SetLanguage(const nsACString & aLanguage); \ NS_IMETHOD GetMisc(nsACString & aMisc); \ NS_IMETHOD SetMisc(const nsACString & aMisc); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIHTTPPROTOCOLHANDLER(_to) \ NS_IMETHOD GetUserAgent(nsACString & aUserAgent) { return _to GetUserAgent(aUserAgent); } \ NS_IMETHOD GetAppName(nsACString & aAppName) { return _to GetAppName(aAppName); } \ NS_IMETHOD GetAppVersion(nsACString & aAppVersion) { return _to GetAppVersion(aAppVersion); } \ NS_IMETHOD GetVendor(nsACString & aVendor) { return _to GetVendor(aVendor); } \ NS_IMETHOD SetVendor(const nsACString & aVendor) { return _to SetVendor(aVendor); } \ NS_IMETHOD GetVendorSub(nsACString & aVendorSub) { return _to GetVendorSub(aVendorSub); } \ NS_IMETHOD SetVendorSub(const nsACString & aVendorSub) { return _to SetVendorSub(aVendorSub); } \ NS_IMETHOD GetVendorComment(nsACString & aVendorComment) { return _to GetVendorComment(aVendorComment); } \ NS_IMETHOD SetVendorComment(const nsACString & aVendorComment) { return _to SetVendorComment(aVendorComment); } \ NS_IMETHOD GetProduct(nsACString & aProduct) { return _to GetProduct(aProduct); } \ NS_IMETHOD SetProduct(const nsACString & aProduct) { return _to SetProduct(aProduct); } \ NS_IMETHOD GetProductSub(nsACString & aProductSub) { return _to GetProductSub(aProductSub); } \ NS_IMETHOD SetProductSub(const nsACString & aProductSub) { return _to SetProductSub(aProductSub); } \ NS_IMETHOD GetProductComment(nsACString & aProductComment) { return _to GetProductComment(aProductComment); } \ NS_IMETHOD SetProductComment(const nsACString & aProductComment) { return _to SetProductComment(aProductComment); } \ NS_IMETHOD GetPlatform(nsACString & aPlatform) { return _to GetPlatform(aPlatform); } \ NS_IMETHOD GetOscpu(nsACString & aOscpu) { return _to GetOscpu(aOscpu); } \ NS_IMETHOD GetLanguage(nsACString & aLanguage) { return _to GetLanguage(aLanguage); } \ NS_IMETHOD SetLanguage(const nsACString & aLanguage) { return _to SetLanguage(aLanguage); } \ NS_IMETHOD GetMisc(nsACString & aMisc) { return _to GetMisc(aMisc); } \ NS_IMETHOD SetMisc(const nsACString & aMisc) { return _to SetMisc(aMisc); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIHTTPPROTOCOLHANDLER(_to) \ NS_IMETHOD GetUserAgent(nsACString & aUserAgent) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUserAgent(aUserAgent); } \ NS_IMETHOD GetAppName(nsACString & aAppName) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAppName(aAppName); } \ NS_IMETHOD GetAppVersion(nsACString & aAppVersion) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAppVersion(aAppVersion); } \ NS_IMETHOD GetVendor(nsACString & aVendor) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetVendor(aVendor); } \ NS_IMETHOD SetVendor(const nsACString & aVendor) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetVendor(aVendor); } \ NS_IMETHOD GetVendorSub(nsACString & aVendorSub) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetVendorSub(aVendorSub); } \ NS_IMETHOD SetVendorSub(const nsACString & aVendorSub) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetVendorSub(aVendorSub); } \ NS_IMETHOD GetVendorComment(nsACString & aVendorComment) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetVendorComment(aVendorComment); } \ NS_IMETHOD SetVendorComment(const nsACString & aVendorComment) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetVendorComment(aVendorComment); } \ NS_IMETHOD GetProduct(nsACString & aProduct) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetProduct(aProduct); } \ NS_IMETHOD SetProduct(const nsACString & aProduct) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetProduct(aProduct); } \ NS_IMETHOD GetProductSub(nsACString & aProductSub) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetProductSub(aProductSub); } \ NS_IMETHOD SetProductSub(const nsACString & aProductSub) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetProductSub(aProductSub); } \ NS_IMETHOD GetProductComment(nsACString & aProductComment) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetProductComment(aProductComment); } \ NS_IMETHOD SetProductComment(const nsACString & aProductComment) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetProductComment(aProductComment); } \ NS_IMETHOD GetPlatform(nsACString & aPlatform) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPlatform(aPlatform); } \ NS_IMETHOD GetOscpu(nsACString & aOscpu) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOscpu(aOscpu); } \ NS_IMETHOD GetLanguage(nsACString & aLanguage) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLanguage(aLanguage); } \ NS_IMETHOD SetLanguage(const nsACString & aLanguage) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetLanguage(aLanguage); } \ NS_IMETHOD GetMisc(nsACString & aMisc) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMisc(aMisc); } \ NS_IMETHOD SetMisc(const nsACString & aMisc) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetMisc(aMisc); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsHttpProtocolHandler : public nsIHttpProtocolHandler { public: NS_DECL_ISUPPORTS NS_DECL_NSIHTTPPROTOCOLHANDLER nsHttpProtocolHandler(); private: ~nsHttpProtocolHandler(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsHttpProtocolHandler, nsIHttpProtocolHandler) nsHttpProtocolHandler::nsHttpProtocolHandler() { /* member initializers and constructor code */ } nsHttpProtocolHandler::~nsHttpProtocolHandler() { /* destructor code */ } /* readonly attribute ACString userAgent; */ NS_IMETHODIMP nsHttpProtocolHandler::GetUserAgent(nsACString & aUserAgent) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute ACString appName; */ NS_IMETHODIMP nsHttpProtocolHandler::GetAppName(nsACString & aAppName) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute ACString appVersion; */ NS_IMETHODIMP nsHttpProtocolHandler::GetAppVersion(nsACString & aAppVersion) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute ACString vendor; */ NS_IMETHODIMP nsHttpProtocolHandler::GetVendor(nsACString & aVendor) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsHttpProtocolHandler::SetVendor(const nsACString & aVendor) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute ACString vendorSub; */ NS_IMETHODIMP nsHttpProtocolHandler::GetVendorSub(nsACString & aVendorSub) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsHttpProtocolHandler::SetVendorSub(const nsACString & aVendorSub) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute ACString vendorComment; */ NS_IMETHODIMP nsHttpProtocolHandler::GetVendorComment(nsACString & aVendorComment) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsHttpProtocolHandler::SetVendorComment(const nsACString & aVendorComment) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute ACString product; */ NS_IMETHODIMP nsHttpProtocolHandler::GetProduct(nsACString & aProduct) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsHttpProtocolHandler::SetProduct(const nsACString & aProduct) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute ACString productSub; */ NS_IMETHODIMP nsHttpProtocolHandler::GetProductSub(nsACString & aProductSub) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsHttpProtocolHandler::SetProductSub(const nsACString & aProductSub) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute ACString productComment; */ NS_IMETHODIMP nsHttpProtocolHandler::GetProductComment(nsACString & aProductComment) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsHttpProtocolHandler::SetProductComment(const nsACString & aProductComment) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute ACString platform; */ NS_IMETHODIMP nsHttpProtocolHandler::GetPlatform(nsACString & aPlatform) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute ACString oscpu; */ NS_IMETHODIMP nsHttpProtocolHandler::GetOscpu(nsACString & aOscpu) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute ACString language; */ NS_IMETHODIMP nsHttpProtocolHandler::GetLanguage(nsACString & aLanguage) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsHttpProtocolHandler::SetLanguage(const nsACString & aLanguage) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute ACString misc; */ NS_IMETHODIMP nsHttpProtocolHandler::GetMisc(nsACString & aMisc) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsHttpProtocolHandler::SetMisc(const nsACString & aMisc) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /** * At initialization time, the HTTP handler will initialize each service * registered under this category: */ #define NS_HTTP_STARTUP_CATEGORY "http-startup-category" /** * nsIObserver notification corresponding to startup category. Services * registered under the startup category will receive this observer topic at * startup if they implement nsIObserver. The "subject" of the notification * is the nsIHttpProtocolHandler instance. */ #define NS_HTTP_STARTUP_TOPIC "http-startup" /** * Before an HTTP request is sent to the server, this observer topic is * notified. The observer of this topic can then choose to set any additional * headers for this request before the request is actually sent to the server. * The "subject" of the notification is the nsIHttpChannel instance. */ #define NS_HTTP_ON_MODIFY_REQUEST_TOPIC "http-on-modify-request" /** * After an HTTP server response is received, this observer topic is notified. * The observer of this topic can interrogate the response. The "subject" of * the notification is the nsIHttpChannel instance. */ #define NS_HTTP_ON_EXAMINE_RESPONSE_TOPIC "http-on-examine-response" /** * The observer of this topic is notified after the received HTTP response * is merged with data from the browser cache. This means that, among other * things, the Content-Type header will be set correctly. */ #define NS_HTTP_ON_EXAMINE_MERGED_RESPONSE_TOPIC "http-on-examine-merged-response" #endif /* __gen_nsIHttpProtocolHandler_h__ */
[ "swgmaster@india.com" ]
swgmaster@india.com
d9be3afd2360e564ae40c29d1fa1a07e9557d04f
57f2381d526410aa5dc2813e0c147b72a8fe83eb
/src/http/v2/h2defs.h
3279370eff22b628f06b4b6fbd7f794d558ed786
[ "MIT" ]
permissive
zoujiaqing/kuma
201878318cbaa855a4d9ea2430c8c70b5fdd8253
0ca8a7a192815e6ea965b00bd74340c1697a0a72
refs/heads/master
2020-12-30T18:30:02.998360
2016-09-11T03:53:03
2016-09-11T03:53:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,253
h
#ifndef __h2defs_H__ #define __h2defs_H__ #include "http/httpdefs.h" #include <string> #include <vector> KUMA_NS_BEGIN const uint32_t H2_MAX_STREAM_ID = 0x7FFFFFFF; const size_t H2_FRAME_HEADER_SIZE = 9; const size_t H2_PRIORITY_PAYLOAD_SIZE = 5; const size_t H2_RST_STREAM_PAYLOAD_SIZE = 4; const size_t H2_SETTING_ITEM_SIZE = 6; const size_t H2_PING_PAYLOAD_SIZE = 8; const size_t H2_WINDOW_UPDATE_PAYLOAD_SIZE = 4; const size_t H2_WINDOW_UPDATE_FRAME_SIZE = + H2_FRAME_HEADER_SIZE + H2_WINDOW_UPDATE_PAYLOAD_SIZE; const uint8_t H2_FRAME_FLAG_END_STREAM = 0x1; const uint8_t H2_FRAME_FLAG_ACK = 0x1; const uint8_t H2_FRAME_FLAG_END_HEADERS = 0x4; const uint8_t H2_FRAME_FLAG_PADDED = 0x8; const uint8_t H2_FRAME_FLAG_PRIORITY = 0x20; enum H2FrameType : uint8_t { DATA = 0, HEADERS = 1, PRIORITY = 2, RST_STREAM = 3, SETTINGS = 4, PUSH_PROMISE = 5, PING = 6, GOAWAY = 7, WINDOW_UPDATE = 8, CONTINUATION = 9 }; enum H2SettingsId : uint16_t { HEADER_TABLE_SIZE = 1, ENABLE_PUSH = 2, MAX_CONCURRENT_STREAMS = 3, INITIAL_WINDOW_SIZE = 4, MAX_FRAME_SIZE = 5, MAX_HEADER_LIST_SIZE = 6 }; enum class H2Error : int32_t { NOERR = 0x0, PROTOCOL_ERROR = 0x1, INTERNAL_ERROR = 0x2, FLOW_CONTROL_ERROR = 0x3, SETTINGS_TIMEOUT = 0x4, STREAM_CLOSED = 0x5, FRAME_SIZE_ERROR = 0x6, REFUSED_STREAM = 0x7, CANCEL = 0x8, COMPRESSION_ERROR = 0x9, CONNECT_ERROR = 0xa, ENHANCE_YOUR_CALM = 0xb, INADEQUATE_SECURITY = 0xc, HTTP_1_1_REQUIRED = 0xd }; using ParamVector = std::vector<std::pair<uint16_t, uint32_t>>; const std::string H2HeaderMethod(":method"); const std::string H2HeaderScheme(":scheme"); const std::string H2HeaderAuthority(":authority"); const std::string H2HeaderPath(":path"); const std::string H2HeaderStatus(":status"); inline bool isPromisedStream(uint32_t streamId) { return !(streamId & 1); } KUMA_NS_END #endif
[ "jamol@live.com" ]
jamol@live.com
89231d754ac08cd34a036305bae98d026b99c8ce
ef33f5d035eb66b19341bcc42d3b466709f5410a
/judge/A001.h
74e22d2e7cd28b771529e1b1e0b1bc6d296a7158
[]
no_license
thisgoatrising/cpp-quiz
3b5c06ed9a114c5f20205be011ada9f816851bde
2191597943a8ae97f45ee1019366757b197a43ca
refs/heads/master
2023-07-17T20:32:33.042231
2021-08-27T03:03:57
2021-08-27T03:03:57
null
0
0
null
null
null
null
GB18030
C++
false
false
785
h
/* ################################################ . Summary : a small c++ judging tool on windows . Author : foxzzz, i@foxzzz.com, QQ 406609631 . Date : 2019/11/01 ################################################ 【输出“你好,世界!”】 输入 (无) 输出 你好,世界! */ #ifndef __A011__ #define __A011__ #ifdef JUDGE_MODE #include "./judge.h" #define ID "A001" namespace foxzzz { class TheJudge : public LooseJudge { public: TheJudge() : LooseJudge(ID, "输出“你好,世界!”") {} private: //virtual ProcedureCall verify() { // return verifyCode; //} //static void verifyCode() { // std::cout << "你好,世界!"; //} }; LAUNCH_JUDGE(TheJudge) } #endif #endif
[ "i@foxzzz.com" ]
i@foxzzz.com
78ffb410f269a06c918f7477cfd6f164f2c626bb
a9b03f4730534da6e25e8a52ea0cd870db7c28b4
/modules/perception/fusion/base/track_pool_types.h
d03b1a4ce0f491990753e361fab502ac11ef062b
[ "Apache-2.0" ]
permissive
zhuangli1987/apollo
6bcf2ddebb23377e701ec9bf2b56c1ea4632bab9
2210bef1ef5aadfeccb48949c07b31de4e581b25
refs/heads/master
2020-03-28T00:31:50.529228
2018-09-25T01:29:51
2018-09-25T01:31:39
147,425,981
0
0
null
2018-09-04T22:11:18
2018-09-04T22:11:18
null
UTF-8
C++
false
false
1,505
h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef PERCEPTION_FUSION_BASE_TRACK_POOL_TYPES_H_ #define PERCEPTION_FUSION_BASE_TRACK_POOL_TYPES_H_ #include "modules/perception/base/concurrent_object_pool.h" #include "modules/perception/fusion/base/track.h" namespace apollo { namespace perception { namespace fusion { struct TrackInitializer { void operator()(Track* track) const { track->Reset(); } }; static const size_t kTrackPoolSize = 3000; // pool typedef collections, // developer should add pool type to the PoolInitialize function in .cc file typedef base::ConcurrentObjectPool<Track, kTrackPoolSize, TrackInitializer> TrackPool; } // namespace fusion } // namespace perception } // namespace apollo #endif // PERCEPTION_FUSION_BASE_TRACK_POOL_TYPES_H_
[ "ycool@users.noreply.github.com" ]
ycool@users.noreply.github.com
8737054fe0945fc456618d95bc533b06381a58e9
620ba8fa8064e2947f7a591d1b2ee29eededb0b0
/src/mec_http_server/request_handler.hpp
5d9713571af62e1341e8821afda6f6f4790a4ec7
[]
no_license
budavarapu/xilinx_mec_poc
a87f414c3332d80638b8008fdb43562fd1ef07dc
b3af38f37a810a4a23a1859167e99f972ea24b8f
refs/heads/master
2022-12-05T10:20:22.609889
2019-09-13T17:51:13
2019-09-13T18:08:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
993
hpp
#ifndef __REQUEST_HANDLER_HPP__ #define __REQUEST_HANDLER_HPP__ #include <string> namespace http { namespace server { struct reply; struct request; /// The common handler for all incoming requests. class request_handler { public: //禁止拷贝构造函数和赋值重载 request_handler(const request_handler&) = delete; request_handler& operator=(const request_handler&) = delete; /// Construct with a directory containing files to be served. explicit request_handler(const std::string& doc_root); /// Handle a request and produce a reply. void handle_request(const request& req, reply& rep); private: /// The directory containing the files to be served. std::string doc_root_;//文件目录 /// Perform URL-decoding on a string. Returns false if the encoding was /// invalid. static bool url_decode(const std::string& in, std::string& out);//URL分析 }; } // namespace server } // namespace http #endif // HTTP_REQUEST_HANDLER_HPP
[ "ipadaxe.cs07g@nctu.edu.tw" ]
ipadaxe.cs07g@nctu.edu.tw
d18ef4f1f4619831d4fdfc18655d180f8ba96bed
372f5678018b9cac4f2c0900b4443664ce293fae
/Tempest/weirdSkins.h
bf9c43633e07dee467110a6ba848c0622591806e
[]
no_license
ClementRivaille/Avant_la_tempete
dfcf60cbe65e35b04e72576ab5cecc9e683550e2
2d349d2f586e5e31eef7186c0371fa3c4be813de
refs/heads/master
2020-06-03T01:39:08.021754
2014-02-19T21:53:46
2014-02-19T21:53:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,508
h
#ifndef WEIRD_SKINS_H #define WEIRD_SKINS_H 1 #include "AReVi/arObject.h" namespace hLib { class Skeleton; class Joint; } namespace AReVi { class Scene3D; class Object3D; class Base3D; class Cylinder3D; class Skin0 : public ArObject { public: AR_CLASS(Skin0) AR_CONSTRUCTOR(Skin0) virtual void setScene(ArRef<Scene3D> scene); virtual bool createGeometries( ArRef<hLib::Skeleton> skeleton ); virtual void setVisible(bool visible); virtual bool getVisible() const; virtual void update( double dt ); //joint selection virtual bool selectJoint( const StlString & name); //filtering the selected joints virtual void setFiltering(bool active); protected: struct SelectedJoint { ArPtr<hLib::Joint> joint; StlVector<ArPtr<Base3D> > filterMemory; ArRef<Base3D> filterResult; }; virtual void _computeFilter(SelectedJoint & selectedJoint); protected: StlVector<ArRef<Object3D> > _objects; bool _visible; ArPtr<Scene3D> _scene; StlVector<StlString> _selectedJointsNames; StlVector<SelectedJoint> _selectedJoints; bool _filter; unsigned int _nextFilter; unsigned int _filterSize; ArPtr<hLib::Skeleton> _skeleton; }; class TrihedronSkin : public Skin0 { public: AR_CLASS(TrihedronSkin) AR_CONSTRUCTOR(TrihedronSkin) virtual bool createGeometries( ArRef<hLib::Skeleton> skeleton ); }; class SpheresSkin : public Skin0 { public: AR_CLASS(SpheresSkin) AR_CONSTRUCTOR(SpheresSkin) virtual void setParameters( double radiusScale, double shapeScale = 1.0, unsigned int count = 50, double radiusMin = 1.0, double radiusMax = 2.0 ); virtual bool createGeometries( ArRef<hLib::Skeleton> skeleton ); virtual void update( double dt ); protected: double _radiusScale; double _shapeScale; unsigned int _count; double _radiusMin; double _radiusMax; }; class CylindersSkin : public Skin0 { public: AR_CLASS(CylindersSkin) AR_CONSTRUCTOR(CylindersSkin) virtual void setRadius( double radius = 0.1); virtual double getRadius() const; virtual bool createGeometries( ArRef<hLib::Skeleton> skeleton ); virtual void update( double dt ); protected: struct Cylinder { ArRef<Cylinder3D> shape; ArRef<Object3D> object; ArPtr<hLib::Joint> joint; }; virtual void _updateCylinder(Cylinder & cylinder); StlVector<Cylinder> _cylinders; double _radius; }; } //namespace AReVi #endif //WEIRD_SKINS
[ "rivaille.clement@orange.fr" ]
rivaille.clement@orange.fr
2c6a679dbf0fa1c527f04a5e42d5aaa86a8b5074
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/mergedcomponents/wlnotify/schedlog.cxx
cf7f2232148843cec826b34ea504254b38afc65c
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
4,973
cxx
//+---------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1993. // // File: schedlog.c // // Contents: Task Scheduler StartShell notification // // Classes: None. // // Functions: // SchedStartShell - queue the work to the WinLogon thread pool. // DoSchedStartShell - notify Sched service that a user logged on. // // History: 07-Mar-01 JBenton Created // //----------------------------------------------------------------------------- // // Note: We don't build/publish a lib here as suggested in wlnotify.cxx. // Rather we include the source file here because there is only a single // simple function. // // Note: We are using the StartShell event because the Scheduler service // expects the user's explorer session to be running. // #include <windows.h> #include <winwlx.h> #define SCHED_SERVICE_NAME TEXT("Schedule") // // The following LOGON and LOGOFF defines must be kept in sync with // the definition in %sdxroot%\admin\services\sched\inc\common.hxx // #define SERVICE_CONTROL_USER_LOGON 128 #define SERVICE_CONTROL_USER_LOGOFF 133 DWORD WINAPI SchedStartShell(LPVOID lpvParam); DWORD WINAPI DoSchedStartShell(LPVOID lpvParam); DWORD WINAPI SchedEventLogOff(LPVOID lpvParam) // // // Routine Description: // // Send a logoff notification to the Task Scheduler service // via a user defined Service Control. // // Arguments: // // lpvParam - Winlogon notification info (unused as of yet) // // Return Value: // // Extended error status from Service control functions. // { DWORD status = ERROR_SUCCESS; SC_HANDLE hSC = NULL; SC_HANDLE hSvc = NULL; BOOL bSucceeded = FALSE; SERVICE_STATUS ServiceStatus; hSC = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); if (hSC == NULL) { return GetLastError(); } hSvc = OpenService(hSC, SCHED_SERVICE_NAME, SERVICE_USER_DEFINED_CONTROL); if (hSvc == NULL) { CloseServiceHandle(hSC); return GetLastError(); } bSucceeded = ControlService(hSvc, SERVICE_CONTROL_USER_LOGOFF, &ServiceStatus); if( !bSucceeded ) { status = GetLastError(); } CloseServiceHandle(hSvc); CloseServiceHandle(hSC); return status; } DWORD WINAPI SchedStartShell(LPVOID lpvParam) { DWORD dwSessionId = 0; // // Don't send logon notification to Terminal Server sessions. // if (ProcessIdToSessionId(GetCurrentProcessId(), &dwSessionId)) { if (dwSessionId == 0) { // // Queue the work to the thread pool since we may // be looping on the notification. // if (QueueUserWorkItem(DoSchedStartShell, lpvParam, WT_EXECUTELONGFUNCTION)) return ERROR_SUCCESS; } else return ERROR_SUCCESS; } return GetLastError(); } DWORD WINAPI DoSchedStartShell(LPVOID lpvParam) // // // Routine Description: // // Send a logon notification to the Task Scheduler service // via a user defined Service Control. // // Arguments: // // lpvParam - Winlogon notification info (unused as of yet) // // Return Value: // // Extended error status from Service control functions. // { DWORD status = ERROR_SUCCESS; PWLX_NOTIFICATION_INFO pTempInfo = (PWLX_NOTIFICATION_INFO) lpvParam; SC_HANDLE hSC = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); if (hSC == NULL) { return GetLastError(); } SC_HANDLE hSvc = OpenService(hSC, SCHED_SERVICE_NAME, SERVICE_USER_DEFINED_CONTROL); if (hSvc == NULL) { CloseServiceHandle(hSC); return GetLastError(); } BOOL fSucceeded; const int NOTIFY_RETRIES = 20; const DWORD NOTIFY_SLEEP = 4000; // // Use a retry loop to notify the service. This is done // because, if the user logs in quickly, the service may not // be started when the shell runs this instance. // for (int i = 1; ; i++) { SERVICE_STATUS Status; fSucceeded = ControlService(hSvc, SERVICE_CONTROL_USER_LOGON, &Status); if (fSucceeded) { break; } if (i >= NOTIFY_RETRIES) { status = GetLastError(); break; } Sleep(NOTIFY_SLEEP); } CloseServiceHandle(hSvc); CloseServiceHandle(hSC); return status; }
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
c3fc9ae02b8d4c467d99b39c78e8e47925f2555f
ff46de7dc37159999e02ae2c430124b34bdd7667
/src/rv.cpp
b4f7f2265247b0ee2b690d59f3e73a0b546d3ea0
[ "BSD-2-Clause-Views" ]
permissive
Network-Dynamics/adevs
f323e11d95f774c886fccc6661e5de8a3bc04d82
6c83e0ecdb27d1d909fea05788a2aa9cf4b1b4bb
refs/heads/master
2021-01-18T12:10:58.463806
2014-01-10T20:47:49
2014-01-10T20:47:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,269
cpp
/** * Copyright (c) 2013, James Nutaro * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. * * Bugs, comments, and questions can be sent to nutaro@gmail.com */ #define _CRT_RAND_S #include <cstdlib> #include "adevs_rand.h" #include <cmath> using namespace adevs; #ifndef PI #define PI 3.14159265358979323846 #endif static double cof[6] = { 76.18009173, -86.50532033, 24.01409822, -1.231739516, 0.120858003e-2, -0.536382e-5 }; // crand random number generator unsigned long crand::next_long() { #ifdef _WIN32 rand_s(&seedp); return seedp; #else return rand_r(&seedp); #endif } // constructor, taking the seeds of the stream adevs::rv::rv(unsigned long seed) { _impl = new crand(seed); } adevs::rv::rv(random_seq* impl) { _impl = impl; } adevs::rv::rv(const rv& src) { _impl = src._impl->copy(); } const adevs::rv& rv::operator=(const rv& src) { delete _impl; _impl = src._impl->copy(); return *this; } void adevs::rv::set_seed(unsigned long seed) { _impl->set_seed (seed); } double adevs::rv::triangular(double a, double b, double c) { double x = _impl->next_dbl (); if (x <= 0.5) return (2.0*(b-a)*x + a); return (2.0*(b-c)*(x-0.5) + c); } double adevs::rv::uniform(double a, double b) { return (_impl->next_dbl() * (b - a) + a); } double adevs::rv::normal(double m, double s) { return m + (sqrt (-2.0 * log (_impl->next_dbl())) * cos (PI * (2.0 * _impl->next_dbl() - 1.0))) * s; } adevs::rv::~rv() { delete _impl; } // return a negative exponentially distributed random number with // the mean as parameter double adevs::rv::exponential(double a) { if (a < 0) { err(ERREXPONENT); } return (a * (-log(_impl->next_dbl()))); } // return a hyperexponentially distributed random number with // the means as parameters to two exponentially distributed variates, // the first with a chance of p of being generated, the second with a // chance of 1-p. double adevs::rv::hyperexponential(double p,double a,double b) { if ( (a < 0) || (b < 0) ) { err(ERREXPONENT); return(0); } else if ( (p <= 0) || (p >= 1) ) { err(PROBVAL); return(0); } else if (probability(p)) { return (a * (-log(_impl->next_dbl()))); } else { return (b * (-log(_impl->next_dbl()))); } } // return a laplace number with the given parameter double adevs::rv::laplace(double a) { if (probability(0.5)) { return (a * ( -log(_impl->next_dbl()) )); } else { return (a * ( log(_impl->next_dbl()) )); } } // return random variable from the erlang distribution double adevs::rv::erlang(unsigned int n,double a) { if (a < 0) { err(ERRERLANG); return(0.0); } else { // use gamma distribution return (gamma((double)n,a)); } } // return random number from the gamma distribution double adevs::rv::gamma(double a,double b) { // rejection method only for a > 1 double xx,yy; if ((a < 0.0) || (b < 0.0)) { err(ERRGAMMA); } if (a < 1.0) { do { xx = pow(_impl->next_dbl(),1.0/a); yy = pow(_impl->next_dbl(),1.0/(1.0-a)); } while (xx+yy > 1.0); xx = xx/(xx+yy); yy = exponential(1); return xx*yy/b; } if (a == 1.0) { return (exponential (1.0) / b); } /* For this method I refer reader to Computer Generation of Gamma Random Variables Tadikamalla, P,R. Management Science / Operations Research Vol 21 Iss 5, May 1978 */ int cnt; int m = (int)floor(a); double U, X, T; double p = a - m; do { U=1; for( cnt = 0; m > cnt; cnt++) { U = U*_impl->next_dbl(); } X = -1*log(U)*(a/m); T = pow((X/a),p)*exp(-1*p*((X/a)-1)); } while( _impl->next_dbl() > T ); return(X*b); } // return a random variable from a chi square distribution with // n degrees of freedom double adevs::rv::chisquare(unsigned int n) { return gamma(0.5*n,0.5); } // return random variable from a beta distribution double adevs::rv::beta(double a,double b) { if (b == 0.0) { err(ERRBETA); } double zz = gamma(a,1.0); return (zz/(zz+gamma(b,1.0))); } // return it from the student distribution double adevs::rv::student(unsigned int n) { return (normal(0.0,1.0)/sqrt(chisquare(n)/n)); } // return a random number from a lognormal distribution double adevs::rv::lognormal(double a,double b) { if (b < 0.0) { err(ERRLOGNORM); } return exp(normal(a,b)); } // return it from a f distribution. double adevs::rv::fdistribution(unsigned int n,unsigned int m) { return ( (m * chisquare(n)) / (n * chisquare(m)) ); } // random number from a weibull distribution double adevs::rv::weibull (double a,double b) { return pow(exponential(a),(1.0/b)); } // get it from a poisson distribution with the given mean double adevs::rv::poisson(double a) { // can we use the direct method double sq=-1.0,alxm=-1.0,g=-1.0,oldm = -1.0; double em,t,yy; if (a < 12.0) { if (a != oldm) { oldm = a; g = exp(-a); } em = -1.0; t = 1.0; do { em += 1.0; t *= _impl->next_dbl(); } while (t > g); } // use the rejection method else { if (a != oldm) { oldm = a; sq = sqrt(2.0 * a); alxm = log(a); g = a*alxm-lngamma(a + 1.0); } do { do { // y is a deviate from a Lorentzian comparison function yy = tan (PI * _impl->next_dbl()); em = sq * yy + a; } while (em < 0.0); em = floor(em); t = 0.9 * (1.0 + yy * yy) * exp(em * alxm - lngamma(em + 1.0) - g); } while (_impl->next_dbl() > t); } return em; } // return a variate from the geometric distribution with event // probability p double adevs::rv::geometric(double p) { if ((p <= 0.0) || (p >= 1.0)) { err(PROBVAL); } return (ceil(log(_impl->next_dbl())/log(1.0 - p))); } // return a variate from the hypergeometric distribution with m the // population, p the chance on success and n the number of items drawn double adevs::rv::hypergeometric(unsigned int m,unsigned int n,double p) { if ((p <= 0.0) || (p >= 1.0)) { err(PROBVAL); } else if (m < n) { err(ERRHYPGEO); } double g = p*m; // the success items double c = m-g; // the non-success items int k=0; for (unsigned int i=0;i<n;i++) // n drawings { if (_impl->next_dbl() <= g/m) // if a success { k++; // success g--; // decrease right items } else { c--; // decrease wrong items } m--; // decrease total } return k; // return deviate } // get it from the binomial distribution with event probability p // and n the number of trials double adevs::rv::binomial(double p,unsigned int n) { unsigned int j; int nold = -1; double am,em,g,angle,prob,bnl,sq,t,yy; double pold = -1.0; double pc,plog,pclog,en,oldg; if ((p <= 0.0) || (p >= 1.0)) { err(PROBVAL); } if (p <= 0.5 ) { prob = p ; } else { prob = 1.0 - p ; } am = n * prob; if (n < 25) { bnl = 0.0; for (j = 1;j <= n;j++) { if (_impl->next_dbl() < prob) { bnl += 1.0; } } } else if (am < 10) { g = exp(-am); t = 1.0; for (j = 0;j <= n;j++) { t = t * _impl->next_dbl(); if (t < g) break; } if (j <= n) { bnl = j; } else { bnl = n; } } else { if (n != nold) { en = n; oldg = lngamma(en + 1.0); nold = n; } if (prob != pold) { pc = 1.0 - prob; plog = log(prob); pclog = log(pc); pold = prob; } sq = sqrt( 2.0 * am * pc ); do { do { angle = PI * _impl->next_dbl(); yy = tan(angle); em = sq * yy + am; } while (em < 0.0 || em >= (en + 1.0)); em = floor(em); t = 1.2 * sq * (1.0 + yy * yy) * exp(oldg - lngamma(em + 1.0) - lngamma(en - em + 1.0) + em * plog + (en - em) * pclog); } while (_impl->next_dbl() > t); bnl = em; } if (prob != p) { bnl = n - bnl; } return bnl; } // return a random variable with probabilty of success equal to p // and n as the number of successes double adevs::rv::negativebinomial(double p,unsigned int n) { if ((p <= 0.0) || (p >= 1.0)) { err(PROBVAL); } return (poisson(gamma(n,p/(1.0-p)))); } double adevs::rv::lngamma(double xx) { double x = xx - 1.0; double tmp = x + 5.5; tmp -= (x + 0.5) * log(tmp); double ser = 1.0; for (int j = 0;j < 6;j++) { x += 1.0; ser += cof[j] / x; } return (-tmp + log(2.50662827465 * ser)); } // return a random variable drawn from the triangular distribution double adevs::rv::triangular(double a) { if ((a < 0.0) || (a > 1.0)) { err(ERRTRIANG); } double xx = _impl->next_dbl(); double yy = _impl->next_dbl(); if (xx > a) { return ( 1.0 - (( 1.0 - a) * sqrt(yy)) ); } else { return (sqrt(yy) * a); } } // return OK with probability p and FALSE with probability 1-p int adevs::rv::probability(double p) { if ((p < 0.0) || (p > 1.0)) { err(PROBVAL); } return (p >= _impl->next_dbl()); } void adevs::rv::err(errorType n) { static const char* errmsg[] = { "negative simulation duration", "negative count", "scheduled events list empty", "cannot have negative time delay", "cannot add NULL event to the queue", "cannot remove an event from an empty queue", "illegal number of columns in histogram", "illegal histogram mode", "probability values must be in range 0 to 1", "must have upper limit > lower limit in uniform distribution", "negative standard deviation in normal distribution", "negative standard deviation in log-normal distribution", "mode out of range in triangular distribution", "value of arguments less than zero", "argument equal to zero in beta function", "negative mean for exponential", "negative mean for erlang", "population size less then number drawn in hypergeometric", "NULL event", "NULL histogram", "simulation object not created or created after other objects", "illegal analysis mode", "illegal histogram form", "cannot open the file", "cannot find a file", "fraction world / screen differs between width and height", "wrong confidence level", "wrong initialization of scan flag", "wrong initialization of suppress flag", "seeds for the generator out of range" }; throw adevs::exception(errmsg[n]); } unsigned long adevs::rv::next_long() { return( _impl->next_long() ); }
[ "smiz@153d293f-9360-418f-87de-c6d3afdd7922" ]
smiz@153d293f-9360-418f-87de-c6d3afdd7922
5bb3061f2b6bcb0f2c91461e6511411d1521c08c
ec363c99c87dce68796441708f7f57818c697351
/fmBSP/src/serial_bytes/SerialBytes.h
e07e27a662dab7e857525855ae4a3ecb074256d5
[]
no_license
Prrrr/FroboMind
f0319acf7da7b2be0aa20bef1fe6b4be6d32c4f5
ad9d8873c6639ac3fbc0435f94b57efa71085a81
refs/heads/master
2021-01-17T22:50:43.941083
2012-06-28T02:42:52
2012-06-28T02:42:52
3,396,151
0
0
null
null
null
null
UTF-8
C++
false
false
1,016
h
/* * SerialBytes.h * * Created on: Feb 20, 2012 * Author: Morten Ege Jensen */ #ifndef SERIALBYTES_H_ #define SERIALBYTES_H_ #include <boost/asio.hpp> #include <boost/system/error_code.hpp> #include <boost/system/system_error.hpp> #include <boost/thread.hpp> #include <boost/asio/read.hpp> #include <ros/ros.h> #include <fmMsgs/serial_bin.h> #include <vector> using namespace std; class SerialBytes { private: // BOOST boost::asio::io_service io_; boost::asio::serial_port serial_; // ROS fmMsgs::serial_bin serial_msg; ros::Publisher serial_pub; ros::Subscriber serial_sub; // TODO: This should not be a constant size vector<uint8_t> buffer; //boost::array<uint8_t, 7> buffer; int baudrate; int bytes; void writeHandler(const fmMsgs::serial_bin::ConstPtr& msg); void readHandler(const boost::system::error_code& error, size_t bytes_transferred); bool openDevice(string dev, int baud); void readSome(); public: SerialBytes(); virtual ~SerialBytes(); }; #endif /* SERIALBYTES_H_ */
[ "ege@ege-VirtualBox.(none)" ]
ege@ege-VirtualBox.(none)
b598f17a448182f848a0297a3e31623784dd9d99
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/old_hunk_543.cpp
0198d5a60c782f90e5d3079c8bdd3f73102cc704
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
166
cpp
nr_deltas++; if (entry->type < 0) die("unable to get type of object %s", sha1_to_hex(entry->idx.sha1)); } else { if (entry->type < 0) { /*
[ "993273596@qq.com" ]
993273596@qq.com
49691353b9cecf763a70e84882d6756347247ba0
86432b51b07eae85712668a8576d4b172220105a
/packages/reel-xxv/tmp/usr/share/xxv-1.7/skins/lcars/status.inc
11667b421e0cf9a4c2ce1b381cbfe7fd76a6dbe8
[]
no_license
hfuerst/Reelvdr-vdr2.2-Ubuntu16.04
e6ddcd50c9f5cf8fe39e63406b08f1e3d6bdd181
a87c2bf4f4f201d29d06202651a0d0b12f77ae26
refs/heads/master
2020-04-07T00:29:04.782748
2017-07-11T17:40:06
2017-07-11T17:40:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
19
inc
../stone/status.inc
[ "frank.musbach@web.de" ]
frank.musbach@web.de
fe1bc331669b9c6d439ee0b6344dbfb17b1a9741
9e8dd3691b77b3739f670f1cbf5df887a54d96f6
/Enemy.hpp
9511d8d7f23177f38262fcc65e997ac0d35ddf79
[]
no_license
antoniorv6/JoustGame
d8ef0be7767f80fae8cdb1577dd501ce40703cbd
3b8a43b416bc2158695aafac9d028af6f93da759
refs/heads/master
2020-03-09T10:36:10.519155
2018-04-13T08:47:18
2018-04-13T08:47:18
128,740,810
1
0
null
null
null
null
UTF-8
C++
false
false
2,153
hpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Enemy.hpp * Author: antonio * * Created on 17 de febrero de 2018, 12:33 */ #pragma once #include <SFML/Graphics.hpp> #include "Juego.hpp" #include "DEFINICIONES.hpp" #include <vector> #include <SFML/Audio.hpp> namespace Anto { class Enemy { public: Enemy(EstructuraJuegoData datos, int tipo, int plataforma); ~Enemy(); void Draw(); void Update(float dt); void CambiaDireccion(int newdir); void AnimarMovimiento(float dt); void AnimarMuerte(float dt); void CheckSalida(); int GetActualState(); void Fly(); void Break(); void ColisionPlataformas(std::vector<sf::Sprite> plataforma); void TrataColision(sf::Sprite sprite_plat); void SpawnEnemigo(int tipo); void Aparecer(); const sf::Sprite &GetSprite() const; void Decidir(); void Flapea(int rep); void Morir(); void Respawn(); int GetPunctuation(); private: EstructuraJuegoData _datos; sf::Sprite _spriteprinc; int tipo; int _direccion; float _direccion_correr; std::vector<sf::IntRect> _framesAnimacion; std::vector<sf::IntRect> _framesAparicion; std::vector<sf::IntRect> _framesMuerte; unsigned int _iteradorAnimacion; unsigned int _iteradorAparicion; unsigned int _iteradorMuerte; int _enemyState; sf::Rect<float> _colisionador; sf::Clock aniClock; sf::Texture _textura; sf::Clock _cambio_lado; sf::Clock _flap_timer; sf::Clock _appearanim; sf::Sprite _aparicion; int punctuation; sf::SoundBuffer flap_buffer; sf::Sound flap_sound; }; }
[ "antoniorv6@gmail.com" ]
antoniorv6@gmail.com
2deb4f2e2f17c9c54a697a9ed50e166520c0d2ec
3060cdd9bea344b8d59729298184b4e75092d22a
/NaoQt/src/Archives/CPKReader.cpp
d63efb080a3f81ebcbc9c9aebd120d27870987f7
[]
no_license
TypeA2/NaoQt
cad95593f88a0d1b6a76fc1bc77570b5007d62fb
766af11fc25ed83095324461484fe6a05cf00b8e
refs/heads/master
2020-03-30T21:44:20.743897
2019-01-15T20:10:58
2019-01-15T20:10:58
151,640,358
0
0
null
null
null
null
UTF-8
C++
false
false
2,443
cpp
#include "Archives/CPKReader.h" #include "Archives/UTFReader.h" #include <QIODevice> // --===-- Constructor --===-- CPKReader::CPKReader(QIODevice* in) : m_device(in) { _readContents(); } // --===-- Static Constructor --===-- CPKReader* CPKReader::create(QIODevice* input) { if (!input->isOpen() || !input->isReadable() || input->isSequential() || input->read(4) != QByteArray("CPK ", 4) || !input->seek(0)) { return nullptr; } return new CPKReader(input); } // --===-- Getters --===-- QVector<CPKReader::FileInfo> CPKReader::files() const { return m_files.values().toVector(); } QVector<QString> CPKReader::dirs() const { return m_dirs.values().toVector(); } // --===-- Parsing --===-- void CPKReader::_readContents() { m_device->seek(16); UTFReader* cpkReader = new UTFReader(UTFReader::readUTF(m_device)); if (cpkReader->getData(0, "TocOffset").isValid()) { quint64 tocOffset = cpkReader->getData(0, "TocOffset").toULongLong(); if (tocOffset > 2048) { tocOffset = 2048; } quint64 offset; if (!cpkReader->getData(0, "ContentOffset").isValid()) { offset = tocOffset; } else if (cpkReader->getData(0, "ContentOffset").toULongLong() < tocOffset) { offset = cpkReader->getData(0, "ContentOffset").toULongLong(); } else { offset = tocOffset; } m_device->seek(cpkReader->getData(0, "TocOffset").toULongLong() + 16); UTFReader* files = new UTFReader(UTFReader::readUTF(m_device)); for (quint16 i = 0; i < files->rowCount(); ++i) { FileInfo entry = { "TOC", files->getData(i, "FileName").toString(), files->getData(i, "DirName").toString(), files->getData(i, "UserString").toString(), files->getData(i, "FileOffset").toULongLong(), offset, files->getData(i, "FileSize").toULongLong(), files->getData(i, "ExtractSize").toULongLong(), files->getData(i, "ID").toUInt() }; m_files.insert((!entry.dir.isEmpty() ? entry.dir + "/" : "") + entry.name, entry); if (!m_dirs.contains(entry.dir)) { m_dirs.insert(entry.dir); } } files->deleteLater(); } delete cpkReader; }
[ "nuanlim29@gmail.com" ]
nuanlim29@gmail.com
374d8476df1f2886b409c9f9d93a40d7b4d6b2f2
aabad3ea455517c28f50bd46ca3435291892a067
/LL/removeDuplicatesFromSortedLL.cpp
9f0b7a2556f03c29bf0a50b27c415d43e3dd6f56
[]
no_license
rohit-100/IP
43dcac05d3a6af7c5009b62186a26981df7cc1d8
49b7afc40e491ad7feb08690e363f53b9e58bc85
refs/heads/master
2020-06-24T23:37:12.177719
2019-07-30T05:58:14
2019-07-30T05:58:14
199,127,100
0
0
null
null
null
null
UTF-8
C++
false
false
972
cpp
#include<bits/stdc++.h> using namespace std; struct linkedList { int data; struct linkedList *next; linkedList(int data){ this->data = data; this->next = NULL; } }; linkedList *get(std::vector<int> &v){ linkedList *root = NULL; for(int x:v){ if(root == NULL){ root = new linkedList(x); continue; } linkedList *temp = root; while(temp->next != NULL)temp = temp->next; temp->next= new linkedList(x); } return root; } void print(linkedList *head){ while(head != NULL){ cout<<head->data<<" "; head = head->next; } cout<<"\n"; } void removeDuplicates(linkedList *head){ while(head != NULL){ int temp = head->data; linkedList *nextDisticnt = head; while(nextDisticnt != NULL and temp == nextDisticnt->data)nextDisticnt=nextDisticnt->next; head->next = nextDisticnt; head = nextDisticnt; } } int main(){ std::vector<int> v = {9,9}; linkedList *root = get(v); removeDuplicates(root); print(root); }
[ "rohitkumarsaw21@gmail.com" ]
rohitkumarsaw21@gmail.com
d13e0c75ab1f78a86e9228d995499015cda47403
0dfb5613ebedc4abc15a58057052bcc02be795d7
/applications/io_board/targets/freertos.armv7m.lpc1768-mbed/config.hxx
029a4d838e2221eb90222ef77dc8020b5b442771
[ "BSD-2-Clause" ]
permissive
dpharris/openmrn-1
31ceb27a46836199bfdc28d85fff080f7614926a
789d062d41fbe1363a88d2e0f1c73b1417c0016f
refs/heads/master
2021-01-16T21:30:39.050143
2015-11-28T19:29:32
2015-11-28T19:29:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,933
hxx
#ifndef _APPLICATIONS_IO_BOARD_TARGET_CONFIG_HXX_ #define _APPLICATIONS_IO_BOARD_TARGET_CONFIG_HXX_ #include "nmranet/ConfiguredConsumer.hxx" #include "nmranet/ConfiguredProducer.hxx" #include "nmranet/ConfigRepresentation.hxx" #include "nmranet/MemoryConfig.hxx" namespace nmranet { /// Defines the identification information for the node. The arguments are: /// /// - 4 (version info, always 4 by the standard /// - Manufacturer name /// - Model name /// - Hardware version /// - Software version /// /// This data will be used for all purposes of the identification: /// /// - the generated cdi.xml will include this data /// - the Simple Node Ident Info Protocol will return this data /// - the ACDI memory space will contain this data. extern const SimpleNodeStaticValues SNIP_STATIC_DATA = { 4, "OpenMRN", "Test IO Board - mbed LPC1768", "mbed LPC1768", "1.01"}; #define NUM_OUTPUTS 4 #define NUM_INPUTS 2 /// Declares a repeated group of a given base group and number of repeats. The /// ProducerConfig and ConsumerConfig groups represent the configuration layout /// needed by the ConfiguredProducer and ConfiguredConsumer classes, and come /// from their respective hxx file. using AllConsumers = RepeatedGroup<ConsumerConfig, NUM_OUTPUTS>; using AllProducers = RepeatedGroup<ProducerConfig, NUM_INPUTS>; /// Defines the main segment in the configuration CDI. This is laid out at /// origin 128 to give space for the ACDI user data at the beginning. CDI_GROUP(IoBoardSegment, Segment(MemoryConfigDefs::SPACE_CONFIG), Offset(128)); /// Each entry declares the name of the current entry, then the type and then /// optional arguments list. CDI_GROUP_ENTRY(consumers, AllConsumers, Name("Output LEDs")); CDI_GROUP_ENTRY(producers, AllProducers, Name("Input buttons")); CDI_GROUP_END(); /// This segment is only needed temporarily until there is program code to set /// the ACDI user data version byte. CDI_GROUP(VersionSeg, Segment(MemoryConfigDefs::SPACE_CONFIG), Name("Version information")); CDI_GROUP_ENTRY(acdi_user_version, Uint8ConfigEntry, Name("ACDI User Data version"), Description("Set to 2 and do not change.")); CDI_GROUP_END(); /// The main structure of the CDI. ConfigDef is the symbol we use in main.cxx /// to refer to the configuration defined here. CDI_GROUP(ConfigDef, MainCdi()); /// Adds the <identification> tag with the values from SNIP_STATIC_DATA above. CDI_GROUP_ENTRY(ident, Identification); /// Adds an <acdi> tag. CDI_GROUP_ENTRY(acdi, Acdi); /// Adds a segment for changing the values in the ACDI user-defined /// space. UserInfoSegment is defined in the system header. CDI_GROUP_ENTRY(userinfo, UserInfoSegment); /// Adds the main configuration segment. CDI_GROUP_ENTRY(seg, IoBoardSegment); /// Adds the versioning segment. CDI_GROUP_ENTRY(version, VersionSeg); CDI_GROUP_END(); } // namespace nmranet #endif // _APPLICATIONS_IO_BOARD_TARGET_CONFIG_HXX_
[ "balazs.racz@gmail.com" ]
balazs.racz@gmail.com
9a40a8ed540f494d4486e8b35e0788941b06ad13
b13ba84041ddf2bc2aa7b1e561a2f23c251f563c
/Rpr/WrapObject/Materials/ImageMaterialObject.cpp
85c4dff4e2c118eb173af849d1717c04db9c9517
[ "MIT" ]
permissive
DINKIN/RadeonProRender-Baikal
0a42c7619dbd5aacdbf0cf5067ffb5a9ca4fb198
daf7b4cc110b50e8c3cbd8cee2e9263ad0b6758a
refs/heads/master
2021-08-24T11:06:43.528368
2017-12-09T12:13:07
2017-12-09T12:13:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,197
cpp
/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************/ #include <OpenImageIO/imageio.h> #include <map> #include <memory> #include "math/int2.h" #include "SceneGraph/texture.h" #include "SceneGraph/material.h" #include "SceneGraph/IO/image_io.h" #include "SceneGraph/iterator.h" #include "ImageMaterialObject.h" #include "WrapObject/Exception.h" using namespace RadeonRays; using namespace Baikal; ImageMaterialObject::ImageMaterialObject(rpr_image_format const in_format, rpr_image_desc const * in_image_desc, void const * in_data) : MaterialObject(Type::kImage) { //tex size int2 tex_size(in_image_desc->image_width, in_image_desc->image_height); //texture takes ownership of its data array //so need to copy input data int pixels_count = tex_size.x * tex_size.y; //bytes per pixel int pixel_bytes = in_format.num_components; int component_bytes = 1; Texture::Format data_format = Texture::Format::kRgba8; switch (in_format.type) { case RPR_COMPONENT_TYPE_UINT8: break; case RPR_COMPONENT_TYPE_FLOAT16: component_bytes = 2; data_format = Texture::Format::kRgba16; break; case RPR_COMPONENT_TYPE_FLOAT32: component_bytes = 4; data_format = Texture::Format::kRgba32; break; default: throw Exception(RPR_ERROR_INVALID_PARAMETER, "TextureObject: invalid format type."); } pixel_bytes *= component_bytes; int data_size = 4 * component_bytes * pixels_count;//4 component baikal texture char* data = new char[data_size]; if (in_format.num_components == 4) { //copy data memcpy(data, in_data, data_size); } else { //copy to 4component texture const char* in_data_cast = static_cast<const char*>(in_data); for (int i = 0; i < pixels_count; ++i) { //copy for (unsigned int comp_ind = 0; comp_ind < in_format.num_components; ++comp_ind) { int index = comp_ind * component_bytes; memcpy(&data[i * 4 * component_bytes + index], &in_data_cast[i * in_format.num_components * component_bytes + index], component_bytes); } //clean other colors for (unsigned int comp_ind = in_format.num_components; comp_ind < 4; ++comp_ind) { memset(&data[i * 4 + comp_ind], 0, component_bytes); } } } m_tex = Texture::Create(data, tex_size, data_format); } ImageMaterialObject::ImageMaterialObject(const std::string& in_path) : MaterialObject(Type::kImage) { //load texture using oiio std::unique_ptr<ImageIo> oiio = ImageIo::CreateImageIo(); Texture::Ptr texture = nullptr; try { texture = oiio->LoadImage(in_path); } catch (...) { throw Exception(RPR_ERROR_IO_ERROR, "TextureObject: failed to load image."); } m_tex = texture; } Baikal::Texture::Ptr ImageMaterialObject::GetTexture() { return m_tex; }
[ "konstantin.zverev@developex.org" ]
konstantin.zverev@developex.org
45f45b3d462274c08e5ecbd53bbe9ab82b064015
6222afcf5e5b70940f137785ecda3eedb5945d1c
/holduino-master/MyoConnect/holduino-src/holduino/holduino.ino
f241f8ecf5d5bb84977e74ce1a236007b510bc9e
[]
no_license
juanp98/VIDASIS
fc4b99afe1211587d3e948f3e18b1db40b75a412
d57d6021b5007ae50970b90ffae935aba4f945d8
refs/heads/master
2020-05-29T16:34:42.160542
2019-05-29T15:43:47
2019-05-29T15:43:47
189,253,290
0
0
null
null
null
null
UTF-8
C++
false
false
2,713
ino
#include <Servo.h> #include <MyoController.h> #define FIST_PIN 4 #define REST_PIN 5 #define WAVEOUT_PIN 6 #define FINGERSSPREAD_PIN 7 #define DOUBLETAP_PIN 8 #define CLOSE 0 #define REST 1 #define OPEN 2 MyoController myo = MyoController(); Servo myServo; int delayT; int angleMod; //must be [0,90] void setup() { Serial.begin(9600); pinMode(FIST_PIN, OUTPUT); pinMode(REST_PIN, OUTPUT); pinMode(WAVEOUT_PIN, OUTPUT); //pinMode(FINGERSSPREAD_PIN, OUTPUT); pinMode(DOUBLETAP_PIN, OUTPUT); myServo.attach(8); angleMod = 90; delayT = 250*(angleMod/45); myo.initMyo(); } void loop() { myo.updatePose(); Serial.println(myo.getCurrentPose()); switch ( myo.getCurrentPose() ) { case rest: digitalWrite(FIST_PIN,LOW); digitalWrite(REST_PIN,HIGH); digitalWrite(WAVEOUT_PIN,LOW); //digitalWrite(FINGERSSPREAD_PIN,LOW); digitalWrite(DOUBLETAP_PIN,LOW); if(REST*angleMod != myServo.read()){ myServo.write(REST*angleMod); //delay(delayT); } break; case fist: digitalWrite(FIST_PIN,HIGH); digitalWrite(REST_PIN,LOW); digitalWrite(WAVEOUT_PIN,LOW); //digitalWrite(FINGERSSPREAD_PIN,LOW); digitalWrite(DOUBLETAP_PIN,LOW); if(CLOSE != myServo.read()){ myServo.write(CLOSE); delay(delayT); } break; // case waveIn: // digitalWrite(WAVEIN_PIN,HIGH); // break; case waveOut: digitalWrite(FIST_PIN,LOW); digitalWrite(REST_PIN,LOW); digitalWrite(WAVEOUT_PIN,HIGH); //digitalWrite(FINGERSSPREAD_PIN,LOW); digitalWrite(DOUBLETAP_PIN,LOW); if(OPEN*angleMod != myServo.read()){ //Serial.write("fingers spread"); myServo.write(OPEN*angleMod); delay(delayT); } break; case fingersSpread: digitalWrite(FIST_PIN,LOW); digitalWrite(REST_PIN,LOW); digitalWrite(WAVEOUT_PIN,HIGH); //digitalWrite(FINGERSSPREAD_PIN,HIGH); digitalWrite(DOUBLETAP_PIN,LOW); if(OPEN*angleMod != myServo.read()){ myServo.write(OPEN*angleMod); delay(delayT); } break; case doubleTap: digitalWrite(FIST_PIN,LOW); digitalWrite(REST_PIN,LOW); digitalWrite(WAVEOUT_PIN,LOW); //digitalWrite(FINGERSSPREAD_PIN,LOW); digitalWrite(DOUBLETAP_PIN,HIGH); myServo.write(CLOSE*angleMod); delay(delayT); myServo.write(REST*angleMod); delay(delayT); myServo.write(CLOSE*angleMod); delay(delayT); myServo.write(REST*angleMod); break; } delay(50); }
[ "noreply@github.com" ]
juanp98.noreply@github.com
00026de552e84378ef9dc6ac1a10d877ef994779
dd66e684f935d001096fbdf4064b17ce3783233a
/ImGui/imgui.cpp
486bb3ea06503f6705ac7ce54b4133c6e062717a
[ "MIT" ]
permissive
viktorpagy/dogwareshit
d95082d5becb1a480f443644ed59230c2a453f95
c9900f2cfce7efc0e4ef4adef700a145789c6d8e
refs/heads/master
2020-03-29T07:42:40.505022
2018-09-20T23:28:06
2018-09-20T23:28:06
149,675,975
1
0
null
null
null
null
UTF-8
C++
false
false
445,793
cpp
// dear imgui, v1.50 WIP // (main code and documentation) // See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. // Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui // Releases change-log at https://github.com/ocornut/imgui/releases // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/772 // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // This library is free but I need your support to sustain development and maintenance. // If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui /* Index - MISSION STATEMENT - END-USER GUIDE - PROGRAMMER GUIDE (read me!) - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS - How can I help? - How do I update to a newer version of ImGui? - What is ImTextureID and how do I display an image? - I integrated ImGui in my engine and the text or lines are blurry.. - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs. - How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? - How can I load a different font than the default? - How can I easily use icons in my application? - How can I load multiple fonts? - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) - ISSUES & TODO-LIST - CODE MISSION STATEMENT ================= - easy to use to create code-driven and data-driven tools - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools - easy to hack and improve - minimize screen real-estate usage - minimize setup and maintenance - minimize state storage on user side - portable, minimize dependencies, run on target (consoles, phones, etc.) - efficient runtime (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything) - read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: - doesn't look fancy, doesn't animate - limited layout features, intricate layouts are typically crafted in code - occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction. END-USER GUIDE ============== - double-click title bar to collapse window - click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin() - click and drag on lower right corner to resize window - click and drag on any empty space to move window - double-click/double-tap on lower right corner grip to auto-fit to content - TAB/SHIFT+TAB to cycle through keyboard editable fields - use mouse wheel to scroll - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true) - CTRL+Click on a slider or drag box to input value as text - text editor: - Hold SHIFT or use mouse to select text. - CTRL+Left/Right to word jump - CTRL+Shift+Left/Right to select words - CTRL+A our Double-Click to select all - CTRL+X,CTRL+C,CTRL+V to use OS clipboard - CTRL+Z,CTRL+Y to undo/redo - ESCAPE to revert text to its original value - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) PROGRAMMER GUIDE ================ - read the FAQ below this section! - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs. - call and read ImGui::ShowTestWindow() for demo code demonstrating most features. - see examples/ folder for standalone sample applications. Prefer reading examples/opengl2_example/ first as it is the simplest. you may be able to grab and copy a ready made imgui_impl_*** file from the examples/. - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme). - getting started: - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'. - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory. - every frame: 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input' 2/ call ImGui::NewFrame() as early as you can! 3/ use any ImGui function you want between NewFrame() and Render() 4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure. (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.) - all rendering information are stored into command-lists until ImGui::Render() is called. - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide. - effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. - refer to the examples applications in the examples/ folder for instruction on how to setup your code. - a typical application skeleton may be: // Application init ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = 1920.0f; io.DisplaySize.y = 1280.0f; io.IniFilename = "imgui.ini"; io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data. // TODO: Fill others settings of the io structure // Load texture atlas // There is a default font so you don't need to care about choosing a font yet unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height); // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID' // Application main loop while (true) { // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.) // TODO: fill all fields of IO structure and call NewFrame ImGuiIO& io = ImGui::GetIO(); io.DeltaTime = 1.0f/60.0f; io.MousePos = mouse_pos; io.MouseDown[0] = mouse_button_0; io.MouseDown[1] = mouse_button_1; io.KeysDown[i] = ... // 2) call NewFrame(), after this point you can use ImGui::* functions anytime ImGui::NewFrame(); // 3) most of your application code here MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); MyGameRender(); // may use any ImGui functions // 4) render & swap video buffers ImGui::Render(); SwapBuffers(); } - You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information. API BREAKING CHANGES ==================== Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. Also read releases logs https://github.com/ocornut/imgui/releases for more details. - 2017/05/01 (1.50) - Renamed ImDrawList::PathFill() to ImDrawList::PathFillConvex() for clarity. - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild(). - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); } If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337). - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. this necessary change will break your rendering function! the fix should be very easy. sorry for that :( - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. - the signature of the io.RenderDrawListsFn handler has changed! ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) became: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). argument 'cmd_lists' -> 'draw_data->CmdLists' argument 'cmd_lists_count' -> 'draw_data->CmdListsCount' ImDrawList 'commands' -> 'CmdBuffer' ImDrawList 'vtx_buffer' -> 'VtxBuffer' ImDrawList n/a -> 'IdxBuffer' (new) ImDrawCmd 'vtx_count' -> 'ElemCount' ImDrawCmd 'clip_rect' -> 'ClipRect' ImDrawCmd 'user_callback' -> 'UserCallback' ImDrawCmd 'texture_id' -> 'TextureId' - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry! - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. this sequence: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); // <Copy to GPU> became: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // <Copy to GPU> io.Fonts->TexID = (your_texture_identifier); you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. it is now recommended that you sample the font texture with bilinear interpolation. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes FREQUENTLY ASKED QUESTIONS (FAQ), TIPS ====================================== Q: How can I help? A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help! - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time. Q: How do I update to a newer version of ImGui? A: Overwrite the following files: imgui.cpp imgui.h imgui_demo.cpp imgui_draw.cpp imgui_internal.h stb_rect_pack.h stb_textedit.h stb_truetype.h Don't overwrite imconfig.h if you have made modification to your copy. Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. If you have a problem with a function, search for its name in the code, there will likely be a comment about it. Please report any issue to the GitHub page! Q: What is ImTextureID and how do I display an image? A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function. ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry! It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc. At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render. Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing. (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!) To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions. ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use. It is your responsibility to get textures uploaded to your GPU. Q: I integrated ImGui in my engine and the text or lines are blurry.. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. Q: I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height). Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes) A: Yes. A primer on the use of labels/IDs in ImGui.. - Elements that are not clickable, such as Text() items don't need an ID. - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget). to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer. Button("OK"); // Label = "OK", ID = hash of "OK" Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel" - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK" in two different windows or in two different locations of a tree. - If you have a same ID twice in the same location, you'll have a conflict: Button("OK"); Button("OK"); // ID collision! Both buttons will be treated as the same. Fear not! this is easy to solve and there are many ways to solve it! - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases. use "##" to pass a complement to the ID that won't be visible to the end-user: Button("Play"); // Label = "Play", ID = hash of "Play" Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above) Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above) - If you want to completely hide the label, but still need an ID: Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!) - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels. For example you may want to include varying information in a window title bar (and windows are uniquely identified by their ID.. obviously) Use "###" to pass a label that isn't part of ID: Button("Hello###ID"; // Label = "Hello", ID = hash of "ID" Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above) sprintf(buf, "My game (%f FPS)###MyGame"); Begin(buf); // Variable label, ID = hash of "MyGame" - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window. This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements. You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack! for (int i = 0; i < 100; i++) { PushID(i); Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique) PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj); Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique) PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj->Name); Button("Click"); // Label = "Click", ID = hash of string + "label" (unique) PopID(); } - More example showing that you can stack multiple prefixes into the ID stack: Button("Click"); // Label = "Click", ID = hash of "Click" PushID("node"); Button("Click"); // Label = "Click", ID = hash of "node" + "Click" PushID(my_ptr); Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click" PopID(); PopID(); - Tree nodes implicitly creates a scope for you by calling PushID(). Button("Click"); // Label = "Click", ID = hash of "Click" if (TreeNode("node")) { Button("Click"); // Label = "Click", ID = hash of "node" + "Click" TreePop(); } - When working with trees, ID are used to preserve the open/close state of each tree node. Depending on your use cases you may want to use strings, indices or pointers as ID. e.g. when displaying a single object that may change over time (1-1 relationship), using a static string as ID will preserve your node open/closed state when the targeted object change. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. experiment and see what makes more sense! Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame, but either should be fine. When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application. When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available. ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow(). (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically have 'io.WantcaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs were for ImGui (e.g. with an array of bool) and filter out the corresponding key-ups.) Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13) A: Use the font atlas to load the TTF file you want: ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() Q: How can I easily use icons in my application? A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings. Read 'How can I load multiple fonts?' and the file 'extra_fonts/README.txt' for instructions. Q: How can I load multiple fonts? A: Use the font atlas to pack them into a single texture: (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.) ImGuiIO& io = ImGui::GetIO(); ImFont* font0 = io.Fonts->AddFontDefault(); ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() // the first loaded font gets used by default // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime // Options ImFontConfig config; config.OversampleH = 3; config.OversampleV = 1; config.GlyphExtraSpacing.x = 1.0f; io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config); // Combine multiple fonts into one (e.g. for icon fonts) ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontDefault(); io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will not work. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha, then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug" - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings) - tip: you can call Render() multiple times (e.g for VR renders). - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui! ISSUES & TODO-LIST ================== Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point it usually moves to the github) - doc: add a proper documentation+regression testing system (#435) - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis) (#690) - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify. - window: allow resizing of child windows (possibly given min/max for each axis?) - window: background options for child windows, border option (disable rounding) - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip) - window: resizing from any sides? + mouse cursor directives for app. !- window: begin with *p_open == false should return false. - window: get size/pos helpers given names (see discussion in #249) - window: a collapsed window can be stuck behind the main menu bar? - window: when window is small, prioritize resize button over close button. - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later. - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic. - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd. - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). !- scrolling: allow immediately effective change of scroll if we haven't appended items yet - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. - widgets: clean up widgets internal toward exposing everything. - widgets: add disabled and read-only modes (#211) - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them. !- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows). - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) - input text: expose CursorPos in char filter event (#816) - input text: flag to disable live update of the user buffer (also applies to float/int text input) - input text: resize behavior - field could stretch when being edited? hover tooltip shows more text? - input text: add ImGuiInputTextFlags_EnterToApply? (off #218) - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725) - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200) - input text multi-line: line numbers? status bar? (follow up on #200) - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725) - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position. - input number: optional range min/max for Input*() functions - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled) - input number: use mouse wheel to step up/down - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack. - button: provide a button that looks framed. - text: proper alignment options - image/image button: misalignment on padded/bordered button? - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? - layout: horizontal layout helper (#97) - layout: horizontal flow until no space left (#404) - layout: more generic alignment state (left/right/centered) for single items? - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding. - layout: BeginGroup() needs a border option. - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125) - columns: add a conditional parameter to SetColumnOffset() (#513, #125) - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125) - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125) - columns: user specify columns size (#513, #125) - columns: flag to add horizontal separator above/below? - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets) - combo: sparse combo boxes (via function call?) / iterators - combo: contents should extends to fit label if combo widget is small - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203) - listbox: multiple selection - listbox: user may want to initial scroll to focus on the one selected value? - listbox: keyboard navigation. - listbox: scrolling should track modified selection. !- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) - popups: add variant using global identifier similar to Begin/End (#402) - popups: border options. richer api like BeginChild() perhaps? (#197) - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred button" and may teleport when moving mouse - menus: local shortcuts, global shortcuts (#456, #126) - menus: icons - menus: menubars: some sort of priority / effect of main menu-bar on desktop size? - menus: calling BeginMenu() twice with a same name doesn't seem to append nicely - statusbar: add a per-window status bar helper similar to what menubar does. - tabs (#261, #351) - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y) !- color: the color helpers/typing is a mess and needs sorting out. - color: add a better color picker (#346) - node/graph editor (#306) - pie menus patterns (#434) - drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479) - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals) - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value) - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) - slider & drag: int data passing through a float - drag float: up/down axis - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits) - tree node / optimization: avoid formatting when clipped. - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling. - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings? - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits? - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) - tree node: tweak color scheme to distinguish headers from selected tree node (#581) - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249) - settings: write more decent code to allow saving/loading new fields - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file - style: add window shadows. - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. - style: color-box not always square? - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc. - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation). - style: global scale setting. - style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle - text: simple markup language for color change? - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. - font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance - font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback. - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) - font: fix AddRemapChar() to work before font has been built. - log: LogButtons() options for specifying depth and/or hiding depth slider - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard) - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs. - filters: set a current filter that tree node can automatically query to hide themselves - filters: handle wildcards (with implicit leading/trailing *), regexps - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus) !- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing - keyboard: full keyboard navigation and focus. (#323) - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622) - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame) - input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71) - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style). - input: support track pad style scrolling & slider edit. - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL) - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? - misc: provide HoveredTime and ActivatedTime to ease the creation of animations. - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438) - style editor: color child window height expressed in multiple of line height. - remote: make a system like RemoteImGui first-class citizen/project (#75) - drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?) - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack. - examples: directx9: save/restore device state more thoroughly. - examples: window minimize, maximize (#583) - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) - optimization: use another hash function than crc32, e.g. FNV1a - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? - optimization: turn some the various stack vectors into statically-sized arrays - optimization: better clipping for multi-component widgets */ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #define IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_PLACEMENT_NEW #include "imgui_internal.h" #include <ctype.h> // toupper, isprint #include <stdlib.h> // NULL, malloc, free, qsort, atoi #include <stdio.h> // vsnprintf, sscanf, printf #include <limits.h> // INT_MIN, INT_MAX #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include <stddef.h> // intptr_t #else #include <stdint.h> // intptr_t #endif #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif // Clang warnings with -Weverything #ifdef __clang__ #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // #pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' // #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers #endif //------------------------------------------------------------------------- // Forward Declarations //------------------------------------------------------------------------- static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); static void PushMultiItemsWidths(int components, float w_full = 0.0f); static float GetDraggedColumnOffset(int column_index); static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); static ImFont* GetDefaultFont(); static void SetCurrentFont(ImFont* font); static void SetCurrentWindow(ImGuiWindow* window); static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond); static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond); static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond); static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); static inline bool IsWindowContentHoverable(ImGuiWindow* window); static void ClearSetNextWindowData(); static void CheckStacksSize(ImGuiWindow* window, bool write); static void Scrollbar(ImGuiWindow* window, bool horizontal); static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list); static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window); static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window); static ImGuiIniData* FindWindowSettings(const char* name); static ImGuiIniData* AddWindowSettings(const char* name); static void LoadIniSettingsFromDisk(const char* ini_filename); static void SaveIniSettingsToDisk(const char* ini_filename); static void MarkIniSettingsDirty(); static void PushColumnClipRect(int column_index = -1); static ImRect GetVisibleRect(); static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags); static void CloseInactivePopups(); static void ClosePopupToLevel(int remaining); static void ClosePopup(ImGuiID id); static bool IsPopupOpen(ImGuiID id); static ImGuiWindow* GetFrontMostModalRootWindow(); static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid); static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data); static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size); static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size); static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2); static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format); //----------------------------------------------------------------------------- // Platform dependent default implementations //----------------------------------------------------------------------------- static const char* GetClipboardTextFn_DefaultImpl(void* user_data); static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text); static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); //----------------------------------------------------------------------------- // Context //----------------------------------------------------------------------------- // Default font atlas storage . // New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable. static ImFontAtlas GImDefaultFontAtlas; // Default context storage + current context pointer. // Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext() // ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by: // - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts) // - or: Changing this variable to be TLS. You may #define GImGui in imconfig.h for further custom hackery. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 #ifndef GImGui static ImGuiContext GImDefaultContext; ImGuiContext* GImGui = &GImDefaultContext; #endif //----------------------------------------------------------------------------- // User facing structures //----------------------------------------------------------------------------- ImGuiStyle::ImGuiStyle() { Alpha = 1.0f; // Global alpha applies to everything in ImGui WindowPadding = ImVec2(8,8); // Padding within a window WindowMinSize = ImVec2(32,32); // Minimum window size WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f); Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f); Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f); Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f); Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f); Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f); Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f); Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f); Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f); Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f); Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f); Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f); Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f); Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); } ImGuiIO::ImGuiIO() { // Most fields are initialized with zero memset(this, 0, sizeof(*this)); DisplaySize = ImVec2(-1.0f, -1.0f); DeltaTime = 1.0f/60.0f; IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; Fonts = &GImDefaultFontAtlas; FontGlobalScale = 1.0f; FontDefault = NULL; DisplayFramebufferScale = ImVec2(1.0f, 1.0f); MousePos = ImVec2(-1,-1); MousePosPrev = ImVec2(-1,-1); MouseDoubleClickTime = 0.30f; MouseDoubleClickMaxDist = 6.0f; MouseDragThreshold = 6.0f; for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f; for (int i = 0; i < ImGuiKey_COUNT; i++) KeyMap[i] = -1; KeyRepeatDelay = 0.250f; KeyRepeatRate = 0.050f; UserData = NULL; // User functions RenderDrawListsFn = NULL; MemAllocFn = malloc; MemFreeFn = free; GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; ClipboardUserData = NULL; ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; // Set OS X style defaults based on __APPLE__ compile time flag #ifdef __APPLE__ OSXBehaviors = true; #endif } // Pass in translated ASCII characters for text input. // - with glfw you can get those from the callback set in glfwSetCharCallback() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(ImWchar c) { const int n = ImStrlenW(InputCharacters); if (n + 1 < IM_ARRAYSIZE(InputCharacters)) { InputCharacters[n] = c; InputCharacters[n+1] = '\0'; } } void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) { // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar); ImWchar wchars[wchars_buf_len]; ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL); for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++) AddInputCharacter(wchars[i]); } //----------------------------------------------------------------------------- // HELPERS //----------------------------------------------------------------------------- #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. #ifdef _WIN32 #define IM_NEWLINE "\r\n" #else #define IM_NEWLINE "\n" #endif bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c) { bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; return ((b1 == b2) && (b2 == b3)); } int ImStricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int ImStrnicmp(const char* str1, const char* str2, int count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } void ImStrncpy(char* dst, const char* src, int count) { if (count < 1) return; strncpy(dst, src, (size_t)count); dst[count-1] = 0; } char* ImStrdup(const char *str) { size_t len = strlen(str) + 1; void* buff = ImGui::MemAlloc(len); return (char*)memcpy(buff, (const void*)str, len); } int ImStrlenW(const ImWchar* str) { int n = 0; while (*str++) n++; return n; } const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line { while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') buf_mid_line--; return buf_mid_line; } const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) { if (!needle_end) needle_end = needle + strlen(needle); const char un0 = (char)toupper(*needle); while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) { if (toupper(*haystack) == un0) { const char* b = needle + 1; for (const char* a = haystack + 1; b < needle_end; a++, b++) if (toupper(*a) != toupper(*b)) break; if (b == needle_end) return haystack; } haystack++; } return NULL; } // MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). // Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. int ImFormatString(char* buf, int buf_size, const char* fmt, ...) { IM_ASSERT(buf_size > 0); va_list args; va_start(args, fmt); int w = vsnprintf(buf, buf_size, fmt, args); va_end(args); if (w == -1 || w >= buf_size) w = buf_size - 1; buf[w] = 0; return w; } int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args) { IM_ASSERT(buf_size > 0); int w = vsnprintf(buf, buf_size, fmt, args); if (w == -1 || w >= buf_size) w = buf_size - 1; buf[w] = 0; return w; } // Pass data_size==0 for zero-terminated strings // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. ImU32 ImHash(const void* data, int data_size, ImU32 seed) { static ImU32 crc32_lut[256] = { 0 }; if (!crc32_lut[1]) { const ImU32 polynomial = 0xEDB88320; for (ImU32 i = 0; i < 256; i++) { ImU32 crc = i; for (ImU32 j = 0; j < 8; j++) crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); crc32_lut[i] = crc; } } seed = ~seed; ImU32 crc = seed; const unsigned char* current = (const unsigned char*)data; if (data_size > 0) { // Known size while (data_size--) crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; } else { // Zero-terminated string while (unsigned char c = *current++) { // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. // Because this syntax is rarely used we are optimizing for the common case. // - If we reach ### in the string we discard the hash so far and reset to the seed. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller. if (c == '#' && current[0] == '#' && current[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } return ~crc; } //----------------------------------------------------------------------------- // ImText* helpers //----------------------------------------------------------------------------- // Convert UTF-8 to 32-bits character, process single character input. // Based on stb_from_utf8() from github.com/nothings/stb/ // We handle UTF-8 decoding error by skipping forward. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { unsigned int c = (unsigned int)-1; const unsigned char* str = (const unsigned char*)in_text; if (!(*str & 0x80)) { c = (unsigned int)(*str++); *out_char = c; return 1; } if ((*str & 0xe0) == 0xc0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 2) return 1; if (*str < 0xc2) return 2; c = (unsigned int)((*str++ & 0x1f) << 6); if ((*str & 0xc0) != 0x80) return 2; c += (*str++ & 0x3f); *out_char = c; return 2; } if ((*str & 0xf0) == 0xe0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 3) return 1; if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x0f) << 12); if ((*str & 0xc0) != 0x80) return 3; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 3; c += (*str++ & 0x3f); *out_char = c; return 3; } if ((*str & 0xf8) == 0xf0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 4) return 1; if (*str > 0xf4) return 4; if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x07) << 18); if ((*str & 0xc0) != 0x80) return 4; c += (unsigned int)((*str++ & 0x3f) << 12); if ((*str & 0xc0) != 0x80) return 4; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 4; c += (*str++ & 0x3f); // utf-8 encodings of values used in surrogate pairs are invalid if ((c & 0xFFFFF800) == 0xD800) return 4; *out_char = c; return 4; } *out_char = 0; return 0; } int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) { ImWchar* buf_out = buf; ImWchar* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes *buf_out++ = (ImWchar)c; } *buf_out = 0; if (in_text_remaining) *in_text_remaining = in_text; return (int)(buf_out - buf); } int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) { int char_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) char_count++; } return char_count; } // Based on stb_to_utf8() from github.com/nothings/stb/ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { if (c < 0x80) { buf[0] = (char)c; return 1; } if (c < 0x800) { if (buf_size < 2) return 0; buf[0] = (char)(0xc0 + (c >> 6)); buf[1] = (char)(0x80 + (c & 0x3f)); return 2; } if (c >= 0xdc00 && c < 0xe000) { return 0; } if (c >= 0xd800 && c < 0xdc00) { if (buf_size < 4) return 0; buf[0] = (char)(0xf0 + (c >> 18)); buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[3] = (char)(0x80 + ((c ) & 0x3f)); return 4; } //else if (c < 0x10000) { if (buf_size < 3) return 0; buf[0] = (char)(0xe0 + (c >> 12)); buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); buf[2] = (char)(0x80 + ((c ) & 0x3f)); return 3; } } static inline int ImTextCountUtf8BytesFromChar(unsigned int c) { if (c < 0x80) return 1; if (c < 0x800) return 2; if (c >= 0xdc00 && c < 0xe000) return 0; if (c >= 0xd800 && c < 0xdc00) return 4; return 3; } int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) { char* buf_out = buf; const char* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) *buf_out++ = (char)c; else buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); } *buf_out = 0; return (int)(buf_out - buf); } int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) { int bytes_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) bytes_count++; else bytes_count += ImTextCountUtf8BytesFromChar(c); } return bytes_count; } ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) { float s = 1.0f/255.0f; return ImVec4( ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); } ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) { ImU32 out; out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; return out; } ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) { ImVec4 c = GImGui->Style.Colors[idx]; c.w *= GImGui->Style.Alpha * alpha_mul; return ColorConvertFloat4ToU32(c); } ImU32 ImGui::GetColorU32(const ImVec4& col) { ImVec4 c = col; c.w *= GImGui->Style.Alpha; return ColorConvertFloat4ToU32(c); } // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) { float K = 0.f; if (g < b) { const float tmp = g; g = b; b = tmp; K = -1.f; } if (r < g) { const float tmp = r; r = g; g = tmp; K = -2.f / 6.f - K; } const float chroma = r - (g < b ? g : b); out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f)); out_s = chroma / (r + 1e-20f); out_v = r; } // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 // also http://en.wikipedia.org/wiki/HSL_and_HSV void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) { if (s == 0.0f) { // gray out_r = out_g = out_b = v; return; } h = fmodf(h, 1.0f) / (60.0f/360.0f); int i = (int)h; float f = h - (float)i; float p = v * (1.0f - s); float q = v * (1.0f - s * f); float t = v * (1.0f - s * (1.0f - f)); switch (i) { case 0: out_r = v; out_g = t; out_b = p; break; case 1: out_r = q; out_g = v; out_b = p; break; case 2: out_r = p; out_g = v; out_b = t; break; case 3: out_r = p; out_g = q; out_b = v; break; case 4: out_r = t; out_g = p; out_b = v; break; case 5: default: out_r = v; out_g = p; out_b = q; break; } } FILE* ImFileOpen(const char* filename, const char* mode) { #if defined(_WIN32) && !defined(__CYGWIN__) // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can) const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1; const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1; ImVector<ImWchar> buf; buf.resize(filename_wsize + mode_wsize); ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL); ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL); return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]); #else return fopen(filename, mode); #endif } // Load file content into memory // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes) { IM_ASSERT(filename && file_open_mode); if (out_file_size) *out_file_size = 0; FILE* f; if ((f = ImFileOpen(filename, file_open_mode)) == NULL) return NULL; long file_size_signed; if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return NULL; } int file_size = (int)file_size_signed; void* file_data = ImGui::MemAlloc(file_size + padding_bytes); if (file_data == NULL) { fclose(f); return NULL; } if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size) { fclose(f); ImGui::MemFree(file_data); return NULL; } if (padding_bytes > 0) memset((void *)(((char*)file_data) + file_size), 0, padding_bytes); fclose(f); if (out_file_size) *out_file_size = file_size; return file_data; } //----------------------------------------------------------------------------- // ImGuiStorage //----------------------------------------------------------------------------- // Helper: Key->value storage void ImGuiStorage::Clear() { Data.clear(); } // std::lower_bound but without the bullshit static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key) { ImVector<ImGuiStorage::Pair>::iterator first = data.begin(); ImVector<ImGuiStorage::Pair>::iterator last = data.end(); int count = (int)(last - first); while (count > 0) { int count2 = count / 2; ImVector<ImGuiStorage::Pair>::iterator mid = first + count2; if (mid->key < key) { first = ++mid; count -= count2 + 1; } else { count = count2; } } return first; } int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_i; } bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const { return GetInt(key, default_val ? 1 : 0) != 0; } float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; } void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return NULL; return it->val_p; } // References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_i; } bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) { return (bool*)GetIntRef(key, default_val ? 1 : 0); } float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_f; } void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_p; } // FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) void ImGuiStorage::SetInt(ImGuiID key, int val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_i = val; } void ImGuiStorage::SetBool(ImGuiID key, bool val) { SetInt(key, val ? 1 : 0); } void ImGuiStorage::SetFloat(ImGuiID key, float val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_f = val; } void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_p = val; } void ImGuiStorage::SetAllInt(int v) { for (int i = 0; i < Data.Size; i++) Data[i].val_i = v; } //----------------------------------------------------------------------------- // ImGuiTextFilter //----------------------------------------------------------------------------- // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) { if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); Build(); } else { InputBuf[0] = 0; CountGrep = 0; } } bool ImGuiTextFilter::Draw(const char* label, float width) { if (width != 0.0f) ImGui::PushItemWidth(width); bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); if (width != 0.0f) ImGui::PopItemWidth(); if (value_changed) Build(); return value_changed; } void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out) { out.resize(0); const char* wb = b; const char* we = wb; while (we < e) { if (*we == separator) { out.push_back(TextRange(wb, we)); wb = we + 1; } we++; } if (wb != we) out.push_back(TextRange(wb, we)); } void ImGuiTextFilter::Build() { Filters.resize(0); TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); input_range.split(',', Filters); CountGrep = 0; for (int i = 0; i != Filters.Size; i++) { Filters[i].trim_blanks(); if (Filters[i].empty()) continue; if (Filters[i].front() != '-') CountGrep += 1; } } bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (Filters.empty()) return true; if (text == NULL) text = ""; for (int i = 0; i != Filters.Size; i++) { const TextRange& f = Filters[i]; if (f.empty()) continue; if (f.front() == '-') { // Subtract if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) return false; } else { // Grep if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) return true; } } // Implicit * grep if (CountGrep == 0) return true; return false; } //----------------------------------------------------------------------------- // ImGuiTextBuffer //----------------------------------------------------------------------------- // On some platform vsnprintf() takes va_list by reference and modifies it. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. #ifndef va_copy #define va_copy(dest, src) (dest = src) #endif // Helper: Text buffer for logging/accumulating text void ImGuiTextBuffer::appendv(const char* fmt, va_list args) { va_list args_copy; va_copy(args_copy, args); int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. if (len <= 0) return; const int write_off = Buf.Size; const int needed_sz = write_off + len; if (write_off + len >= Buf.Capacity) { int double_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity); } Buf.resize(needed_sz); ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy); } void ImGuiTextBuffer::append(const char* fmt, ...) { va_list args; va_start(args, fmt); appendv(fmt, args); va_end(args); } //----------------------------------------------------------------------------- // ImGuiSimpleColumns //----------------------------------------------------------------------------- ImGuiSimpleColumns::ImGuiSimpleColumns() { Count = 0; Spacing = Width = NextWidth = 0.0f; memset(Pos, 0, sizeof(Pos)); memset(NextWidths, 0, sizeof(NextWidths)); } void ImGuiSimpleColumns::Update(int count, float spacing, bool clear) { IM_ASSERT(Count <= IM_ARRAYSIZE(Pos)); Count = count; Width = NextWidth = 0.0f; Spacing = spacing; if (clear) memset(NextWidths, 0, sizeof(NextWidths)); for (int i = 0; i < Count; i++) { if (i > 0 && NextWidths[i] > 0.0f) Width += Spacing; Pos[i] = (float)(int)Width; Width += NextWidths[i]; NextWidths[i] = 0.0f; } } float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double { NextWidth = 0.0f; NextWidths[0] = ImMax(NextWidths[0], w0); NextWidths[1] = ImMax(NextWidths[1], w1); NextWidths[2] = ImMax(NextWidths[2], w2); for (int i = 0; i < 3; i++) NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f); return ImMax(Width, NextWidth); } float ImGuiSimpleColumns::CalcExtraSpace(float avail_w) { return ImMax(0.0f, avail_w - Width); } //----------------------------------------------------------------------------- // ImGuiListClipper //----------------------------------------------------------------------------- static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) { // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. Consider moving within SetCursorXXX functions? ImGui::SetCursorPosY(pos_y); ImGuiWindow* window = ImGui::GetCurrentWindow(); window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage. window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. if (window->DC.ColumnsCount > 1) window->DC.ColumnsCellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 // Use case B: Begin() called from constructor with items_height>0 // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. void ImGuiListClipper::Begin(int count, float items_height) { StartPosY = ImGui::GetCursorPosY(); ItemsHeight = items_height; ItemsCount = count; StepNo = 0; DisplayEnd = DisplayStart = -1; if (ItemsHeight > 0.0f) { ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display if (DisplayStart > 0) SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor StepNo = 2; } } void ImGuiListClipper::End() { if (ItemsCount < 0) return; // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. if (ItemsCount < INT_MAX) SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor ItemsCount = -1; StepNo = 3; } bool ImGuiListClipper::Step() { if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems) { ItemsCount = -1; return false; } if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. { DisplayStart = 0; DisplayEnd = 1; StartPosY = ImGui::GetCursorPosY(); StepNo = 1; return true; } if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. { if (ItemsCount == 1) { ItemsCount = -1; return false; } float items_height = ImGui::GetCursorPosY() - StartPosY; IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically Begin(ItemsCount-1, items_height); DisplayStart++; DisplayEnd++; StepNo = 3; return true; } if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. { IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); StepNo = 3; return true; } if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. End(); return false; } //----------------------------------------------------------------------------- // ImGuiWindow //----------------------------------------------------------------------------- ImGuiWindow::ImGuiWindow(const char* name) { Name = ImStrdup(name); ID = ImHash(name, 0); IDStack.push_back(ID); MoveId = GetID("#MOVE"); Flags = 0; IndexWithinParent = 0; PosFloat = Pos = ImVec2(0.0f, 0.0f); Size = SizeFull = ImVec2(0.0f, 0.0f); SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); WindowPadding = ImVec2(0.0f, 0.0f); Scroll = ImVec2(0.0f, 0.0f); ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); ScrollbarX = ScrollbarY = false; ScrollbarSizes = ImVec2(0.0f, 0.0f); BorderSize = 0.0f; Active = WasActive = false; Accessed = false; Collapsed = false; SkipItems = false; BeginCount = 0; PopupId = 0; AutoFitFramesX = AutoFitFramesY = -1; AutoFitOnlyGrows = false; AutoPosLastDirection = -1; HiddenFrames = 0; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing; SetWindowPosCenterWanted = false; LastFrameActive = -1; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList)); IM_PLACEMENT_NEW(DrawList) ImDrawList(); DrawList->_OwnerName = Name; RootWindow = NULL; RootNonPopupWindow = NULL; ParentWindow = NULL; FocusIdxAllCounter = FocusIdxTabCounter = -1; FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX; FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX; } ImGuiWindow::~ImGuiWindow() { DrawList->~ImDrawList(); ImGui::MemFree(DrawList); DrawList = NULL; ImGui::MemFree(Name); Name = NULL; } ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetID(const void* ptr) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHash(&ptr, sizeof(void*), seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); return ImHash(str, str_end ? (int)(str_end - str) : 0, seed); } //----------------------------------------------------------------------------- // Internal API exposed in imgui_internal.h //----------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.CurrentWindow = window; if (window) g.FontSize = window->CalcFontSize(); } ImGuiWindow* ImGui::GetParentWindow() { ImGuiContext& g = *GImGui; IM_ASSERT(g.CurrentWindowStack.Size >= 2); return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2]; } void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.ActiveId = id; g.ActiveIdAllowOverlap = false; g.ActiveIdIsJustActivated = true; if (id) g.ActiveIdIsAlive = true; g.ActiveIdWindow = window; } void ImGui::ClearActiveID() { SetActiveID(0, NULL); } void ImGui::SetHoveredID(ImGuiID id) { ImGuiContext& g = *GImGui; g.HoveredId = id; g.HoveredIdAllowOverlap = false; } void ImGui::KeepAliveID(ImGuiID id) { ImGuiContext& g = *GImGui; if (g.ActiveId == id) g.ActiveIdIsAlive = true; } // Advance cursor given item size for layout. void ImGui::ItemSize(const ImVec2& size, float text_offset_y) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; // Always align ourselves on pixel boundaries ImGuiContext& g = *GImGui; const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // Debug window->DC.PrevLineHeight = line_height; window->DC.PrevLineTextBaseOffset = text_base_offset; window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f; } void ImGui::ItemSize(const ImRect& bb, float text_offset_y) { ItemSize(bb.GetSize(), text_offset_y); } // Declare item bounding box for clipping and interaction. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface // declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd(). bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id) { ImGuiWindow* window = GetCurrentWindow(); window->DC.LastItemId = id ? *id : 0; window->DC.LastItemRect = bb; window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; if (IsClippedEx(bb, id, false)) return false; // This is a sensible default, but widgets are free to override it after calling ItemAdd() ImGuiContext& g = *GImGui; if (IsMouseHoveringRect(bb.Min, bb.Max)) { // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background) // So that clicking on items with no active id such as Text() still returns true with IsItemHovered() window->DC.LastItemHoveredRect = true; if (g.HoveredRootWindow == window->RootWindow) if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveId)) if (IsWindowContentHoverable(window)) window->DC.LastItemHoveredAndUsable = true; } return true; } bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindowRead(); if (!bb.Overlaps(window->ClipRect)) if (!id || *id != GImGui->ActiveId) if (clip_even_when_logged || !g.LogEnabled) return true; return false; } // NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic. bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs) { ImGuiContext& g = *GImGui; if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap) { ImGuiWindow* window = GetCurrentWindowRead(); if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow)) if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max)) if (IsWindowContentHoverable(g.HoveredRootWindow)) return true; } return false; } bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop) { ImGuiContext& g = *GImGui; const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus; window->FocusIdxAllCounter++; if (allow_keyboard_focus) window->FocusIdxTabCounter++; // Process keyboard input at this point: TAB, Shift-TAB switch focus // We can always TAB out of a widget that doesn't allow tabbing in. if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) { // Modulo on index will be applied at the end of frame once we've got the total counter of items. window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); } if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) return true; if (allow_keyboard_focus) if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent) return true; return false; } void ImGui::FocusableItemUnregister(ImGuiWindow* window) { window->FocusIdxAllCounter--; window->FocusIdxTabCounter--; } ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) { ImGuiContext& g = *GImGui; ImVec2 content_max; if (size.x < 0.0f || size.y < 0.0f) content_max = g.CurrentWindow->Pos + GetContentRegionMax(); if (size.x <= 0.0f) size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x; if (size.y <= 0.0f) size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y; return size; } float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { if (wrap_pos_x < 0.0f) return 0.0f; ImGuiWindow* window = GetCurrentWindowRead(); if (wrap_pos_x == 0.0f) wrap_pos_x = GetContentRegionMax().x + window->Pos.x; else if (wrap_pos_x > 0.0f) wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space return ImMax(wrap_pos_x - pos.x, 1.0f); } //----------------------------------------------------------------------------- void* ImGui::MemAlloc(size_t sz) { GImGui->IO.MetricsAllocs++; return GImGui->IO.MemAllocFn(sz); } void ImGui::MemFree(void* ptr) { if (ptr) GImGui->IO.MetricsAllocs--; return GImGui->IO.MemFreeFn(ptr); } const char* ImGui::GetClipboardText() { return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : ""; } void ImGui::SetClipboardText(const char* text) { if (GImGui->IO.SetClipboardTextFn) GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text); } const char* ImGui::GetVersion() { return IMGUI_VERSION; } // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module ImGuiContext* ImGui::GetCurrentContext() { return GImGui; } void ImGui::SetCurrentContext(ImGuiContext* ctx) { #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. #else GImGui = ctx; #endif } ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*)) { if (!malloc_fn) malloc_fn = malloc; ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext)); IM_PLACEMENT_NEW(ctx) ImGuiContext(); ctx->IO.MemAllocFn = malloc_fn; ctx->IO.MemFreeFn = free_fn ? free_fn : free; return ctx; } void ImGui::DestroyContext(ImGuiContext* ctx) { void (*free_fn)(void*) = ctx->IO.MemFreeFn; ctx->~ImGuiContext(); free_fn(ctx); if (GImGui == ctx) SetCurrentContext(NULL); } ImGuiIO& ImGui::GetIO() { return GImGui->IO; } ImGuiStyle& ImGui::GetStyle() { return GImGui->Style; } // Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL; } float ImGui::GetTime() { return GImGui->Time; } int ImGui::GetFrameCount() { return GImGui->FrameCount; } void ImGui::NewFrame() { ImGuiContext& g = *GImGui; // Check user data IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues) IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f); IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting if (!g.Initialized) { // Initialize on first frame g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer)); IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer(); IM_ASSERT(g.Settings.empty()); LoadIniSettingsFromDisk(g.IO.IniFilename); g.Initialized = true; } SetCurrentFont(GetDefaultFont()); IM_ASSERT(g.Font->IsLoaded()); g.Time += g.IO.DeltaTime; g.FrameCount += 1; g.Tooltip[0] = '\0'; g.OverlayDrawList.Clear(); g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); g.OverlayDrawList.PushClipRectFullScreen(); // Mark rendering data as invalid to prevent user who may have a handle on it to use it g.RenderDrawData.Valid = false; g.RenderDrawData.CmdLists = NULL; g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0; // Update inputs state if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) g.IO.MousePos = ImVec2(-9999.0f, -9999.0f); if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta g.IO.MouseDelta = ImVec2(0.0f, 0.0f); else g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; g.IO.MousePosPrev = g.IO.MousePos; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f; g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f; g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i]; g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f; g.IO.MouseDoubleClicked[i] = false; if (g.IO.MouseClicked[i]) { if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime) { if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) g.IO.MouseDoubleClicked[i] = true; g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click } else { g.IO.MouseClickedTime[i] = g.Time; } g.IO.MouseClickedPos[i] = g.IO.MousePos; g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; } else if (g.IO.MouseDown[i]) { g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i])); } } memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration)); for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Calculate frame-rate for the user, as a purely luxurious feature g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame)); // Clear reference to active widget if the widget isn't alive anymore g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; g.HoveredIdAllowOverlap = false; if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) ClearActiveID(); g.ActiveIdPreviousFrame = g.ActiveId; g.ActiveIdIsAlive = false; g.ActiveIdIsJustActivated = false; // Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows. if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId) { KeepAliveID(g.MovedWindowMoveId); IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow); IM_ASSERT(g.MovedWindow->RootWindow->MoveId == g.MovedWindowMoveId); if (g.IO.MouseDown[0]) { if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove)) { g.MovedWindow->PosFloat += g.IO.MouseDelta; if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings) && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)) MarkIniSettingsDirty(); } FocusWindow(g.MovedWindow); } else { ClearActiveID(); g.MovedWindow = NULL; g.MovedWindowMoveId = 0; } } else { g.MovedWindow = NULL; g.MovedWindowMoveId = 0; } // Delay saving settings so we don't spam disk too much if (g.SettingsDirtyTimer > 0.0f) { g.SettingsDirtyTimer -= g.IO.DeltaTime; if (g.SettingsDirtyTimer <= 0.0f) SaveIniSettingsToDisk(g.IO.IniFilename); } // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false); if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow)) g.HoveredRootWindow = g.HoveredWindow->RootWindow; else g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true); if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow()) { g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f); ImGuiWindow* window = g.HoveredRootWindow; while (window && window != modal_window) window = window->ParentWindow; if (!window) g.HoveredRootWindow = g.HoveredWindow = NULL; } else { g.ModalWindowDarkeningRatio = 0.0f; } // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application. // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership. int mouse_earliest_button_down = -1; bool mouse_any_down = false; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { if (g.IO.MouseClicked[i]) g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); mouse_any_down |= g.IO.MouseDown[i]; if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i]) mouse_earliest_button_down = i; } bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; if (g.CaptureMouseNextFrame != -1) g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0); else g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty()); g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0); g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId); g.MouseCursor = ImGuiMouseCursor_Arrow; g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1; g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. if (!mouse_avail_to_imgui) g.HoveredWindow = g.HoveredRootWindow = NULL; // Scale & Scrolling if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed) { ImGuiWindow* window = g.HoveredWindow; if (g.IO.KeyCtrl) { if (g.IO.FontAllowUserScaling) { // Zoom / Scale window float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); float scale = new_font_scale / window->FontWindowScale; window->FontWindowScale = new_font_scale; const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; window->Pos += offset; window->PosFloat += offset; window->Size *= scale; window->SizeFull *= scale; } } else if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) { // Scroll const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines); } } // Pressing TAB activate widget focus // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus. if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false)) g.FocusedWindow->FocusIdxTabRequestNext = 0; // Mark all windows as not visible for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; window->WasActive = window->Active; window->Active = false; window->Accessed = false; } // Closing the focused window restore focus to the first active root window in descending z-order if (g.FocusedWindow && !g.FocusedWindow->WasActive) for (int i = g.Windows.Size-1; i >= 0; i--) if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow)) { FocusWindow(g.Windows[i]); break; } // No window should be open at the beginning of the frame. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack.resize(0); g.CurrentPopupStack.resize(0); CloseInactivePopups(); // Create implicit window - we will only render it if the user has added something to it. ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver); ImGui::Begin("Debug"); } // NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations. void ImGui::Shutdown() { ImGuiContext& g = *GImGui; // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky. g.IO.Fonts->Clear(); // Cleanup of other data are conditional on actually having used ImGui. if (!g.Initialized) return; SaveIniSettingsToDisk(g.IO.IniFilename); for (int i = 0; i < g.Windows.Size; i++) { g.Windows[i]->~ImGuiWindow(); ImGui::MemFree(g.Windows[i]); } g.Windows.clear(); g.WindowsSortBuffer.clear(); g.CurrentWindow = NULL; g.CurrentWindowStack.clear(); g.FocusedWindow = NULL; g.HoveredWindow = NULL; g.HoveredRootWindow = NULL; g.ActiveIdWindow = NULL; g.MovedWindow = NULL; for (int i = 0; i < g.Settings.Size; i++) ImGui::MemFree(g.Settings[i].Name); g.Settings.clear(); g.ColorModifiers.clear(); g.StyleModifiers.clear(); g.FontStack.clear(); g.OpenPopupStack.clear(); g.CurrentPopupStack.clear(); g.SetNextWindowSizeConstraintCallback = NULL; g.SetNextWindowSizeConstraintCallbackUserData = NULL; for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].clear(); g.OverlayDrawList.ClearFreeMemory(); g.ColorEditModeStorage.Clear(); if (g.PrivateClipboard) { ImGui::MemFree(g.PrivateClipboard); g.PrivateClipboard = NULL; } g.InputTextState.Text.clear(); g.InputTextState.InitialText.clear(); g.InputTextState.TempTextBuffer.clear(); if (g.LogFile && g.LogFile != stdout) { fclose(g.LogFile); g.LogFile = NULL; } if (g.LogClipboard) { g.LogClipboard->~ImGuiTextBuffer(); ImGui::MemFree(g.LogClipboard); } g.Initialized = false; } static ImGuiIniData* FindWindowSettings(const char* name) { ImGuiContext& g = *GImGui; ImGuiID id = ImHash(name, 0); for (int i = 0; i != g.Settings.Size; i++) { ImGuiIniData* ini = &g.Settings[i]; if (ini->Id == id) return ini; } return NULL; } static ImGuiIniData* AddWindowSettings(const char* name) { GImGui->Settings.resize(GImGui->Settings.Size + 1); ImGuiIniData* ini = &GImGui->Settings.back(); ini->Name = ImStrdup(name); ini->Id = ImHash(name, 0); ini->Collapsed = false; ini->Pos = ImVec2(FLT_MAX,FLT_MAX); ini->Size = ImVec2(0,0); return ini; } // Zero-tolerance, poor-man .ini parsing // FIXME: Write something less rubbish static void LoadIniSettingsFromDisk(const char* ini_filename) { ImGuiContext& g = *GImGui; if (!ini_filename) return; int file_size; char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_size, 1); if (!file_data) return; ImGuiIniData* settings = NULL; const char* buf_end = file_data + file_size; for (const char* line_start = file_data; line_start < buf_end; ) { const char* line_end = line_start; while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') line_end++; if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') { char name[64]; ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1); settings = FindWindowSettings(name); if (!settings) settings = AddWindowSettings(name); } else if (settings) { float x, y; int i; if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y); else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); else if (sscanf(line_start, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } line_start = line_end+1; } ImGui::MemFree(file_data); } static void SaveIniSettingsToDisk(const char* ini_filename) { ImGuiContext& g = *GImGui; g.SettingsDirtyTimer = 0.0f; if (!ini_filename) return; // Gather data from windows that were active during this session for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Flags & ImGuiWindowFlags_NoSavedSettings) continue; ImGuiIniData* settings = FindWindowSettings(window->Name); settings->Pos = window->Pos; settings->Size = window->SizeFull; settings->Collapsed = window->Collapsed; } // Write .ini file // If a window wasn't opened in this session we preserve its settings FILE* f = ImFileOpen(ini_filename, "wt"); if (!f) return; for (int i = 0; i != g.Settings.Size; i++) { const ImGuiIniData* settings = &g.Settings[i]; if (settings->Pos.x == FLT_MAX) continue; const char* name = settings->Name; if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() name = p; fprintf(f, "[%s]\n", name); fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); fprintf(f, "Collapsed=%d\n", settings->Collapsed); fprintf(f, "\n"); } fclose(f); } static void MarkIniSettingsDirty() { ImGuiContext& g = *GImGui; if (g.SettingsDirtyTimer <= 0.0f) g.SettingsDirtyTimer = g.IO.IniSavingRate; } // FIXME: Add a more explicit sort order in the window structure. static int ChildWindowComparer(const void* lhs, const void* rhs) { const ImGuiWindow* a = *(const ImGuiWindow**)lhs; const ImGuiWindow* b = *(const ImGuiWindow**)rhs; if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) return d; if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) return d; if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox)) return d; return (a->IndexWithinParent - b->IndexWithinParent); } static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window) { out_sorted_windows.push_back(window); if (window->Active) { int count = window->DC.ChildWindows.Size; if (count > 1) qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); for (int i = 0; i < count; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (child->Active) AddWindowToSortedBuffer(out_sorted_windows, child); } } } static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list) { if (draw_list->CmdBuffer.empty()) return; // Remove trailing command if unused ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) { draw_list->CmdBuffer.pop_back(); if (draw_list->CmdBuffer.empty()) return; } // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = 2 bytes = 64K vertices) // If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly. IM_ASSERT((int64_t)draw_list->_VtxCurrentIdx <= ((int64_t)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above. out_render_list.push_back(draw_list); GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size; GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size; } static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window) { AddDrawListToRenderList(out_render_list, window->DrawList); for (int i = 0; i < window->DC.ChildWindows.Size; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (!child->Active) // clipped children may have been marked not active continue; if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0) continue; AddWindowToRenderList(out_render_list, child); } } // When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); window->ClipRect = window->DrawList->_ClipRectStack.back(); } void ImGui::PopClipRect() { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PopClipRect(); window->ClipRect = window->DrawList->_ClipRectStack.back(); } // This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. void ImGui::EndFrame() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again // Render tooltip if (g.Tooltip[0]) { ImGui::BeginTooltip(); ImGui::TextUnformatted(g.Tooltip); ImGui::EndTooltip(); } // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f) { g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y); g.OsImePosSet = g.OsImePosRequest; } // Hide implicit "Debug" window if it hasn't been used IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls if (g.CurrentWindow && !g.CurrentWindow->Accessed) g.CurrentWindow->Active = false; ImGui::End(); // Click to focus window and start moving (after we're done with all our widgets) if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0]) { if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear { if (g.HoveredRootWindow != NULL) { FocusWindow(g.HoveredWindow); if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove)) { g.MovedWindow = g.HoveredWindow; g.MovedWindowMoveId = g.HoveredRootWindow->MoveId; SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow); } } else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL) { // Clicking on void disable focus FocusWindow(NULL); } } } // Sort the window list so that all child windows are after their parent // We cannot do that on FocusWindow() because childs may not exist yet g.WindowsSortBuffer.resize(0); g.WindowsSortBuffer.reserve(g.Windows.Size); for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it continue; AddWindowToSortedBuffer(g.WindowsSortBuffer, window); } IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong g.Windows.swap(g.WindowsSortBuffer); // Clear Input data for next frame g.IO.MouseWheel = 0.0f; memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); g.FrameCountEnded = g.FrameCount; } void ImGui::Render() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() if (g.FrameCountEnded != g.FrameCount) ImGui::EndFrame(); g.FrameCountRendered = g.FrameCount; // Skip render altogether if alpha is 0.0 // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false. if (g.Style.Alpha > 0.0f) { // Gather windows to render g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0; for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].resize(0); for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0) { // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, .. g.IO.MetricsActiveWindows++; if (window->Flags & ImGuiWindowFlags_Popup) AddWindowToRenderList(g.RenderDrawLists[1], window); else if (window->Flags & ImGuiWindowFlags_Tooltip) AddWindowToRenderList(g.RenderDrawLists[2], window); else AddWindowToRenderList(g.RenderDrawLists[0], window); } } // Flatten layers int n = g.RenderDrawLists[0].Size; int flattened_size = n; for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) flattened_size += g.RenderDrawLists[i].Size; g.RenderDrawLists[0].resize(flattened_size); for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) { ImVector<ImDrawList*>& layer = g.RenderDrawLists[i]; if (layer.empty()) continue; memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); n += layer.Size; } // Draw software mouse cursor if requested if (g.IO.MouseDrawCursor) { const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor]; const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset; const ImVec2 size = cursor_data.Size; const ImTextureID tex_id = g.IO.Fonts->TexID; g.OverlayDrawList.PushTextureID(tex_id); g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,255)); // Black border g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], IM_COL32(255,255,255,255)); // White fill g.OverlayDrawList.PopTextureID(); } if (!g.OverlayDrawList.VtxBuffer.empty()) AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList); // Setup draw data g.RenderDrawData.Valid = true; g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL; g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size; g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices; g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices; // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData() if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) g.IO.RenderDrawListsFn(&g.RenderDrawData); } } const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) { const char* text_display_end = text; if (!text_end) text_end = (const char*)-1; while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) text_display_end++; return text_display_end; } // Pass text data straight to log (without being displayed) void ImGui::LogText(const char* fmt, ...) { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; va_list args; va_start(args, fmt); if (g.LogFile) { vfprintf(g.LogFile, fmt, args); } else { g.LogClipboard->appendv(fmt, args); } va_end(args); } // Internal version that takes a position to decide on newline placement and pad items according to their depth. // We split text into individual lines to add current tree level padding static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = ImGui::GetCurrentWindowRead(); if (!text_end) text_end = ImGui::FindRenderedTextEnd(text, text_end); const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1; window->DC.LogLinePosY = ref_pos.y; const char* text_remaining = text; if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth g.LogStartDepth = window->DC.TreeDepth; const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth); for (;;) { // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. const char* line_end = text_remaining; while (line_end < text_end) if (*line_end == '\n') break; else line_end++; if (line_end >= text_end) line_end = NULL; const bool is_first_line = (text == text_remaining); bool is_last_line = false; if (line_end == NULL) { is_last_line = true; line_end = text_end; } if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0)) { const int char_count = (int)(line_end - text_remaining); if (log_new_line || !is_first_line) ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); else ImGui::LogText(" %.*s", char_count, text_remaining); } if (is_last_line) break; text_remaining = line_end + 1; } } // Internal ImGui functions to render text // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Hide anything after a '##' string const char* text_display_end; if (hide_text_after_hash) { text_display_end = FindRenderedTextEnd(text, text_end); } else { if (!text_end) text_end = text + strlen(text); // FIXME-OPT text_display_end = text_end; } const int text_len = (int)(text_display_end - text); if (text_len > 0) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); if (g.LogEnabled) LogRenderedText(pos, text, text_display_end); } } void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (!text_end) text_end = text + strlen(text); // FIXME-OPT const int text_len = (int)(text_end - text); if (text_len > 0) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); if (g.LogEnabled) LogRenderedText(pos, text, text_end); } } // Default clip_rect uses (pos_min,pos_max) // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { // Hide anything after a '##' string const char* text_display_end = FindRenderedTextEnd(text, text_end); const int text_len = (int)(text_display_end - text); if (text_len == 0) return; ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Perform CPU side clipping for single clipped element to avoid using scissor state ImVec2 pos = pos_min; const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); // Render if (need_clipping) { ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); } else { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); } if (g.LogEnabled) LogRenderedText(pos, text, text_display_end); } // Render a rectangle shaped with optional rounding and borders void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); if (border && (window->Flags & ImGuiWindowFlags_ShowBorders)) { window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding); } } // Render a triangle to denote expanded/collapsed state void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const float h = g.FontSize * 1.00f; const float r = h * 0.40f * scale; ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale); ImVec2 a, b, c; if (is_open) { center.y -= r*0.25f; a = center + ImVec2(0,1)*r; b = center + ImVec2(-0.866f,-0.5f)*r; c = center + ImVec2(0.866f,-0.5f)*r; } else { a = center + ImVec2(1,0)*r; b = center + ImVec2(-0.500f,0.866f)*r; c = center + ImVec2(-0.500f,-0.866f)*r; } window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text)); } void ImGui::RenderBullet(ImVec2 pos) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); } void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); ImVec2 a, b, c; float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f); float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f); a.x = pos.x + 0.5f + start_x; b.x = a.x + rem_third; c.x = a.x + rem_third * 3.0f; b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y); a.y = b.y - rem_third; c.y = b.y - rem_third * 2.0f; window->DrawList->PathLineTo(a); window->DrawList->PathLineTo(b); window->DrawList->PathLineTo(c); window->DrawList->PathStroke(col, false); } // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { ImGuiContext& g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string else text_display_end = text_end; ImFont* font = g.Font; const float font_size = g.FontSize; if (text == text_display_end) return ImVec2(0.0f, font_size); ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field) const float font_scale = font_size / font->FontSize; const float character_spacing_x = 1.0f * font_scale; if (text_size.x > 0.0f) text_size.x -= character_spacing_x; text_size.x = (float)(int)(text_size.x + 0.95f); return text_size; } // Helper to calculate coarse clipping of large list of evenly sized items. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindowRead(); if (g.LogEnabled) { // If logging is active, do not perform any clipping *out_items_display_start = 0; *out_items_display_end = items_count; return; } if (window->SkipItems) { *out_items_display_start = *out_items_display_end = 0; return; } const ImVec2 pos = window->DC.CursorPos; int start = (int)((window->ClipRect.Min.y - pos.y) / items_height); int end = (int)((window->ClipRect.Max.y - pos.y) / items_height); start = ImClamp(start, 0, items_count); end = ImClamp(end + 1, start, items_count); *out_items_display_start = start; *out_items_display_end = end; } // Find window given position, search front-to-back // FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) { ImGuiContext& g = *GImGui; for (int i = g.Windows.Size-1; i >= 0; i--) { ImGuiWindow* window = g.Windows[i]; if (!window->Active) continue; if (window->Flags & ImGuiWindowFlags_NoInputs) continue; if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) continue; // Using the clipped AABB so a child window will typically be clipped by its parent. ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding); if (bb.Contains(pos)) return window; } return NULL; } // Test if mouse cursor is hovering given rectangle // NB- Rectangle is clipped by our current clip setting // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindowRead(); // Clip ImRect rect_clipped(r_min, r_max); if (clip) rect_clipped.Clip(window->ClipRect); // Expand for touch input const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); return rect_for_touch.Contains(g.IO.MousePos); } bool ImGui::IsMouseHoveringWindow() { ImGuiContext& g = *GImGui; return g.HoveredWindow == g.CurrentWindow; } bool ImGui::IsMouseHoveringAnyWindow() { ImGuiContext& g = *GImGui; return g.HoveredWindow != NULL; } bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos) { return FindHoveredWindow(pos, false) != NULL; } static bool IsKeyPressedMap(ImGuiKey key, bool repeat) { const int key_index = GImGui->IO.KeyMap[key]; return ImGui::IsKeyPressed(key_index, repeat); } int ImGui::GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= 0 && key < ImGuiKey_COUNT); return GImGui->IO.KeyMap[key]; } bool ImGui::IsKeyDown(int key_index) { if (key_index < 0) return false; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); return GImGui->IO.KeysDown[key_index]; } bool ImGui::IsKeyPressed(int key_index, bool repeat) { ImGuiContext& g = *GImGui; if (key_index < 0) return false; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownDuration[key_index]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) { float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) return true; } return false; } bool ImGui::IsKeyReleased(int key_index) { ImGuiContext& g = *GImGui; if (key_index < 0) return false; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); if (g.IO.KeysDownDurationPrev[key_index] >= 0.0f && !g.IO.KeysDown[key_index]) return true; return false; } bool ImGui::IsMouseDown(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDown[button]; } bool ImGui::IsMouseClicked(int button, bool repeat) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); const float t = g.IO.MouseDownDuration[button]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) { float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) return true; } return false; } bool ImGui::IsMouseReleased(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseReleased[button]; } bool ImGui::IsMouseDoubleClicked(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } bool ImGui::IsMouseDragging(int button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (!g.IO.MouseDown[button]) return false; if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; } ImVec2 ImGui::GetMousePos() { return GImGui->IO.MousePos; } // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() { ImGuiContext& g = *GImGui; if (g.CurrentPopupStack.Size > 0) return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen; return g.IO.MousePos; } ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; if (g.IO.MouseDown[button]) if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment). return ImVec2(0.0f, 0.0f); } void ImGui::ResetMouseDragDelta(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr g.IO.MouseClickedPos[button] = g.IO.MousePos; } ImGuiMouseCursor ImGui::GetMouseCursor() { return GImGui->MouseCursor; } void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) { GImGui->MouseCursor = cursor_type; } void ImGui::CaptureKeyboardFromApp(bool capture) { GImGui->CaptureKeyboardNextFrame = capture ? 1 : 0; } void ImGui::CaptureMouseFromApp(bool capture) { GImGui->CaptureMouseNextFrame = capture ? 1 : 0; } bool ImGui::IsItemHovered() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemHoveredAndUsable; } bool ImGui::IsItemHoveredRect() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemHoveredRect; } bool ImGui::IsItemActive() { ImGuiContext& g = *GImGui; if (g.ActiveId) { ImGuiWindow* window = GetCurrentWindowRead(); return g.ActiveId == window->DC.LastItemId; } return false; } bool ImGui::IsItemClicked(int mouse_button) { return IsMouseClicked(mouse_button) && IsItemHovered(); } bool ImGui::IsAnyItemHovered() { return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0; } bool ImGui::IsAnyItemActive() { return GImGui->ActiveId != 0; } bool ImGui::IsItemVisible() { ImGuiWindow* window = GetCurrentWindowRead(); ImRect r(window->ClipRect); return r.Overlaps(window->DC.LastItemRect); } // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. void ImGui::SetItemAllowOverlap() { ImGuiContext& g = *GImGui; if (g.HoveredId == g.CurrentWindow->DC.LastItemId) g.HoveredIdAllowOverlap = true; if (g.ActiveId == g.CurrentWindow->DC.LastItemId) g.ActiveIdAllowOverlap = true; } ImVec2 ImGui::GetItemRectMin() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Min; } ImVec2 ImGui::GetItemRectMax() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Max; } ImVec2 ImGui::GetItemRectSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.GetSize(); } ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward) { ImGuiWindow* window = GetCurrentWindowRead(); ImRect rect = window->DC.LastItemRect; rect.Expand(outward); return rect.GetClosestPoint(pos, on_edge); } // Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value. void ImGui::SetTooltipV(const char* fmt, va_list args) { ImGuiContext& g = *GImGui; ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args); } void ImGui::SetTooltip(const char* fmt, ...) { va_list args; va_start(args, fmt); SetTooltipV(fmt, args); va_end(args); } static ImRect GetVisibleRect() { ImGuiContext& g = *GImGui; if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax); return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); } void ImGui::BeginTooltip() { ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; ImGui::Begin("##Tooltip", NULL, flags); } void ImGui::EndTooltip() { IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls ImGui::End(); } static bool IsPopupOpen(ImGuiID id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id; } // Mark popup as open (toggle toward open state). // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) void ImGui::OpenPopupEx(const char* str_id, bool reopen_existing) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiID id = window->GetID(str_id); int current_stack_size = g.CurrentPopupStack.Size; ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here) if (g.OpenPopupStack.Size < current_stack_size + 1) g.OpenPopupStack.push_back(popup_ref); else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id) { g.OpenPopupStack.resize(current_stack_size+1); g.OpenPopupStack[current_stack_size] = popup_ref; } } void ImGui::OpenPopup(const char* str_id) { ImGui::OpenPopupEx(str_id, false); } static void CloseInactivePopups() { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.empty()) return; // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. // Don't close our own child popup windows int n = 0; if (g.FocusedWindow) { for (n = 0; n < g.OpenPopupStack.Size; n++) { ImGuiPopupRef& popup = g.OpenPopupStack[n]; if (!popup.Window) continue; IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) continue; bool has_focus = false; for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++) has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow); if (!has_focus) break; } } if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below g.OpenPopupStack.resize(n); } static ImGuiWindow* GetFrontMostModalRootWindow() { ImGuiContext& g = *GImGui; for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window) if (front_most_popup->Flags & ImGuiWindowFlags_Modal) return front_most_popup; return NULL; } static void ClosePopupToLevel(int remaining) { ImGuiContext& g = *GImGui; if (remaining > 0) ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window); else ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow); g.OpenPopupStack.resize(remaining); } static void ClosePopup(ImGuiID id) { if (!IsPopupOpen(id)) return; ImGuiContext& g = *GImGui; ClosePopupToLevel(g.OpenPopupStack.Size - 1); } // Close the popup we have begin-ed into. void ImGui::CloseCurrentPopup() { ImGuiContext& g = *GImGui; int popup_idx = g.CurrentPopupStack.Size - 1; if (popup_idx < 0 || popup_idx > g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) return; while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu)) popup_idx--; ClosePopupToLevel(popup_idx); } static inline void ClearSetNextWindowData() { ImGuiContext& g = *GImGui; g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0; g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false; } static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(str_id); if (!IsPopupOpen(id)) { ClearSetNextWindowData(); // We behave like Begin() and need to consume those values return false; } ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; char name[20]; if (flags & ImGuiWindowFlags_ChildMenu) ImFormatString(name, IM_ARRAYSIZE(name), "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth else ImFormatString(name, IM_ARRAYSIZE(name), "##popup_%08x", id); // Not recycling, so we can close/open during the same frame bool is_open = ImGui::Begin(name, NULL, flags); if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) ImGui::EndPopup(); return is_open; } bool ImGui::BeginPopup(const char* str_id) { if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance { ClearSetNextWindowData(); // We behave like Begin() and need to consume those values return false; } return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders); } bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(name); if (!IsPopupOpen(id)) { ClearSetNextWindowData(); // We behave like Begin() and need to consume those values return false; } ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings; bool is_open = ImGui::Begin(name, p_open, flags); if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) { ImGui::EndPopup(); if (is_open) ClosePopup(id); return false; } return is_open; } void ImGui::EndPopup() { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls IM_ASSERT(GImGui->CurrentPopupStack.Size > 0); ImGui::End(); if (!(window->Flags & ImGuiWindowFlags_Modal)) ImGui::PopStyleVar(); } // This is a helper to handle the most simple case of associating one named popup to one given widget. // 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling // this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers. // 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect() // and passing true to the OpenPopupEx(). // Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that // the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu // driven by click position. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) { if (IsItemHovered() && IsMouseClicked(mouse_button)) OpenPopupEx(str_id, false); return BeginPopup(str_id); } bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button) { if (!str_id) str_id = "window_context_menu"; if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button)) if (also_over_items || !IsAnyItemHovered()) OpenPopupEx(str_id, true); return BeginPopup(str_id); } bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) { if (!str_id) str_id = "void_context_menu"; if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button)) OpenPopupEx(str_id, true); return BeginPopup(str_id); } static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiWindow* window = ImGui::GetCurrentWindow(); ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; const ImVec2 content_avail = ImGui::GetContentRegionAvail(); ImVec2 size = ImFloor(size_arg); if (size.x <= 0.0f) { if (size.x == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitX; size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues) } if (size.y <= 0.0f) { if (size.y == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitY; size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y); } if (border) flags |= ImGuiWindowFlags_ShowBorders; flags |= extra_flags; char title[256]; if (name) ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s.%08X", window->Name, name, id); else ImFormatString(title, IM_ARRAYSIZE(title), "%s.%08X", window->Name, id); bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags); if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) ImGui::GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders; return ret; } bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags); } static bool BeginChildExNew(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiWindow* window = ImGui::GetCurrentWindow(); ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow; const ImVec2 content_avail = ImGui::GetContentRegionAvail(); ImVec2 size = ImFloor(size_arg); if (size.x <= 0.0f) { if (size.x == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitX; size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues) } if (size.y <= 0.0f) { if (size.y == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitY; size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y); } if (border) flags |= ImGuiWindowFlags_ShowBorders; flags |= extra_flags; char title[256]; if (name) ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s.%08X", window->Name, name, id); else ImFormatString(title, IM_ARRAYSIZE(title), "%s.%08X", window->Name, id); bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags); if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) ImGui::GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders; if (extra_flags == ImGuiWindowFlags_ChildZeus) { ImVec2 WinPos = ImGui::GetWindowPos(); ImVec2 child_bb(window->DC.CursorPos.x, window->DC.CursorPos.y); window->DrawList->AddText(child_bb + ImVec2((size_arg.x / 2) - 30, -12), ImColor(255, 255, 255, 255), name); } return ret; } bool ImGui::BeginChildNew(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); return BeginChildExNew(str_id, window->GetID(str_id), size_arg, border, extra_flags); } bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { return BeginChildEx(NULL, id, size_arg, border, extra_flags); } void ImGui::EndChild() { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1) { ImGui::End(); } else { // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting. ImVec2 sz = GetWindowSize(); if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f sz.x = ImMax(4.0f, sz.x); if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY) sz.y = ImMax(4.0f, sz.y); ImGui::End(); window = GetCurrentWindow(); ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz); ItemSize(sz); ItemAdd(bb, NULL); } } // Helper to create a child window / scrolling region that looks like a normal widget frame. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]); ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); } void ImGui::EndChildFrame() { ImGui::EndChild(); ImGui::PopStyleVar(2); ImGui::PopStyleColor(); } // Save and compare stack sizes on Begin()/End() to detect usage errors static void CheckStacksSize(ImGuiWindow* window, bool write) { // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) ImGuiContext& g = *GImGui; int* p_backup = &window->DC.StackSizesBackup[0]; { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop() { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup() { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup() { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor() { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar() { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont() IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); } static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner) { const ImGuiStyle& style = GImGui->Style; // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it. ImVec2 safe_padding = style.DisplaySafeAreaPadding; ImRect r_outer(GetVisibleRect()); r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f)); ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size); for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction). { const int dir = (n == -1) ? *last_dir : n; ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y); if (rect.GetWidth() < size.x || rect.GetHeight() < size.y) continue; *last_dir = dir; return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y); } // Fallback, try to keep within display *last_dir = -1; ImVec2 pos = base_pos; pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); return pos; } ImGuiWindow* ImGui::FindWindowByName(const char* name) { // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block ImGuiContext& g = *GImGui; ImGuiID id = ImHash(name, 0); for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i]->ID == id) return g.Windows[i]; return NULL; } static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; // Create window the first time ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); IM_PLACEMENT_NEW(window) ImGuiWindow(name); window->Flags = flags; if (flags & ImGuiWindowFlags_NoSavedSettings) { // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. window->Size = window->SizeFull = size; } else { // Retrieve settings from .ini file // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. window->PosFloat = ImVec2(60, 60); window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); ImGuiIniData* settings = FindWindowSettings(name); if (!settings) { settings = AddWindowSettings(name); } else { window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver; window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver; window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver; } if (settings->Pos.x != FLT_MAX) { window->PosFloat = settings->Pos; window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); window->Collapsed = settings->Collapsed; } if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize)) size = settings->Size; window->Size = window->SizeFull = size; } if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { window->AutoFitFramesX = window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } else { if (window->Size.x <= 0.0f) window->AutoFitFramesX = 2; if (window->Size.y <= 0.0f) window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); } if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once else g.Windows.push_back(window); return window; } static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size) { ImGuiContext& g = *GImGui; if (g.SetNextWindowSizeConstraint) { // Using -1,-1 on either X/Y axis to preserve the current size. ImRect cr = g.SetNextWindowSizeConstraintRect; new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; if (g.SetNextWindowSizeConstraintCallback) { ImGuiSizeConstraintCallbackData data; data.UserData = g.SetNextWindowSizeConstraintCallbackUserData; data.Pos = window->Pos; data.CurrentSize = window->SizeFull; data.DesiredSize = new_size; g.SetNextWindowSizeConstraintCallback(&data); new_size = data.DesiredSize; } } if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) new_size = ImMax(new_size, g.Style.WindowMinSize); window->SizeFull = new_size; } // Push a new ImGui window to add widgets to. // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. // - Begin/End can be called multiple times during the frame with the same window name to append content. // - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). // You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. // - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. // - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. // - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin(). bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags); } bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; IM_ASSERT(name != NULL); // Window name required IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet if (flags & ImGuiWindowFlags_NoInputs) flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; // Find or create bool window_is_new = false; ImGuiWindow* window = FindWindowByName(name); if (!window) { window = CreateNewWindow(name, size_on_first_use, flags); window_is_new = true; } const int current_frame = ImGui::GetFrameCount(); const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); if (first_begin_of_the_frame) window->Flags = (ImGuiWindowFlags)flags; else flags = window->Flags; // Add to stack ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL; g.CurrentWindowStack.push_back(window); SetCurrentWindow(window); CheckStacksSize(window, true); IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; window_was_active &= (window->PopupId == popup_ref.PopupId); window_was_active &= (window == popup_ref.Window); popup_ref.Window = window; g.CurrentPopupStack.push_back(popup_ref); window->PopupId = popup_ref.PopupId; } const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1); // Process SetNextWindow***() calls bool window_pos_set_by_api = false, window_size_set_by_api = false; if (g.SetNextWindowPosCond) { const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing; window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0; if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f) { window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); } else { SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond); } window->DC.CursorPos = backup_cursor_pos; g.SetNextWindowPosCond = 0; } if (g.SetNextWindowSizeCond) { if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing; window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0; SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond); g.SetNextWindowSizeCond = 0; } if (g.SetNextWindowContentSizeCond) { window->SizeContentsExplicit = g.SetNextWindowContentSizeVal; g.SetNextWindowContentSizeCond = 0; } else if (first_begin_of_the_frame) { window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); } if (g.SetNextWindowCollapsedCond) { if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing; SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond); g.SetNextWindowCollapsedCond = 0; } if (g.SetNextWindowFocus) { ImGui::SetWindowFocus(); g.SetNextWindowFocus = false; } // Update known root window (if we are a child window, otherwise window == window->RootWindow) int root_idx, root_non_popup_idx; for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--) if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow)) break; for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--) if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) break; window->ParentWindow = parent_window; window->RootWindow = g.CurrentWindowStack[root_idx]; window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color. // When reusing window again multiple times a frame, just append content (don't need to setup again) if (first_begin_of_the_frame) { window->Active = true; window->IndexWithinParent = 0; window->BeginCount = 0; window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); window->LastFrameActive = current_frame; window->IDStack.resize(1); // Clear draw list, setup texture, outer clipping rectangle window->DrawList->Clear(); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); ImRect fullscreen_rect(GetVisibleRect()); if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup))) PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); else PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true); if (!window_was_active) { // Popup first latch mouse position, will position itself when it appears next frame window->AutoPosLastDirection = -1; if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) window->PosFloat = g.IO.MousePos; } // Collapse window by double-clicking on title bar // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) { ImRect title_bar_rect = window->TitleBarRect(); if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]) { window->Collapsed = !window->Collapsed; if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkIniSettingsDirty(); FocusWindow(window); } } else { window->Collapsed = false; } // SIZE // Save contents size from last frame for auto-fitting (unless explicitly specified) window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x)); window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y)); // Hide popup/tooltip window when first appearing while we measure size (because we recycle them) if (window->HiddenFrames > 0) window->HiddenFrames--; if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active) { window->HiddenFrames = 1; if (flags & ImGuiWindowFlags_AlwaysAutoResize) { if (!window_size_set_by_api) window->Size = window->SizeFull = ImVec2(0.f, 0.f); window->SizeContents = ImVec2(0.f, 0.f); } } // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects. window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding; // Calculate auto-fit size ImVec2 size_auto_fit; if ((flags & ImGuiWindowFlags_Tooltip) != 0) { // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose. size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y); } else { size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding)); // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding. if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)) size_auto_fit.y += style.ScrollbarSize; if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar)) size_auto_fit.x += style.ScrollbarSize; size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f); } // Handle automatic resize if (window->Collapsed) { // We still process initial auto-fit on collapsed windows to get a window width, // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. if (window->AutoFitFramesX > 0) window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; if (window->AutoFitFramesY > 0) window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; } else { if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api) { window->SizeFull = size_auto_fit; } else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api) { // Auto-fit only grows during the first few frames if (window->AutoFitFramesX > 0) window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; if (window->AutoFitFramesY > 0) window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkIniSettingsDirty(); } } // Apply minimum/maximum window size constraints and final size ApplySizeFullWithConstraint(window, window->SizeFull); window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull; // POSITION // Position child window if (flags & ImGuiWindowFlags_ChildWindow) { window->IndexWithinParent = parent_window->DC.ChildWindows.Size; parent_window->DC.ChildWindows.push_back(window); } if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) { window->Pos = window->PosFloat = parent_window->DC.CursorPos; window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin(). } bool window_pos_center = false; window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0); window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden); if (window_pos_center) { // Center (any sort of window) SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f), 0); } else if (flags & ImGuiWindowFlags_ChildMenu) { // Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. IM_ASSERT(window_pos_set_by_api); float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value). ImRect rect_to_avoid; if (parent_window->DC.MenuBarAppending) rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); else rect_to_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); } else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden) { ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1); window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); } // Position tooltip (always follows mouse) if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api) { ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead? window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid); if (window->AutoPosLastDirection == -1) window->PosFloat = g.IO.MousePos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. } // Clamp position so it stays visible if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) { if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. { ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size; window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding); } } window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); // Default item width. Make it proportional to window size if window manually resizes if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); else window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); // Prepare for focus requests window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX; // Apply scrolling if (window->ScrollTarget.x < FLT_MAX) { window->Scroll.x = window->ScrollTarget.x; window->ScrollTarget.x = FLT_MAX; } if (window->ScrollTarget.y < FLT_MAX) { float center_ratio = window->ScrollTargetCenterRatio.y; window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * (window->TitleBarHeight() + window->MenuBarHeight())) - (center_ratio * window->SizeFull.y); window->ScrollTarget.y = FLT_MAX; } window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f)); if (!window->Collapsed && !window->SkipItems) window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes)); // Modal window darkens what is behind them if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow()) window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio)); // Draw window + handle manual resize ImRect title_bar_rect = window->TitleBarRect(); const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; if (window->Collapsed) { // Draw title bar only RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding); } else { ImU32 resize_col = 0; const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f); if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize)) { // Manual resize const ImVec2 br = window->Rect().GetBR(); const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br); const ImGuiID resize_id = window->GetID("#RESIZE"); bool hovered, held; ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds); resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeNWSE; if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) { // Manual auto-fit when double-clicking ApplySizeFullWithConstraint(window, size_auto_fit); if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkIniSettingsDirty(); ClearActiveID(); } else if (held) { // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos); if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkIniSettingsDirty(); } window->Size = window->SizeFull; title_bar_rect = window->TitleBarRect(); } // Scrollbars window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar)); window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f; // Window background, Default Alpha ImGuiCol bg_color_idx = ImGuiCol_WindowBg; if ((flags & ImGuiWindowFlags_ComboBox) != 0) bg_color_idx = ImGuiCol_ComboBg; else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0) bg_color_idx = ImGuiCol_PopupBg; else if ((flags & ImGuiWindowFlags_ChildWindow) != 0) bg_color_idx = ImGuiCol_ChildWindowBg; ImVec4 bg_color = style.Colors[bg_color_idx]; if (bg_alpha >= 0.0f) bg_color.w = bg_alpha; bg_color.w *= style.Alpha; if (bg_color.w > 0.0f) window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImGuiCorner_All : ImGuiCorner_BottomLeft|ImGuiCorner_BottomRight); // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, ImGuiCorner_TopLeft|ImGuiCorner_TopRight); // Menu bar if (flags & ImGuiWindowFlags_MenuBar) { ImRect menu_bar_rect = window->MenuBarRect(); if (flags & ImGuiWindowFlags_ShowBorders) window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border)); window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImGuiCorner_TopLeft|ImGuiCorner_TopRight); } // Scrollbars if (window->ScrollbarX) Scrollbar(window, true); if (window->ScrollbarY) Scrollbar(window, false); // Render resize grip // (after the input handling so we don't have a frame of latency) if (!(flags & ImGuiWindowFlags_NoResize)) { const ImVec2 br = window->Rect().GetBR(); window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize)); window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size)); window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3); window->DrawList->PathFillConvex(resize_col); } // Borders if (flags & ImGuiWindowFlags_ShowBorders) { window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding); window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding); if (!(flags & ImGuiWindowFlags_NoTitleBar)) window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border)); } } // Update ContentsRegionMax. All the variable it depends on are set above in this function. window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x; window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x)); window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y)); // Setup drawing context window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x; window->DC.GroupOffsetX = 0.0f; window->DC.ColumnsOffsetX = 0.0f; window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y); window->DC.CursorPos = window->DC.CursorStartPos; window->DC.CursorPosPrevLine = window->DC.CursorPos; window->DC.CursorMaxPos = window->DC.CursorStartPos; window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.MenuBarAppending = false; window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x); window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; window->DC.ChildWindows.resize(0); window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled window->DC.AllowKeyboardFocus = true; window->DC.ButtonRepeat = false; window->DC.ItemWidthStack.resize(0); window->DC.AllowKeyboardFocusStack.resize(0); window->DC.ButtonRepeatStack.resize(0); window->DC.TextWrapPosStack.resize(0); window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = 1; window->DC.ColumnsStartPosY = window->DC.CursorPos.y; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY; window->DC.TreeDepth = 0; window->DC.StateStorage = &window->StateStorage; window->DC.GroupStack.resize(0); window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active); if (window->AutoFitFramesX > 0) window->AutoFitFramesX--; if (window->AutoFitFramesY > 0) window->AutoFitFramesY--; // New windows appears in front (we need to do that AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) if (!window_was_active && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup)) FocusWindow(window); // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { if (p_open != NULL) { const float pad = 2.0f; const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f; if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad)) *p_open = false; } const ImVec2 text_size = CalcTextSize(name, NULL, true); if (!(flags & ImGuiWindowFlags_NoCollapse)) RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f); ImVec2 text_min = window->Pos; ImVec2 text_max = window->Pos + ImVec2(window->Size.x, style.FramePadding.y*2 + text_size.y); ImRect clip_rect; clip_rect.Max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton() float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); text_min.x += pad_left; text_max.x -= pad_right; clip_rect.Min = ImVec2(text_min.x, window->Pos.y); RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); } // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() window->WindowRectClipped = window->Rect(); window->WindowRectClipped.Clip(window->ClipRect); // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. // Maybe we can support CTRL+C on every element? /* if (g.ActiveId == move_id) if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) ImGui::LogToClipboard(); */ } // Inner clipping rectangle // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior. const ImRect title_bar_rect = window->TitleBarRect(); const float border_size = window->BorderSize; ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size); clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size); PushClipRect(clip_rect.Min, clip_rect.Max, true); // Clear 'accessed' flag last thing if (first_begin_of_the_frame) window->Accessed = false; window->BeginCount++; g.SetNextWindowSizeConstraint = false; // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar). if (flags & ImGuiWindowFlags_ChildWindow) { IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); window->Collapsed = parent_window && parent_window->Collapsed; if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y); // We also hide the window from rendering because we've already added its border to the command list. // (we could perform the check earlier in the function but it is simpler at this point) if (window->Collapsed) window->Active = false; } if (style.Alpha <= 0.0f) window->Active = false; // Return false if we don't intend to display anything to allow user to perform an early out optimization window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0; return !window->SkipItems; } void ImGui::End() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->DC.ColumnsCount != 1) // close columns set if any is open Columns(1, "#CLOSECOLUMNS"); PopClipRect(); // inner window clip rectangle // Stop logging if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging LogFinish(); // Pop // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin(). g.CurrentWindowStack.pop_back(); if (window->Flags & ImGuiWindowFlags_Popup) g.CurrentPopupStack.pop_back(); CheckStacksSize(window, false); SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); } // Vertical scrollbar // The entire piece of code below is rather confusing because: // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. static void Scrollbar(ImGuiWindow* window, bool horizontal) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY"); // Render background bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; const ImRect window_rect = window->Rect(); const float border_size = window->BorderSize; ImRect bb = horizontal ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size) : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); if (!horizontal) bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f) return; float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; int window_rounding_corners; if (horizontal) window_rounding_corners = ImGuiCorner_BottomLeft | (other_scrollbar ? 0 : ImGuiCorner_BottomRight); else window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImGuiCorner_TopRight : 0) | (other_scrollbar ? 0 : ImGuiCorner_BottomRight); window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners); bb.Reduce(ImVec2(ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f))); // V denote the main axis of the scrollbar float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y; float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w; float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; // The grabable box size generally represent the amount visible (vs the total scrollable amount) // But we maintain a minimum size in pixel to allow for the user to still aim inside. const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_v)), style.GrabMinSize), scrollbar_size_v); const float grab_h_norm = grab_h_pixels / scrollbar_size_v; // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). bool held = false; bool hovered = false; const bool previously_held = (g.ActiveId == id); ImGui::ButtonBehavior(bb, id, &hovered, &held); float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); float scroll_ratio = ImSaturate(scroll_v / scroll_max); float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; if (held && grab_h_norm < 1.0f) { float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y; // Click position in scrollbar normalized space (0.0f->1.0f) const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); ImGui::SetHoveredID(id); bool seek_absolute = false; if (!previously_held) { // On initial click calculate the distance between mouse and the center of the grab if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) { *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } else { seek_absolute = true; *click_delta_to_grab_center_v = 0.0f; } } // Apply scroll // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); if (horizontal) window->Scroll.x = scroll_v; else window->Scroll.y = scroll_v; // Update values for rendering scroll_ratio = ImSaturate(scroll_v / scroll_max); grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Update distance to grab now that we have seeked and saturated if (seek_absolute) *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } // Render const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); if (horizontal) window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding); else window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding); } // Moving window to front of display (which happens to be back of our sorted list) void ImGui::FocusWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing. g.FocusedWindow = window; // Passing NULL allow to disable keyboard focus if (!window) return; // And move its root window to the top of the pile if (window->RootWindow) window = window->RootWindow; // Steal focus on active widgets if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it.. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window) ClearActiveID(); // Bring to front if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window) return; for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i] == window) { g.Windows.erase(g.Windows.begin() + i); break; } g.Windows.push_back(window); } void ImGui::PushItemWidth(float item_width) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); } static void PushMultiItemsWidths(int components, float w_full) { ImGuiWindow* window = ImGui::GetCurrentWindow(); const ImGuiStyle& style = GImGui->Style; if (w_full <= 0.0f) w_full = ImGui::CalcItemWidth(); const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); window->DC.ItemWidthStack.push_back(w_item_last); for (int i = 0; i < components-1; i++) window->DC.ItemWidthStack.push_back(w_item_one); window->DC.ItemWidth = window->DC.ItemWidthStack.back(); } void ImGui::PopItemWidth() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidthStack.pop_back(); window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } float ImGui::CalcItemWidth() { ImGuiWindow* window = GetCurrentWindowRead(); float w = window->DC.ItemWidth; if (w < 0.0f) { // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well. float width_to_right_edge = GetContentRegionAvail().x; w = ImMax(1.0f, width_to_right_edge + w); } w = (float)(int)w; return w; } static ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } static void SetCurrentFont(ImFont* font) { ImGuiContext& g = *GImGui; IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(font->Scale > 0.0f); g.Font = font; g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale; g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel; } void ImGui::PushFont(ImFont* font) { ImGuiContext& g = *GImGui; if (!font) font = GetDefaultFont(); SetCurrentFont(font); g.FontStack.push_back(font); g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() { ImGuiContext& g = *GImGui; g.CurrentWindow->DrawList->PopTextureID(); g.FontStack.pop_back(); SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); } void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) { ImGuiWindow* window = GetCurrentWindow(); window->DC.AllowKeyboardFocus = allow_keyboard_focus; window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus); } void ImGui::PopAllowKeyboardFocus() { ImGuiWindow* window = GetCurrentWindow(); window->DC.AllowKeyboardFocusStack.pop_back(); window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back(); } void ImGui::PushButtonRepeat(bool repeat) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ButtonRepeat = repeat; window->DC.ButtonRepeatStack.push_back(repeat); } void ImGui::PopButtonRepeat() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ButtonRepeatStack.pop_back(); window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back(); } void ImGui::PushTextWrapPos(float wrap_pos_x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPos = wrap_pos_x; window->DC.TextWrapPosStack.push_back(wrap_pos_x); } void ImGui::PopTextWrapPos() { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPosStack.pop_back(); window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); } void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) { ImGuiContext& g = *GImGui; ImGuiColMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; g.ColorModifiers.push_back(backup); g.Style.Colors[idx] = col; } void ImGui::PopStyleColor(int count) { ImGuiContext& g = *GImGui; while (count > 0) { ImGuiColMod& backup = g.ColorModifiers.back(); g.Style.Colors[backup.Col] = backup.BackupValue; g.ColorModifiers.pop_back(); count--; } } struct ImGuiStyleVarInfo { ImGuiDataType Type; ImU32 Offset; void* GetVarPtr() const { return (void*)((unsigned char*)&GImGui->Style + Offset); } }; static const ImGuiStyleVarInfo GStyleVarInfo[ImGuiStyleVar_Count_] = { { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildWindowRounding) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, }; static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) { IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_); return &GStyleVarInfo[idx]; } void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float) { float* pvar = (float*)var_info->GetVarPtr(); GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } IM_ASSERT(0); // Called function with wrong-type? Variable is not a float. } void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float2) { ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(); GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2. } void ImGui::PopStyleVar(int count) { ImGuiContext& g = *GImGui; while (count > 0) { ImGuiStyleMod& backup = g.StyleModifiers.back(); const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr()) = backup.BackupFloat[0]; else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr()) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]); else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr()) = backup.BackupInt[0]; g.StyleModifiers.pop_back(); count--; } } const char* ImGui::GetStyleColName(ImGuiCol idx) { // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; switch (idx) { case ImGuiCol_Text: return "Text"; case ImGuiCol_TextDisabled: return "TextDisabled"; case ImGuiCol_WindowBg: return "WindowBg"; case ImGuiCol_ChildWindowBg: return "ChildWindowBg"; case ImGuiCol_PopupBg: return "PopupBg"; case ImGuiCol_Border: return "Border"; case ImGuiCol_BorderShadow: return "BorderShadow"; case ImGuiCol_FrameBg: return "FrameBg"; case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; case ImGuiCol_FrameBgActive: return "FrameBgActive"; case ImGuiCol_TitleBg: return "TitleBg"; case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; case ImGuiCol_TitleBgActive: return "TitleBgActive"; case ImGuiCol_MenuBarBg: return "MenuBarBg"; case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; case ImGuiCol_ComboBg: return "ComboBg"; case ImGuiCol_CheckMark: return "CheckMark"; case ImGuiCol_SliderGrab: return "SliderGrab"; case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; case ImGuiCol_Button: return "Button"; case ImGuiCol_ButtonHovered: return "ButtonHovered"; case ImGuiCol_ButtonActive: return "ButtonActive"; case ImGuiCol_Header: return "Header"; case ImGuiCol_HeaderHovered: return "HeaderHovered"; case ImGuiCol_HeaderActive: return "HeaderActive"; case ImGuiCol_Column: return "Column"; case ImGuiCol_ColumnHovered: return "ColumnHovered"; case ImGuiCol_ColumnActive: return "ColumnActive"; case ImGuiCol_ResizeGrip: return "ResizeGrip"; case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; case ImGuiCol_CloseButton: return "CloseButton"; case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered"; case ImGuiCol_CloseButtonActive: return "CloseButtonActive"; case ImGuiCol_PlotLines: return "PlotLines"; case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening"; } IM_ASSERT(0); return "Unknown"; } bool ImGui::IsWindowHovered() { ImGuiContext& g = *GImGui; return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow); } bool ImGui::IsWindowFocused() { ImGuiContext& g = *GImGui; return g.FocusedWindow == g.CurrentWindow; } bool ImGui::IsRootWindowFocused() { ImGuiContext& g = *GImGui; return g.FocusedWindow == g.CurrentWindow->RootWindow; } bool ImGui::IsRootWindowOrAnyChildFocused() { ImGuiContext& g = *GImGui; return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow; } bool ImGui::IsRootWindowOrAnyChildHovered() { ImGuiContext& g = *GImGui; return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow); } float ImGui::GetWindowWidth() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.x; } float ImGui::GetWindowHeight() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.y; } ImVec2 ImGui::GetWindowPos() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; return window->Pos; } static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) { window->DC.CursorMaxPos.y += window->Scroll.y; window->Scroll.y = new_scroll_y; window->DC.CursorMaxPos.y -= window->Scroll.y; } static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowPosAllowFlags & cond) == 0) return; window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); window->SetWindowPosCenterWanted = false; // Set const ImVec2 old_pos = window->Pos; window->PosFloat = pos; window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected. } void ImGui::SetWindowPos(const ImVec2& pos, ImGuiSetCond cond) { ImGuiWindow* window = GetCurrentWindowRead(); SetWindowPos(window, pos, cond); } void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowPos(window, pos, cond); } ImVec2 ImGui::GetWindowSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Size; } static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) return; window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); // Set if (size.x > 0.0f) { window->AutoFitFramesX = 0; window->SizeFull.x = size.x; } else { window->AutoFitFramesX = 2; window->AutoFitOnlyGrows = false; } if (size.y > 0.0f) { window->AutoFitFramesY = 0; window->SizeFull.y = size.y; } else { window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } } void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond) { SetWindowSize(GImGui->CurrentWindow, size, cond); } void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond) { ImGuiWindow* window = FindWindowByName(name); if (window) SetWindowSize(window, size, cond); } static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) return; window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); // Set window->Collapsed = collapsed; } void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond) { SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); } bool ImGui::IsWindowCollapsed() { return GImGui->CurrentWindow->Collapsed; } void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond) { ImGuiWindow* window = FindWindowByName(name); if (window) SetWindowCollapsed(window, collapsed, cond); } void ImGui::SetWindowFocus() { FocusWindow(GImGui->CurrentWindow); } void ImGui::SetWindowFocus(const char* name) { if (name) { if (ImGuiWindow* window = FindWindowByName(name)) FocusWindow(window); } else { FocusWindow(NULL); } } void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextWindowPosVal = pos; g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX); g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextWindowSizeVal = size; g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data) { ImGuiContext& g = *GImGui; g.SetNextWindowSizeConstraint = true; g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max); g.SetNextWindowSizeConstraintCallback = custom_callback; g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data; } void ImGui::SetNextWindowContentSize(const ImVec2& size) { ImGuiContext& g = *GImGui; g.SetNextWindowContentSizeVal = size; g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; } void ImGui::SetNextWindowContentWidth(float width) { ImGuiContext& g = *GImGui; g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f); g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; } void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextWindowCollapsedVal = collapsed; g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowFocus() { ImGuiContext& g = *GImGui; g.SetNextWindowFocus = true; } // In window space (not screen space!) ImVec2 ImGui::GetContentRegionMax() { ImGuiWindow* window = GetCurrentWindowRead(); ImVec2 mx = window->ContentsRegionRect.Max; if (window->DC.ColumnsCount != 1) mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x; return mx; } ImVec2 ImGui::GetContentRegionAvail() { ImGuiWindow* window = GetCurrentWindowRead(); return GetContentRegionMax() - (window->DC.CursorPos - window->Pos); } float ImGui::GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // In window space (not screen space!) ImVec2 ImGui::GetWindowContentRegionMin() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ContentsRegionRect.Min; } ImVec2 ImGui::GetWindowContentRegionMax() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ContentsRegionRect.Max; } float ImGui::GetWindowContentRegionWidth() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x; } float ImGui::GetTextLineHeight() { ImGuiContext& g = *GImGui; return g.FontSize; } float ImGui::GetTextLineHeightWithSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.ItemSpacing.y; } float ImGui::GetItemsLineHeightWithSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; } ImDrawList* ImGui::GetWindowDrawList() { ImGuiWindow* window = GetCurrentWindow(); return window->DrawList; } ImFont* ImGui::GetFont() { return GImGui->Font; } float ImGui::GetFontSize() { return GImGui->FontSize; } ImVec2 ImGui::GetFontTexUvWhitePixel() { return GImGui->FontTexUvWhitePixel; } void ImGui::SetWindowFontScale(float scale) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = window->CalcFontSize(); } // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. // Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. ImVec2 ImGui::GetCursorPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos - window->Pos + window->Scroll; } float ImGui::GetCursorPosX() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; } float ImGui::GetCursorPosY() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; } void ImGui::SetCursorPos(const ImVec2& local_pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = window->Pos - window->Scroll + local_pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } void ImGui::SetCursorPosX(float x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); } void ImGui::SetCursorPosY(float y) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); } ImVec2 ImGui::GetCursorStartPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorStartPos - window->Pos; } ImVec2 ImGui::GetCursorScreenPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos; } void ImGui::SetCursorScreenPos(const ImVec2& screen_pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = screen_pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } float ImGui::GetScrollX() { return GImGui->CurrentWindow->Scroll.x; } float ImGui::GetScrollY() { return GImGui->CurrentWindow->Scroll.y; } float ImGui::GetScrollMaxX() { ImGuiWindow* window = GetCurrentWindowRead(); return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x; } float ImGui::GetScrollMaxY() { ImGuiWindow* window = GetCurrentWindowRead(); return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y; } void ImGui::SetScrollX(float scroll_x) { ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.x = scroll_x; window->ScrollTargetCenterRatio.x = 0.0f; } void ImGui::SetScrollY(float scroll_y) { ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY window->ScrollTargetCenterRatio.y = 0.0f; } void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y); if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y) window->ScrollTarget.y = 0.0f; window->ScrollTargetCenterRatio.y = center_y_ratio; } // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. void ImGui::SetScrollHere(float center_y_ratio) { ImGuiWindow* window = GetCurrentWindow(); float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio); } void ImGui::SetKeyboardFocusHere(int offset) { ImGuiWindow* window = GetCurrentWindow(); window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; window->FocusIdxTabRequestNext = INT_MAX; } void ImGui::SetStateStorage(ImGuiStorage* tree) { ImGuiWindow* window = GetCurrentWindow(); window->DC.StateStorage = tree ? tree : &window->StateStorage; } ImGuiStorage* ImGui::GetStateStorage() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.StateStorage; } void ImGui::TextV(const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); TextUnformatted(g.TempBuffer, text_end); } void ImGui::Text(const char* fmt, ...) { va_list args; va_start(args, fmt); TextV(fmt, args); va_end(args); } void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) { PushStyleColor(ImGuiCol_Text, col); TextV(fmt, args); PopStyleColor(); } void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) { va_list args; va_start(args, fmt); TextColoredV(col, fmt, args); va_end(args); } void ImGui::TextDisabledV(const char* fmt, va_list args) { PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]); TextV(fmt, args); PopStyleColor(); } void ImGui::TextDisabled(const char* fmt, ...) { va_list args; va_start(args, fmt); TextDisabledV(fmt, args); va_end(args); } void ImGui::TextWrappedV(const char* fmt, va_list args) { bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set if (need_wrap) PushTextWrapPos(0.0f); TextV(fmt, args); if (need_wrap) PopTextWrapPos(); } void ImGui::TextWrapped(const char* fmt, ...) { va_list args; va_start(args, fmt); TextWrappedV(fmt, args); va_end(args); } void ImGui::TextUnformatted(const char* text, const char* text_end) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; IM_ASSERT(text != NULL); const char* text_begin = text; if (text_end == NULL) text_end = text + strlen(text); // FIXME-OPT const float wrap_pos_x = window->DC.TextWrapPos; const bool wrap_enabled = wrap_pos_x >= 0.0f; if (text_end - text > 2000 && !wrap_enabled) { // Long text! // Perform manual coarse clipping to optimize for long multi-line text // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. const char* line = text; const float line_height = GetTextLineHeight(); const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset); const ImRect clip_rect = window->ClipRect; ImVec2 text_size(0,0); if (text_pos.y <= clip_rect.Max.y) { ImVec2 pos = text_pos; // Lines to skip (can't skip when logging text) if (!g.LogEnabled) { int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); if (lines_skippable > 0) { int lines_skipped = 0; while (line < text_end && lines_skipped < lines_skippable) { const char* line_end = strchr(line, '\n'); if (!line_end) line_end = text_end; line = line_end + 1; lines_skipped++; } pos.y += lines_skipped * line_height; } } // Lines to render if (line < text_end) { ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); while (line < text_end) { const char* line_end = strchr(line, '\n'); if (IsClippedEx(line_rect, NULL, false)) break; const ImVec2 line_size = CalcTextSize(line, line_end, false); text_size.x = ImMax(text_size.x, line_size.x); RenderText(pos, line, line_end, false); if (!line_end) line_end = text_end; line = line_end + 1; line_rect.Min.y += line_height; line_rect.Max.y += line_height; pos.y += line_height; } // Count remaining lines int lines_skipped = 0; while (line < text_end) { const char* line_end = strchr(line, '\n'); if (!line_end) line_end = text_end; line = line_end + 1; lines_skipped++; } pos.y += lines_skipped * line_height; } text_size.y += (pos - text_pos).y; } ImRect bb(text_pos, text_pos + text_size); ItemSize(bb); ItemAdd(bb, NULL); } else { const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); // Account of baseline offset ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size); if (!ItemAdd(bb, NULL)) return; // Render (we don't hide text after ## in this end-user function) RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); } } void ImGui::AlignFirstTextHeightToWidgets() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height. ImGuiContext& g = *GImGui; ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y); SameLine(0, 0); } // Add a label+text combo aligned to other label+value widgets void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, NULL)) return; // Render const char* value_text_begin = &g.TempBuffer[0]; const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); } void ImGui::LabelText(const char* label, const char* fmt, ...) { va_list args; va_start(args, fmt); LabelTextV(label, fmt, args); va_end(args); } static inline bool IsWindowContentHoverable(ImGuiWindow* window) { // An active popup disable hovering on other windows (apart from its own children) ImGuiContext& g = *GImGui; if (ImGuiWindow* focused_window = g.FocusedWindow) if (ImGuiWindow* focused_root_window = focused_window->RootWindow) if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow) return false; return true; } bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (flags & ImGuiButtonFlags_Disabled) { if (out_hovered) *out_hovered = false; if (out_held) *out_held = false; if (g.ActiveId == id) ClearActiveID(); return false; } if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0) flags |= ImGuiButtonFlags_PressedOnClickRelease; bool pressed = false; bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0); if (hovered) { SetHoveredID(id); if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) { // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat // PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds // PressedOnClick | <on click> | <on click> <on repeat> <on repeat> .. // PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release) // PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> .. if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) { SetActiveID(id, window); // Hold on ID FocusWindow(window); g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; } if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0])) { pressed = true; ClearActiveID(); FocusWindow(window); } if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0]) { if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release> pressed = true; ClearActiveID(); } // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true)) pressed = true; } } bool held = false; if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { held = true; } else { if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release> pressed = true; ClearActiveID(); } } // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. if (hovered && (flags & ImGuiButtonFlags_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) hovered = pressed = held = false; if (out_hovered) *out_hovered = hovered; if (out_held) *out_held = held; return pressed; } bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 pos = window->DC.CursorPos; if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); const ImRect bb(pos, pos + size); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); // Automatically close popups //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); return pressed; } bool ImGui::Button(const char* label, const ImVec2& size_arg) { return ButtonEx(label, size_arg, 0); } bool ImGui::MyButtonExXD(const char* label, const ImVec2& size_arg, bool inuse, ImGuiButtonFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 pos = window->DC.CursorPos; if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); const ImRect bb(pos, pos + size); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); //RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); if (!inuse) window->DrawList->AddRectFilled(ImVec2(bb.Min.x, bb.Max.y - 4), ImVec2(bb.Max.x, bb.Max.y), col); else window->DrawList->AddRectFilled(ImVec2(bb.Min.x, bb.Max.y - 4), ImVec2(bb.Max.x, bb.Max.y), col); RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); // Automatically close popups //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); return pressed; } bool ImGui::MyButton(const char* label, bool inuse, const ImVec2& size_arg) { return MyButtonExXD(label, size_arg, inuse, 0); } // Small buttons fits within text without additional vertical spacing. bool ImGui::SmallButton(const char* label) { ImGuiContext& g = *GImGui; float backup_padding_y = g.Style.FramePadding.y; g.Style.FramePadding.y = 0.0f; bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine); g.Style.FramePadding.y = backup_padding_y; return pressed; } // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiID id = window->GetID(str_id); ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); return pressed; } // Upper-right button to close a window. bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) { ImGuiWindow* window = GetCurrentWindow(); const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); const ImVec2 center = bb.GetCenter(); window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12); const float cross_extent = (radius * 0.7071f) - 1.0f; if (hovered) { window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text)); window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text)); } return pressed; } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); if (border_col.w > 0.0f) bb.Max += ImVec2(2,2); ItemSize(bb); if (!ItemAdd(bb, NULL)) return; if (border_col.w > 0.0f) { window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col)); } else { window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); } } // frame_padding < 0: uses FramePadding from style (default) // frame_padding = 0: no framing // frame_padding > 0: set framing size // The color used are the button colors. bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Default to using texture ID as ID. User can still push string/integer prefixes. // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. PushID((void *)user_texture_id); const ImGuiID id = window->GetID("#image"); PopID(); const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2); const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); if (bg_col.w > 0.0f) window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); return pressed; } // Start logging ImGui output to TTY void ImGui::LogToTTY(int max_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; ImGuiWindow* window = GetCurrentWindowRead(); g.LogEnabled = true; g.LogFile = stdout; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } // Start logging ImGui output to given file void ImGui::LogToFile(int max_depth, const char* filename) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; ImGuiWindow* window = GetCurrentWindowRead(); if (!filename) { filename = g.IO.LogFilename; if (!filename) return; } g.LogFile = ImFileOpen(filename, "ab"); if (!g.LogFile) { IM_ASSERT(g.LogFile != NULL); // Consider this an error return; } g.LogEnabled = true; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } // Start logging ImGui output to clipboard void ImGui::LogToClipboard(int max_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; ImGuiWindow* window = GetCurrentWindowRead(); g.LogEnabled = true; g.LogFile = NULL; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } void ImGui::LogFinish() { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; LogText(IM_NEWLINE); g.LogEnabled = false; if (g.LogFile != NULL) { if (g.LogFile == stdout) fflush(g.LogFile); else fclose(g.LogFile); g.LogFile = NULL; } if (g.LogClipboard->size() > 1) { SetClipboardText(g.LogClipboard->begin()); g.LogClipboard->clear(); } } // Helper to display logging buttons void ImGui::LogButtons() { ImGuiContext& g = *GImGui; PushID("LogButtons"); const bool log_to_tty = Button("Log To TTY"); SameLine(); const bool log_to_file = Button("Log To File"); SameLine(); const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); PushItemWidth(80.0f); PushAllowKeyboardFocus(false); SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); PopAllowKeyboardFocus(); PopItemWidth(); PopID(); // Start logging at the end of the function so that the buttons don't appear in the log if (log_to_tty) LogToTTY(g.LogAutoExpandMaxDepth); if (log_to_file) LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename); if (log_to_clipboard) LogToClipboard(g.LogAutoExpandMaxDepth); } bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) { if (flags & ImGuiTreeNodeFlags_Leaf) return true; // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiStorage* storage = window->DC.StateStorage; bool is_open; if (g.SetNextTreeNodeOpenCond != 0) { if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always) { is_open = g.SetNextTreeNodeOpenVal; storage->SetInt(id, is_open); } else { // We treat ImGuiSetCondition_Once and ImGuiSetCondition_FirstUseEver the same because tree node state are not saved persistently. const int stored_value = storage->GetInt(id, -1); if (stored_value == -1) { is_open = g.SetNextTreeNodeOpenVal; storage->SetInt(id, is_open); } else { is_open = stored_value != 0; } } g.SetNextTreeNodeOpenCond = 0; } else { is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; } // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). // NB- If we are above max depth we still allow manually opened nodes to be logged. if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) is_open = true; return is_open; } bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f); if (!label_end) label_end = FindRenderedTextEnd(label); const ImVec2 label_size = CalcTextSize(label, label_end, false); // We vertically grow up to current line height up the typical widget height. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { // Framed header expand a little outside the default padding bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; } const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser ItemSize(ImVec2(text_width, frame_height), text_base_offset_y); // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing // (Ideally we'd want to add a flag for the user to specify we want want the hit test to be done up to the right side of the content or not) const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y); bool is_open = TreeNodeBehaviorIsOpen(id, flags); if (!ItemAdd(interact_bb, &id)) { if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushRawID(id); return is_open; } // Flags that affects opening behavior: // - 0(default) ..................... single-click anywhere to open // - OpenOnDoubleClick .............. double-click anywhere to open // - OpenOnArrow .................... single-click on arrow to open // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0); if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0); bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf)) { bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)); if (flags & ImGuiTreeNodeFlags_OpenOnArrow) toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)); if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) toggled |= g.IO.MouseDoubleClicked[0]; if (toggled) { is_open = !is_open; window->DC.StateStorage->SetInt(id, is_open); } } if (flags & ImGuiTreeNodeFlags_AllowOverlapMode) SetItemAllowOverlap(); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y); if (display_frame) { // Framed type RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f); if (g.LogEnabled) { // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. const char log_prefix[] = "\n##"; const char log_suffix[] = "##"; LogRenderedText(text_pos, log_prefix, log_prefix+3); RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); LogRenderedText(text_pos, log_suffix+1, log_suffix+3); } else { RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); } } else { // Unframed typed for tree nodes if (hovered || (flags & ImGuiTreeNodeFlags_Selected)) RenderFrame(bb.Min, bb.Max, col, false); if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); else if (!(flags & ImGuiTreeNodeFlags_Leaf)) RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f); if (g.LogEnabled) LogRenderedText(text_pos, ">"); RenderText(text_pos, label, label_end, false); } if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushRawID(id); return is_open; } // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). // This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label); } bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; if (p_open && !*p_open) return false; ImGuiID id = window->GetID(label); bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), label); if (p_open) { // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. ImGuiContext& g = *GImGui; float button_sz = g.FontSize * 0.5f; if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz)) *p_open = false; } return is_open; } bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), flags, label, NULL); } bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end); } bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end); } bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) { return TreeNodeExV(str_id, 0, fmt, args); } bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) { return TreeNodeExV(ptr_id, 0, fmt, args); } bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(str_id, flags, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(str_id, 0, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNode(const char* label) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), 0, label, NULL); } void ImGui::TreeAdvanceToLabelPos() { ImGuiContext& g = *GImGui; g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing(); } // Horizontal distance preceding label when using TreeNode() or Bullet() float ImGui::GetTreeNodeToLabelSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + (g.Style.FramePadding.x * 2.0f); } void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextTreeNodeOpenVal = is_open; g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::PushID(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(str_id)); } void ImGui::PushID(const char* str_id_begin, const char* str_id_end) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(str_id_begin, str_id_end)); } void ImGui::PushID(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(ptr_id)); } void ImGui::PushID(int int_id) { const void* ptr_id = (void*)(intptr_t)int_id; ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(ptr_id)); } void ImGui::PopID() { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.pop_back(); } ImGuiID ImGui::GetID(const char* str_id) { return GImGui->CurrentWindow->GetID(str_id); } ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) { return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end); } ImGuiID ImGui::GetID(const void* ptr_id) { return GImGui->CurrentWindow->GetID(ptr_id); } void ImGui::Bullet() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); ItemSize(bb); if (!ItemAdd(bb, NULL)) { SameLine(0, style.FramePadding.x*2); return; } // Render and stay on same line RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); SameLine(0, style.FramePadding.x*2); } // Text with a little bullet aligned to the typical tree node. void ImGui::BulletTextV(const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const char* text_begin = g.TempBuffer; const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding ItemSize(bb); if (!ItemAdd(bb, NULL)) return; // Render RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false); } void ImGui::BulletText(const char* fmt, ...) { va_list args; va_start(args, fmt); BulletTextV(fmt, args); va_end(args); } static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size) { if (data_type == ImGuiDataType_Int) ImFormatString(buf, buf_size, display_format, *(int*)data_ptr); else if (data_type == ImGuiDataType_Float) ImFormatString(buf, buf_size, display_format, *(float*)data_ptr); } static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size) { if (data_type == ImGuiDataType_Int) { if (decimal_precision < 0) ImFormatString(buf, buf_size, "%d", *(int*)data_ptr); else ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr); } else if (data_type == ImGuiDataType_Float) { if (decimal_precision < 0) ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? else ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr); } } static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1 { if (data_type == ImGuiDataType_Int) { if (op == '+') *(int*)value1 = *(int*)value1 + *(const int*)value2; else if (op == '-') *(int*)value1 = *(int*)value1 - *(const int*)value2; } else if (data_type == ImGuiDataType_Float) { if (op == '+') *(float*)value1 = *(float*)value1 + *(const float*)value2; else if (op == '-') *(float*)value1 = *(float*)value1 - *(const float*)value2; } } // User can input math operators (e.g. +100) to edit a numerical values. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format) { while (ImCharIsSpace(*buf)) buf++; // We don't support '-' op because it would conflict with inputing negative value. // Instead you can use +-100 to subtract from an existing value char op = buf[0]; if (op == '+' || op == '*' || op == '/') { buf++; while (ImCharIsSpace(*buf)) buf++; } else { op = 0; } if (!buf[0]) return false; if (data_type == ImGuiDataType_Int) { if (!scalar_format) scalar_format = "%d"; int* v = (int*)data_ptr; const int old_v = *v; int arg0 = *v; if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) return false; // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision float arg1 = 0.0f; if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract) else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant return (old_v != *v); } else if (data_type == ImGuiDataType_Float) { // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in scalar_format = "%f"; float* v = (float*)data_ptr; const float old_v = *v; float arg0 = *v; if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) return false; float arg1 = 0.0f; if (sscanf(buf, scalar_format, &arg1) < 1) return false; if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract) else if (op == '*') { *v = arg0 * arg1; } // Multiply else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide else { *v = arg1; } // Assign constant return (old_v != *v); } return false; } // Create text input in place of a slider (when CTRL+Clicking on slider) bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen) SetActiveID(g.ScalarAsInputTextId, window); SetHoveredID(0); FocusableItemUnregister(window); char buf[32]; DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf)); bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); if (g.ScalarAsInputTextId == 0) { // First frame IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible) g.ScalarAsInputTextId = g.ActiveId; SetHoveredID(id); } else if (g.ActiveId != g.ScalarAsInputTextId) { // Release g.ScalarAsInputTextId = 0; } if (text_value_changed) return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL); return false; } // Parse display precision back from the display format string int ImGui::ParseFormatPrecision(const char* fmt, int default_precision) { int precision = default_precision; while ((fmt = strchr(fmt, '%')) != NULL) { fmt++; if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%" while (*fmt >= '0' && *fmt <= '9') fmt++; if (*fmt == '.') { precision = atoi(fmt + 1); if (precision < 0 || precision > 10) precision = default_precision; } break; } return precision; } float ImGui::RoundScalar(float value, int decimal_precision) { // Round past decimal precision // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0 // FIXME: Investigate better rounding methods static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision); bool negative = value < 0.0f; value = fabsf(value); float remainder = fmodf(value, min_step); if (remainder <= min_step*0.5f) value -= remainder; else value += (min_step - remainder); return negative ? -value : value; } static inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos) { if (v_min == v_max) return 0.0f; const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_non_linear) { if (v_clamped < 0.0f) { const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min); return (1.0f - powf(f, 1.0f/power)) * linear_zero_pos; } else { const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min)); return linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos); } } // Linear slider return (v_clamped - v_min) / (v_max - v_min); } bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = g.Style; // Draw frame RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0; const float grab_padding = 2.0f; const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f); float grab_sz; if (decimal_precision > 0) grab_sz = ImMin(style.GrabMinSize, slider_sz); else grab_sz = ImMin(ImMax(1.0f * (slider_sz / ((v_min < v_max ? v_max - v_min : v_min - v_max) + 1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit const float slider_usable_sz = slider_sz - grab_sz; const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f; const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f; // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f float linear_zero_pos = 0.0f; // 0.0->1.0f if (v_min * v_max < 0.0f) { // Different sign const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power); const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power); linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0); } else { // Same sign linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; } // Process clicking on the slider bool value_changed = false; if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; float clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f; if (!is_horizontal) clicked_t = 1.0f - clicked_t; float new_value; if (is_non_linear) { // Account for logarithmic scale on both sides of the zero if (clicked_t < linear_zero_pos) { // Negative: rescale to the negative range before powering float a = 1.0f - (clicked_t / linear_zero_pos); a = powf(a, power); new_value = ImLerp(ImMin(v_max,0.0f), v_min, a); } else { // Positive: rescale to the positive range before powering float a; if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f) a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos); else a = clicked_t; a = powf(a, power); new_value = ImLerp(ImMax(v_min,0.0f), v_max, a); } } else { // Linear slider new_value = ImLerp(v_min, v_max, clicked_t); } // Round past decimal precision new_value = RoundScalar(new_value, decimal_precision); if (*v != new_value) { *v = new_value; value_changed = true; } } else { ClearActiveID(); } } // Calculate slider grab positioning float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos); // Draw if (!is_horizontal) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); ImRect grab_bb; if (is_horizontal) grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding)); else grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f)); window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); return value_changed; } // Use power!=1.0 for logarithmic sliders. // Adjust display_format to decorate the value with a prefix or a suffix. // "%.3f" 1.234 // "%5.2f secs" 01.23 secs // "Gold: %.0f" Gold: 1 bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); // NB- we don't call ItemSize() yet because we may turn into a text edit box below if (!ItemAdd(total_bb, &id)) { ItemSize(total_bb, style.FramePadding.y); return false; } const bool hovered = IsHovered(frame_bb, id); if (hovered) SetHoveredID(id); if (!display_format) display_format = "%.3f"; int decimal_precision = ParseFormatPrecision(display_format, 3); // Tabbing or CTRL-clicking on Slider turns it into an input box bool start_text_input = false; const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); if (tab_focus_requested || (hovered && g.IO.MouseClicked[0])) { SetActiveID(id, window); FocusWindow(window); if (tab_focus_requested || g.IO.KeyCtrl) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); ItemSize(total_bb, style.FramePadding.y); // Actual slider behavior + render grab const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(frame_bb, &id)) return false; const bool hovered = IsHovered(frame_bb, id); if (hovered) SetHoveredID(id); if (!display_format) display_format = "%.3f"; int decimal_precision = ParseFormatPrecision(display_format, 3); if (hovered && g.IO.MouseClicked[0]) { SetActiveID(id, window); FocusWindow(window); } // Actual slider behavior + render grab bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. // For the vertical slider we allow centered text to overlap the frame padding char value_buf[64]; char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max) { float v_deg = (*v_rad) * 360.0f / (2*IM_PI); bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); *v_rad = v_deg * (2*IM_PI) / 360.0f; return value_changed; } bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } // Add multiple sliders on 1 line for compact edition of multiple components bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 2, v_min, v_max, display_format, power); } bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 3, v_min, v_max, display_format, power); } bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 4, v_min, v_max, display_format, power); } bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 2, v_min, v_max, display_format); } bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 3, v_min, v_max, display_format); } bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 4, v_min, v_max, display_format); } bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); bool value_changed = false; // Process clicking on the drag if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { if (g.ActiveIdIsJustActivated) { // Lock current value on click g.DragCurrentValue = *v; g.DragLastMouseDelta = ImVec2(0.f, 0.f); } float v_cur = g.DragCurrentValue; const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f); if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f) { float speed = v_speed; if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX) speed = (v_max - v_min) * g.DragSpeedDefaultRatio; if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f) speed = speed * g.DragSpeedScaleFast; if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f) speed = speed * g.DragSpeedScaleSlow; float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed; if (fabsf(power - 1.0f) > 0.001f) { // Logarithmic curve on both side of 0.0 float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur; float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f; float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign); float v1_abs = v1 >= 0.0f ? v1 : -v1; float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign } else { v_cur += delta; } g.DragLastMouseDelta.x = mouse_drag_delta.x; // Clamp if (v_min < v_max) v_cur = ImClamp(v_cur, v_min, v_max); g.DragCurrentValue = v_cur; } // Round to user desired precision, then apply v_cur = RoundScalar(v_cur, decimal_precision); if (*v != v_cur) { *v = v_cur; value_changed = true; } } else { ClearActiveID(); } } return value_changed; } bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); // NB- we don't call ItemSize() yet because we may turn into a text edit box below if (!ItemAdd(total_bb, &id)) { ItemSize(total_bb, style.FramePadding.y); return false; } const bool hovered = IsHovered(frame_bb, id); if (hovered) SetHoveredID(id); if (!display_format) display_format = "%.3f"; int decimal_precision = ParseFormatPrecision(display_format, 3); // Tabbing or CTRL-clicking on Drag turns it into an input box bool start_text_input = false; const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0]))) { SetActiveID(id, window); FocusWindow(window); if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0]) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); // Actual drag behavior ItemSize(total_bb, style.FramePadding.y); const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); return value_changed; } bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power); } bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power); } bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power); } bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); PushMultiItemsWidths(2); bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); PopID(); return value_changed; } // NB: v_speed is float to allow adjusting the drag speed with more precision bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format); *v = (int)v_f; return value_changed; } bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format) { return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format); } bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format) { return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format); } bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format) { return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format); } bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); PushMultiItemsWidths(2); bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); PopID(); return value_changed; } void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImVec2 label_size = CalcTextSize(label, NULL, true); if (graph_size.x == 0.0f) graph_size.x = CalcItemWidth(); if (graph_size.y == 0.0f) graph_size.y = label_size.y + (style.FramePadding.y * 2); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, NULL)) return; // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) { float v_min = FLT_MAX; float v_max = -FLT_MAX; for (int i = 0; i < values_count; i++) { const float v = values_getter(data, i); v_min = ImMin(v_min, v); v_max = ImMax(v_max, v); } if (scale_min == FLT_MAX) scale_min = v_min; if (scale_max == FLT_MAX) scale_max = v_max; } RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); if (values_count > 0) { int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); // Tooltip on hover int v_hovered = -1; if (IsHovered(inner_bb, 0)) { const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); const int v_idx = (int)(t * item_count); IM_ASSERT(v_idx >= 0 && v_idx < values_count); const float v0 = values_getter(data, (v_idx + values_offset) % values_count); const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); if (plot_type == ImGuiPlotType_Lines) SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); else if (plot_type == ImGuiPlotType_Histogram) SetTooltip("%d: %8.4g", v_idx, v0); v_hovered = v_idx; } const float t_step = 1.0f / (float)res_w; float v0 = values_getter(data, (0 + values_offset) % values_count); float t0 = 0.0f; ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); for (int n = 0; n < res_w; n++) { const float t1 = t0 + t_step; const int v1_idx = (int)(t0 * item_count + 0.5f); IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, 1.0f)); if (plot_type == ImGuiPlotType_Lines) { window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); } else if (plot_type == ImGuiPlotType_Histogram) { if (pos1.x >= pos0.x + 2.0f) pos1.x -= 1.0f; window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); } t0 = t1; tp0 = tp1; } } // Text overlay if (overlay_text) RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); } struct ImGuiPlotArrayGetterData { const float* Values; int Stride; ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } }; static float Plot_ArrayGetter(void* data, int idx) { ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); return v; } void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, NULL)) return; // Render fraction = ImSaturate(fraction); RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); bb.Reduce(ImVec2(window->BorderSize, window->BorderSize)); const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, style.FrameRounding); // Default displaying the fraction as percentage string, but user can override it char overlay_buf[32]; if (!overlay) { ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); overlay = overlay_buf; } ImVec2 overlay_size = CalcTextSize(overlay, NULL); if (overlay_size.x > 0.0f) RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); } void ImGui::RenderCheckMark1(ImVec2 pos, ImU32 col, float sz) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; float thickness = ImMax(sz / 5.0f, 1.0f); sz -= thickness * 0.5f; pos += ImVec2(thickness*0.25f, thickness*0.25f); float third = sz / 3.0f; float bx = pos.x + third; float by = pos.y + sz - third * 0.5f; window->DrawList->PathLineTo(ImVec2(bx - third, by - third)); window->DrawList->PathLineTo(ImVec2(bx, by)); window->DrawList->PathLineTo(ImVec2(bx + third * 2, by - third * 2)); window->DrawList->PathStroke(col, false, thickness); } bool ImGui::Checkbox(const char * label, bool * v) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y * 2, label_size.y + style.FramePadding.y * 2)); // We want a square shape to we use Y twice ItemSize(check_bb, style.FramePadding.y); ImRect total_bb = check_bb; if (label_size.x > 0) SameLine(0, style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); if (label_size.x > 0) { ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); } if (!ItemAdd(total_bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) *v = !(*v); RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_CheckMarkHover : ImGuiCol_CheckMarkBg), true, style.FrameRounding); if (*v) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); RenderCheckMark1(check_bb.Min + ImVec2(pad, pad), GetColorU32(ImGuiCol_CheckMark), check_bb.GetWidth() - pad * 2.0f); } if (g.LogEnabled) LogRenderedText(text_bb.Min, *v ? "[x]" : "[ ]"); if (label_size.x > 0.0f) RenderText(text_bb.Min, label); return pressed; } bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) { bool v = ((*flags & flags_value) == flags_value); bool pressed = Checkbox(label, &v); if (pressed) { if (v) *flags |= flags_value; else *flags &= ~flags_value; } return pressed; } bool ImGui::RadioButton(const char* label, bool active) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1)); ItemSize(check_bb, style.FramePadding.y); ImRect total_bb = check_bb; if (label_size.x > 0) SameLine(0, style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); if (label_size.x > 0) { ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); total_bb.Add(text_bb); } if (!ItemAdd(total_bb, &id)) return false; ImVec2 center = check_bb.GetCenter(); center.x = (float)(int)center.x + 0.5f; center.y = (float)(int)center.y + 0.5f; const float radius = check_bb.GetHeight() * 0.5f; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); if (active) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16); } if (window->Flags & ImGuiWindowFlags_ShowBorders) { window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16); window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16); } if (g.LogEnabled) LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )"); if (label_size.x > 0.0f) RenderText(text_bb.GetTL(), label); return pressed; } bool ImGui::RadioButton(const char* label, int* v, int v_button) { const bool pressed = RadioButton(label, *v == v_button); if (pressed) { *v = v_button; } return pressed; } static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) { int line_count = 0; const char* s = text_begin; while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding if (c == '\n') line_count++; s--; if (s[0] != '\n' && s[0] != '\r') line_count++; *out_text_end = s; return line_count; } static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) { ImFont* font = GImGui->Font; const float line_height = GImGui->FontSize; const float scale = line_height / font->FontSize; ImVec2 text_size = ImVec2(0,0); float line_width = 0.0f; const ImWchar* s = text_begin; while (s < text_end) { unsigned int c = (unsigned int)(*s++); if (c == '\n') { text_size.x = ImMax(text_size.x, line_width); text_size.y += line_height; line_width = 0.0f; if (stop_on_new_line) break; continue; } if (c == '\r') continue; const float char_width = font->GetCharAdvance((unsigned short)c) * scale; line_width += char_width; } if (text_size.x < line_width) text_size.x = line_width; if (out_offset) *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n text_size.y += line_height; if (remaining) *remaining = s; return text_size; } // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) namespace ImGuiStb { static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; } static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); } static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) { const ImWchar* text = obj->Text.Data; const ImWchar* text_remaining = NULL; const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true); r->x0 = 0.0f; r->x1 = size.x; r->baseline_y_delta = size.y; r->ymin = 0.0f; r->ymax = size.y; r->num_chars = (int)(text_remaining - (text + line_start_idx)); } static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; } static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } #ifdef __APPLE__ // FIXME: Move setting to IO structure static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; } static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } #else static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } #endif #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) { ImWchar* dst = obj->Text.Data + pos; // We maintain our buffer length in both UTF-8 and wchar formats obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); obj->CurLenW -= n; // Offset remaining text const ImWchar* src = obj->Text.Data + pos + n; while (ImWchar c = *src++) *dst++ = c; *dst = '\0'; } static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) { const int text_len = obj->CurLenW; IM_ASSERT(pos <= text_len); if (new_text_len + text_len + 1 > obj->Text.Size) return false; const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) return false; ImWchar* text = obj->Text.Data; if (pos != text_len) memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); obj->CurLenW += new_text_len; obj->CurLenA += new_text_len_utf8; obj->Text[obj->CurLenW] = '\0'; return true; } // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word #define STB_TEXTEDIT_K_SHIFT 0x20000 #define STB_TEXTEDIT_IMPLEMENTATION #include "stb_textedit.h" } void ImGuiTextEditState::OnKeyPressed(int key) { stb_textedit_key(this, &StbState, key); CursorFollow = true; CursorAnimReset(); } // Public API to manipulate UTF-8 text // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) // FIXME: The existence of this rarely exercised code path is a bit of a nuisance. void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count) { IM_ASSERT(pos + bytes_count <= BufTextLen); char* dst = Buf + pos; const char* src = Buf + pos + bytes_count; while (char c = *src++) *dst++ = c; *dst = '\0'; if (CursorPos + bytes_count >= pos) CursorPos -= bytes_count; else if (CursorPos >= pos) CursorPos = pos; SelectionStart = SelectionEnd = CursorPos; BufDirty = true; BufTextLen -= bytes_count; } void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) { const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); if (new_text_len + BufTextLen + 1 >= BufSize) return; if (BufTextLen != pos) memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); Buf[BufTextLen + new_text_len] = '\0'; if (CursorPos >= pos) CursorPos += new_text_len; SelectionStart = SelectionEnd = CursorPos; BufDirty = true; BufTextLen += new_text_len; } // Return false to discard a character. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { unsigned int c = *p_char; if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) { bool pass = false; pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput)); if (!pass) return false; } if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. return false; if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank)) { if (flags & ImGuiInputTextFlags_CharsDecimal) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) return false; if (flags & ImGuiInputTextFlags_CharsHexadecimal) if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return false; if (flags & ImGuiInputTextFlags_CharsUppercase) if (c >= 'a' && c <= 'z') *p_char = (c += (unsigned int)('A'-'a')); if (flags & ImGuiInputTextFlags_CharsNoBlank) if (ImCharIsSpace(c)) return false; } if (flags & ImGuiInputTextFlags_CallbackCharFilter) { ImGuiTextEditCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; callback_data.EventChar = (ImWchar)c; callback_data.Flags = flags; callback_data.UserData = user_data; if (callback(&callback_data) != 0) return false; *p_char = callback_data.EventChar; if (!callback_data.EventChar) return false; } return true; } #define VK_LBUTTON 0x01 #define VK_RBUTTON 0x02 #define VK_MBUTTON 0x04 /* NOT contiguous with L & RBUTTON */ #define VK_XBUTTON1 0x05 /* NOT contiguous with L & RBUTTON */ #define VK_XBUTTON2 0x06 /* NOT contiguous with L & RBUTTON */ #define VK_BACK 0x08 #define VK_RMENU 0xA5 #define VK_LMENU 0xA4 const char* const KeyNames[] = { "Unknown", "VK_LBUTTON", "VK_RBUTTON", "VK_CANCEL", "VK_MBUTTON", "VK_XBUTTON1", "VK_XBUTTON2", "Unknown", "VK_BACK", "VK_TAB", "Unknown", "Unknown", "VK_CLEAR", "VK_RETURN", "Unknown", "Unknown", "VK_SHIFT", "VK_CONTROL", "VK_MENU", "VK_PAUSE", "VK_CAPITAL", "VK_KANA", "Unknown", "VK_JUNJA", "VK_FINAL", "VK_KANJI", "Unknown", "VK_ESCAPE", "VK_CONVERT", "VK_NONCONVERT", "VK_ACCEPT", "VK_MODECHANGE", "VK_SPACE", "VK_PRIOR", "VK_NEXT", "VK_END", "VK_HOME", "VK_LEFT", "VK_UP", "VK_RIGHT", "VK_DOWN", "VK_SELECT", "VK_PRINT", "VK_EXECUTE", "VK_SNAPSHOT", "VK_INSERT", "VK_DELETE", "VK_HELP", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "VK_LWIN", "VK_RWIN", "VK_APPS", "Unknown", "VK_SLEEP", "VK_NUMPAD0", "VK_NUMPAD1", "VK_NUMPAD2", "VK_NUMPAD3", "VK_NUMPAD4", "VK_NUMPAD5", "VK_NUMPAD6", "VK_NUMPAD7", "VK_NUMPAD8", "VK_NUMPAD9", "VK_MULTIPLY", "VK_ADD", "VK_SEPARATOR", "VK_SUBTRACT", "VK_DECIMAL", "VK_DIVIDE", "VK_F1", "VK_F2", "VK_F3", "VK_F4", "VK_F5", "VK_F6", "VK_F7", "VK_F8", "VK_F9", "VK_F10", "VK_F11", "VK_F12", "VK_F13", "VK_F14", "VK_F15", "VK_F16", "VK_F17", "VK_F18", "VK_F19", "VK_F20", "VK_F21", "VK_F22", "VK_F23", "VK_F24", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "VK_NUMLOCK", "VK_SCROLL", "VK_OEM_NEC_EQUAL", "VK_OEM_FJ_MASSHOU", "VK_OEM_FJ_TOUROKU", "VK_OEM_FJ_LOYA", "VK_OEM_FJ_ROYA", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "VK_LSHIFT", "VK_RSHIFT", "VK_LCONTROL", "VK_RCONTROL", "VK_LMENU", "VK_RMENU" }; bool ImGui::Hotkey(const char* label, int* k, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), label_size.y + style.FramePadding.y*2.0f); const ImRect frame_bb(window->DC.CursorPos + ImVec2(label_size.x + style.ItemInnerSpacing.x, 0.0f), window->DC.CursorPos + size); const ImRect total_bb(window->DC.CursorPos, frame_bb.Max); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, &id)) return false; const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, false); const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool hovered = IsHovered(frame_bb, id); if (hovered) { SetHoveredID(id); g.MouseCursor = ImGuiMouseCursor_TextInput; } const bool user_clicked = hovered && io.MouseClicked[0]; if (focus_requested || user_clicked) { if (g.ActiveId != id) { // Start edition memset(io.MouseDown, 0, sizeof(io.MouseDown)); memset(io.KeysDown, 0, sizeof(io.KeysDown)); *k = 0; } SetActiveID(id, window); FocusWindow(window); } else if (io.MouseClicked[0]) { // Release focus when we click outside if (g.ActiveId == id) ClearActiveID(); } bool value_changed = false; int key = *k; if (g.ActiveId == id) { for (auto i = 0; i < 5; i++) { if (io.MouseDown[i]) { switch (i) { case 0: key = VK_LBUTTON; break; case 1: key = VK_RBUTTON; break; case 2: key = VK_MBUTTON; break; case 3: key = VK_XBUTTON1; break; case 4: key = VK_XBUTTON2; break; } value_changed = true; ClearActiveID(); } } if (!value_changed) { for (auto i = VK_BACK; i <= VK_RMENU; i++) { if (io.KeysDown[i]) { key = i; value_changed = true; ClearActiveID(); } } } if (IsKeyPressedMap(ImGuiKey_Escape)) { *k = 0; ClearActiveID(); } else { *k = key; } } // Render // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is Set 'buf' might still be the old value. We Set buf to NULL to prevent accidental usage from now on. char buf_display[64] = "None"; RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); if (*k != 0 && g.ActiveId != id) { strcpy(buf_display, KeyNames[*k]); } else if (g.ActiveId == id) { strcpy(buf_display, "<Press a key>"); } const ImRect clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 render_pos = frame_bb.Min + style.FramePadding; ImGui::RenderTextClipped(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding, buf_display, NULL, NULL, style.ButtonTextAlign, &clip_rect); //draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, NULL, 0.0f, &clip_rect); if (label_size.x > 0) RenderText(ImVec2(total_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } // Edit a string of text // NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect. // FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188 bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) ImGuiContext& g = *GImGui; const ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0; const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn BeginGroup(); const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); ImGuiWindow* draw_window = window; if (is_multiline) { if (!BeginChildFrame(id, frame_bb.GetSize())) { EndChildFrame(); EndGroup(); return false; } draw_window = GetCurrentWindow(); size.x -= draw_window->ScrollbarSizes.x; } else { ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, &id)) return false; } // Password pushes a temporary font with only a fallback glyph if (is_password) { const ImFont::Glyph* glyph = g.Font->FindGlyph('*'); ImFont* password_font = &g.InputTextPasswordFont; password_font->FontSize = g.Font->FontSize; password_font->Scale = g.Font->Scale; password_font->DisplayOffset = g.Font->DisplayOffset; password_font->Ascent = g.Font->Ascent; password_font->Descent = g.Font->Descent; password_font->ContainerAtlas = g.Font->ContainerAtlas; password_font->FallbackGlyph = glyph; password_font->FallbackXAdvance = glyph->XAdvance; IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty()); PushFont(password_font); } // NB: we are only allowed to access 'edit_state' if we are the active widget. ImGuiTextEditState& edit_state = g.InputTextState; const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool hovered = IsHovered(frame_bb, id); if (hovered) { SetHoveredID(id); g.MouseCursor = ImGuiMouseCursor_TextInput; } const bool user_clicked = hovered && io.MouseClicked[0]; const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY"); bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0; if (focus_requested || user_clicked || user_scrolled) { if (g.ActiveId != id) { // Start edition // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) const int prev_len_w = edit_state.CurLenW; edit_state.Text.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. edit_state.InitialText.resize(buf_size+1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size); const char* buf_end = NULL; edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. edit_state.CursorAnimReset(); // Preserve cursor position and undo/redo stack if we come back to same widget // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW); if (recycle_state) { // Recycle existing cursor/selection/undo stack but clamp position // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. edit_state.CursorClamp(); } else { edit_state.Id = id; edit_state.ScrollX = 0.0f; stb_textedit_initialize_state(&edit_state.StbState, !is_multiline); if (!is_multiline && focus_requested_by_code) select_all = true; } if (flags & ImGuiInputTextFlags_AlwaysInsertMode) edit_state.StbState.insert_mode = true; if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) select_all = true; } SetActiveID(id, window); FocusWindow(window); } else if (io.MouseClicked[0]) { // Release focus when we click outside if (g.ActiveId == id) ClearActiveID(); } bool value_changed = false; bool enter_pressed = false; if (g.ActiveId == id) { if (!is_editable && !g.ActiveIdIsJustActivated) { // When read-only we always use the live data passed to the function edit_state.Text.resize(buf_size+1); const char* buf_end = NULL; edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); edit_state.CurLenA = (int)(buf_end - buf); edit_state.CursorClamp(); } edit_state.BufSizeA = buf_size; // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. // Down the line we should have a cleaner library-wide concept of Selected vs Active. g.ActiveIdAllowOverlap = !io.MouseDown[0]; // Edit in progress const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX; const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); const bool osx_double_click_selects_words = io.OSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0])) { edit_state.SelectAll(); edit_state.SelectedAllMouseLock = true; } else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0]) { // Select a word only, OS X style (by simulating keystrokes) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); } else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) { stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y); edit_state.CursorAnimReset(); } else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) { stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y); edit_state.CursorAnimReset(); edit_state.CursorFollow = true; } if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) edit_state.SelectedAllMouseLock = false; if (io.InputCharacters[0]) { // Process text input (before we check for Return because using some IME will effectively send a Return?) // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters. if (!(io.KeyCtrl && !io.KeyAlt) && is_editable) { for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++) if (unsigned int c = (unsigned int)io.InputCharacters[n]) { // Insert character if they pass filtering if (!InputTextFilterCharacter(&c, flags, callback, user_data)) continue; edit_state.OnKeyPressed((int)c); } } // Consume characters memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); } // Handle various key-presses bool cancel_edit = false; const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); const bool is_shortcut_key_only = (io.OSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl const bool is_wordmove_key_down = io.OSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl const bool is_startend_key_down = io.OSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) { if (!edit_state.HasSelection()) { if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); else if (io.OSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); } edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Enter)) { bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) { ClearActiveID(); enter_pressed = true; } else if (is_editable) { unsigned int c = '\n'; // Insert new line if (InputTextFilterCharacter(&c, flags, callback, user_data)) edit_state.OnKeyPressed((int)c); } } else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable) { unsigned int c = '\t'; // Insert TAB if (InputTextFilterCharacter(&c, flags, callback, user_data)) edit_state.OnKeyPressed((int)c); } else if (IsKeyPressedMap(ImGuiKey_Escape)) { ClearActiveID(); cancel_edit = true; } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; } else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection())) { // Cut, Copy const bool cut = IsKeyPressedMap(ImGuiKey_X); if (cut && !edit_state.HasSelection()) edit_state.SelectAll(); if (io.SetClipboardTextFn) { const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW; edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1); ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie); SetClipboardText(edit_state.TempTextBuffer.Data); } if (cut) { edit_state.CursorFollow = true; stb_textedit_cut(&edit_state, &edit_state.StbState); } } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable) { // Paste if (const char* clipboard = GetClipboardText()) { // Filter pasted buffer const int clipboard_len = (int)strlen(clipboard); ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar)); int clipboard_filtered_len = 0; for (const char* s = clipboard; *s; ) { unsigned int c; s += ImTextCharFromUtf8(&c, s, NULL); if (c == 0) break; if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data)) continue; clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; } clipboard_filtered[clipboard_filtered_len] = 0; if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation { stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); edit_state.CursorFollow = true; } ImGui::MemFree(clipboard_filtered); } } if (cancel_edit) { // Restore initial value if (is_editable) { ImStrncpy(buf, edit_state.InitialText.Data, buf_size); value_changed = true; } } else { // Apply new value immediately - copy modified buffer back // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. if (is_editable) { edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4); ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL); } // User callback if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) { IM_ASSERT(callback != NULL); // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. ImGuiInputTextFlags event_flag = 0; ImGuiKey event_key = ImGuiKey_COUNT; if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab)) { event_flag = ImGuiInputTextFlags_CallbackCompletion; event_key = ImGuiKey_Tab; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_UpArrow; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_DownArrow; } else if (flags & ImGuiInputTextFlags_CallbackAlways) event_flag = ImGuiInputTextFlags_CallbackAlways; if (event_flag) { ImGuiTextEditCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); callback_data.EventFlag = event_flag; callback_data.Flags = flags; callback_data.UserData = user_data; callback_data.ReadOnly = !is_editable; callback_data.EventKey = event_key; callback_data.Buf = edit_state.TempTextBuffer.Data; callback_data.BufTextLen = edit_state.CurLenA; callback_data.BufSize = edit_state.BufSizeA; callback_data.BufDirty = false; // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) ImWchar* text = edit_state.Text.Data; const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor); const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start); const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end); // Call user code callback(&callback_data); // Read back what user may have modified IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA); IM_ASSERT(callback_data.Flags == flags); if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); if (callback_data.BufDirty) { IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL); edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() edit_state.CursorAnimReset(); } } } // Copy back to user buffer if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0) { ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size); value_changed = true; } } } // Render // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on. const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL; if (!is_multiline) RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; ImVec2 text_size(0.f, 0.f); const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY")); if (g.ActiveId == id || is_currently_scrolling) { edit_state.CursorAnim += io.DeltaTime; // This is going to be messy. We need to: // - Display the text (this alone can be more easily clipped) // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) // - Measure text height (for scrollbar) // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. const ImWchar* text_begin = edit_state.Text.Data; ImVec2 cursor_offset, select_start_offset; { // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. const ImWchar* searches_input_ptr[2]; searches_input_ptr[0] = text_begin + edit_state.StbState.cursor; searches_input_ptr[1] = NULL; int searches_remaining = 1; int searches_result_line_number[2] = { -1, -999 }; if (edit_state.StbState.select_start != edit_state.StbState.select_end) { searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); searches_result_line_number[1] = -1; searches_remaining++; } // Iterate all lines to find our line numbers // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. searches_remaining += is_multiline ? 1 : 0; int line_count = 0; for (const ImWchar* s = text_begin; *s != 0; s++) if (*s == '\n') { line_count++; if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } } line_count++; if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count; if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count; // Calculate 2d position by finding the beginning of the line and measuring distance cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; cursor_offset.y = searches_result_line_number[0] * g.FontSize; if (searches_result_line_number[1] >= 0) { select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; select_start_offset.y = searches_result_line_number[1] * g.FontSize; } // Calculate text height if (is_multiline) text_size = ImVec2(size.x, line_count * g.FontSize); } // Scroll if (edit_state.CursorFollow) { // Horizontal scroll in chunks of quarter width if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) { const float scroll_increment_x = size.x * 0.25f; if (cursor_offset.x < edit_state.ScrollX) edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); else if (cursor_offset.x - size.x >= edit_state.ScrollX) edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); } else { edit_state.ScrollX = 0.0f; } // Vertical scroll if (is_multiline) { float scroll_y = draw_window->Scroll.y; if (cursor_offset.y - g.FontSize < scroll_y) scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); else if (cursor_offset.y - size.y >= scroll_y) scroll_y = cursor_offset.y - size.y; draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag draw_window->Scroll.y = scroll_y; render_pos.y = draw_window->DC.CursorPos.y; } } edit_state.CursorFollow = false; const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f); // Draw selection if (edit_state.StbState.select_start != edit_state.StbState.select_end) { const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end); float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. float bg_offy_dn = is_multiline ? 0.0f : 2.0f; ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg); ImVec2 rect_pos = render_pos + select_start_offset - render_scroll; for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) { if (rect_pos.y > clip_rect.w + g.FontSize) break; if (rect_pos.y < clip_rect.y) { while (p < text_selected_end) if (*p++ == '\n') break; } else { ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn)); rect.Clip(clip_rect); if (rect.Overlaps(clip_rect)) draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); } rect_pos.x = render_pos.x - render_scroll.x; rect_pos.y += g.FontSize; } } draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect); // Draw blinking cursor bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f; ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll; ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) if (is_editable) g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize); } else { // Render text only const char* buf_end = NULL; if (is_multiline) text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); } if (is_multiline) { Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line EndChildFrame(); EndGroup(); } if (is_password) PopFont(); // Log as text if (g.LogEnabled && !is_password) LogRenderedText(render_pos, buf_display, NULL); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) return enter_pressed; else return value_changed; } bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); } bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); } // NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument) bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImVec2 label_size = CalcTextSize(label, NULL, true); BeginGroup(); PushID(label); const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f; if (step_ptr) PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2)); char buf[64]; DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf)); bool value_changed = false; if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal)) extra_flags |= ImGuiInputTextFlags_CharsDecimal; extra_flags |= ImGuiInputTextFlags_AutoSelectAll; if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format); // Step buttons if (step_ptr) { PopItemWidth(); SameLine(0, style.ItemInnerSpacing.x); if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) { DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); value_changed = true; } SameLine(0, style.ItemInnerSpacing.x); if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) { DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); value_changed = true; } } PopID(); if (label_size.x > 0) { SameLine(0, style.ItemInnerSpacing.x); RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label); ItemSize(label_size, style.FramePadding.y); } EndGroup(); return value_changed; } bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) { char display_format[16]; if (decimal_precision < 0) strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1 else ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision); return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags); } bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags) { // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags); } bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags) { return InputFloatN(label, v, 2, decimal_precision, extra_flags); } bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags) { return InputFloatN(label, v, 3, decimal_precision, extra_flags); } bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags) { return InputFloatN(label, v, 4, decimal_precision, extra_flags); } bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags) { return InputIntN(label, v, 2, extra_flags); } bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags) { return InputIntN(label, v, 3, extra_flags); } bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags) { return InputIntN(label, v, 4, extra_flags); } static bool Items_ArrayGetter(void* data, int idx, const char** out_text) { const char* const* items = (const char* const*)data; if (out_text) *out_text = items[idx]; return true; } static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) { // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. const char* items_separated_by_zeros = (const char*)data; int items_count = 0; const char* p = items_separated_by_zeros; while (*p) { if (idx == items_count) break; p += strlen(p) + 1; items_count++; } if (!*p) return false; if (out_text) *out_text = p; return true; } // Combo box helper allowing to pass an array of strings. bool ImGui::Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items) { const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); return value_changed; } // Combo box helper allowing to pass all items in a single string. bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) { int items_count = 0; const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open while (*p) { p += strlen(p) + 1; items_count++; } bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); return value_changed; } // Combo box function. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, &id)) return false; const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f); const bool hovered = IsHovered(frame_bb, id); bool popup_open = IsPopupOpen(id); bool popup_opened_now = false; const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true); if (*current_item >= 0 && *current_item < items_count) { const char* item_text; if (items_getter(data, *current_item, &item_text)) RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL, ImVec2(0.0f,0.0f)); } if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); if (hovered) { SetHoveredID(id); if (g.IO.MouseClicked[0]) { ClearActiveID(); if (IsPopupOpen(id)) { ClosePopup(id); } else { FocusWindow(window); OpenPopup(label); popup_open = popup_opened_now = true; } } } bool value_changed = false; if (IsPopupOpen(id)) { // Size default to hold ~7 items if (height_in_items < 0) height_in_items = 7; float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3); float popup_y1 = frame_bb.Max.y; float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y); if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y)) { // Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement) popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y); popup_y2 = frame_bb.Min.y; } ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2)); SetNextWindowPos(popup_rect.Min); SetNextWindowSize(popup_rect.GetSize()); PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0); if (BeginPopupEx(label, flags)) { // Display items Spacing(); for (int i = 0; i < items_count; i++) { PushID((void*)(intptr_t)i); const bool item_selected = (i == *current_item); const char* item_text; if (!items_getter(data, i, &item_text)) item_text = "*Unknown item*"; if (Selectable(item_text, item_selected)) { ClearActiveID(); value_changed = true; *current_item = i; } if (item_selected && popup_opened_now) SetScrollHere(); PopID(); } EndPopup(); } PopStyleVar(); } return value_changed; } // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID. bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) PopClipRect(); ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); ImVec2 pos = window->DC.CursorPos; pos.y += window->DC.CurrentLineTextBaseOffset; ImRect bb(pos, pos + size); ItemSize(bb); // Fill horizontal space. ImVec2 window_padding = window->WindowPadding; float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x); ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); ImRect bb_with_spacing(pos, pos + size_draw); if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) bb_with_spacing.Max.x += window_padding.x; // Selectables are tightly packed together, we extend the box to cover spacing between selectable. float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); float spacing_R = style.ItemSpacing.x - spacing_L; float spacing_D = style.ItemSpacing.y - spacing_U; bb_with_spacing.Min.x -= spacing_L; bb_with_spacing.Min.y -= spacing_U; bb_with_spacing.Max.x += spacing_R; bb_with_spacing.Max.y += spacing_D; if (!ItemAdd(bb_with_spacing, &id)) { if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) PushColumnClipRect(); return false; } ImGuiButtonFlags button_flags = 0; if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick; if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease; if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; bool hovered, held; bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags); if (flags & ImGuiSelectableFlags_Disabled) selected = false; // Render if (hovered || selected) { const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f); } if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) { PushColumnClipRect(); bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x); } if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f)); if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); // Automatically close popups if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) CloseCurrentPopup(); return pressed; } bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { if (Selectable(label, *p_selected, flags, size_arg)) { *p_selected = !*p_selected; return true; } return false; } // Helper to calculate the size of a listbox and display a label on the right. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty" bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = GetStyle(); const ImGuiID id = GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); window->DC.LastItemRect = bb; BeginGroup(); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); BeginChildFrame(id, frame_bb.GetSize()); return true; } bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items) { // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. // However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution. if (height_in_items < 0) height_in_items = ImMin(items_count, 7); float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f); // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). ImVec2 size; size.x = 0.0f; size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y; return ListBoxHeader(label, size); } void ImGui::ListBoxFooter() { ImGuiWindow* parent_window = GetParentWindow(); const ImRect bb = parent_window->DC.LastItemRect; const ImGuiStyle& style = GetStyle(); EndChildFrame(); // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) // We call SameLine() to restore DC.CurrentLine* data SameLine(); parent_window->DC.CursorPos = bb.Min; ItemSize(bb, style.FramePadding.y); EndGroup(); } bool ImGui::ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_items) { const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); return value_changed; } bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { if (!ListBoxHeader(label, items_count, height_in_items)) return false; // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. bool value_changed = false; ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { const bool item_selected = (i == *current_item); const char* item_text; if (!items_getter(data, i, &item_text)) item_text = "*Unknown item*"; PushID(i); if (Selectable(item_text, item_selected)) { *current_item = i; value_changed = true; } PopID(); } ListBoxFooter(); return value_changed; } bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; ImVec2 pos = window->DC.CursorPos; ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), ImVec2(w, 0.0f)); if (shortcut_size.x > 0.0f) { PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false); PopStyleColor(); } if (selected) RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled)); return pressed; } bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) { if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled)) { if (p_selected) *p_selected = !*p_selected; return true; } return false; } bool ImGui::BeginMainMenuBar() { ImGuiContext& g = *GImGui; SetNextWindowPos(ImVec2(0.0f, 0.0f)); SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f)); PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0)); if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar) || !BeginMenuBar()) { End(); PopStyleVar(2); return false; } g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x; return true; } void ImGui::EndMainMenuBar() { EndMenuBar(); End(); PopStyleVar(2); } bool ImGui::BeginMenuBar() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; if (!(window->Flags & ImGuiWindowFlags_MenuBar)) return false; IM_ASSERT(!window->DC.MenuBarAppending); BeginGroup(); // Save position PushID("##menubar"); ImRect rect = window->MenuBarRect(); PushClipRect(ImVec2(ImFloor(rect.Min.x+0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x+0.5f), ImFloor(rect.Max.y+0.5f)), false); window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y); window->DC.LayoutType = ImGuiLayoutType_Horizontal; window->DC.MenuBarAppending = true; AlignFirstTextHeightToWidgets(); return true; } void ImGui::EndMenuBar() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); IM_ASSERT(window->DC.MenuBarAppending); PopClipRect(); PopID(); window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x; window->DC.GroupStack.back().AdvanceCursor = false; EndGroup(); window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.MenuBarAppending = false; } bool ImGui::BeginMenu(const char* label, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(label, NULL, true); ImGuiWindow* backed_focused_window = g.FocusedWindow; bool pressed; bool menu_is_open = IsPopupOpen(id); bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus")); if (menuset_is_open) g.FocusedWindow = window; // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos). ImVec2 popup_pos, pos = window->DC.CursorPos; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight()); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); float w = label_size.x; pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); PopStyleVar(); SameLine(); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); } else { popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false); if (!enabled) PopStyleColor(); } bool hovered = enabled && IsHovered(window->DC.LastItemRect, id); if (menuset_is_open) g.FocusedWindow = backed_focused_window; bool want_open = false, want_close = false; if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) { // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. bool moving_within_opened_triangle = false; if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window) { if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window) { ImRect next_window_rect = next_window->Rect(); ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); moving_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc); //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug } } want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle); want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed); } else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close { want_close = true; want_open = menu_is_open = false; } else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others want_open = true; if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' want_close = true; if (want_close && IsPopupOpen(id)) ClosePopupToLevel(GImGui->CurrentPopupStack.Size); if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size) { // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame. OpenPopup(label); return false; } menu_is_open |= want_open; if (want_open) OpenPopup(label); if (menu_is_open) { SetNextWindowPos(popup_pos, ImGuiSetCond_Always); ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu); menu_is_open = BeginPopupEx(label, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) } return menu_is_open; } void ImGui::EndMenu() { EndPopup(); } // A little colored square. Return true when clicked. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID("#colorbutton"); const float square_size = g.FontSize; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); ItemSize(bb, small_height ? 0.0f : style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding); if (hovered) SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8_SAT(col.x), IM_F32_TO_INT8_SAT(col.y), IM_F32_TO_INT8_SAT(col.z), IM_F32_TO_INT8_SAT(col.w)); return pressed; } bool ImGui::ColorEdit3(const char* label, float col[3]) { float col4[4]; col4[0] = col[0]; col4[1] = col[1]; col4[2] = col[2]; col4[3] = 1.0f; const bool value_changed = ColorEdit4(label, col4, false); col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; return value_changed; } // Edit colors components (each component in 0.0f..1.0f range // Use CTRL-Click to input value and TAB to go to next item. bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w_full = CalcItemWidth(); const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f); ImGuiColorEditMode edit_mode = window->DC.ColorEditMode; if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton) edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3; float f[4] = { col[0], col[1], col[2], col[3] }; if (edit_mode == ImGuiColorEditMode_HSV) ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; int components = alpha ? 4 : 3; bool value_changed = false; BeginGroup(); PushID(label); const bool hsv = (edit_mode == 1); switch (edit_mode) { case ImGuiColorEditMode_RGB: case ImGuiColorEditMode_HSV: { // RGB/HSV 0..255 Sliders const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x); const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x); const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; const char* fmt_table[3][4] = { { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } }; const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1]; PushItemWidth(w_item_one); for (int n = 0; n < components; n++) { if (n > 0) SameLine(0, style.ItemInnerSpacing.x); if (n + 1 == components) PushItemWidth(w_item_last); value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]); } PopItemWidth(); PopItemWidth(); } break; case ImGuiColorEditMode_HEX: { // RGB Hexadecimal Input const float w_slider_all = w_full - square_sz; char buf[64]; if (alpha) ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]); else ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]); PushItemWidth(w_slider_all - style.ItemInnerSpacing.x); if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) { value_changed |= true; char* p = buf; while (*p == '#' || ImCharIsSpace(*p)) p++; i[0] = i[1] = i[2] = i[3] = 0; if (alpha) sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) else sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); } PopItemWidth(); } break; } SameLine(0, style.ItemInnerSpacing.x); const ImVec4 col_display(col[0], col[1], col[2], 1.0f); if (ColorButton(col_display)) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here if (IsItemHovered()) SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8_SAT(col[0]), IM_F32_TO_INT8_SAT(col[1]), IM_F32_TO_INT8_SAT(col[2]), IM_F32_TO_INT8_SAT(col[3])); if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) { SameLine(0, style.ItemInnerSpacing.x); const char* button_titles[3] = { "RGB", "HSV", "HEX" }; if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups)) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! } const char* label_display_end = FindRenderedTextEnd(label); if (label != label_display_end) { SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x); TextUnformatted(label, label_display_end); } // Convert back for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; if (edit_mode == 1) ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); if (value_changed) { col[0] = f[0]; col[1] = f[1]; col[2] = f[2]; if (alpha) col[3] = f[3]; } PopID(); EndGroup(); return value_changed; } void ImGui::ColorEditMode(ImGuiColorEditMode mode) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ColorEditMode = mode; } // Horizontal separating line. void ImGui::Separator() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; if (window->DC.ColumnsCount > 1) PopClipRect(); float x1 = window->Pos.x; float x2 = window->Pos.x + window->Size.x; if (!window->DC.GroupStack.empty()) x1 += window->DC.IndentX; const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f)); ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout. if (!ItemAdd(bb, NULL)) { if (window->DC.ColumnsCount > 1) PushColumnClipRect(); return; } window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Border)); ImGuiContext& g = *GImGui; if (g.LogEnabled) LogText(IM_NEWLINE "--------------------------------"); if (window->DC.ColumnsCount > 1) { PushColumnClipRect(); window->DC.ColumnsCellMinY = window->DC.CursorPos.y; } } void ImGui::Spacing() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ItemSize(ImVec2(0,0)); } void ImGui::Dummy(const ImVec2& size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); ItemAdd(bb, NULL); } bool ImGui::IsRectVisible(const ImVec2& size) { ImGuiWindow* window = GetCurrentWindowRead(); return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); } bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) { ImGuiWindow* window = GetCurrentWindowRead(); return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) void ImGui::BeginGroup() { ImGuiWindow* window = GetCurrentWindow(); window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); ImGuiGroupData& group_data = window->DC.GroupStack.back(); group_data.BackupCursorPos = window->DC.CursorPos; group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; group_data.BackupIndentX = window->DC.IndentX; group_data.BackupGroupOffsetX = window->DC.GroupOffsetX; group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight; group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; group_data.BackupLogLinePosY = window->DC.LogLinePosY; group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive; group_data.AdvanceCursor = true; window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX; window->DC.IndentX = window->DC.GroupOffsetX; window->DC.CursorMaxPos = window->DC.CursorPos; window->DC.CurrentLineHeight = 0.0f; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; } void ImGui::EndGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls ImGuiGroupData& group_data = window->DC.GroupStack.back(); ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos); group_bb.Max.y -= g.Style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves. group_bb.Max = ImMax(group_bb.Min, group_bb.Max); window->DC.CursorPos = group_data.BackupCursorPos; window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight; window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; window->DC.IndentX = group_data.BackupIndentX; window->DC.GroupOffsetX = group_data.BackupGroupOffsetX; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; if (group_data.AdvanceCursor) { window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); ItemAdd(group_bb, NULL); } // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will function on the entire group. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context. const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow); if (active_id_within_group) window->DC.LastItemId = g.ActiveId; if (active_id_within_group && g.HoveredId == g.ActiveId) window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = true; window->DC.GroupStack.pop_back(); //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // Debug } // Gets back to previous line and continue with horizontal layout // pos_x == 0 : follow right after previous item // pos_x != 0 : align to specified x position (relative to window/group left) // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 // spacing_w >= 0 : enforce spacing amount void ImGui::SameLine(float pos_x, float spacing_w) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; if (pos_x != 0.0f) { if (spacing_w < 0.0f) spacing_w = 0.0f; window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } else { if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x; window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } window->DC.CurrentLineHeight = window->DC.PrevLineHeight; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; } void ImGui::NewLine() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. ItemSize(ImVec2(0,0)); else ItemSize(ImVec2(0.0f, GImGui->FontSize)); } void ImGui::NextColumn() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems || window->DC.ColumnsCount <= 1) return; ImGuiContext& g = *GImGui; PopItemWidth(); PopClipRect(); window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount) { // Columns 1+ cancel out IndentX window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x; window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent); } else { window->DC.ColumnsCurrent = 0; window->DC.ColumnsOffsetX = 0.0f; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY; window->DrawList->ChannelsSetCurrent(0); } window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); window->DC.CursorPos.y = window->DC.ColumnsCellMinY; window->DC.CurrentLineHeight = 0.0f; window->DC.CurrentLineTextBaseOffset = 0.0f; PushColumnClipRect(); PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup } int ImGui::GetColumnIndex() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.ColumnsCurrent; } int ImGui::GetColumnsCount() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.ColumnsCount; } static float GetDraggedColumnOffset(int column_index) { // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. ImGuiContext& g = *GImGui; ImGuiWindow* window = ImGui::GetCurrentWindowRead(); IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets. IM_ASSERT(g.ActiveId == window->DC.ColumnsSetId + ImGuiID(column_index)); float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x; x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing); return (float)(int)x; } float ImGui::GetColumnOffset(int column_index) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindowRead(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; if (g.ActiveId) { const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); if (g.ActiveId == column_id) return GetDraggedColumnOffset(column_index); } IM_ASSERT(column_index < window->DC.ColumnsData.Size); const float t = window->DC.ColumnsData[column_index].OffsetNorm; const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); return (float)(int)x_offset; } void ImGui::SetColumnOffset(int column_index, float offset) { ImGuiWindow* window = GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; IM_ASSERT(column_index < window->DC.ColumnsData.Size); const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); window->DC.ColumnsData[column_index].OffsetNorm = t; const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); window->DC.StateStorage->SetFloat(column_id, t); } float ImGui::GetColumnWidth(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); return w; } static void PushColumnClipRect(int column_index) { ImGuiWindow* window = ImGui::GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f); float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f); ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true); } void ImGui::Columns(int columns_count, const char* id, bool border) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); if (window->DC.ColumnsCount != 1) { if (window->DC.ColumnsCurrent != 0) ItemSize(ImVec2(0,0)); // Advance to column 0 PopItemWidth(); PopClipRect(); window->DrawList->ChannelsMerge(); window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = window->DC.ColumnsCellMaxY; } // Draw columns borders and handle resize at the time of "closing" a columns set if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems) { const float y1 = window->DC.ColumnsStartPosY; const float y2 = window->DC.CursorPos.y; for (int i = 1; i < window->DC.ColumnsCount; i++) { float x = window->Pos.x + GetColumnOffset(i); const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(i); const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2)); if (IsClippedEx(column_rect, &column_id, false)) continue; bool hovered, held; ButtonBehavior(column_rect, column_id, &hovered, &held); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; // Draw before resize so our items positioning are in sync with the line being drawn const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); const float xi = (float)(int)x; window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col); if (held) { if (g.ActiveIdIsJustActivated) g.ActiveIdClickOffset.x -= 4; // Store from center of column line (we used a 8 wide rect for columns clicking) x = GetDraggedColumnOffset(i); SetColumnOffset(i, x); } } } // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. PushID(0x11223347 + (id ? 0 : columns_count)); window->DC.ColumnsSetId = window->GetID(id ? id : "columns"); PopID(); // Set state for first column window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = columns_count; window->DC.ColumnsShowBorders = border; const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x; window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x; window->DC.ColumnsStartPosY = window->DC.CursorPos.y; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffsetX = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); if (window->DC.ColumnsCount != 1) { // Cache column offsets window->DC.ColumnsData.resize(columns_count + 1); for (int column_index = 0; column_index < columns_count + 1; column_index++) { const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); KeepAliveID(column_id); const float default_t = column_index / (float)window->DC.ColumnsCount; const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store a union into the map?) window->DC.ColumnsData[column_index].OffsetNorm = t; } window->DrawList->ChannelsSplit(window->DC.ColumnsCount); PushColumnClipRect(); PushItemWidth(GetColumnWidth() * 0.65f); } else { window->DC.ColumnsData.resize(0); } } void ImGui::Indent(float indent_w) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; } void ImGui::Unindent(float indent_w) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; } void ImGui::TreePush(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); window->DC.TreeDepth++; PushID(str_id ? str_id : "#TreePush"); } void ImGui::TreePush(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); window->DC.TreeDepth++; PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); } void ImGui::TreePushRawID(ImGuiID id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); window->DC.TreeDepth++; window->IDStack.push_back(id); } void ImGui::TreePop() { ImGuiWindow* window = GetCurrentWindow(); Unindent(); window->DC.TreeDepth--; PopID(); } void ImGui::Value(const char* prefix, bool b) { Text("%s: %s", prefix, (b ? "true" : "false")); } void ImGui::Value(const char* prefix, int v) { Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, unsigned int v) { Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, float v, const char* float_format) { if (float_format) { char fmt[64]; ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); Text(fmt, prefix, v); } else { Text("%s: %.3f", prefix, v); } } // FIXME: May want to remove those helpers? void ImGui::ValueColor(const char* prefix, const ImVec4& v) { Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); SameLine(); ColorButton(v, true); } void ImGui::ValueColor(const char* prefix, ImU32 v) { Text("%s: %08X", prefix, v); SameLine(); ColorButton(ColorConvertU32ToFloat4(v), true); } //----------------------------------------------------------------------------- // PLATFORM DEPENDENT HELPERS //----------------------------------------------------------------------------- #if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)) #undef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // Win32 API clipboard implementation #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) #ifdef _MSC_VER #pragma comment(lib, "user32") #endif static const char* GetClipboardTextFn_DefaultImpl(void*) { static ImVector<char> buf_local; buf_local.clear(); if (!OpenClipboard(NULL)) return NULL; HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); if (wbuf_handle == NULL) return NULL; if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle)) { int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; buf_local.resize(buf_len); ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL); } GlobalUnlock(wbuf_handle); CloseClipboard(); return buf_local.Data; } static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { if (!OpenClipboard(NULL)) return; const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); if (wbuf_handle == NULL) return; ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle); ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); GlobalUnlock(wbuf_handle); EmptyClipboard(); SetClipboardData(CF_UNICODETEXT, wbuf_handle); CloseClipboard(); } #else // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static const char* GetClipboardTextFn_DefaultImpl(void*) { return GImGui->PrivateClipboard; } // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { ImGuiContext& g = *GImGui; if (g.PrivateClipboard) { ImGui::MemFree(g.PrivateClipboard); g.PrivateClipboard = NULL; } const char* text_end = text + strlen(text); g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1); memcpy(g.PrivateClipboard, text, (size_t)(text_end - text)); g.PrivateClipboard[(int)(text_end - text)] = 0; } #endif // Win32 API IME support (for Asian languages, etc.) #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS) #include <imm.h> #ifdef _MSC_VER #pragma comment(lib, "imm32") #endif static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) { // Notify OS Input Method Editor of text input position if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) if (HIMC himc = ImmGetContext(hwnd)) { COMPOSITIONFORM cf; cf.ptCurrentPos.x = x; cf.ptCurrentPos.y = y; cf.dwStyle = CFS_FORCE_POSITION; ImmSetCompositionWindow(himc, &cf); } } #else static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} #endif //----------------------------------------------------------------------------- // HELP //----------------------------------------------------------------------------- void ImGui::ShowMetricsWindow(bool* p_open) { if (ImGui::Begin("ImGui Metrics", p_open)) { ImGui::Text("ImGui %s", ImGui::GetVersion()); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3); ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs); static bool show_clip_rects = true; ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects); ImGui::Separator(); struct Funcs { static void NodeDrawList(ImDrawList* draw_list, const char* label) { bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) if (node_open) ImGui::TreePop(); return; } if (!node_open) return; ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list overlay_draw_list->PushClipRectFullScreen(); int elem_offset = 0; for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) { if (pcmd->UserCallback) { ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); continue; } ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); if (show_clip_rects && ImGui::IsItemHovered()) { ImRect clip_rect = pcmd->ClipRect; ImRect vtxs_rect; for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); } if (!pcmd_node_open) continue; ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) { char buf[300], *buf_p = buf; ImVec2 triangles_pos[3]; for (int n = 0; n < 3; n++, vtx_i++) { ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i]; triangles_pos[n] = v.pos; buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); } ImGui::Selectable(buf, false); if (ImGui::IsItemHovered()) overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle } ImGui::TreePop(); } overlay_draw_list->PopClipRect(); ImGui::TreePop(); } static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label) { if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) return; for (int i = 0; i < windows.Size; i++) Funcs::NodeWindow(windows[i], "Window"); ImGui::TreePop(); } static void NodeWindow(ImGuiWindow* window, const char* label) { if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) return; NodeDrawList(window->DrawList, "DrawList"); ImGui::BulletText("Pos: (%.1f,%.1f)", window->Pos.x, window->Pos.y); ImGui::BulletText("Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); ImGui::BulletText("Scroll: (%.2f,%.2f)", window->Scroll.x, window->Scroll.y); if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); ImGui::TreePop(); } }; ImGuiContext& g = *GImGui; // Access private state Funcs::NodeWindows(g.Windows, "Windows"); if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size)) { for (int i = 0; i < g.RenderDrawLists[0].Size; i++) Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList"); ImGui::TreePop(); } if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size)) { for (int i = 0; i < g.OpenPopupStack.Size; i++) { ImGuiWindow* window = g.OpenPopupStack[i].Window; ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); } ImGui::TreePop(); } if (ImGui::TreeNode("Basic state")) { ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL"); ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); ImGui::Text("HoveredID: 0x%08X/0x%08X", g.HoveredId, g.HoveredIdPreviousFrame); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not ImGui::Text("ActiveID: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame); ImGui::TreePop(); } } ImGui::End(); } //----------------------------------------------------------------------------- // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. // Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL #include "imgui_user.inl" #endif //-----------------------------------------------------------------------------
[ "jackabis@hotmail.com" ]
jackabis@hotmail.com
870bd1feaa16db2b40ac7b2f6202cfb1cc7057f7
ae25bffa378345c49e5ef5a0347f2c121c7a0f31
/ns-2.1b8a/estimator.cc
277a067833c92d1f883ce69a731ec910ec7fcef5
[]
no_license
smilemare/NS-2.1b8a-MacOS
49a00733c4aee95e86324d595bb7e85d98259be9
b556e49bf6ff88df0bdd983baaae68a809676f88
refs/heads/master
2020-12-24T15:22:53.671307
2014-10-31T10:04:37
2014-10-31T10:04:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,398
cc
/* -*- Mode:C++; c-basic-offset:8; tab-width:8; indent-tabs-mode:t -*- */ /* * Copyright (c) Xerox Corporation 1997. All rights reserved. * * License is granted to copy, to use, and to make and to use derivative * works for research and evaluation purposes, provided that Xerox is * acknowledged in all documentation pertaining to any such copy or * derivative work. Xerox grants no other licenses expressed or * implied. The Xerox trade name should not be used in any advertising * without its written permission. * * XEROX CORPORATION MAKES NO REPRESENTATIONS CONCERNING EITHER THE * MERCHANTABILITY OF THIS SOFTWARE OR THE SUITABILITY OF THIS SOFTWARE * FOR ANY PARTICULAR PURPOSE. The software is provided "as is" without * express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * software. */ #ifndef lint static const char rcsid[] = "@(#) $Header: /nfs/jade/vint/CVSROOT/ns-2/estimator.cc,v 1.7 1999/03/13 03:52:47 haoboy Exp $"; #endif #include "estimator.h" Estimator::Estimator() : meas_mod_(0),avload_(0.0),est_timer_(this), measload_(0.0), tchan_(0), omeasload_(0), oavload_(0) { bind("period_",&period_); bind("src_", &src_); bind("dst_", &dst_); avload_.tracer(this); avload_.name("\"Estimated Util.\""); measload_.tracer(this); measload_.name("\"Measured Util.\""); } int Estimator::command(int argc, const char*const* argv) { Tcl& tcl = Tcl::instance(); if (argc==2) { if (strcmp(argv[1],"load-est") == 0) { tcl.resultf("%.3f",double(avload_)); return(TCL_OK); } else if (strcmp(argv[1],"link-utlzn") == 0) { tcl.resultf("%.3f",meas_mod_->bitcnt()/period_); return(TCL_OK); } } if (argc == 3) { if (strcmp(argv[1], "attach") == 0) { int mode; const char* id = argv[2]; tchan_ = Tcl_GetChannel(tcl.interp(), (char*)id, &mode); if (tchan_ == 0) { tcl.resultf("Estimator: trace: can't attach %s for writing", id); return (TCL_ERROR); } return (TCL_OK); } if (strcmp(argv[1], "setbuf") == 0) { /* some sub classes actually do something here */ return(TCL_OK); } } return NsObject::command(argc,argv); } void Estimator::setmeasmod (MeasureMod *measmod) { meas_mod_=measmod; } void Estimator::start() { avload_=0; measload_ = 0; est_timer_.resched(period_); } void Estimator::stop() { est_timer_.cancel(); } void Estimator::timeout(int) { estimate(); est_timer_.resched(period_); } void Estimator_Timer::expire(Event* /*e*/) { est_->timeout(0); } void Estimator::trace(TracedVar* v) { char wrk[500]; double *p, newval; /* check for right variable */ if (strcmp(v->name(), "\"Estimated Util.\"") == 0) { p = &oavload_; } else if (strcmp(v->name(), "\"Measured Util.\"") == 0) { p = &omeasload_; } else { fprintf(stderr, "Estimator: unknown trace var %s\n", v->name()); return; } newval = double(*((TracedDouble*)v)); if (tchan_) { int n; double t = Scheduler::instance().clock(); /* f -t 0.0 -s 1 -a SA -T v -n Num -v 0 -o 0 */ sprintf(wrk, "f -t %g -s %d -a %s:%d-%d -T v -n %s -v %g -o %g", t, src_, actype_, src_, dst_, v->name(), newval, *p); n = strlen(wrk); wrk[n] = '\n'; wrk[n+1] = 0; (void)Tcl_Write(tchan_, wrk, n+1); } *p = newval; return; } void Estimator::setactype(const char* type) { actype_ = new char[strlen(type)+1]; strcpy(actype_, type); return; }
[ "smilemare@foxmail.com" ]
smilemare@foxmail.com
a7dbb20301c8cb12664bf5e00dad15856e30de6a
b4fc47d2ff55347cb70e36c9a4ddef1e715bc35b
/Stickman Empire/mina_hierro.cpp
515a4637de2b3c145d1ed9c4947c6ada062a9455
[]
no_license
Luismvst/Stickman-Empire
c7cfb20963c3d74121d3686f6317c5e0d8f0810f
afa52fd0e1e9077a110dca245c66324fd5e89dc6
refs/heads/master
2021-06-16T12:29:22.004753
2017-05-08T21:32:22
2017-05-08T21:32:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
100
cpp
#include "mina_hierro.h" mina_hierro::mina_hierro(void) { } mina_hierro::~mina_hierro(void) { }
[ "javier.martinez@blatech.com" ]
javier.martinez@blatech.com
a989b09081835d8ed64d1ef6928d1ef64f4a03a5
104f116e2a012aa37679cec150d4e08db6312986
/test/normalize_ops_test.cpp
41d2b744926ac00344049608f942cc4089d32ab4
[ "MIT" ]
permissive
ROCmSupport/AMDMIGraphX
905efb57287818e7ba425db9b53a876ab5c7c2c7
62a1b87bac64ca51b9ba87865e909ff12c475031
refs/heads/master
2023-02-17T04:32:36.987671
2021-01-18T13:20:35
2021-01-18T13:20:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,573
cpp
#include <migraphx/normalize_ops.hpp> #include <migraphx/dead_code_elimination.hpp> #include <migraphx/pass_manager.hpp> #include <migraphx/make_op.hpp> #include <migraphx/functional.hpp> #include <migraphx/op/normalize_attribute.hpp> #include <basic_ops.hpp> #include <test.hpp> struct normalize_test_op { std::vector<int64_t> axes = {}; template <class Self, class F> static auto reflect(Self& self, F f) { return migraphx::pack(f(self.axes, "axes")); } migraphx::value attributes() const { migraphx::value normalize; normalize["axes"] = migraphx::value::array{migraphx::op::normalize_attribute::clip_max, migraphx::op::normalize_attribute::clip_min}; return {{"normalize_axes", normalize}}; } std::string name() const { return "normalize_ops_test::test_op"; } migraphx::shape normalize_compute_shape(std::vector<migraphx::shape> inputs) const { return inputs[0]; } migraphx::argument compute(migraphx::context&, const migraphx::shape& output_shape, const std::vector<migraphx::argument>&) const { return {output_shape}; } }; void run_pass(migraphx::program& p) { migraphx::run_passes(*p.get_main_module(), {migraphx::normalize_ops{}, migraphx::dead_code_elimination{}}); } migraphx::program create_gather(int64_t axis) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape sd{migraphx::shape::float_type, {2, 3, 4}}; migraphx::shape si{migraphx::shape::int64_type, {2, 3}}; auto di = mm->add_parameter("data", sd); auto ii = mm->add_parameter("ind", si); auto r = mm->add_instruction(migraphx::make_op("gather", {{"axis", axis}}), di, ii); mm->add_return({r}); return p; } TEST_CASE(gather_test) { auto p1 = create_gather(-3); auto p2 = create_gather(0); run_pass(p1); EXPECT(p1 == p2); } TEST_CASE(gather_test_1) { auto p1 = create_gather(1); auto p2 = create_gather(1); run_pass(p1); EXPECT(p1 == p2); } migraphx::program create_reduce_mean(const std::vector<int64_t>& axes) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3, 4, 5}}; auto si = mm->add_parameter("data", s); auto r = mm->add_instruction(migraphx::make_op("reduce_mean", {{"axes", axes}}), si); mm->add_return({r}); return p; } TEST_CASE(reduce_mean_test) { migraphx::program p1 = create_reduce_mean({0, 1, -1}); migraphx::program p2 = create_reduce_mean({0, 1, 3}); run_pass(p1); EXPECT(p1 == p2); } TEST_CASE(reduce_mean_test_1) { migraphx::program p1 = create_reduce_mean({0, 1, 2}); migraphx::program p2 = create_reduce_mean({0, 1, 2}); run_pass(p1); EXPECT(p1 == p2); } migraphx::program create_slice(const std::vector<int64_t>& axes, const std::vector<int64_t>& starts, const std::vector<int64_t>& ends) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3, 4, 5}}; auto si = mm->add_parameter("data", s); auto r = mm->add_instruction( migraphx::make_op("slice", {{"axes", axes}, {"starts", starts}, {"ends", ends}}), si); mm->add_return({r}); return p; } TEST_CASE(slice_test) { migraphx::program p1 = create_slice({0, 1, -1}, {-5, 1, -3}, {2, 2, 8}); migraphx::program p2 = create_slice({0, 1, 3}, {0, 1, 2}, {2, 2, 5}); run_pass(p1); EXPECT(p1 == p2); } TEST_CASE(slice_test_1) { migraphx::program p1 = create_slice({0, 1, 3}, {0, 1, -3}, {1, 2, 5}); migraphx::program p2 = create_slice({0, 1, 3}, {0, 1, 2}, {1, 2, 5}); run_pass(p1); EXPECT(p1 == p2); } migraphx::program create_test_op(const std::vector<int64_t>& axes) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape sd{migraphx::shape::float_type, {2, 3, 4}}; auto di = mm->add_parameter("data", sd); auto r = mm->add_instruction(normalize_test_op{axes}, di); mm->add_return({r}); return p; } TEST_CASE(test_op) { std::vector<int64_t> axes1 = {-4, 5}; auto p1 = create_test_op(axes1); std::vector<int64_t> axes2 = {1, 2}; auto p2 = create_test_op(axes2); run_pass(p1); EXPECT(p1 == p2); } int main(int argc, const char* argv[]) { test::run(argc, argv); }
[ "noreply@github.com" ]
ROCmSupport.noreply@github.com
bf4a5b9281f7667067ef27d100123a6a0392058b
5692f5bfde9ede2da32ad0ce2eb0abc961701ff7
/JageToolUnit/Public/GExplosion.h
0a1bbf127586fd59151f7ea121b77c96a224db3c
[]
no_license
Jagez/JageGithub
267bdb1f8cf3409d13aeb62faac857501059be60
63aa1ae42be1547f5fef799b3c1ee817a1fccc06
refs/heads/master
2023-06-18T03:11:51.147469
2021-07-17T13:27:44
2021-07-17T13:27:44
386,945,203
0
0
null
null
null
null
UTF-8
C++
false
false
1,268
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "GExplosion.generated.h" UCLASS() class JAGETOOLUNIT_API AGExplosion : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AGExplosion(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Explosion") class UStaticMeshComponent* StaticMeshComp; UPROPERTY(EditDefaultsOnly, Category = "Explosion") class URadialForceComponent* RadialForceComp; UPROPERTY(EditDefaultsOnly, Category = "Explosion") class UGHealthComponent* HealthComponent; UPROPERTY(EditDefaultsOnly, Category = "Explosion") float ExplosionRadius; UPROPERTY(EditDefaultsOnly, Category = "Explosion") float ExplosionImpulse; UPROPERTY(EditDefaultsOnly, Category = "Explosion") class UParticleSystem* ExplosionEffect; private: UFUNCTION() void OnHealthChanged(class UGHealthComponent* HealthCoomponent , float Health , float DetlaHealth , const class UDamageType* DamageType , class AController* InstigatedBy , AActor* DamageCauser); };
[ "lwk283587151@outlook.com" ]
lwk283587151@outlook.com
d159cdf9d20a3ceed34df1fbc7bc4846784a0e85
0383b0b5099675c6831b35a8aed8adfd5f2abf70
/testSRC/bridgeTest.cpp
60c63620eb1fe522bcfd51329f567cab5b9c7341
[]
no_license
lanqingzi/DesignPattern
72ffc083005905908fa844158f6dc63fcc334eb0
4085a85cdec4ac3807db0a01ae8a76441755d7f9
refs/heads/master
2020-06-19T21:53:25.764704
2019-08-20T04:59:54
2019-08-20T04:59:54
149,331,604
0
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
// // Created by LAN on 8/18/2019. // #include "Bridge.h" #include <iostream> using namespace std; namespace bridge { void test() { cout << "bridge test" << endl; MobileBrand* mi = new Xiaomi(); MobileBrand* hua = new Huawei(); mi->setApp(new Contact()); hua->setApp(new Contact()); hua->setApp(new Game()); mi->showApps(); hua->showApps(); } }
[ "lanqingzi@gmail.com" ]
lanqingzi@gmail.com
242deeb827d58f6ddb5cdaeb6324bf4c67b9661f
598b739869abe01c2541ece728708ecdd078ef06
/OOPGame/armura_tertiara.h
8de197b608b11dd3ecdd297884830dd6bf6ef38f
[]
no_license
bogdanmacovei/OOP-Game-CPP
c7d5a888d002e46a951f1f939e349dcdc9dcfada
f2f486a2c6bfac93afb8b1a37e65204f908e405f
refs/heads/master
2021-05-14T19:30:16.604177
2017-12-31T10:53:25
2017-12-31T10:53:25
115,857,678
1
0
null
null
null
null
UTF-8
C++
false
false
249
h
#ifndef ARMURA_TERTIARA_H #define ARMURA_TERTIARA_H class Tertiara : public Armura { public: Tertiara (); ~Tertiara (); int getProtectie () const; std :: string getNume () const; }; #endif // ARMURA_TERTIARA_H
[ "bogdanmaco@yahoo.com" ]
bogdanmaco@yahoo.com
371a8652ffaae5c92d749ae5f9f03d6cc047f1e8
774f43ada2d36c938d541509dee89b22b6a796df
/include/drivers/driver.h
2c0aec06bc3a043e4588ddf72e14e5337f46809d
[]
no_license
ZirongCai/myos
bcdc0f45dc8a6cfa1bf35cc761c8742d9ffcfdba
b3765edc1f8f565164262c12a4fca7a652c6c8f9
refs/heads/main
2023-03-03T11:59:09.178044
2021-02-11T22:45:44
2021-02-11T22:45:44
315,337,184
0
0
null
null
null
null
UTF-8
C++
false
false
602
h
#ifndef __MYOS__DRIVERS__DRIVER_H #define __MYOS__DRIVERS__DRIVER_H namespace myos { namespace drivers { class Driver { public: Driver(); ~Driver(); virtual void Activate(); virtual int Reset(); virtual void Deactivate(); }; class DriverManager { private: Driver* drivers[255]; int numDrivers; public: DriverManager(); void AddDriver(Driver*); void ActivateAll(); }; } } #endif
[ "cai.zirong09@gmail.com" ]
cai.zirong09@gmail.com
4498ed412bcbee79faebd281e6fd15241247db23
d4f845dfe57ea8ced233d1cdef3c5f5869a70e15
/AdventOfCode/December11.h
343bc2c0dfa66b0e84513f70f42071f84812d9ba
[]
no_license
j-p-e-g/AdventOfCode2017
8a918a1b7788caf4ba77cfd671d225107a542ed6
853faef481dc7c37dd2e33a989c280a33b7d9150
refs/heads/master
2021-05-06T01:43:17.834734
2018-02-12T19:49:34
2018-02-12T19:57:44
114,456,626
0
0
null
null
null
null
UTF-8
C++
false
false
2,449
h
#pragma once #include <map> #include <string> #include <vector> #include "AdventOfCodeBase.h" /* https://adventofcode.com/2017/day/11 Part 1: a program comes up to you, clearly in distress. "It's my child process," she says, "he's gotten lost in an infinite grid!" Fortunately for her, you have plenty of experience with infinite grids. Unfortunately for you, it's a hex grid. The hexagons ("hexes") in this grid are aligned such that adjacent hexes can be found to the north, northeast, southeast, south, southwest, and northwest: \ n / nw +--+ ne / \ -+ +- \ / sw +--+ se / s \ You have the path the child process took. Starting where he started, you need to determine the fewest number of steps required to reach him. (A "step" means to move from the hex you are in to any adjacent hex.) For example: ne,ne,ne is 3 steps away. ne,ne,sw,sw is 0 steps away (back where you started). ne,ne,s,s is 2 steps away (se,se). se,sw,se,sw,sw is 3 steps away (s,s,sw). */ namespace AdventOfCode { namespace December11 { struct Cell { Cell() = delete; Cell(int _x, int _y) { x = _x; y = _y; } bool operator ==(const Cell& other) { return x == other.x && y == other.y; } void operator +=(const Cell& other) { x += other.x; y += other.y; } int x = 0; int y = 0; }; class InfiniteHexGrid : protected AdventOfCodeBase { public: InfiniteHexGrid(); InfiniteHexGrid(const std::vector<std::string>& path); InfiniteHexGrid(const std::string& fileName); ~InfiniteHexGrid() = default; public: // AdventOfCodeBase virtual bool ParseLine(const std::string& inputLine) override; virtual void OutputResultToConsole() const override; // ~AdventOfCodeBase public: Cell GetTargetCell() const; int GetPathLength() const { return static_cast<int>(m_path.size()); } // for sanity checks std::vector<std::string> GetSimplifiedPath() const; static int GetTargetDistanceToOrigin(const Cell& target); protected: Cell GetDirection(std::string dirString) const; private: void SetupDirections(); protected: std::vector<std::string> m_path; std::map<std::string, Cell> m_directions; private: Cell m_pathTarget = Cell(0, 0); }; }}
[ "j-p-e-g@users.noreply.github.com" ]
j-p-e-g@users.noreply.github.com
3b90eaddd77ea8ea4e31ec8a592610b3c3db3f96
aaa3af2efd517fba89aa8cb961806283d626e7c3
/src/tfm/tfmp_tfm_data_ligkern.cc
f7558e271f8e6e9e346006f6f05af81489368868
[ "MIT" ]
permissive
erician/tfm-parser
cb03ca8dd38eefb6bd0da737062cf47d135825ca
1bd091b46b53cb019b928c40dcdfa306f22a1e24
refs/heads/master
2020-04-14T07:35:24.674840
2019-02-16T13:58:45
2019-02-16T13:58:45
163,716,679
0
0
null
null
null
null
UTF-8
C++
false
false
1,796
cc
#ifndef TFMP_TFM_TFMP_TFM_DATA_LIGKERN_H_ #include "tfm/tfmp_tfm_data_ligkern.h" #endif #ifndef TFMP_TFM_TFMP_TFM_CONST_H_ #include "tfm/tfmp_tfm_const.h" #endif namespace tfmp{ namespace tfm{ namespace data{ LigKernCommand::LigKernCommand() { skip_ = 0; next_char_ = 0; op_ = 0; remainder_ = 0; } LigKernCommand::LigKernCommand(char *bytes) { skip_ = (unsigned char)bytes[0]; next_char_ = (unsigned char)bytes[1]; op_ = (unsigned char)bytes[2]; remainder_ = (unsigned char)bytes[3]; } LigKernCommand::~LigKernCommand() { ; } int LigKernCommand::Show(tfmp::DisplayBoard *display_board) { display_board->Puts(std::to_string(skip_) + "\n"); display_board->Puts(std::to_string(next_char_) + "\n"); display_board->Puts(std::to_string(op_) + "\n"); display_board->Puts(std::to_string(remainder_) + "\n"); return 0; } int LigKernCommand::Interpret() { return 0; } LigKern::LigKern() { nl_ = 0; command_ = NULL; } LigKern::~LigKern() { for(int i=0; i<nl_; i++) { delete command_[i]; } delete []command_; } int LigKern::Parse(unsigned int nl, std::ifstream* tfm_ifs) { nl_ = nl; command_ = new struct LigKernCommand*[nl_]; char *buff = new char [tfmp::tfm::kSizeofLigKernCommand]; for(int i=0; i<nl_; i++) { tfm_ifs->read(buff, tfmp::tfm::kSizeofLigKernCommand); command_[i] = new struct LigKernCommand(buff); } delete []buff; return 0; } int LigKern::Show(tfmp::DisplayBoard *display_board) { display_board->Puts(std::to_string(nl_) + "\n"); for(int i=0; i<nl_; i++) { display_board->Puts(std::to_string(i) + "\n"); command_[i]->Show(display_board); } return 0; } } // namespace data } // namespace tfm } // namespace tfmp
[ "zkliuchaojie@163.com" ]
zkliuchaojie@163.com
4ff19795671ca672ac0ca70a13be71b69e205de0
c982aa8340a14e3b00eebc17ad026a57f55f1d12
/Libelas/Libelas/elas.h
279a6d316cebde4c0aa2ce9b5d2ccea58ea201cf
[]
no_license
richardseba/TFG-Code
4506dc596619bec5f8f052a7476822d7612ad53c
d7c2c602e7efe00a63552250602efdc164f9b20d
refs/heads/master
2021-03-22T05:15:53.441154
2019-01-09T14:16:15
2019-01-09T14:16:15
121,611,165
0
0
null
2019-04-01T07:43:59
2018-02-15T09:29:23
C++
UTF-8
C++
false
false
10,086
h
/* Copyright 2011. All rights reserved. Institute of Measurement and Control Systems Karlsruhe Institute of Technology, Germany This file is part of libelas. Authors: Andreas Geiger libelas is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or any later version. libelas is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libelas; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ // Main header file. Include this to use libelas in your code. #ifndef __ELAS_H__ #define __ELAS_H__ #include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <vector> #include <emmintrin.h> // define fixed-width datatypes for Visual Studio projects #include <stdint.h> #ifdef PROFILE #include "timer.h" #endif class Elas { public: enum setting {ROBOTICS,MIDDLEBURY,CVC}; // parameter settings struct parameters { int32_t disp_min; // min disparity int32_t disp_max; // max disparity float support_threshold; // max. uniqueness ratio (best vs. second best support match) int32_t support_texture; // min texture for support points int32_t candidate_stepsize; // step size of regular grid on which support points are matched int32_t incon_window_size; // window size of inconsistent support point check int32_t incon_threshold; // disparity similarity threshold for support point to be considered consistent int32_t incon_min_support; // minimum number of consistent support points bool add_corners; // add support points at image corners with nearest neighbor disparities int32_t grid_size; // size of neighborhood for additional support point extrapolation float beta; // image likelihood parameter float gamma; // prior constant float sigma; // prior sigma float sradius; // prior sigma radius int32_t match_texture; // min texture for dense matching int32_t lr_threshold; // disparity threshold for left/right consistency check float speckle_sim_threshold; // similarity threshold for speckle segmentation int32_t speckle_size; // maximal size of a speckle (small speckles get removed) int32_t ipol_gap_width; // interpolate small gaps (left<->right, top<->bottom) bool filter_median; // optional median filter (approximated) bool filter_adaptive_mean; // optional adaptive mean filter (approximated) bool postprocess_only_left; // saves time by not postprocessing the right image bool subsampling; // saves time by only computing disparities for each 2nd pixel // note: for this option D1 and D2 must be passed with size // width/2 x height/2 (rounded towards zero) // constructor parameters (setting s=ROBOTICS) { // default settings in a robotics environment // (do not produce results in half-occluded areas // and are a bit more robust towards lighting etc.) if (s==ROBOTICS) { disp_min = 0; disp_max = 1000; support_threshold = 0.85; support_texture = 10; candidate_stepsize = 5; incon_window_size = 5; incon_threshold = 5; incon_min_support = 5; add_corners = 0; grid_size = 20; beta = 0.02; gamma = 3; sigma = 1; sradius = 2; match_texture = 1; lr_threshold = 2; speckle_sim_threshold = 1; speckle_size = 200; ipol_gap_width = 3; filter_median = 0; filter_adaptive_mean = 1; postprocess_only_left = 1; subsampling = 0; //CVC parameters } else if(s==CVC) { disp_min = 0; disp_max = 255; support_threshold = 0.65; support_texture = 50; candidate_stepsize = 5; incon_window_size = 5; incon_threshold = 5; incon_min_support = 5; add_corners = 1; grid_size = 20; beta = 0.02; gamma = 5; sigma = 1; sradius = 3; match_texture = 1; lr_threshold = 2; speckle_sim_threshold = 1; speckle_size = 200; ipol_gap_width = 10; filter_median = 0; filter_adaptive_mean = 1; postprocess_only_left = 1; subsampling = 0; // default settings for middlebury benchmark // (interpolate all missing disparities) } else { disp_min = 0; disp_max = 255; support_threshold = 0.95; support_texture = 10; candidate_stepsize = 5; incon_window_size = 5; incon_threshold = 5; incon_min_support = 5; add_corners = 1; grid_size = 20; beta = 0.02; gamma = 5; sigma = 1; sradius = 3; match_texture = 0; lr_threshold = 2; speckle_sim_threshold = 1; speckle_size = 200; ipol_gap_width = 5000; filter_median = 1; filter_adaptive_mean = 0; postprocess_only_left = 1; subsampling = 0; } } }; // constructor, input: parameters Elas (parameters param) : param(param) {} // deconstructor ~Elas () {} // matching function // inputs: pointers to left (I1) and right (I2) intensity image (uint8, input) // pointers to left (D1) and right (D2) disparity image (float, output) // dims[0] = width of I1 and I2 // dims[1] = height of I1 and I2 // dims[2] = bytes per line (often equal to width, but allowed to differ) // note: D1 and D2 must be allocated before (bytes per line = width) // if subsampling is not active their size is width x height, // otherwise width/2 x height/2 (rounded towards zero) void process (uint8_t* I1,uint8_t* I2,float* D1,float* D2,const int32_t* dims); private: struct support_pt { int32_t u; int32_t v; int32_t d; support_pt(int32_t u,int32_t v,int32_t d):u(u),v(v),d(d){} }; struct triangle { int32_t c1,c2,c3; float t1a,t1b,t1c; float t2a,t2b,t2c; triangle(int32_t c1,int32_t c2,int32_t c3):c1(c1),c2(c2),c3(c3){} }; inline uint32_t getAddressOffsetImage (const int32_t& u,const int32_t& v,const int32_t& width) { return v*width+u; } inline uint32_t getAddressOffsetGrid (const int32_t& x,const int32_t& y,const int32_t& d,const int32_t& width,const int32_t& disp_num) { return (y*width+x)*disp_num+d; } // support point functions void removeInconsistentSupportPoints (int16_t* D_can,int32_t D_can_width,int32_t D_can_height); void removeRedundantSupportPoints (int16_t* D_can,int32_t D_can_width,int32_t D_can_height, int32_t redun_max_dist, int32_t redun_threshold, bool vertical); void addCornerSupportPoints (std::vector<support_pt> &p_support); inline int16_t computeMatchingDisparity (const int32_t &u,const int32_t &v,uint8_t* I1_desc,uint8_t* I2_desc,const bool &right_image); std::vector<support_pt> computeSupportMatches (uint8_t* I1_desc,uint8_t* I2_desc); // triangulation & grid std::vector<triangle> computeDelaunayTriangulation (std::vector<support_pt> p_support,int32_t right_image); void computeDisparityPlanes (std::vector<support_pt> p_support,std::vector<triangle> &tri,int32_t right_image); void createGrid (std::vector<support_pt> p_support,int32_t* disparity_grid,int32_t* grid_dims,bool right_image); // matching inline void updatePosteriorMinimum (__m128i* I2_block_addr,const int32_t &d,const int32_t &w, const __m128i &xmm1,__m128i &xmm2,int32_t &val,int32_t &min_val,int32_t &min_d); inline void updatePosteriorMinimum (__m128i* I2_block_addr,const int32_t &d, const __m128i &xmm1,__m128i &xmm2,int32_t &val,int32_t &min_val,int32_t &min_d); inline void findMatch (int32_t &u,int32_t &v,float &plane_a,float &plane_b,float &plane_c, int32_t* disparity_grid,int32_t *grid_dims,uint8_t* I1_desc,uint8_t* I2_desc, int32_t *P,int32_t &plane_radius,bool &valid,bool &right_image,float* D); void computeDisparity (std::vector<support_pt> p_support,std::vector<triangle> tri,int32_t* disparity_grid,int32_t* grid_dims, uint8_t* I1_desc,uint8_t* I2_desc,bool right_image,float* D); // L/R consistency check void leftRightConsistencyCheck (float* D1,float* D2); // postprocessing void removeSmallSegments (float* D); void gapInterpolation (float* D); // optional postprocessing void adaptiveMean (float* D); void median (float* D); // parameter set parameters param; // memory aligned input images + dimensions uint8_t *I1,*I2; int32_t width,height,bpl; // profiling timer #ifdef PROFILE Timer timer; #endif }; #endif
[ "richardseba@users.noreply.github.com" ]
richardseba@users.noreply.github.com
66f9a5f2dc0c521204550bab86f30020fe2ca5ab
7e522089dc55393159a7cfddfe98506f2cf70717
/SupervisedSequence.cpp
915c7e88f53e3127d23e647291f306b781f15ca7
[]
no_license
danathughes/cNeuralNetwork
27d6d77f5f1eb18d8ebf09a0b40dab33e72c4c87
b494f426a7c2be50ac96388535d2ffcba387624b
refs/heads/master
2016-09-03T06:59:55.953486
2015-07-11T04:14:14
2015-07-11T04:14:14
35,659,535
0
0
null
2015-07-08T00:31:36
2015-05-15T07:13:40
C++
UTF-8
C++
false
false
724
cpp
/** * \class SupervisedData * * \brief An instance of supervised data * * \author $Author: dh$ * * \version $Version: 1.0$ * * \date $Date: 27-June-2015$ * * Contact: danathughes@gmail.com * * */ #include "SupervisedSequence.h" using namespace std; SupervisedSequence::SupervisedSequence(vector<Eigen::VectorXd> input, vector<Eigen::VectorXd> target) { for(int i=0; i<input.size(); i++) { this->input.push_back(input.at(i)); this->target.push_back(target.at(i)); } } SupervisedSequence::~SupervisedSequence() { } Eigen::VectorXd SupervisedSequence::getInputAt(int idx) { return this->input.at(idx); } Eigen::VectorXd SupervisedSequence::getTargetAt(int idx) { return this->target.at(idx); }
[ "danathughes@gmail.com" ]
danathughes@gmail.com
a97b9e57343e04d4f9852d7dfaa793a7762c778c
d89cf43409cc73e316b23360575eea5d5bf4d071
/Builders/CustomBuilders/Water/WaterScooterBuilder.cpp
bc4129247b32258b6805e07338bca2f8fa64c1e4
[ "Unlicense" ]
permissive
Wyder7PL/Builder
1aec2fbaeedf6bfc22b3d13e285a2dd9bf2fa907
c5fa84ce832015740883a2a89de9ca4cfc88c7c2
refs/heads/master
2020-05-20T00:13:29.986354
2019-05-06T23:21:45
2019-05-06T23:21:45
185,282,365
0
0
Unlicense
2019-05-06T23:21:46
2019-05-06T22:48:21
C++
UTF-8
C++
false
false
412
cpp
#include "WaterScooterBuilder.h" std::string WaterScooterBuilder::GetName() { return "Water Scooter"; } SmallEngine * WaterScooterBuilder::CreateSmallEngine() { return new SmallEngine_B1(); } SmallVehicleBody * WaterScooterBuilder::CreateSmallVehicleBody() { return new ScooterBody(); } SmallBoatShell * WaterScooterBuilder::CreateLowerSmallLandVehiclePart() { return new SmallBoatShell_A(); }
[ "wyder@spoko.pl" ]
wyder@spoko.pl
ca0062c45d4f65420ef7d0240d98b5173d385f6c
a8b457da0f2f327320b27a5f0bffe7a55685de7c
/src/base58.h
604d89581cbfc2a593f84b9e5974dbb49aa74729
[ "MIT" ]
permissive
pineplatform/protcoin
6ea97b3923b26f85f47983ce6ab3d1865340a496
1e3dbf298fd9bbba5eb729ab1a93a21b948c78fd
refs/heads/master
2020-06-21T07:40:46.604718
2019-07-28T03:06:25
2019-07-28T03:06:25
197,385,055
2
1
null
null
null
null
UTF-8
C++
false
false
5,568
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * Why base-58 instead of standard base-64 encoding? * - Don't want 0OIl characters that look the same in some fonts and * could be used to create visually identical looking account numbers. * - A string with non-alphanumeric characters is not as easily accepted as an account number. * - E-mail usually won't line-break if there's no punctuation to break at. * - Double-clicking selects the whole number as one word if it's all alphanumeric. */ #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H #include "chainparams.h" #include "key.h" #include "pubkey.h" #include "script/script.h" #include "script/standard.h" #include <string> #include <vector> /** * Encode a byte sequence as a base58-encoded string. * pbegin and pend cannot be NULL, unless both are. */ std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend); /** * Encode a byte vector as a base58-encoded string */ std::string EncodeBase58(const std::vector<unsigned char>& vch); /** * Decode a base58-encoded string (psz) into a byte vector (vchRet). * return true if decoding is successful. * psz cannot be NULL. */ bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet); /** * Decode a base58-encoded string (psz) into a string. * psz cannot be NULL. */ std::string DecodeBase58(const char* psz); /** * Decode a base58-encoded string (str) into a byte vector (vchRet). * return true if decoding is successful. */ bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet); /** * Encode a byte vector into a base58-encoded string, including checksum */ std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn); /** * Decode a base58-encoded string (psz) that includes a checksum into a byte * vector (vchRet), return true if decoding is successful */ inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet); /** * Decode a base58-encoded string (str) that includes a checksum into a byte * vector (vchRet), return true if decoding is successful */ inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet); /** * Base class for all base58-encoded data */ class CBase58Data { protected: //! the version byte(s) std::vector<unsigned char> vchVersion; //! the actually encoded data typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar; vector_uchar vchData; CBase58Data(); void SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize); void SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend); public: bool SetString(const char* psz, unsigned int nVersionBytes = 1); bool SetString(const std::string& str); std::string ToString() const; int CompareTo(const CBase58Data& b58) const; bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; } bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; } bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; } bool operator<(const CBase58Data& b58) const { return CompareTo(b58) < 0; } bool operator>(const CBase58Data& b58) const { return CompareTo(b58) > 0; } }; /** base58-encoded Protcoin addresses. * Public-key-hash-addresses have version 0 (or 111 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 5 (or 196 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CBitcoinAddress : public CBase58Data { public: bool Set(const CKeyID& id); bool Set(const CScriptID& id); bool Set(const CTxDestination& dest); bool IsValid() const; bool IsValid(const CChainParams& params) const; CBitcoinAddress() {} CBitcoinAddress(const CTxDestination& dest) { Set(dest); } CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); } CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); } CTxDestination Get() const; bool GetKeyID(CKeyID& keyID) const; bool IsScript() const; }; /** * A base58-encoded secret key */ class CBitcoinSecret : public CBase58Data { public: void SetKey(const CKey& vchSecret); CKey GetKey(); bool IsValid() const; bool SetString(const char* pszSecret); bool SetString(const std::string& strSecret); CBitcoinSecret(const CKey& vchSecret) { SetKey(vchSecret); } CBitcoinSecret() {} }; template <typename K, int Size, CChainParams::Base58Type Type> class CBitcoinExtKeyBase : public CBase58Data { public: void SetKey(const K& key) { unsigned char vch[Size]; key.Encode(vch); SetData(Params().Base58Prefix(Type), vch, vch + Size); } K GetKey() { K ret; ret.Decode(&vchData[0], &vchData[Size]); return ret; } CBitcoinExtKeyBase(const K& key) { SetKey(key); } CBitcoinExtKeyBase() {} }; typedef CBitcoinExtKeyBase<CExtKey, 74, CChainParams::EXT_SECRET_KEY> CBitcoinExtKey; typedef CBitcoinExtKeyBase<CExtPubKey, 74, CChainParams::EXT_PUBLIC_KEY> CBitcoinExtPubKey; #endif // BITCOIN_BASE58_H
[ "hrrrrr@naver.com" ]
hrrrrr@naver.com
f65b07d9796a21d6fc0443744a68d301954c8750
fc123e9ead8e4301349bbf46d89e6d95052dba54
/Camara.cpp
140bd1c1cac70da3f098f5a62ae5128ad9270971
[]
no_license
houhongyi/DHCameraCpture
2b518ca0db1f3d3bb3c328b91c032879613dd5c5
b10b3846b6e796f31d0af87dca3312aca15aeb65
refs/heads/master
2020-03-28T13:39:48.142182
2018-09-12T03:27:21
2018-09-12T03:27:21
148,415,592
1
0
null
null
null
null
UTF-8
C++
false
false
9,626
cpp
#include "Camera.h" int g_LibConnect_n=0;//相机Lib引用计数 每个相机Inite会使得次值+1 close会使得此值-1 非线程安全 int Camera::Init(char* No) { if(CameraState_) { printf("Warning> Camera No:%s has inited.\r\n",No); return -1; } GX_STATUS status = GX_STATUS_SUCCESS; int ret = 0; GX_OPEN_PARAM open_param; //初始化设备打开参数,默认打开序号为1的设备 open_param.accessMode = GX_ACCESS_EXCLUSIVE; open_param.openMode = GX_OPEN_INDEX; open_param.pszContent = No; //如果是第一个调用lib的相机,首先链接Lib if(0==g_LibConnect_n) { //链接Lib status = GXInitLib(); if(status != GX_STATUS_SUCCESS) { GetErrorString(status); printf("Erro>Inite Camera No:%s Fail.\r\n",No); return -1; } } g_LibConnect_n+=1;//连接库如果成功 全局Lib计数 加一 uint32_t device_number = 0; status = GXUpdateDeviceList(&device_number, 1000);//获取设备台数 if(status != GX_STATUS_SUCCESS) { GetErrorString(status); return -1; } if(device_number <= 0) { printf("Erro> No device Connected\r\n"); return -1; } //打开摄像头 status = GXOpenDevice(&open_param, &hdevice_); if(status == GX_STATUS_SUCCESS) { printf("Open Camera No:%s Success.\r\n",No); CameraState_=Camera_State_Inited; } else { printf("Erro>Open Camera No:%s Fail.\r\n",No); return -1; } while(1) { status = GXSetEnum(hdevice_, GX_ENUM_ACQUISITION_MODE, GX_ACQ_MODE_CONTINUOUS);//设置采集模式为连续采集 if(status!=GX_STATUS_SUCCESS)break; status = GXSetEnum(hdevice_, GX_ENUM_TRIGGER_MODE, GX_TRIGGER_MODE_ON);//设置触发开关为ON if(status!=GX_STATUS_SUCCESS)break; status = GXSetEnum(hdevice_, GX_ENUM_TRIGGER_SOURCE, GX_TRIGGER_SOURCE_SOFTWARE);//设置触发源为软触发 if(status!=GX_STATUS_SUCCESS)break; status = GXGetEnum(hdevice_, GX_ENUM_PIXEL_FORMAT, &pixel_format_);//获取相机输出数据的颜色格式 if(status!=GX_STATUS_SUCCESS)break; status = GXGetEnum(hdevice_, GX_ENUM_PIXEL_COLOR_FILTER, &color_filter_);//相机采集图像为彩色还是黑白 if(status!=GX_STATUS_SUCCESS)break; break; } if(status!=GX_STATUS_SUCCESS)GetErrorString(status); else printf("Camara Set Ok\r\n"); //为采集做准备 为获取的图像分配存储空间 int64_t payload_size = 0; status = GXGetInt(hdevice_, GX_INT_PAYLOAD_SIZE, &payload_size); if(!frame_data_.pImgBuf) frame_data_.pImgBuf = malloc(payload_size); if(!raw8_buffer_)//将非8位raw数据转换成8位数据的时候的中转缓冲buffer raw8_buffer_ = malloc(payload_size); if(!rgb_frame_data_) rgb_frame_data_ = malloc(payload_size * 3); status = GXGetBufferLength(hdevice_, GX_BUFFER_FRAME_INFORMATION, &frameinfo_datasize_);//获取帧信息长度并申请帧信息数据空间 if(status!=GX_STATUS_SUCCESS)GetErrorString(status); if(frameinfo_datasize_ > 0) { frameinfo_data_ = malloc(frameinfo_datasize_); } if(!(frame_data_.pImgBuf && raw8_buffer_ && rgb_frame_data_ )) { printf("Erro>Failed to allocate memory\n"); return -1; } frame_.create(1024,1280,CV_8UC3); //frame_=cv::Mat(frame_data_.nWidth,frame_data_.nHeight,CV_8UC3,cv::Scalar(0,0,0)).clone(); return 0; } int Camera::ReInit() { return 0; } int Camera::Start() { GX_STATUS status = GX_STATUS_SUCCESS; status = GXSendCommand(hdevice_, GX_COMMAND_ACQUISITION_START);//发送开采命令 if(status != GX_STATUS_SUCCESS)GetErrorString(status); } int Camera::Stop() { GX_STATUS status = GXSendCommand(hdevice_, GX_COMMAND_ACQUISITION_STOP);//停止采集 } int Camera::Triger() { GX_STATUS status = GX_STATUS_SUCCESS; status = GXSendCommand(hdevice_, GX_COMMAND_TRIGGER_SOFTWARE); if(status != GX_STATUS_SUCCESS)GetErrorString(status); } int Camera::GetImg() { GX_STATUS status = GXGetImage(hdevice_, &frame_data_, 100); if(status == GX_STATUS_SUCCESS) { ProcessData(frame_data_.pImgBuf, raw8_buffer_, rgb_frame_data_, frame_data_.nWidth, frame_data_.nHeight, pixel_format_, color_filter_);//将Raw数据处理成RGB数据 if(frame_.cols!=frame_data_.nWidth || frame_.rows!=frame_data_.nHeight) cv::resize(frame_,frame_,cv::Size(frame_data_.nWidth,frame_data_.nHeight)); frame_.data=(unsigned char *)rgb_frame_data_; cv::cvtColor(frame_,frame_,cv::COLOR_RGB2BGR); } else GetErrorString(status); } int Camera::SaveImg() { cv::imwrite("outimg.jpg",frame_); return 0; } int Camera::Close() { //释放camera资源 GX_STATUS status = GXCloseDevice(hdevice_); status = GXSendCommand(hdevice_, GX_COMMAND_ACQUISITION_STOP);//停止采集 //释放buffer if(frame_data_.pImgBuf != NULL) { free(frame_data_.pImgBuf); frame_data_.pImgBuf = NULL; } if(raw8_buffer_ != NULL) { free(raw8_buffer_); raw8_buffer_ = NULL; } if(rgb_frame_data_ != NULL) { free(rgb_frame_data_); rgb_frame_data_ = NULL; } if(frameinfo_data_ != NULL) { free(frameinfo_data_); frameinfo_data_ = NULL; } g_LibConnect_n-=1; if(0==g_LibConnect_n)//最后一个camera 调用close 释放lib { status = GXCloseLib();//关闭Lib } return 0; } void Camera::ProcessData(void *image_buffer, void *image_raw8_buffer, void *image_rgb_buffer, int image_width, int image_height, int pixel_format, int color_filter) { switch(pixel_format) { //当数据格式为12位时,位数转换为4-11 case GX_PIXEL_FORMAT_BAYER_GR12: case GX_PIXEL_FORMAT_BAYER_RG12: case GX_PIXEL_FORMAT_BAYER_GB12: case GX_PIXEL_FORMAT_BAYER_BG12: //将12位格式的图像转换为8位格式 DxRaw16toRaw8(image_buffer, image_raw8_buffer, image_width, image_height, DX_BIT_4_11); //将Raw8图像转换为RGB图像以供显示 DxRaw8toRGB24(image_raw8_buffer, image_rgb_buffer, image_width, image_height, RAW2RGB_NEIGHBOUR, DX_PIXEL_COLOR_FILTER(color_filter), false); break; //当数据格式为10位时,位数转换为2-9 case GX_PIXEL_FORMAT_BAYER_GR10: case GX_PIXEL_FORMAT_BAYER_RG10: case GX_PIXEL_FORMAT_BAYER_GB10: case GX_PIXEL_FORMAT_BAYER_BG10: //将10位格式的图像转换为8位格式,有效位数2-9 DxRaw16toRaw8(image_buffer, image_raw8_buffer, image_width, image_height, DX_BIT_2_9); //将Raw8图像转换为RGB图像以供显示 DxRaw8toRGB24(image_raw8_buffer, image_rgb_buffer, image_width, image_height,RAW2RGB_NEIGHBOUR, DX_PIXEL_COLOR_FILTER(color_filter),false); break; case GX_PIXEL_FORMAT_BAYER_GR8: case GX_PIXEL_FORMAT_BAYER_RG8: case GX_PIXEL_FORMAT_BAYER_GB8: case GX_PIXEL_FORMAT_BAYER_BG8: //将Raw8图像转换为RGB图像以供显示 DxRaw8toRGB24(image_buffer,image_rgb_buffer, image_width, image_height,RAW2RGB_NEIGHBOUR, DX_PIXEL_COLOR_FILTER(color_filter),false); break; case GX_PIXEL_FORMAT_MONO12: //将12位格式的图像转换为8位格式 DxRaw16toRaw8(image_buffer, image_raw8_buffer, image_width, image_height, DX_BIT_4_11); //将Raw8图像转换为RGB图像以供显示 DxRaw8toRGB24(image_raw8_buffer, image_rgb_buffer, image_width, image_height, RAW2RGB_NEIGHBOUR, DX_PIXEL_COLOR_FILTER(NONE),false); break; case GX_PIXEL_FORMAT_MONO10: //将10位格式的图像转换为8位格式 DxRaw16toRaw8(image_buffer, image_raw8_buffer, image_width, image_height, DX_BIT_4_11); //将Raw8图像转换为RGB图像以供显示 DxRaw8toRGB24(image_raw8_buffer, image_rgb_buffer, image_width, image_height,RAW2RGB_NEIGHBOUR, DX_PIXEL_COLOR_FILTER(NONE),false); break; case GX_PIXEL_FORMAT_MONO8: //将Raw8图像转换为RGB图像以供显示 DxRaw8toRGB24(image_buffer, image_rgb_buffer, image_width, image_height,RAW2RGB_NEIGHBOUR, DX_PIXEL_COLOR_FILTER(NONE),false); break; default: break; } } void Camera::GetErrorString(GX_STATUS error_status) { char *error_info = NULL; size_t size = 0; GX_STATUS status = GX_STATUS_SUCCESS; // 获取错误描述信息长度 status = GXGetLastError(&error_status, NULL, &size); error_info = new char[size]; if (error_info == NULL) { printf("<Failed to allocate memory>\n"); return ; } // 获取错误信息描述 status = GXGetLastError(&error_status, error_info, &size); if (status != GX_STATUS_SUCCESS) { printf("<GXGetLastError call fail>\n"); } else { printf("%s\n", (char*)error_info); } // 释放资源 if (error_info != NULL) { delete[]error_info; error_info = NULL; } }
[ "houhongyi@qq.com" ]
houhongyi@qq.com
b0c979064215c148be612fac5ed9c0ff4e5dc4ce
bc5b17dffc6f951e2781484c0a7f0c055d037b27
/include/System/Rapidxml.h
14fd945fca0645635678182deb4ed682eca17a34
[]
no_license
MassonY/Blue
2dc8821b476c18a11acce06408a698b0fd3b3aae
8d3d07861362ea28f29d4e4a972731ec3fa7ec37
refs/heads/master
2021-05-28T13:03:00.417108
2013-08-31T21:05:51
2013-08-31T21:05:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
134,071
h
#ifndef RAPIDXML_H #define RAPIDXML_H // Copyright (C) 2006, 2009 Marcin Kalicinski // Version 1.13 // Revision $DateTime: 2009/05/13 01:46:17 $ //! \file rapidxml.h This file contains rapidxml parser and DOM implementation // If standard library is disabled, user must provide implementations of required functions and typedefs #if !defined(RAPIDXML_NO_STDLIB) #include <cstdlib> // For std::size_t #include <cassert> // For assert #include <new> // For placement new #endif // On MSVC, disable "conditional expression is constant" warning (level 4). // This warning is almost impossible to avoid with certain types of templated code #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4127) // Conditional expression is constant #endif /////////////////////////////////////////////////////////////////////////// // RAPIDXML_PARSE_ERROR #if defined(RAPIDXML_NO_EXCEPTIONS) #define RAPIDXML_PARSE_ERROR(what, where) { parse_error_handler(what, where); assert(0); } namespace rapidxml { //! When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, //! this function is called to notify user about the error. //! It must be defined by the user. //! <br><br> //! This function cannot return. If it does, the results are undefined. //! <br><br> //! A very simple definition might look like that: //! <pre> //! void %rapidxml::%parse_error_handler(const char *what, void *where) //! { //! std::cout << "Parse error: " << what << "\n"; //! std::abort(); //! } //! </pre> //! \param what Human readable description of the error. //! \param where Pointer to character data where error was detected. void parse_error_handler(const char *what, void *where); } #else #include <exception> // For std::exception #define RAPIDXML_PARSE_ERROR(what, where) throw parse_error(what, where) namespace rapidxml { //! Parse error exception. //! This exception is thrown by the parser when an error occurs. //! Use what() function to get human-readable error message. //! Use where() function to get a pointer to position within source text where error was detected. //! <br><br> //! If throwing exceptions by the parser is undesirable, //! it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included. //! This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception. //! This function must be defined by the user. //! <br><br> //! This class derives from <code>std::exception</code> class. class parse_error: public std::exception { public: //! Constructs parse error parse_error(const char *what, void *where) : m_what(what) , m_where(where) { } //! Gets human readable description of error. //! \return Pointer to null terminated description of the error. virtual const char *what() const throw() { return m_what; } //! Gets pointer to character data where error happened. //! Ch should be the same as char type of xml_document that produced the error. //! \return Pointer to location within the parsed string where error occured. template<class Ch> Ch *where() const { return reinterpret_cast<Ch *>(m_where); } private: const char *m_what; void *m_where; }; } #endif /////////////////////////////////////////////////////////////////////////// // Pool sizes #ifndef RAPIDXML_STATIC_POOL_SIZE // Size of static memory block of memory_pool. // Define RAPIDXML_STATIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value. // No dynamic memory allocations are performed by memory_pool until static memory is exhausted. #define RAPIDXML_STATIC_POOL_SIZE (64 * 1024) #endif #ifndef RAPIDXML_DYNAMIC_POOL_SIZE // Size of dynamic memory block of memory_pool. // Define RAPIDXML_DYNAMIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value. // After the static block is exhausted, dynamic blocks with approximately this size are allocated by memory_pool. #define RAPIDXML_DYNAMIC_POOL_SIZE (64 * 1024) #endif #ifndef RAPIDXML_ALIGNMENT // Memory allocation alignment. // Define RAPIDXML_ALIGNMENT before including rapidxml.hpp if you want to override the default value, which is the size of pointer. // All memory allocations for nodes, attributes and strings will be aligned to this value. // This must be a power of 2 and at least 1, otherwise memory_pool will not work. #define RAPIDXML_ALIGNMENT sizeof(void *) #endif namespace rapidxml { // Forward declarations template<class Ch> class xml_node; template<class Ch> class xml_attribute; template<class Ch> class xml_document; //! Enumeration listing all node types produced by the parser. //! Use xml_node::type() function to query node type. enum node_type { node_document, //!< A document node. Name and value are empty. node_element, //!< An element node. Name contains element name. Value contains text of first data node. node_data, //!< A data node. Name is empty. Value contains data text. node_cdata, //!< A CDATA node. Name is empty. Value contains data text. node_comment, //!< A comment node. Name is empty. Value contains comment text. node_declaration, //!< A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes. node_doctype, //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text. node_pi //!< A PI node. Name contains target. Value contains instructions. }; /////////////////////////////////////////////////////////////////////// // Parsing flags //! Parse flag instructing the parser to not create data nodes. //! Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_data_nodes = 0x1; //! Parse flag instructing the parser to not use text of first data node as a value of parent element. //! Can be combined with other flags by use of | operator. //! Note that child data nodes of element node take precendence over its value when printing. //! That is, if element has one or more child data nodes <em>and</em> a value, the value will be ignored. //! Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements. //! <br><br> //! See xml_document::parse() function. const int parse_no_element_values = 0x2; //! Parse flag instructing the parser to not place zero terminators after strings in the source text. //! By default zero terminators are placed, modifying source text. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_string_terminators = 0x4; //! Parse flag instructing the parser to not translate entities in the source text. //! By default entities are translated, modifying source text. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_entity_translation = 0x8; //! Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters. //! By default, UTF-8 handling is enabled. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_utf8 = 0x10; //! Parse flag instructing the parser to create XML declaration node. //! By default, declaration node is not created. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_declaration_node = 0x20; //! Parse flag instructing the parser to create comments nodes. //! By default, comment nodes are not created. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_comment_nodes = 0x40; //! Parse flag instructing the parser to create DOCTYPE node. //! By default, doctype node is not created. //! Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_doctype_node = 0x80; //! Parse flag instructing the parser to create PI nodes. //! By default, PI nodes are not created. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_pi_nodes = 0x100; //! Parse flag instructing the parser to validate closing tag names. //! If not set, name inside closing tag is irrelevant to the parser. //! By default, closing tags are not validated. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_validate_closing_tags = 0x200; //! Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes. //! By default, whitespace is not trimmed. //! This flag does not cause the parser to modify source text. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_trim_whitespace = 0x400; //! Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character. //! Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag. //! By default, whitespace is not normalized. //! If this flag is specified, source text will be modified. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_normalize_whitespace = 0x800; // Compound flags //! Parse flags which represent default behaviour of the parser. //! This is always equal to 0, so that all other flags can be simply ored together. //! Normally there is no need to inconveniently disable flags by anding with their negated (~) values. //! This also means that meaning of each flag is a <i>negation</i> of the default setting. //! For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is <i>enabled</i> by default, //! and using the flag will disable it. //! <br><br> //! See xml_document::parse() function. const int parse_default = 0; //! A combination of parse flags that forbids any modifications of the source text. //! This also results in faster parsing. However, note that the following will occur: //! <ul> //! <li>names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends</li> //! <li>entities will not be translated</li> //! <li>whitespace will not be normalized</li> //! </ul> //! See xml_document::parse() function. const int parse_non_destructive = parse_no_string_terminators | parse_no_entity_translation; //! A combination of parse flags resulting in fastest possible parsing, without sacrificing important data. //! <br><br> //! See xml_document::parse() function. const int parse_fastest = parse_non_destructive | parse_no_data_nodes; //! A combination of parse flags resulting in largest amount of data being extracted. //! This usually results in slowest parsing. //! <br><br> //! See xml_document::parse() function. const int parse_full = parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags; /////////////////////////////////////////////////////////////////////// // Internals //! \cond internal namespace internal { // Struct that contains lookup tables for the parser // It must be a template to allow correct linking (because it has static data members, which are defined in a header file). template<int Dummy> struct lookup_tables { static const unsigned char lookup_whitespace[256]; // Whitespace table static const unsigned char lookup_node_name[256]; // Node name table static const unsigned char lookup_text[256]; // Text table static const unsigned char lookup_text_pure_no_ws[256]; // Text table static const unsigned char lookup_text_pure_with_ws[256]; // Text table static const unsigned char lookup_attribute_name[256]; // Attribute name table static const unsigned char lookup_attribute_data_1[256]; // Attribute data table with single quote static const unsigned char lookup_attribute_data_1_pure[256]; // Attribute data table with single quote static const unsigned char lookup_attribute_data_2[256]; // Attribute data table with double quotes static const unsigned char lookup_attribute_data_2_pure[256]; // Attribute data table with double quotes static const unsigned char lookup_digits[256]; // Digits static const unsigned char lookup_upcase[256]; // To uppercase conversion table for ASCII characters }; // Find length of the string template<class Ch> inline std::size_t measure(const Ch *p) { const Ch *tmp = p; while (*tmp) ++tmp; return tmp - p; } // Compare strings for equality template<class Ch> inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, std::size_t size2, bool case_sensitive) { if (size1 != size2) return false; if (case_sensitive) { for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) if (*p1 != *p2) return false; } else { for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) if (lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p1)] != lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p2)]) return false; } return true; } } //! \endcond /////////////////////////////////////////////////////////////////////// // Memory pool //! This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation. //! In most cases, you will not need to use this class directly. //! However, if you need to create nodes manually or modify names/values of nodes, //! you are encouraged to use memory_pool of relevant xml_document to allocate the memory. //! Not only is this faster than allocating them by using <code>new</code> operator, //! but also their lifetime will be tied to the lifetime of document, //! possibly simplyfing memory management. //! <br><br> //! Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool. //! You can also call allocate_string() function to allocate strings. //! Such strings can then be used as names or values of nodes without worrying about their lifetime. //! Note that there is no <code>free()</code> function -- all allocations are freed at once when clear() function is called, //! or when the pool is destroyed. //! <br><br> //! It is also possible to create a standalone memory_pool, and use it //! to allocate nodes, whose lifetime will not be tied to any document. //! <br><br> //! Pool maintains <code>RAPIDXML_STATIC_POOL_SIZE</code> bytes of statically allocated memory. //! Until static memory is exhausted, no dynamic memory allocations are done. //! When static memory is exhausted, pool allocates additional blocks of memory of size <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> each, //! by using global <code>new[]</code> and <code>delete[]</code> operators. //! This behaviour can be changed by setting custom allocation routines. //! Use set_allocator() function to set them. //! <br><br> //! Allocations for nodes, attributes and strings are aligned at <code>RAPIDXML_ALIGNMENT</code> bytes. //! This value defaults to the size of pointer on target architecture. //! <br><br> //! To obtain absolutely top performance from the parser, //! it is important that all nodes are allocated from a single, contiguous block of memory. //! Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably. //! If required, you can tweak <code>RAPIDXML_STATIC_POOL_SIZE</code>, <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> and <code>RAPIDXML_ALIGNMENT</code> //! to obtain best wasted memory to performance compromise. //! To do it, define their values before rapidxml.hpp file is included. //! \param Ch Character type of created nodes. template<class Ch = char> class memory_pool { public: //! \cond internal typedef void *(alloc_func)(std::size_t); // Type of user-defined function used to allocate memory typedef void (free_func)(void *); // Type of user-defined function used to free memory //! \endcond //! Constructs empty pool with default allocator functions. memory_pool() : m_alloc_func(0) , m_free_func(0) { init(); } //! Destroys pool and frees all the memory. //! This causes memory occupied by nodes allocated by the pool to be freed. //! Nodes allocated from the pool are no longer valid. ~memory_pool() { clear(); } //! Allocates a new node from the pool, and optionally assigns name and value to it. //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function //! will call rapidxml::parse_error_handler() function. //! \param type Type of node to create. //! \param name Name to assign to the node, or 0 to assign no name. //! \param value Value to assign to the node, or 0 to assign no value. //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string. //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string. //! \return Pointer to allocated node. This pointer will never be NULL. xml_node<Ch> *allocate_node(node_type type, const Ch *name = 0, const Ch *value = 0, std::size_t name_size = 0, std::size_t value_size = 0) { void *memory = allocate_aligned(sizeof(xml_node<Ch>)); xml_node<Ch> *node = new(memory) xml_node<Ch>(type); if (name) { if (name_size > 0) node->name(name, name_size); else node->name(name); } if (value) { if (value_size > 0) node->value(value, value_size); else node->value(value); } return node; } //! Allocates a new attribute from the pool, and optionally assigns name and value to it. //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function //! will call rapidxml::parse_error_handler() function. //! \param name Name to assign to the attribute, or 0 to assign no name. //! \param value Value to assign to the attribute, or 0 to assign no value. //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string. //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string. //! \return Pointer to allocated attribute. This pointer will never be NULL. xml_attribute<Ch> *allocate_attribute(const Ch *name = 0, const Ch *value = 0, std::size_t name_size = 0, std::size_t value_size = 0) { void *memory = allocate_aligned(sizeof(xml_attribute<Ch>)); xml_attribute<Ch> *attribute = new(memory) xml_attribute<Ch>; if (name) { if (name_size > 0) attribute->name(name, name_size); else attribute->name(name); } if (value) { if (value_size > 0) attribute->value(value, value_size); else attribute->value(value); } return attribute; } //! Allocates a char array of given size from the pool, and optionally copies a given string to it. //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function //! will call rapidxml::parse_error_handler() function. //! \param source String to initialize the allocated memory with, or 0 to not initialize it. //! \param size Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated. //! \return Pointer to allocated char array. This pointer will never be NULL. Ch *allocate_string(const Ch *source = 0, std::size_t size = 0) { assert(source || size); // Either source or size (or both) must be specified if (size == 0) size = internal::measure(source) + 1; Ch *result = static_cast<Ch *>(allocate_aligned(size * sizeof(Ch))); if (source) for (std::size_t i = 0; i < size; ++i) result[i] = source[i]; return result; } //! Clones an xml_node and its hierarchy of child nodes and attributes. //! Nodes and attributes are allocated from this memory pool. //! Names and values are not cloned, they are shared between the clone and the source. //! Result node can be optionally specified as a second parameter, //! in which case its contents will be replaced with cloned source node. //! This is useful when you want to clone entire document. //! \param source Node to clone. //! \param result Node to put results in, or 0 to automatically allocate result node //! \return Pointer to cloned node. This pointer will never be NULL. xml_node<Ch> *clone_node(const xml_node<Ch> *source, xml_node<Ch> *result = 0) { // Prepare result node if (result) { result->remove_all_attributes(); result->remove_all_nodes(); result->type(source->type()); } else result = allocate_node(source->type()); // Clone name and value result->name(source->name(), source->name_size()); result->value(source->value(), source->value_size()); // Clone child nodes and attributes for (xml_node<Ch> *child = source->first_node(); child; child = child->next_sibling()) result->append_node(clone_node(child)); for (xml_attribute<Ch> *attr = source->first_attribute(); attr; attr = attr->next_attribute()) result->append_attribute(allocate_attribute(attr->name(), attr->value(), attr->name_size(), attr->value_size())); return result; } //! Clears the pool. //! This causes memory occupied by nodes allocated by the pool to be freed. //! Any nodes or strings allocated from the pool will no longer be valid. void clear() { while (m_begin != m_static_memory) { char *previous_begin = reinterpret_cast<header *>(align(m_begin))->previous_begin; if (m_free_func) m_free_func(m_begin); else delete[] m_begin; m_begin = previous_begin; } init(); } //! Sets or resets the user-defined memory allocation functions for the pool. //! This can only be called when no memory is allocated from the pool yet, otherwise results are undefined. //! Allocation function must not return invalid pointer on failure. It should either throw, //! stop the program, or use <code>longjmp()</code> function to pass control to other place of program. //! If it returns invalid pointer, results are undefined. //! <br><br> //! User defined allocation functions must have the following forms: //! <br><code> //! <br>void *allocate(std::size_t size); //! <br>void free(void *pointer); //! </code><br> //! \param af Allocation function, or 0 to restore default function //! \param ff Free function, or 0 to restore default function void set_allocator(alloc_func *af, free_func *ff) { assert(m_begin == m_static_memory && m_ptr == align(m_begin)); // Verify that no memory is allocated yet m_alloc_func = af; m_free_func = ff; } private: struct header { char *previous_begin; }; void init() { m_begin = m_static_memory; m_ptr = align(m_begin); m_end = m_static_memory + sizeof(m_static_memory); } char *align(char *ptr) { std::size_t alignment = ((RAPIDXML_ALIGNMENT - (std::size_t(ptr) & (RAPIDXML_ALIGNMENT - 1))) & (RAPIDXML_ALIGNMENT - 1)); return ptr + alignment; } char *allocate_raw(std::size_t size) { // Allocate void *memory; if (m_alloc_func) // Allocate memory using either user-specified allocation function or global operator new[] { memory = m_alloc_func(size); assert(memory); // Allocator is not allowed to return 0, on failure it must either throw, stop the program or use longjmp } else { memory = new char[size]; #ifdef RAPIDXML_NO_EXCEPTIONS if (!memory) // If exceptions are disabled, verify memory allocation, because new will not be able to throw bad_alloc RAPIDXML_PARSE_ERROR("out of memory", 0); #endif } return static_cast<char *>(memory); } void *allocate_aligned(std::size_t size) { // Calculate aligned pointer char *result = align(m_ptr); // If not enough memory left in current pool, allocate a new pool if (result + size > m_end) { // Calculate required pool size (may be bigger than RAPIDXML_DYNAMIC_POOL_SIZE) std::size_t pool_size = RAPIDXML_DYNAMIC_POOL_SIZE; if (pool_size < size) pool_size = size; // Allocate std::size_t alloc_size = sizeof(header) + (2 * RAPIDXML_ALIGNMENT - 2) + pool_size; // 2 alignments required in worst case: one for header, one for actual allocation char *raw_memory = allocate_raw(alloc_size); // Setup new pool in allocated memory char *pool = align(raw_memory); header *new_header = reinterpret_cast<header *>(pool); new_header->previous_begin = m_begin; m_begin = raw_memory; m_ptr = pool + sizeof(header); m_end = raw_memory + alloc_size; // Calculate aligned pointer again using new pool result = align(m_ptr); } // Update pool and return aligned pointer m_ptr = result + size; return result; } char *m_begin; // Start of raw memory making up current pool char *m_ptr; // First free byte in current pool char *m_end; // One past last available byte in current pool char m_static_memory[RAPIDXML_STATIC_POOL_SIZE]; // Static raw memory alloc_func *m_alloc_func; // Allocator function, or 0 if default is to be used free_func *m_free_func; // Free function, or 0 if default is to be used }; /////////////////////////////////////////////////////////////////////////// // XML base //! Base class for xml_node and xml_attribute implementing common functions: //! name(), name_size(), value(), value_size() and parent(). //! \param Ch Character type to use template<class Ch = char> class xml_base { public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction // Construct a base with empty name, value and parent xml_base() : m_name(0) , m_value(0) , m_parent(0) { } /////////////////////////////////////////////////////////////////////////// // Node data access //! Gets name of the node. //! Interpretation of name depends on type of node. //! Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. //! <br><br> //! Use name_size() function to determine length of the name. //! \return Name of node, or empty string if node has no name. Ch *name() const { return m_name ? m_name : nullstr(); } //! Gets size of node name, not including terminator character. //! This function works correctly irrespective of whether name is or is not zero terminated. //! \return Size of node name, in characters. std::size_t name_size() const { return m_name ? m_name_size : 0; } //! Gets value of node. //! Interpretation of value depends on type of node. //! Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. //! <br><br> //! Use value_size() function to determine length of the value. //! \return Value of node, or empty string if node has no value. Ch *value() const { return m_value ? m_value : nullstr(); } //! Gets size of node value, not including terminator character. //! This function works correctly irrespective of whether value is or is not zero terminated. //! \return Size of node value, in characters. std::size_t value_size() const { return m_value ? m_value_size : 0; } /////////////////////////////////////////////////////////////////////////// // Node modification //! Sets name of node to a non zero-terminated string. //! See \ref ownership_of_strings. //! <br><br> //! Note that node does not own its name or value, it only stores a pointer to it. //! It will not delete or otherwise free the pointer on destruction. //! It is reponsibility of the user to properly manage lifetime of the string. //! The easiest way to achieve it is to use memory_pool of the document to allocate the string - //! on destruction of the document the string will be automatically freed. //! <br><br> //! Size of name must be specified separately, because name does not have to be zero terminated. //! Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated). //! \param name Name of node to set. Does not have to be zero terminated. //! \param size Size of name, in characters. This does not include zero terminator, if one is present. void name(const Ch *name, std::size_t size) { m_name = const_cast<Ch *>(name); m_name_size = size; } //! Sets name of node to a zero-terminated string. //! See also \ref ownership_of_strings and xml_node::name(const Ch *, std::size_t). //! \param name Name of node to set. Must be zero terminated. void name(const Ch *name) { this->name(name, internal::measure(name)); } //! Sets value of node to a non zero-terminated string. //! See \ref ownership_of_strings. //! <br><br> //! Note that node does not own its name or value, it only stores a pointer to it. //! It will not delete or otherwise free the pointer on destruction. //! It is reponsibility of the user to properly manage lifetime of the string. //! The easiest way to achieve it is to use memory_pool of the document to allocate the string - //! on destruction of the document the string will be automatically freed. //! <br><br> //! Size of value must be specified separately, because it does not have to be zero terminated. //! Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated). //! <br><br> //! If an element has a child node of type node_data, it will take precedence over element value when printing. //! If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser. //! \param value value of node to set. Does not have to be zero terminated. //! \param size Size of value, in characters. This does not include zero terminator, if one is present. void value(const Ch *value, std::size_t size) { m_value = const_cast<Ch *>(value); m_value_size = size; } //! Sets value of node to a zero-terminated string. //! See also \ref ownership_of_strings and xml_node::value(const Ch *, std::size_t). //! \param value Vame of node to set. Must be zero terminated. void value(const Ch *value) { this->value(value, internal::measure(value)); } /////////////////////////////////////////////////////////////////////////// // Related nodes access //! Gets node parent. //! \return Pointer to parent node, or 0 if there is no parent. xml_node<Ch> *parent() const { return m_parent; } protected: // Return empty string static Ch *nullstr() { static Ch zero = Ch('\0'); return &zero; } Ch *m_name; // Name of node, or 0 if no name Ch *m_value; // Value of node, or 0 if no value std::size_t m_name_size; // Length of node name, or undefined of no name std::size_t m_value_size; // Length of node value, or undefined if no value xml_node<Ch> *m_parent; // Pointer to parent node, or 0 if none }; //! Class representing attribute node of XML document. //! Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base). //! Note that after parse, both name and value of attribute will point to interior of source text used for parsing. //! Thus, this text must persist in memory for the lifetime of attribute. //! \param Ch Character type to use. template<class Ch = char> class xml_attribute: public xml_base<Ch> { friend class xml_node<Ch>; public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction //! Constructs an empty attribute with the specified type. //! Consider using memory_pool of appropriate xml_document if allocating attributes manually. xml_attribute() { } /////////////////////////////////////////////////////////////////////////// // Related nodes access //! Gets document of which attribute is a child. //! \return Pointer to document that contains this attribute, or 0 if there is no parent document. xml_document<Ch> *document() const { if (xml_node<Ch> *node = this->parent()) { while (node->parent()) node = node->parent(); return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0; } else return 0; } //! Gets previous attribute, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *previous_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_prev_attribute; attribute; attribute = attribute->m_prev_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return this->m_parent ? m_prev_attribute : 0; } //! Gets next attribute, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *next_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_next_attribute; attribute; attribute = attribute->m_next_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return this->m_parent ? m_next_attribute : 0; } private: xml_attribute<Ch> *m_prev_attribute; // Pointer to previous sibling of attribute, or 0 if none; only valid if parent is non-zero xml_attribute<Ch> *m_next_attribute; // Pointer to next sibling of attribute, or 0 if none; only valid if parent is non-zero }; /////////////////////////////////////////////////////////////////////////// // XML node //! Class representing a node of XML document. //! Each node may have associated name and value strings, which are available through name() and value() functions. //! Interpretation of name and value depends on type of the node. //! Type of node can be determined by using type() function. //! <br><br> //! Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. //! Thus, this text must persist in the memory for the lifetime of node. //! \param Ch Character type to use. template<class Ch = char> class xml_node: public xml_base<Ch> { public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction //! Constructs an empty node with the specified type. //! Consider using memory_pool of appropriate document to allocate nodes manually. //! \param type Type of node to construct. xml_node(node_type type) : m_type(type) , m_first_node(0) , m_first_attribute(0) { } /////////////////////////////////////////////////////////////////////////// // Node data access //! Gets type of node. //! \return Type of node. node_type type() const { return m_type; } /////////////////////////////////////////////////////////////////////////// // Related nodes access //! Gets document of which node is a child. //! \return Pointer to document that contains this node, or 0 if there is no parent document. xml_document<Ch> *document() const { xml_node<Ch> *node = const_cast<xml_node<Ch> *>(this); while (node->parent()) node = node->parent(); return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0; } //! Gets first child node, optionally matching node name. //! \param name Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found child, or 0 if not found. xml_node<Ch> *first_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *child = m_first_node; child; child = child->next_sibling()) if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive)) return child; return 0; } else return m_first_node; } //! Gets last child node, optionally matching node name. //! Behaviour is undefined if node has no children. //! Use first_node() to test if node has children. //! \param name Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found child, or 0 if not found. xml_node<Ch> *last_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { assert(m_first_node); // Cannot query for last child if node has no children if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *child = m_last_node; child; child = child->previous_sibling()) if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive)) return child; return 0; } else return m_last_node; } //! Gets previous sibling node, optionally matching node name. //! Behaviour is undefined if node has no parent. //! Use parent() to test if node has a parent. //! \param name Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found sibling, or 0 if not found. xml_node<Ch> *previous_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { assert(this->m_parent); // Cannot query for siblings if node has no parent if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *sibling = m_prev_sibling; sibling; sibling = sibling->m_prev_sibling) if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive)) return sibling; return 0; } else return m_prev_sibling; } //! Gets next sibling node, optionally matching node name. //! Behaviour is undefined if node has no parent. //! Use parent() to test if node has a parent. //! \param name Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found sibling, or 0 if not found. xml_node<Ch> *next_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { assert(this->m_parent); // Cannot query for siblings if node has no parent if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling) if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive)) return sibling; return 0; } else return m_next_sibling; } //! Gets first attribute of node, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *first_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_first_attribute; attribute; attribute = attribute->m_next_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return m_first_attribute; } //! Gets last attribute of node, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *last_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_last_attribute; attribute; attribute = attribute->m_prev_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return m_first_attribute ? m_last_attribute : 0; } /////////////////////////////////////////////////////////////////////////// // Node modification //! Sets type of node. //! \param type Type of node to set. void type(node_type type) { m_type = type; } /////////////////////////////////////////////////////////////////////////// // Node manipulation //! Prepends a new child node. //! The prepended child becomes the first child, and all existing children are moved one position back. //! \param child Node to prepend. void prepend_node(xml_node<Ch> *child) { assert(child && !child->parent() && child->type() != node_document); if (first_node()) { child->m_next_sibling = m_first_node; m_first_node->m_prev_sibling = child; } else { child->m_next_sibling = 0; m_last_node = child; } m_first_node = child; child->m_parent = this; child->m_prev_sibling = 0; } //! Appends a new child node. //! The appended child becomes the last child. //! \param child Node to append. void append_node(xml_node<Ch> *child) { assert(child && !child->parent() && child->type() != node_document); if (first_node()) { child->m_prev_sibling = m_last_node; m_last_node->m_next_sibling = child; } else { child->m_prev_sibling = 0; m_first_node = child; } m_last_node = child; child->m_parent = this; child->m_next_sibling = 0; } //! Inserts a new child node at specified place inside the node. //! All children after and including the specified node are moved one position back. //! \param where Place where to insert the child, or 0 to insert at the back. //! \param child Node to insert. void insert_node(xml_node<Ch> *where, xml_node<Ch> *child) { assert(!where || where->parent() == this); assert(child && !child->parent() && child->type() != node_document); if (where == m_first_node) prepend_node(child); else if (where == 0) append_node(child); else { child->m_prev_sibling = where->m_prev_sibling; child->m_next_sibling = where; where->m_prev_sibling->m_next_sibling = child; where->m_prev_sibling = child; child->m_parent = this; } } //! Removes first child node. //! If node has no children, behaviour is undefined. //! Use first_node() to test if node has children. void remove_first_node() { assert(first_node()); xml_node<Ch> *child = m_first_node; m_first_node = child->m_next_sibling; if (child->m_next_sibling) child->m_next_sibling->m_prev_sibling = 0; else m_last_node = 0; child->m_parent = 0; } //! Removes last child of the node. //! If node has no children, behaviour is undefined. //! Use first_node() to test if node has children. void remove_last_node() { assert(first_node()); xml_node<Ch> *child = m_last_node; if (child->m_prev_sibling) { m_last_node = child->m_prev_sibling; child->m_prev_sibling->m_next_sibling = 0; } else m_first_node = 0; child->m_parent = 0; } //! Removes specified child from the node // \param where Pointer to child to be removed. void remove_node(xml_node<Ch> *where) { assert(where && where->parent() == this); assert(first_node()); if (where == m_first_node) remove_first_node(); else if (where == m_last_node) remove_last_node(); else { where->m_prev_sibling->m_next_sibling = where->m_next_sibling; where->m_next_sibling->m_prev_sibling = where->m_prev_sibling; where->m_parent = 0; } } //! Removes all child nodes (but not attributes). void remove_all_nodes() { for (xml_node<Ch> *node = first_node(); node; node = node->m_next_sibling) node->m_parent = 0; m_first_node = 0; } //! Prepends a new attribute to the node. //! \param attribute Attribute to prepend. void prepend_attribute(xml_attribute<Ch> *attribute) { assert(attribute && !attribute->parent()); if (first_attribute()) { attribute->m_next_attribute = m_first_attribute; m_first_attribute->m_prev_attribute = attribute; } else { attribute->m_next_attribute = 0; m_last_attribute = attribute; } m_first_attribute = attribute; attribute->m_parent = this; attribute->m_prev_attribute = 0; } //! Appends a new attribute to the node. //! \param attribute Attribute to append. void append_attribute(xml_attribute<Ch> *attribute) { assert(attribute && !attribute->parent()); if (first_attribute()) { attribute->m_prev_attribute = m_last_attribute; m_last_attribute->m_next_attribute = attribute; } else { attribute->m_prev_attribute = 0; m_first_attribute = attribute; } m_last_attribute = attribute; attribute->m_parent = this; attribute->m_next_attribute = 0; } //! Inserts a new attribute at specified place inside the node. //! All attributes after and including the specified attribute are moved one position back. //! \param where Place where to insert the attribute, or 0 to insert at the back. //! \param attribute Attribute to insert. void insert_attribute(xml_attribute<Ch> *where, xml_attribute<Ch> *attribute) { assert(!where || where->parent() == this); assert(attribute && !attribute->parent()); if (where == m_first_attribute) prepend_attribute(attribute); else if (where == 0) append_attribute(attribute); else { attribute->m_prev_attribute = where->m_prev_attribute; attribute->m_next_attribute = where; where->m_prev_attribute->m_next_attribute = attribute; where->m_prev_attribute = attribute; attribute->m_parent = this; } } //! Removes first attribute of the node. //! If node has no attributes, behaviour is undefined. //! Use first_attribute() to test if node has attributes. void remove_first_attribute() { assert(first_attribute()); xml_attribute<Ch> *attribute = m_first_attribute; if (attribute->m_next_attribute) { attribute->m_next_attribute->m_prev_attribute = 0; } else m_last_attribute = 0; attribute->m_parent = 0; m_first_attribute = attribute->m_next_attribute; } //! Removes last attribute of the node. //! If node has no attributes, behaviour is undefined. //! Use first_attribute() to test if node has attributes. void remove_last_attribute() { assert(first_attribute()); xml_attribute<Ch> *attribute = m_last_attribute; if (attribute->m_prev_attribute) { attribute->m_prev_attribute->m_next_attribute = 0; m_last_attribute = attribute->m_prev_attribute; } else m_first_attribute = 0; attribute->m_parent = 0; } //! Removes specified attribute from node. //! \param where Pointer to attribute to be removed. void remove_attribute(xml_attribute<Ch> *where) { assert(first_attribute() && where->parent() == this); if (where == m_first_attribute) remove_first_attribute(); else if (where == m_last_attribute) remove_last_attribute(); else { where->m_prev_attribute->m_next_attribute = where->m_next_attribute; where->m_next_attribute->m_prev_attribute = where->m_prev_attribute; where->m_parent = 0; } } //! Removes all attributes of node. void remove_all_attributes() { for (xml_attribute<Ch> *attribute = first_attribute(); attribute; attribute = attribute->m_next_attribute) attribute->m_parent = 0; m_first_attribute = 0; } private: /////////////////////////////////////////////////////////////////////////// // Restrictions // No copying xml_node(const xml_node &); void operator =(const xml_node &); /////////////////////////////////////////////////////////////////////////// // Data members // Note that some of the pointers below have UNDEFINED values if certain other pointers are 0. // This is required for maximum performance, as it allows the parser to omit initialization of // unneded/redundant values. // // The rules are as follows: // 1. first_node and first_attribute contain valid pointers, or 0 if node has no children/attributes respectively // 2. last_node and last_attribute are valid only if node has at least one child/attribute respectively, otherwise they contain garbage // 3. prev_sibling and next_sibling are valid only if node has a parent, otherwise they contain garbage node_type m_type; // Type of node; always valid xml_node<Ch> *m_first_node; // Pointer to first child node, or 0 if none; always valid xml_node<Ch> *m_last_node; // Pointer to last child node, or 0 if none; this value is only valid if m_first_node is non-zero xml_attribute<Ch> *m_first_attribute; // Pointer to first attribute of node, or 0 if none; always valid xml_attribute<Ch> *m_last_attribute; // Pointer to last attribute of node, or 0 if none; this value is only valid if m_first_attribute is non-zero xml_node<Ch> *m_prev_sibling; // Pointer to previous sibling of node, or 0 if none; this value is only valid if m_parent is non-zero xml_node<Ch> *m_next_sibling; // Pointer to next sibling of node, or 0 if none; this value is only valid if m_parent is non-zero }; /////////////////////////////////////////////////////////////////////////// // XML document //! This class represents root of the DOM hierarchy. //! It is also an xml_node and a memory_pool through public inheritance. //! Use parse() function to build a DOM tree from a zero-terminated XML text string. //! parse() function allocates memory for nodes and attributes by using functions of xml_document, //! which are inherited from memory_pool. //! To access root node of the document, use the document itself, as if it was an xml_node. //! \param Ch Character type to use. template<class Ch = char> class xml_document: public xml_node<Ch>, public memory_pool<Ch> { public: //! Constructs empty XML document xml_document() : xml_node<Ch>(node_document) { } //! Parses zero-terminated XML string according to given flags. //! Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used. //! The string must persist for the lifetime of the document. //! In case of error, rapidxml::parse_error exception will be thrown. //! <br><br> //! If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning. //! Make sure that data is zero-terminated. //! <br><br> //! Document can be parsed into multiple times. //! Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool. //! \param text XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser. template<int Flags> void parse(Ch *text) { assert(text); // Remove current contents this->remove_all_nodes(); this->remove_all_attributes(); // Parse BOM, if any parse_bom<Flags>(text); // Parse children while (1) { // Skip whitespace before node skip<whitespace_pred, Flags>(text); if (*text == 0) break; // Parse and append new child if (*text == Ch('<')) { ++text; // Skip '<' if (xml_node<Ch> *node = parse_node<Flags>(text)) this->append_node(node); } else RAPIDXML_PARSE_ERROR("expected <", text); } } //! Clears the document by deleting all nodes and clearing the memory pool. //! All nodes owned by document pool are destroyed. void clear() { this->remove_all_nodes(); this->remove_all_attributes(); memory_pool<Ch>::clear(); } private: /////////////////////////////////////////////////////////////////////// // Internal character utility functions // Detect whitespace character struct whitespace_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_whitespace[static_cast<unsigned char>(ch)]; } }; // Detect node name character struct node_name_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_node_name[static_cast<unsigned char>(ch)]; } }; // Detect attribute name character struct attribute_name_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_attribute_name[static_cast<unsigned char>(ch)]; } }; // Detect text character (PCDATA) struct text_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_text[static_cast<unsigned char>(ch)]; } }; // Detect text character (PCDATA) that does not require processing struct text_pure_no_ws_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_text_pure_no_ws[static_cast<unsigned char>(ch)]; } }; // Detect text character (PCDATA) that does not require processing struct text_pure_with_ws_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_text_pure_with_ws[static_cast<unsigned char>(ch)]; } }; // Detect attribute value character template<Ch Quote> struct attribute_value_pred { static unsigned char test(Ch ch) { if (Quote == Ch('\'')) return internal::lookup_tables<0>::lookup_attribute_data_1[static_cast<unsigned char>(ch)]; if (Quote == Ch('\"')) return internal::lookup_tables<0>::lookup_attribute_data_2[static_cast<unsigned char>(ch)]; return 0; // Should never be executed, to avoid warnings on Comeau } }; // Detect attribute value character template<Ch Quote> struct attribute_value_pure_pred { static unsigned char test(Ch ch) { if (Quote == Ch('\'')) return internal::lookup_tables<0>::lookup_attribute_data_1_pure[static_cast<unsigned char>(ch)]; if (Quote == Ch('\"')) return internal::lookup_tables<0>::lookup_attribute_data_2_pure[static_cast<unsigned char>(ch)]; return 0; // Should never be executed, to avoid warnings on Comeau } }; // Insert coded character, using UTF8 or 8-bit ASCII template<int Flags> static void insert_coded_character(Ch *&text, unsigned long code) { if (Flags & parse_no_utf8) { // Insert 8-bit ASCII character // Todo: possibly verify that code is less than 256 and use replacement char otherwise? text[0] = static_cast<unsigned char>(code); text += 1; } else { // Insert UTF8 sequence if (code < 0x80) // 1 byte sequence { text[0] = static_cast<unsigned char>(code); text += 1; } else if (code < 0x800) // 2 byte sequence { text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast<unsigned char>(code | 0xC0); text += 2; } else if (code < 0x10000) // 3 byte sequence { text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast<unsigned char>(code | 0xE0); text += 3; } else if (code < 0x110000) // 4 byte sequence { text[3] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast<unsigned char>(code | 0xF0); text += 4; } else // Invalid, only codes up to 0x10FFFF are allowed in Unicode { RAPIDXML_PARSE_ERROR("invalid numeric character entity", text); } } } // Skip characters until predicate evaluates to true template<class StopPred, int Flags> static void skip(Ch *&text) { Ch *tmp = text; while (StopPred::test(*tmp)) ++tmp; text = tmp; } // Skip characters until predicate evaluates to true while doing the following: // - replacing XML character entity references with proper characters (&apos; &amp; &quot; &lt; &gt; &#...;) // - condensing whitespace sequences to single space character template<class StopPred, class StopPredPure, int Flags> static Ch *skip_and_expand_character_refs(Ch *&text) { // If entity translation, whitespace condense and whitespace trimming is disabled, use plain skip if (Flags & parse_no_entity_translation && !(Flags & parse_normalize_whitespace) && !(Flags & parse_trim_whitespace)) { skip<StopPred, Flags>(text); return text; } // Use simple skip until first modification is detected skip<StopPredPure, Flags>(text); // Use translation skip Ch *src = text; Ch *dest = src; while (StopPred::test(*src)) { // If entity translation is enabled if (!(Flags & parse_no_entity_translation)) { // Test if replacement is needed if (src[0] == Ch('&')) { switch (src[1]) { // &amp; &apos; case Ch('a'): if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';')) { *dest = Ch('&'); ++dest; src += 5; continue; } if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && src[5] == Ch(';')) { *dest = Ch('\''); ++dest; src += 6; continue; } break; // &quot; case Ch('q'): if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && src[5] == Ch(';')) { *dest = Ch('"'); ++dest; src += 6; continue; } break; // &gt; case Ch('g'): if (src[2] == Ch('t') && src[3] == Ch(';')) { *dest = Ch('>'); ++dest; src += 4; continue; } break; // &lt; case Ch('l'): if (src[2] == Ch('t') && src[3] == Ch(';')) { *dest = Ch('<'); ++dest; src += 4; continue; } break; // &#...; - assumes ASCII case Ch('#'): if (src[2] == Ch('x')) { unsigned long code = 0; src += 3; // Skip &#x while (1) { unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)]; if (digit == 0xFF) break; code = code * 16 + digit; ++src; } insert_coded_character<Flags>(dest, code); // Put character in output } else { unsigned long code = 0; src += 2; // Skip &# while (1) { unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)]; if (digit == 0xFF) break; code = code * 10 + digit; ++src; } insert_coded_character<Flags>(dest, code); // Put character in output } if (*src == Ch(';')) ++src; else RAPIDXML_PARSE_ERROR("expected ;", src); continue; // Something else default: // Ignore, just copy '&' verbatim break; } } } // If whitespace condensing is enabled if (Flags & parse_normalize_whitespace) { // Test if condensing is needed if (whitespace_pred::test(*src)) { *dest = Ch(' '); ++dest; // Put single space in dest ++src; // Skip first whitespace char // Skip remaining whitespace chars while (whitespace_pred::test(*src)) ++src; continue; } } // No replacement, only copy character *dest++ = *src++; } // Return new end text = src; return dest; } /////////////////////////////////////////////////////////////////////// // Internal parsing functions // Parse BOM, if any template<int Flags> void parse_bom(Ch *&text) { // UTF-8? if (static_cast<unsigned char>(text[0]) == 0xEF && static_cast<unsigned char>(text[1]) == 0xBB && static_cast<unsigned char>(text[2]) == 0xBF) { text += 3; // Skup utf-8 bom } } // Parse XML declaration (<?xml...) template<int Flags> xml_node<Ch> *parse_xml_declaration(Ch *&text) { // If parsing of declaration is disabled if (!(Flags & parse_declaration_node)) { // Skip until end of declaration while (text[0] != Ch('?') || text[1] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 2; // Skip '?>' return 0; } // Create declaration xml_node<Ch> *declaration = this->allocate_node(node_declaration); // Skip whitespace before attributes or ?> skip<whitespace_pred, Flags>(text); // Parse declaration attributes parse_node_attributes<Flags>(text, declaration); // Skip ?> if (text[0] != Ch('?') || text[1] != Ch('>')) RAPIDXML_PARSE_ERROR("expected ?>", text); text += 2; return declaration; } // Parse XML comment (<!--...) template<int Flags> xml_node<Ch> *parse_comment(Ch *&text) { // If parsing of comments is disabled if (!(Flags & parse_comment_nodes)) { // Skip until end of comment while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 3; // Skip '-->' return 0; // Do not produce comment node } // Remember value start Ch *value = text; // Skip until end of comment while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } // Create comment node xml_node<Ch> *comment = this->allocate_node(node_comment); comment->value(value, text - value); // Place zero terminator after comment value if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); text += 3; // Skip '-->' return comment; } // Parse DOCTYPE template<int Flags> xml_node<Ch> *parse_doctype(Ch *&text) { // Remember value start Ch *value = text; // Skip to > while (*text != Ch('>')) { // Determine character type switch (*text) { // If '[' encountered, scan for matching ending ']' using naive algorithm with depth // This works for all W3C test files except for 2 most wicked case Ch('['): { ++text; // Skip '[' int depth = 1; while (depth > 0) { switch (*text) { case Ch('['): ++depth; break; case Ch(']'): --depth; break; case 0: RAPIDXML_PARSE_ERROR("unexpected end of data", text); } ++text; } break; } // Error on end of text case Ch('\0'): RAPIDXML_PARSE_ERROR("unexpected end of data", text); // Other character, skip it default: ++text; } } // If DOCTYPE nodes enabled if (Flags & parse_doctype_node) { // Create a new doctype node xml_node<Ch> *doctype = this->allocate_node(node_doctype); doctype->value(value, text - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); text += 1; // skip '>' return doctype; } else { text += 1; // skip '>' return 0; } } // Parse PI template<int Flags> xml_node<Ch> *parse_pi(Ch *&text) { // If creation of PI nodes is enabled if (Flags & parse_pi_nodes) { // Create pi node xml_node<Ch> *pi = this->allocate_node(node_pi); // Extract PI target name Ch *name = text; skip<node_name_pred, Flags>(text); if (text == name) RAPIDXML_PARSE_ERROR("expected PI target", text); pi->name(name, text - name); // Skip whitespace between pi target and pi skip<whitespace_pred, Flags>(text); // Remember start of pi Ch *value = text; // Skip to '?>' while (text[0] != Ch('?') || text[1] != Ch('>')) { if (*text == Ch('\0')) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } // Set pi value (verbatim, no entity expansion or whitespace normalization) pi->value(value, text - value); // Place zero terminator after name and value if (!(Flags & parse_no_string_terminators)) { pi->name()[pi->name_size()] = Ch('\0'); pi->value()[pi->value_size()] = Ch('\0'); } text += 2; // Skip '?>' return pi; } else { // Skip to '?>' while (text[0] != Ch('?') || text[1] != Ch('>')) { if (*text == Ch('\0')) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 2; // Skip '?>' return 0; } } // Parse and append data // Return character that ends data. // This is necessary because this character might have been overwritten by a terminating 0 template<int Flags> Ch parse_and_append_data(xml_node<Ch> *node, Ch *&text, Ch *contents_start) { // Backup to contents start if whitespace trimming is disabled if (!(Flags & parse_trim_whitespace)) text = contents_start; // Skip until end of data Ch *value = text, *end; if (Flags & parse_normalize_whitespace) end = skip_and_expand_character_refs<text_pred, text_pure_with_ws_pred, Flags>(text); else end = skip_and_expand_character_refs<text_pred, text_pure_no_ws_pred, Flags>(text); // Trim trailing whitespace if flag is set; leading was already trimmed by whitespace skip after > if (Flags & parse_trim_whitespace) { if (Flags & parse_normalize_whitespace) { // Whitespace is already condensed to single space characters by skipping function, so just trim 1 char off the end if (*(end - 1) == Ch(' ')) --end; } else { // Backup until non-whitespace character is found while (whitespace_pred::test(*(end - 1))) --end; } } // If characters are still left between end and value (this test is only necessary if normalization is enabled) // Create new data node if (!(Flags & parse_no_data_nodes)) { xml_node<Ch> *data = this->allocate_node(node_data); data->value(value, end - value); node->append_node(data); } // Add data to parent node if no data exists yet if (!(Flags & parse_no_element_values)) if (*node->value() == Ch('\0')) node->value(value, end - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) { Ch ch = *text; *end = Ch('\0'); return ch; // Return character that ends data; this is required because zero terminator overwritten it } // Return character that ends data return *text; } // Parse CDATA template<int Flags> xml_node<Ch> *parse_cdata(Ch *&text) { // If CDATA is disabled if (Flags & parse_no_data_nodes) { // Skip until end of cdata while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 3; // Skip ]]> return 0; // Do not produce CDATA node } // Skip until end of cdata Ch *value = text; while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } // Create new cdata node xml_node<Ch> *cdata = this->allocate_node(node_cdata); cdata->value(value, text - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); text += 3; // Skip ]]> return cdata; } // Parse element node template<int Flags> xml_node<Ch> *parse_element(Ch *&text) { // Create element node xml_node<Ch> *element = this->allocate_node(node_element); // Extract element name Ch *name = text; skip<node_name_pred, Flags>(text); if (text == name) RAPIDXML_PARSE_ERROR("expected element name", text); element->name(name, text - name); // Skip whitespace between element name and attributes or > skip<whitespace_pred, Flags>(text); // Parse attributes, if any parse_node_attributes<Flags>(text, element); // Determine ending type if (*text == Ch('>')) { ++text; parse_node_contents<Flags>(text, element); } else if (*text == Ch('/')) { ++text; if (*text != Ch('>')) RAPIDXML_PARSE_ERROR("expected >", text); ++text; } else RAPIDXML_PARSE_ERROR("expected >", text); // Place zero terminator after name if (!(Flags & parse_no_string_terminators)) element->name()[element->name_size()] = Ch('\0'); // Return parsed element return element; } // Determine node type, and parse it template<int Flags> xml_node<Ch> *parse_node(Ch *&text) { // Parse proper node type switch (text[0]) { // <... default: // Parse and append element node return parse_element<Flags>(text); // <?... case Ch('?'): ++text; // Skip ? if ((text[0] == Ch('x') || text[0] == Ch('X')) && (text[1] == Ch('m') || text[1] == Ch('M')) && (text[2] == Ch('l') || text[2] == Ch('L')) && whitespace_pred::test(text[3])) { // '<?xml ' - xml declaration text += 4; // Skip 'xml ' return parse_xml_declaration<Flags>(text); } else { // Parse PI return parse_pi<Flags>(text); } // <!... case Ch('!'): // Parse proper subset of <! node switch (text[1]) { // <!- case Ch('-'): if (text[2] == Ch('-')) { // '<!--' - xml comment text += 3; // Skip '!--' return parse_comment<Flags>(text); } break; // <![ case Ch('['): if (text[2] == Ch('C') && text[3] == Ch('D') && text[4] == Ch('A') && text[5] == Ch('T') && text[6] == Ch('A') && text[7] == Ch('[')) { // '<![CDATA[' - cdata text += 8; // Skip '![CDATA[' return parse_cdata<Flags>(text); } break; // <!D case Ch('D'): if (text[2] == Ch('O') && text[3] == Ch('C') && text[4] == Ch('T') && text[5] == Ch('Y') && text[6] == Ch('P') && text[7] == Ch('E') && whitespace_pred::test(text[8])) { // '<!DOCTYPE ' - doctype text += 9; // skip '!DOCTYPE ' return parse_doctype<Flags>(text); } } // switch // Attempt to skip other, unrecognized node types starting with <! ++text; // Skip ! while (*text != Ch('>')) { if (*text == 0) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } ++text; // Skip '>' return 0; // No node recognized } } // Parse contents of the node - children, data etc. template<int Flags> void parse_node_contents(Ch *&text, xml_node<Ch> *node) { // For all children and text while (1) { // Skip whitespace between > and node contents Ch *contents_start = text; // Store start of node contents before whitespace is skipped skip<whitespace_pred, Flags>(text); Ch next_char = *text; // After data nodes, instead of continuing the loop, control jumps here. // This is because zero termination inside parse_and_append_data() function // would wreak havoc with the above code. // Also, skipping whitespace after data nodes is unnecessary. after_data_node: // Determine what comes next: node closing, child node, data node, or 0? switch (next_char) { // Node closing or child node case Ch('<'): if (text[1] == Ch('/')) { // Node closing text += 2; // Skip '</' if (Flags & parse_validate_closing_tags) { // Skip and validate closing tag name Ch *closing_name = text; skip<node_name_pred, Flags>(text); if (!internal::compare(node->name(), node->name_size(), closing_name, text - closing_name, true)) RAPIDXML_PARSE_ERROR("invalid closing tag name", text); } else { // No validation, just skip name skip<node_name_pred, Flags>(text); } // Skip remaining whitespace after node name skip<whitespace_pred, Flags>(text); if (*text != Ch('>')) RAPIDXML_PARSE_ERROR("expected >", text); ++text; // Skip '>' return; // Node closed, finished parsing contents } else { // Child node ++text; // Skip '<' if (xml_node<Ch> *child = parse_node<Flags>(text)) node->append_node(child); } break; // End of data - error case Ch('\0'): RAPIDXML_PARSE_ERROR("unexpected end of data", text); // Data node default: next_char = parse_and_append_data<Flags>(node, text, contents_start); goto after_data_node; // Bypass regular processing after data nodes } } } // Parse XML attributes of the node template<int Flags> void parse_node_attributes(Ch *&text, xml_node<Ch> *node) { // For all attributes while (attribute_name_pred::test(*text)) { // Extract attribute name Ch *name = text; ++text; // Skip first character of attribute name skip<attribute_name_pred, Flags>(text); if (text == name) RAPIDXML_PARSE_ERROR("expected attribute name", name); // Create new attribute xml_attribute<Ch> *attribute = this->allocate_attribute(); attribute->name(name, text - name); node->append_attribute(attribute); // Skip whitespace after attribute name skip<whitespace_pred, Flags>(text); // Skip = if (*text != Ch('=')) RAPIDXML_PARSE_ERROR("expected =", text); ++text; // Add terminating zero after name if (!(Flags & parse_no_string_terminators)) attribute->name()[attribute->name_size()] = 0; // Skip whitespace after = skip<whitespace_pred, Flags>(text); // Skip quote and remember if it was ' or " Ch quote = *text; if (quote != Ch('\'') && quote != Ch('"')) RAPIDXML_PARSE_ERROR("expected ' or \"", text); ++text; // Extract attribute value and expand char refs in it Ch *value = text, *end; const int AttFlags = Flags & ~parse_normalize_whitespace; // No whitespace normalization in attributes if (quote == Ch('\'')) end = skip_and_expand_character_refs<attribute_value_pred<Ch('\'')>, attribute_value_pure_pred<Ch('\'')>, AttFlags>(text); else end = skip_and_expand_character_refs<attribute_value_pred<Ch('"')>, attribute_value_pure_pred<Ch('"')>, AttFlags>(text); // Set attribute value attribute->value(value, end - value); // Make sure that end quote is present if (*text != quote) RAPIDXML_PARSE_ERROR("expected ' or \"", text); ++text; // Skip quote // Add terminating zero after value if (!(Flags & parse_no_string_terminators)) attribute->value()[attribute->value_size()] = 0; // Skip whitespace after attribute value skip<whitespace_pred, Flags>(text); } } }; //! \cond internal namespace internal { // Whitespace (space \n \r \t) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_whitespace[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, // 0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F }; // Node name (anything but space \n \r \t / > ? \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_node_name[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) (anything but < \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_text[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) that does not require processing when ws normalization is disabled // (anything but < \0 &) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_text_pure_no_ws[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) that does not require processing when ws normalizationis is enabled // (anything but < \0 & space \n \r \t) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_text_pure_with_ws[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute name (anything but space \n \r \t / < > = ? ! \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_name[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with single quote (anything but ' \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with single quote that does not require processing (anything but ' \0 &) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1_pure[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with double quote (anything but " \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with double quote that does not require processing (anything but " \0 &) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2_pure[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Digits (dec and hex, 255 denotes end of numeric character reference) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_digits[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 2 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,255,255,255,255,255,255, // 3 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 4 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 5 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 6 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 7 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255 // F }; // Upper case conversion template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_upcase[256] = { // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A B C D E F 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // 0 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, // 1 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, // 2 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // 3 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 4 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, // 5 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 6 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123,124,125,126,127, // 7 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, // 8 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, // 9 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, // A 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, // B 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, // C 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, // D 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239, // E 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255 // F }; } //! \endcond } // Undefine internal macros #undef RAPIDXML_PARSE_ERROR // On MSVC, restore warnings state #ifdef _MSC_VER #pragma warning(pop) #endif #endif #ifndef RAPIDXML_PRINT_HPP_INCLUDED #define RAPIDXML_PRINT_HPP_INCLUDED // Copyright (C) 2006, 2009 Marcin Kalicinski // Version 1.13 // Revision $DateTime: 2009/05/13 01:46:17 $ //! \file rapidxml_print.hpp This file contains rapidxml printer implementation // Only include streams if not disabled #ifndef RAPIDXML_NO_STREAMS #include <ostream> #include <iterator> #endif namespace rapidxml { /////////////////////////////////////////////////////////////////////// // Printing flags const int print_no_indenting = 0x1; //!< Printer flag instructing the printer to suppress indenting of XML. See print() function. /////////////////////////////////////////////////////////////////////// // Internal //! \cond internal namespace internal { /////////////////////////////////////////////////////////////////////////// // Internal character operations // Copy characters from given range to given output iterator template<class OutIt, class Ch> inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out) { while (begin != end) *out++ = *begin++; return out; } // Copy characters from given range to given output iterator and expand // characters into references (&lt; &gt; &apos; &quot; &amp;) template<class OutIt, class Ch> inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out) { while (begin != end) { if (*begin == noexpand) { *out++ = *begin; // No expansion, copy character } else { switch (*begin) { case Ch('<'): *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';'); break; case Ch('>'): *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';'); break; case Ch('\''): *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';'); break; case Ch('"'): *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';'); break; case Ch('&'): *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';'); break; default: *out++ = *begin; // No expansion, copy character } } ++begin; // Step to next character } return out; } // Fill given output iterator with repetitions of the same character template<class OutIt, class Ch> inline OutIt fill_chars(OutIt out, int n, Ch ch) { for (int i = 0; i < n; ++i) *out++ = ch; return out; } // Find character template<class Ch, Ch ch> inline bool find_char(const Ch *begin, const Ch *end) { while (begin != end) if (*begin++ == ch) return true; return false; } /////////////////////////////////////////////////////////////////////////// // Internal printing operations // Print attributes of the node template<class OutIt, class Ch> inline OutIt print_attributes(OutIt out, const xml_node<Ch> *node, int flags) { for (xml_attribute<Ch> *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute()) { if (attribute->name() && attribute->value()) { // Print attribute name *out = Ch(' '), ++out; out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out); *out = Ch('='), ++out; // Print attribute value using appropriate quote type if (find_char<Ch, Ch('"')>(attribute->value(), attribute->value() + attribute->value_size())) { *out = Ch('\''), ++out; out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('"'), out); *out = Ch('\''), ++out; } else { *out = Ch('"'), ++out; out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\''), out); *out = Ch('"'), ++out; } } } return out; } // Print data node template<class OutIt, class Ch> inline OutIt print_data_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_data); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); return out; } // Print data node template<class OutIt, class Ch> inline OutIt print_cdata_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_cdata); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'); ++out; *out = Ch('!'); ++out; *out = Ch('['); ++out; *out = Ch('C'); ++out; *out = Ch('D'); ++out; *out = Ch('A'); ++out; *out = Ch('T'); ++out; *out = Ch('A'); ++out; *out = Ch('['); ++out; out = copy_chars(node->value(), node->value() + node->value_size(), out); *out = Ch(']'); ++out; *out = Ch(']'); ++out; *out = Ch('>'); ++out; return out; } // Forward declare template<class OutIt, class Ch> OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent); // Print element node template<class OutIt, class Ch> inline OutIt print_element_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_element); // Print element name and attributes, if any if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; out = copy_chars(node->name(), node->name() + node->name_size(), out); out = print_attributes(out, node, flags); // If node is childless if (node->value_size() == 0 && !node->first_node()) { // Print childless node tag ending *out = Ch('/'), ++out; *out = Ch('>'), ++out; } else { // Print normal node tag ending *out = Ch('>'), ++out; // Test if node contains a single data node only (and no other nodes) xml_node<Ch> *child = node->first_node(); if (!child) { // If node has no children, only print its value without indenting out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); } else if (child->next_sibling() == 0 && child->type() == node_data) { // If node has a sole data child, only print its value without indenting out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out); } else { // Print all children with full indenting if (!(flags & print_no_indenting)) *out = Ch('\n'), ++out; out = print_children(out, node, flags, indent + 1); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); } // Print node end *out = Ch('<'), ++out; *out = Ch('/'), ++out; out = copy_chars(node->name(), node->name() + node->name_size(), out); *out = Ch('>'), ++out; } return out; } // Print declaration node template<class OutIt, class Ch> inline OutIt print_declaration_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { // Print declaration start if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('?'), ++out; *out = Ch('x'), ++out; *out = Ch('m'), ++out; *out = Ch('l'), ++out; // Print attributes out = print_attributes(out, node, flags); // Print declaration end *out = Ch('?'), ++out; *out = Ch('>'), ++out; return out; } // Print comment node template<class OutIt, class Ch> inline OutIt print_comment_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_comment); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('!'), ++out; *out = Ch('-'), ++out; *out = Ch('-'), ++out; out = copy_chars(node->value(), node->value() + node->value_size(), out); *out = Ch('-'), ++out; *out = Ch('-'), ++out; *out = Ch('>'), ++out; return out; } // Print doctype node template<class OutIt, class Ch> inline OutIt print_doctype_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_doctype); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('!'), ++out; *out = Ch('D'), ++out; *out = Ch('O'), ++out; *out = Ch('C'), ++out; *out = Ch('T'), ++out; *out = Ch('Y'), ++out; *out = Ch('P'), ++out; *out = Ch('E'), ++out; *out = Ch(' '), ++out; out = copy_chars(node->value(), node->value() + node->value_size(), out); *out = Ch('>'), ++out; return out; } // Print pi node template<class OutIt, class Ch> inline OutIt print_pi_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_pi); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('?'), ++out; out = copy_chars(node->name(), node->name() + node->name_size(), out); *out = Ch(' '), ++out; out = copy_chars(node->value(), node->value() + node->value_size(), out); *out = Ch('?'), ++out; *out = Ch('>'), ++out; return out; } // Print node template<class OutIt, class Ch> inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { // Print proper node type switch (node->type()) { // Document case node_document: out = print_children(out, node, flags, indent); break; // Element case node_element: out = print_element_node(out, node, flags, indent); break; // Data case node_data: out = print_data_node(out, node, flags, indent); break; // CDATA case node_cdata: out = print_cdata_node(out, node, flags, indent); break; // Declaration case node_declaration: out = print_declaration_node(out, node, flags, indent); break; // Comment case node_comment: out = print_comment_node(out, node, flags, indent); break; // Doctype case node_doctype: out = print_doctype_node(out, node, flags, indent); break; // Pi case node_pi: out = print_pi_node(out, node, flags, indent); break; // Unknown default: assert(0); break; } // If indenting not disabled, add line break after node if (!(flags & print_no_indenting)) *out = Ch('\n'), ++out; // Return modified iterator return out; } // Print children of the node template<class OutIt, class Ch> inline OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent) { for (xml_node<Ch> *child = node->first_node(); child; child = child->next_sibling()) out = print_node(out, child, flags, indent); return out; } } //! \endcond /////////////////////////////////////////////////////////////////////////// // Printing //! Prints XML to given output iterator. //! \param out Output iterator to print to. //! \param node Node to be printed. Pass xml_document to print entire document. //! \param flags Flags controlling how XML is printed. //! \return Output iterator pointing to position immediately after last character of printed text. template<class OutIt, class Ch> inline OutIt print(OutIt out, const xml_node<Ch> &node, int flags = 0) { return internal::print_node(out, &node, flags, 0); } #ifndef RAPIDXML_NO_STREAMS //! Prints XML to given output stream. //! \param out Output stream to print to. //! \param node Node to be printed. Pass xml_document to print entire document. //! \param flags Flags controlling how XML is printed. //! \return Output stream. template<class Ch> inline std::basic_ostream<Ch> &print(std::basic_ostream<Ch> &out, const xml_node<Ch> &node, int flags = 0) { print(std::ostream_iterator<Ch>(out), node, flags); return out; } //! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process. //! \param out Output stream to print to. //! \param node Node to be printed. //! \return Output stream. template<class Ch> inline std::basic_ostream<Ch> &operator <<(std::basic_ostream<Ch> &out, const xml_node<Ch> &node) { return print(out, node); } #endif } #endif
[ "yohan.masson@neuf.fr" ]
yohan.masson@neuf.fr
4bfeb3e151a5fe33a60e98b1698efde5fb8053e8
27707bdfc9abb761dd98062390fc33c00178f1c6
/socks1.cpp
0c3cdb11ed08d8747e7d44fd19787572ddd864f5
[ "MIT" ]
permissive
skyh0rn/Codechef
e1dfb60c52ecb3d1c30d48cc685794d6f9305e26
83821c0b6056e3d631ad1d3273b41727074537bb
refs/heads/master
2023-04-15T08:16:50.120468
2021-05-08T06:14:17
2021-05-08T06:14:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,174
cpp
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <set> #include <map> #include <climits> #include <cmath> using namespace std; #define ll long long #define ck cout<<"check\n" #define p(i) cout<<i<<"\n" #define spc " " #define wis(x) cerr << #x << " is " << x << endl #define MOD 1000000007 #define mx(a,b) ( (a) > (b) ? (a) : (b)) #define mn(a,b) ( (a) < (b) ? (a) : (b)) #define test int test;cin>>test;while(test--) #define f(i,L,R) for (int i = L; i < R; i++) #define fe(i,L,R) for (int i = L; i <= R; i++) #define ff(i,L,R) for (int i = L; i > R; i--) #define ffe(i,L,R) for (int i = L; i >= R; i--) #define mp(a,b) make_pair(a,b) #define ain(a,i,n) f(j,i,n) cin>>a[j] #define aout(a,i,n) f(j,i,n) cout<<a[j]<<" \n"[j==n-1] #define cnl cout<<'\n' typedef vector<int> vi; typedef vector<ll> vll; typedef vector<vi> vvi; typedef pair<int,int> ii; #define fi first #define se second #define pb push_back #define pf push_front typedef unsigned long long ull; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int a,b,c; cin>>a>>b>>c; if(a==b||b==c||c==a) p("Yes"); else p("no"); return 0; }
[ "akkiind4@gmail.com" ]
akkiind4@gmail.com
4627ae47a5fd25f7d3e7682350215aa3ef471ddc
00f0b07283610491a7086727a9b832e37fb14836
/src/test/alert_tests.cpp
35fda55383669568869770029024d950217aace0
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
TrustPlus/TRUSTplusXTP
9b8e870a9546cd9fb291023d1e3ad3d3ac69c84f
bcd9e4acb200808c51bfde3707c7544bf26b88bd
refs/heads/master
2020-04-13T03:29:33.446223
2019-02-16T18:13:45
2019-02-16T18:13:45
162,933,401
4
4
MIT
2019-11-14T05:22:27
2018-12-24T00:25:55
C++
UTF-8
C++
false
false
9,086
cpp
// Copyright (c) 2013-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Unit tests for alert system #include "alert.h" #include "chain.h" #include "chainparams.h" #include "clientversion.h" #include "data/alertTests.raw.h" #include "main.h" // For PartitionCheck #include "serialize.h" #include "streams.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_trustplus.h" #include <fstream> #include <boost/filesystem/operations.hpp> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> // // Sign a CAlert and serialize it // bool SignAndSave(CAlert &alert) { // Sign if(!alert.Sign()) { printf("SignAndSave() : could not sign alert:\n%s", alert.ToString().c_str()); return false; } std::string strFilePath = "src/test/data/alertTests.raw"; // open output file and associate it with CAutoFile FILE *file = fopen(strFilePath.c_str(), "ab+"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s: Failed to open file %s", __func__, strFilePath); try { fileout << alert; } catch (std::exception &e) { return error("%s: Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); return true; } // // alertTests contains 8 alerts, generated with this code // void GenerateAlertTests() { CAlert alert; alert.nRelayUntil = 60; alert.nExpiration = 24 * 60 * 60; alert.nID = 1; alert.nCancel = 0; // cancels previous messages up to this ID number alert.nMinVer = 0; // These versions are protocol versions alert.nMaxVer = 999001; alert.nPriority = 1; alert.strComment = "Alert comment"; alert.strStatusBar = "Alert 1"; SignAndSave(alert); alert.setSubVer.insert(std::string("/Satoshi:0.1.0/")); alert.strStatusBar = "Alert 1 for Satoshi 0.1.0"; SignAndSave(alert); alert.setSubVer.insert(std::string("/Satoshi:0.2.0/")); alert.strStatusBar = "Alert 1 for Satoshi 0.1.0, 0.2.0"; SignAndSave(alert); alert.setSubVer.clear(); ++alert.nID; alert.nCancel = 1; alert.nPriority = 100; alert.strStatusBar = "Alert 2, cancels 1"; SignAndSave(alert); alert.nExpiration += 60; ++alert.nID; SignAndSave(alert); ++alert.nID; alert.nMinVer = 11; alert.nMaxVer = 22; SignAndSave(alert); ++alert.nID; alert.strStatusBar = "Alert 2 for Satoshi 0.1.0"; alert.setSubVer.insert(std::string("/Satoshi:0.1.0/")); SignAndSave(alert); ++alert.nID; alert.nMinVer = 0; alert.nMaxVer = 999999; alert.strStatusBar = "Evil Alert'; /bin/ls; echo '"; alert.setSubVer.clear(); SignAndSave(alert); } struct ReadAlerts : public TestingSetup { ReadAlerts() { std::vector<unsigned char> vch(alert_tests::alertTests, alert_tests::alertTests + sizeof(alert_tests::alertTests)); CDataStream stream(vch, SER_DISK, CLIENT_VERSION); try { while (!stream.eof()) { CAlert alert; stream >> alert; alerts.push_back(alert); } } catch (const std::exception&) { } } ~ReadAlerts() { } static std::vector<std::string> read_lines(boost::filesystem::path filepath) { std::vector<std::string> result; std::ifstream f(filepath.string().c_str()); std::string line; while (std::getline(f,line)) result.push_back(line); return result; } std::vector<CAlert> alerts; }; BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts) // Steps to generate alert tests: // - update alerts in GenerateAlertTests() (optional) // - enable code below (#if 1) // - replace "fffffffffffffffffffffffffffffffffffffffffffffffffff" with the actual MAINNET privkey // - recompile and run "/path/to/test_trustplus -t Alert_test" // // NOTE: make sure to disable code and remove alert privkey when you're done! // #if 0 BOOST_AUTO_TEST_CASE(GenerateAlerts) { SoftSetArg("-alertkey", "fffffffffffffffffffffffffffffffffffffffffffffffffff"); GenerateAlertTests(); } #endif BOOST_AUTO_TEST_CASE(AlertApplies) { SetMockTime(11); const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey(); BOOST_FOREACH(const CAlert& alert, alerts) { BOOST_CHECK(alert.CheckSignature(alertKey)); } BOOST_CHECK(alerts.size() >= 3); // Matches: BOOST_CHECK(alerts[0].AppliesTo(1, "")); BOOST_CHECK(alerts[0].AppliesTo(999001, "")); BOOST_CHECK(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/")); BOOST_CHECK(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/")); // Don't match: BOOST_CHECK(!alerts[0].AppliesTo(-1, "")); BOOST_CHECK(!alerts[0].AppliesTo(999002, "")); BOOST_CHECK(!alerts[1].AppliesTo(1, "")); BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0")); BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0")); BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/")); BOOST_CHECK(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/")); SetMockTime(0); } BOOST_AUTO_TEST_CASE(AlertNotify) { SetMockTime(11); const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey(); boost::filesystem::path temp = GetTempPath() / boost::filesystem::unique_path("alertnotify-%%%%.txt"); mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string(); BOOST_FOREACH(CAlert alert, alerts) alert.ProcessAlert(alertKey, false); std::vector<std::string> r = read_lines(temp); BOOST_CHECK_EQUAL(r.size(), 4u); // Windows built-in echo semantics are different than posixy shells. Quotes and // whitespace are printed literally. #ifndef WIN32 BOOST_CHECK_EQUAL(r[0], "Alert 1"); BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1"); BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1"); BOOST_CHECK_EQUAL(r[3], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed #else BOOST_CHECK_EQUAL(r[0], "'Alert 1' "); BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' "); BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' "); BOOST_CHECK_EQUAL(r[3], "'Evil Alert; /bin/ls; echo ' "); #endif boost::filesystem::remove(temp); SetMockTime(0); } static bool falseFunc() { return false; } BOOST_AUTO_TEST_CASE(PartitionAlert) { // Test PartitionCheck CCriticalSection csDummy; CBlockIndex indexDummy[100]; CChainParams& params = Params(CBaseChainParams::MAIN); int64_t nPowTargetSpacing = params.GetConsensus().nPowTargetSpacing; // Generate fake blockchain timestamps relative to // an arbitrary time: int64_t now = 1427379054; SetMockTime(now); for (int i = 0; i < 100; i++) { indexDummy[i].phashBlock = NULL; if (i == 0) indexDummy[i].pprev = NULL; else indexDummy[i].pprev = &indexDummy[i-1]; indexDummy[i].nHeight = i; indexDummy[i].nTime = now - (100-i)*nPowTargetSpacing; // Other members don't matter, the partition check code doesn't // use them } strMiscWarning = ""; // Test 1: chain with blocks every nPowTargetSpacing seconds, // as normal, no worries: PartitionCheck(falseFunc, csDummy, &indexDummy[99], nPowTargetSpacing); BOOST_CHECK_MESSAGE(strMiscWarning.empty(), strMiscWarning); // Test 2: go 52.5 minutes without a block, expect a warning: now += (3*60*60+30*60)/4; // we have 4x faster blocks SetMockTime(now); PartitionCheck(falseFunc, csDummy, &indexDummy[99], nPowTargetSpacing); BOOST_CHECK(!strMiscWarning.empty()); BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning); strMiscWarning = ""; // Test 3: test the "partition alerts only go off once per day" // code: now += 60*10; SetMockTime(now); PartitionCheck(falseFunc, csDummy, &indexDummy[99], nPowTargetSpacing); BOOST_CHECK(strMiscWarning.empty()); // Test 4: get 2.5 times as many blocks as expected: now += 60*60*24; // Pretend it is a day later SetMockTime(now); int64_t quickSpacing = nPowTargetSpacing*2/5; for (int i = 0; i < 100; i++) // Tweak chain timestamps: indexDummy[i].nTime = now - (100-i)*quickSpacing; PartitionCheck(falseFunc, csDummy, &indexDummy[99], nPowTargetSpacing); BOOST_CHECK(!strMiscWarning.empty()); BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning); strMiscWarning = ""; SetMockTime(0); } BOOST_AUTO_TEST_SUITE_END()
[ "github@mitchellmint.com" ]
github@mitchellmint.com
d6770ad2d972667894a9711aca011a9765118811
e166dc332f805316b51f826beed2b6f9fadeab1c
/IR_IoT_Remote/IR_IoT_Remote.ino
33bedccf14c64fe5be74b00bfe53a4f637c7349e
[]
no_license
mrWheel/IR_IoT_Remote
784d2b00d33decc2c79512d006a3bf46c42103a0
69d90e5030505ee89a5c620b0ec3c466fcd5a746
refs/heads/master
2020-06-19T18:53:18.223814
2019-08-27T09:23:50
2019-08-27T09:23:50
196,831,934
0
0
null
null
null
null
UTF-8
C++
false
false
13,565
ino
/* *************************************************************************** ** Program : IR_IoT_Remote */ #define _FW_VERSION "v0.2.2 WS (27-08-2019)" /* ** ** Copyright (c) 2019 Willem Aandewiel ** ** TERMS OF USE: MIT License. See bottom of file. *************************************************************************** Arduino-IDE settings for ESP-12E: - Board: "NodeMCU 1.0 (ESP-12E Module)" - Flash mode: "DIO" / "DOUT" - Flash size: "4M (2M SPIFFS)" - CPU Frequency: "80 MHz" - Debug port: "Disabled" - Debug Level: "None" - IwIP Variant: "v2 Lower Memory" - VTables: "Flash" - Reset Method: "nodemcu" | "none" - CPU Frequency: "80 MHz" - Buildin Led: "1" - Upload Speed: "115200" - Erase Flash: "Only Sketch" */ #include <IRremoteESP8266.h> // https://github.com/markszabo/IRremoteESP8266 [v2.6.2 (20190616)] #include <IRrecv.h> #include <IRsend.h> #include <IRutils.h> // ==================== start of TUNEABLE PARAMETERS ==================== // An IR detector/demodulator is connected to GPIO12 const uint16_t kRecvPin = 12; // The Serial connection baud rate. const uint32_t kBaudRate = 115200; // As this program is a special purpose capture/decoder, let us use a larger // than normal buffer so we can handle Air Conditioner remote codes. const uint16_t kCaptureBufferSize = 1024; // kTimeout is the Nr. of milli-Seconds of no-more-data before we consider a // message ended. // NOTE: Don't exceed kMaxTimeoutMs. Typically 130ms. #if DECODE_AC // Some A/C units have gaps in their protocols of ~40ms. e.g. Kelvinator // A value this large may swallow repeats of some protocols const uint8_t kTimeout = 50; #else // DECODE_AC // Suits most messages, while not swallowing many repeats. const uint8_t kTimeout = 15; #endif // DECODE_AC // NOTE: Set this value very high to effectively turn off UNKNOWN detection. const uint16_t kMinUnknownSize = 12; // ==================== end of TUNEABLE PARAMETERS ==================== #include <OneWire.h> #include <DallasTemperature.h> #include <TimeLib.h> // https://github.com/PaulStoffregen/Time #include "Debug.h" #define _HOSTNAME "IRremote" #include "networkStuff.h" #define ONE_WIRE_PIN 13 // GPIO02 - GPIO pin waar DS18B20 op aangesloten is #define IR_LEDPIN 4 #define RED_LEDPIN 5 //#define kRecvPin 12 #define GRN_LEDPIN 14 #define _SETTINGS_FILE "/settings.ini" #define _MAX_BUTTONS 20 IRsend irsend(IR_LEDPIN); // Set the GPIO to be used to sending the message. // Use turn on the save buffer feature for more complete capture coverage. IRrecv irrecv(kRecvPin, kCaptureBufferSize, kTimeout, true); decode_results results; // Somewhere to store the results typedef struct { uint8_t Sequence; char buttonLabel[30]; char pulseFile[32]; } dataStruct; dataStruct Buttons[_MAX_BUTTONS + 1]; uint16_t maxButtons = 0; static char *flashMode[] { "QIO", "QOUT", "DIO", "DOUT", "UnKnown" }; enum { TAB_CONTROL, TAB_LEARN, TAB_EDIT, TAB_UNKNOWN }; float tn0, inTemp0 = 0.0, lastTemp, DS18B20Temp; bool hasDS18B20sensor; uint32_t nextSecond, nextStateSend, nextDS18B20PollTime, waitForPulse; uint64_t upTimeSeconds; String hostnameMAC, jsonString, lastResetReason; char inChar; // Console input char cMsg[100]; uint16_t rawData[500]; // placeholder for read data uint16_t noPulses; char wsSend[100]; // String to send via WebSocket bool newTab = true; int8_t clientActiveTab; float clientInTemp0; const int timeZone = 1; // Central European (Winter) Time unsigned int localPort = 8888; // local port to listen for UDP packets time_t prevDisplay = 0; // when the digital clock was displayed // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_PIN); // Pass our oneWire reference to Dallas Temperature. DallasTemperature DS18B20(&oneWire); // arrays to hold device address DeviceAddress DS18B20_0; DeviceAddress DS18B20addr[8]; /***************************************************************************/ //===============START OF PROTOTYPES========================================= //======= The Arduino IDE creates prototypes of all ========================= //======= functions so this realy is not necessary ========================= //float getInsideTemp(uint8_t); //time_t getNtpTime(); //void splitString(String, char, String*, uint8_t ); //void writeSettings(); //===============END OF PROTOTYPES=========================================== //======================================================================= // Display the human readable state of an A/C message if we can. void dumpACInfo(decode_results *results) { String description = ""; // If we got a human-readable description of the message, display it. if (description != "") Serial.println("Mesg Desc.: " + description); } // dumpACInfo() //======================================================================= bool startLearning() { waitForPulse = millis() + 30000; digitalWrite(GRN_LEDPIN, HIGH); _dThis = true; Debug("Start learning .."); #if DECODE_HASH // Ignore messages with less than minimum on or off pulses. irrecv.setUnknownThreshold(kMinUnknownSize); #endif // DECODE_HASH irrecv.enableIRIn(); // Start the receiver while(millis() < waitForPulse) { yield(); // Check if the IR code has been received. if (irrecv.decode(&results)) { // Display a crude timestamp. uint32_t now = millis(); Debugf("\nTimestamp : %06u.%03u\n", now / 1000, now % 1000); if (results.overflow) Debugf("WARNING: IR code is too big for buffer (>= %d). " "This result shouldn't be trusted until this is resolved. " "Edit & increase kCaptureBufferSize.\n", kCaptureBufferSize); // Display the basic output of what we found. Debug(resultToHumanReadableBasic(&results)); dumpACInfo(&results); // Display any extra A/C info if we have it. yield(); // Feed the WDT as the text output can take a while to print. // Display the library version the message was captured with. Debug("Library : v"); Debugln(_IRREMOTEESP8266_VERSION_); Debugln(); // Output RAW timing info of the result. Debugln(resultToTimingInfo(&results)); yield(); // Feed the WDT (again) // Output the results as source code Debugln(resultToSourceCode(&results)); Debugln(""); // Blank line between entries yield(); // Feed the WDT (again) irrecv.disableIRIn(); // End the receiver digitalWrite(GRN_LEDPIN, LOW); return true; } HttpServer.handleClient(); webSocket.loop(); } // while waitForPulse irrecv.disableIRIn(); // End the receiver digitalWrite(GRN_LEDPIN, LOW); Debugln(" .. time out!"); return false; } // startLearning() //======================================================================= void setup() { Serial.begin ( 115200 ); lastResetReason = ESP.getResetReason(); pinMode(IR_LEDPIN, OUTPUT); pinMode(RED_LEDPIN, OUTPUT); pinMode(GRN_LEDPIN, OUTPUT); setTime(dateTime2Epoch(__DATE__, __TIME__)); startWiFi(); _dThis = true; Debugf("last Reset Reason [%s]\n", lastResetReason.c_str()); _dThis = true; Debugf("Compile time [%04d-%02d-%02d @ %02d:%02d:%02d]\n", year(), month(), day(), hour(), minute(), second()); startTelnet(); for (int f=0; f<10; f++) { delay(200); digitalWrite(GRN_LEDPIN, digitalRead(RED_LEDPIN)); digitalWrite(RED_LEDPIN, !digitalRead(RED_LEDPIN)); } digitalWrite(RED_LEDPIN, LOW); digitalWrite(GRN_LEDPIN, LOW); /* * list all services with the cammand: * dns-sd -B _arduino . * dns-sd -B _http . */ startMDNS(_HOSTNAME); _dThis = true; Debugln("addService('http', 'tcp' 80)"); MDNS.addService("http", "tcp", 80); MDNS.port(80); // webserver Debugln("addService('arduino', 'tcp' 81)"); MDNS.addService("arduino", "tcp", 81); MDNS.port(81); // webSockets webSocket.begin(); webSocket.onEvent(webSocketEvent); _dThis = true; if (!startNTP()) { _dThis = true; Debugln("ERROR!!! No NTP server reached!\n"); } _dThis = true; if (!SPIFFS.begin()) { Debugln("SPIFFS Mount failed\n"); // Serious problem with SPIFFS } else { Debugln("SPIFFS Mount succesfull"); } HttpServer.on("/ReBoot", HTTP_POST, handleReBoot); HttpServer.on("/restAPI", HTTP_GET, handleRestAPI); HttpServer.on("/restapi", HTTP_GET, handleRestAPI); HttpServer.serveStatic("/", SPIFFS, "/IR_IoT_Remote.html"); HttpServer.serveStatic("/IR_IoT_Remote.js", SPIFFS, "/IR_IoT_Remote.js"); HttpServer.serveStatic("/IR_IoT_Remote.css", SPIFFS, "/IR_IoT_Remote.css"); HttpServer.serveStatic("/FSexplorer.png", SPIFFS, "/FSexplorer.png"); HttpServer.on("/FSexplorer", HTTP_POST, handleFileDelete); HttpServer.on("/FSexplorer", handleRoot); HttpServer.on("/FSexplorer/upload", HTTP_POST, []() { HttpServer.send(200, "text/plain", ""); }, handleFileUpload); //HttpServer.onNotFound([]() { // if (!handleFileRead(HttpServer.uri())) // HttpServer.send(404, "text/plain", "FileNotFound"); //}); HttpServer.onNotFound([]() { if (HttpServer.uri() == "/update") { HttpServer.send(200, "text/html", "/update" ); } else { _dThis = true; Debugf("onNotFound(%s)\n", HttpServer.uri().c_str()); if (HttpServer.uri() == "/") { reloadPage("/"); } } if (!handleFileRead(HttpServer.uri())) { HttpServer.send(404, "text/plain", "FileNotFound"); } }); HttpUpdater.setup(&HttpServer); HttpServer.begin(); _dThis = true; Debugln( "HTTP server started\n" ); _dThis = true; Debug("setup(): Start Time: "); Debugf("%02d:%02d:%02d\n", hour(), minute(), second()); DS18B20.begin(); // locate devices on the bus _dThis = true; Debugf("Locating DS18B20 sensors... Found [%d] devices\n", DS18B20.getDeviceCount()); // search() looks for the next device. Returns 1 if a new address has been // returned. A zero might mean that the bus is shorted, there are no devices, // or you have already retrieved all of them. It might be a good idea to // check the CRC to make sure you didn't get garbage. The order is // deterministic. You will always get the same devices in the same order // // Must be called before search() //DS18B20_0 = null; oneWire.reset_search(); _dThis = true; if (DS18B20.getDeviceCount() == 0) Debugln("Unable to find address for DS18B20's"); inTemp0 = getInsideTemp(0); _dThis = true; if (!hasDS18B20sensor) { inTemp0 = 0; tn0 = 0; Debugln("setup(): no inside temperature sensors found!"); } else { Debugln("setup(): has inside temperature sensor(s)"); //inTemp0 = getInsideTemp(0); tn0 = inTemp0; } for (int f=0; f<6; f++) { delay(500); digitalWrite(RED_LEDPIN, !digitalRead(RED_LEDPIN)); } digitalWrite(RED_LEDPIN, LOW); _dThis = true; Debugf("last Reset Reason [%s]\n", lastResetReason.c_str()); // --- initialize ----- readSettings(); clientActiveTab = TAB_UNKNOWN; upTimeSeconds = millis() / 1000; nextSecond = millis() + 1000; nextStateSend = millis() + 2000; nextDS18B20PollTime = millis() + 10000; _dThis = true; Debugln("================ done with setup() =====================\n"); } // setup() //======================================================================= void loop() { HttpServer.handleClient(); MDNS.update(); webSocket.loop(); if (millis() > nextDS18B20PollTime) { nextDS18B20PollTime = millis() + 30000; handleSensor(); digitalWrite(GRN_LEDPIN, HIGH); delay(100); digitalWrite(GRN_LEDPIN, LOW); } handleKeyInput(); // menu if (millis() > nextSecond) { nextSecond += 1000; upTimeSeconds++; } if (millis() > nextStateSend) { nextStateSend += 2000; } } // loop() /*************************************************************************** * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ***************************************************************************/
[ "Willem@Aandewiel.nl" ]
Willem@Aandewiel.nl
03f4384ddd3971617a37269b2225115a0c104003
f5f053975aadd70cadbf3831cb27d2873e51c808
/ceGame/SoundAPI.cpp
352fe3debfdceb9ca8e182cc163366cbc8cd3c40
[]
no_license
YoelShoshan/Dooake
fd5ded20b21075276c27899215392f6078d8713e
254b74bc8fa30d38511d5bda992a59253cc8c37d
refs/heads/master
2021-01-20T11:11:23.048481
2016-09-15T20:03:32
2016-09-15T20:03:32
68,323,638
1
0
null
null
null
null
UTF-8
C++
false
false
6,680
cpp
#include "stdafx.h" #include "SoundAPI.h" #include <iostream> #include <string.h> //#include "NeHeGL.h" //extern GL_Window* g_pWindow; // Main Window #include "fmod_errors.h" #include "fmod.h" #include "LogFile_I.h" extern ILogFile* g_pLogFile; #include "Camera.h" //extern CCamera g_Camera1; // FSOUND_3D_SetAttributes(int channel, const float *pos, const float *vel); // FSOUND_3D_SetMinMaxDistance(int channel, float min, float max); //DLL_API void F_API FSOUND_3D_Listener_SetAttributes(const float *pos, const float *vel, float fx, float fy, float fz, float tx, float ty, float tz); CSoundAPI::CSoundAPI() { /*for (int i=0;i<SM_MAX_CHANNELS;i++) { m_ppChannels[i] = new int; (*m_ppChannels[i]) = i ; }*/ //m_pBackgroundMusic = NULL; m_bInitedCorrectly=false; } CSoundAPI::~CSoundAPI() { } // init fmod a bool CSoundAPI::Init(void) { // debug debug //return false; char strMessage[255] = {0}; float f = FSOUND_GetVersion(); if (FSOUND_GetVersion() < FMOD_VERSION) // we need same dll version { sprintf(strMessage, "Wrong FMOD dll version! You should be using FMOD %f", FMOD_VERSION); MessageBox(HWND_DESKTOP, strMessage, "Error", MB_OK); return false; } FSOUND_SetOutput(FSOUND_OUTPUT_DSOUND); FSOUND_SetMixer(FSOUND_MIXER_AUTODETECT); // Initialize the FMod Sound System with good quality sound and a global focus if (!FSOUND_Init(44100, 32, 0)) { sprintf(strMessage, "%s", FMOD_ErrorString(FSOUND_GetError())); MessageBox(HWND_DESKTOP, strMessage, "Error", MB_OK); return false; } //FSOUND_3D_SetDistanceFactor(3.28f*8.f); //FSOUND_3D_SetDistanceFactor(3.28f*8.f*105.f); //FSOUND_3D_SetDistanceFactor(3.28f*8.f*200.f); //previous FSOUND_3D_SetDistanceFactor(3.28f*5.f*200.f); m_bInitedCorrectly=true; return true; } bool CSoundAPI::LoadSample(const char* pcFileName,FSOUND_SAMPLE*& pSound) { if (!m_bInitedCorrectly) return false; if(pSound!=NULL) { FSOUND_Sample_Free(pSound); pSound = NULL; } //pSound = FSOUND_Sample_Load(FSOUND_FREE, pcFileName, 0, 0, 0); pSound = FSOUND_Sample_Load(FSOUND_FREE, pcFileName, FSOUND_HW3D | FSOUND_FORCEMONO, 0, 0); if (!pSound) { char temp[200]; sprintf_s(temp,200,"Error trying to load [%s]",pcFileName); g_pLogFile->OutPutPlainText(temp,"3","000099",true,LOG_MESSAGE_WARNING_LVL_0); return false; } FSOUND_Sample_SetMinMaxDistance(pSound, 4.0f, 10000.0f); return true; } bool CSoundAPI::PlaySample(FSOUND_SAMPLE*& pSound) { if (!m_bInitedCorrectly) return false; int channel = FSOUND_PlaySound(FSOUND_FREE, pSound); FSOUND_SetVolume(channel, 255); // FixMe //FSOUND_SetVolume(channel, 150); // FixMe return true; } bool CSoundAPI::PlaySample(FSOUND_SAMPLE*& pSound,int iVolume) { if (!m_bInitedCorrectly) return false; int channel = FSOUND_PlaySound(FSOUND_FREE, pSound); FSOUND_SetVolume(channel, iVolume); return true; } bool CSoundAPI::PlaySample3D(FSOUND_SAMPLE*& pSound,const CVec3f& vPos,int iVolume) { if (!m_bInitedCorrectly) return false; //FSOUND_Sample_SetMinMaxDistance(pSound, 4.0f, 10000.0f); //FSOUND_Sample_SetMinMaxDistance(pSound, 20.0f, 100000.0f); //FSOUND_Sample_SetMinMaxDistance(pSound, 10.0f, 10000.0f); FSOUND_Sample_SetMinMaxDistance(pSound, 200.0f, 100000.0f); int channel = FSOUND_PlaySound(FSOUND_FREE, pSound); FSOUND_SetVolume(channel, iVolume); float Pos[3]; Pos[0] = vPos.v[0]; Pos[1] = vPos.v[1]; Pos[2] = vPos.v[2]; /*Pos[0] = 0; Pos[1] = 0; Pos[2] = 40;*/ float vel[3] = { 0,0,0 }; FSOUND_3D_SetAttributes(channel,&Pos[0],&vel[0]); return true; } bool CSoundAPI::FreeSound(FSOUND_SAMPLE*& pSound) { if (!m_bInitedCorrectly) return false; if(pSound!=NULL) { FSOUND_Sample_Free(pSound); pSound = NULL; } return true; } // load and play a sound sample bool CSoundAPI::LoadPlaySound(char* pcFileName, FSOUND_SAMPLE*& pSound) { if (!m_bInitedCorrectly) return false; if(pSound!=NULL) { FSOUND_Sample_Free(pSound); pSound = NULL; } // todo: i might need to fill the length parameter with actuall value... //(int index, const char *name_or_data, unsigned int mode, int offset, int length); pSound = FSOUND_Sample_Load(FSOUND_FREE, pcFileName, 0, 0, 0); int channel = FSOUND_PlaySound(FSOUND_FREE, pSound); FSOUND_SetVolume(channel, 255); // FixMe return true; } // play looped music bool CSoundAPI::LoadStream(char* pcFileName, FSOUND_STREAM*& pStream) { if (!m_bInitedCorrectly) return false; if(pStream) { FSOUND_Stream_Close(pStream); pStream = NULL; } pStream = FSOUND_Stream_Open(pcFileName, FSOUND_LOOP_NORMAL, 0,0); if (!pStream) return false; return true; } bool CSoundAPI::FreeStream(FSOUND_STREAM*& pStream) { if (!m_bInitedCorrectly) return false; if(pStream) { FSOUND_Stream_Close(pStream); pStream = NULL; } return true; } bool CSoundAPI::StopStream(FSOUND_STREAM*& pStream) { if (!m_bInitedCorrectly) return false; if (pStream) FSOUND_Stream_Stop(pStream); return true; } bool CSoundAPI::PlayStream(FSOUND_STREAM*& pStream) { if (!m_bInitedCorrectly) return false; int channel = FSOUND_Stream_Play(FSOUND_FREE, pStream); FSOUND_SetVolume(channel, 255); // FixMe return true; } bool CSoundAPI::PlayStream(FSOUND_STREAM*& pStream,int iVolume) { if (!m_bInitedCorrectly) return false; int channel = FSOUND_Stream_Play(FSOUND_FREE, pStream); FSOUND_SetVolume(channel, iVolume); // FixMe return true; } bool CSoundAPI::PlayLoopedMusic(char* pcFileName, FSOUND_STREAM*& pStream, int* channel) { if (!m_bInitedCorrectly) return false; if( (*channel) <0) { return false; } if(pStream!=NULL) { FSOUND_Stream_Close(pStream); pStream = NULL; } pStream = FSOUND_Stream_Open(pcFileName, 0, 0,0); *channel = FSOUND_Stream_Play(FSOUND_FREE, pStream); return true; } void CSoundAPI::Update(void) { if (!m_bInitedCorrectly) return; FSOUND_Update(); } void CSoundAPI::UpdateListenerPosition(const CVec3f& vPos,const CVec3f& vLookDir) { if (!m_bInitedCorrectly) return; // Here i'm supposed to update the listener position! /*g_Camera1.m_PosZNegated.v[0] = g_Camera1.m_Pos.v[0]; g_Camera1.m_PosZNegated.v[1] = g_Camera1.m_Pos.v[1]; g_Camera1.m_PosZNegated.v[2] = -g_Camera1.m_Pos.v[2]; g_Camera1.ReturnLookDirectionNormalized(); g_Camera1.m_LookDirectionZNegated.v[0] = g_Camera1.m_LookDirection.v[0]; g_Camera1.m_LookDirectionZNegated.v[1] = g_Camera1.m_LookDirection.v[1]; g_Camera1.m_LookDirectionZNegated.v[2] = -g_Camera1.m_LookDirection.v[2];*/ FSOUND_3D_Listener_SetAttributes(&vPos.v[0],NULL, vLookDir.x,vLookDir.y,vLookDir.z, 0.f,1.f,0.f); }
[ "yoelshoshan@gmail.com" ]
yoelshoshan@gmail.com
781be445c33968f2bb2c717b96c26657e44504b5
d3e72cb3fcd23a63dbc309a8b734197236881334
/AI5Runtime/NameReferenceVariant.h
1ac91faddf3a78920f72c3c17e00638f9b77a618
[]
no_license
andreasjhkarlsson/ai5
ce69b3d33ce9e96830518ebc7f5da577c9a84cf8
2c7819d6ef9d75760e45a20f47c5e645c79e37df
refs/heads/master
2021-05-28T23:14:39.955421
2015-03-05T13:59:26
2015-03-05T13:59:26
31,716,003
1
0
null
null
null
null
UTF-8
C++
false
false
511
h
#pragma once #include "namevariant.h" #include "PooledObject.h" class NameReferenceVariant : public NameVariant { public: friend class GC; static const VARIANT_TYPE TYPE = NAME_REFERENCE; static NameReferenceVariant* Create(const VariantReference<>&); ~NameReferenceVariant(void); virtual void setValue(const VariantReference<>& var); virtual const VariantReference<>& getValue(); static const int POOL_SIZE = 1024; private: NameReferenceVariant(const VariantReference<>& value); };
[ "andreas.karlsson3@gmail.com" ]
andreas.karlsson3@gmail.com
53af4b870bd20d9f5f7e2cc3e79c9e8063000924
7e8b4a9afe31d64c19fcaed2a03c7f541f32df24
/src/AEE++/dui/dui_waitcursor.h
13d5e6d8015f68433983869506e4ea0bd2c95e21
[]
no_license
huangjingpei/clearid
4e5c3756fee739ff6576e15b511562e6c9e097e8
6048b4567c10a6836ec2572410d1d44318f0f5ec
refs/heads/master
2022-11-04T11:07:58.370829
2020-06-08T14:00:03
2020-06-08T14:00:03
270,690,015
0
0
null
null
null
null
UTF-8
C++
false
false
601
h
#ifndef _DUI_WAIT_CURSOR_H_ #define _DUI_WAIT_CURSOR_H_ #include "dui_control.h" class DUIWaitCursor : public DUIControl { public: DUIWaitCursor(bool isAA = true); virtual ~DUIWaitCursor(); virtual void SetAttribute(const AEEStringRef& szName, const AEEStringRef& szValue); protected: virtual void OnPaintContent(DUIDC* pDC, int nParentX, int nParentY); static void _OnTimerPaint(int nTimerId, void* pUser); void OnTimerPaint(); void ReleaseBmp(); private: DUIBmpHandle mBmpHandle; int mInterval; int mCurDegree; int mTimerId; bool mIsAA; }; #endif//_DUI_WAIT_CURSOR_H_
[ "huangjingpei@gmail.com" ]
huangjingpei@gmail.com
8eeab504a4a764cf30890e0d72f5970c8da61bb5
75a6ca082761b718468072ec64fb97b074a71b2f
/DirectX/ShootingGame/CCamera.cpp
7e8ac190838b8c0abaaef863aa9d20f5881d041b
[]
no_license
dadm8473/Study
14cb9f50f5ae2534db5e07397475acd542703eb5
4c0c8fb97283b725dae459cf8d9d91a03b84d2bd
refs/heads/master
2020-09-05T22:25:08.104637
2020-01-02T03:41:37
2020-01-02T03:41:37
220,226,011
0
0
null
null
null
null
UTF-8
C++
false
false
604
cpp
#include "DXUT.h" #include "Header.h" CCamera::CCamera() : position(0, 0), center(384, 700), limitPos_Min(-50, 0), limitPos_Max(50, 0), target(NULL), speed(1) { } CCamera::~CCamera() { } void CCamera::Update(float deltatime) { if (target) D3DXVec2Lerp(&position, &position, &(target->position - center), speed); else return; if (position.x <= limitPos_Min.x) position.x = limitPos_Min.x; if (position.x >= limitPos_Max.x) position.x = limitPos_Max.x; if (position.y <= limitPos_Min.y) position.y = limitPos_Min.y; if (position.y >= limitPos_Max.y) position.y = limitPos_Max.y; }
[ "dadm8473@gmail.com" ]
dadm8473@gmail.com
317dcc29eaa2ab15c901ce0adff6a6dbd4cf1476
bece32885c5582a348f886cb39ebc4bfeeaf3885
/insidecpp/ch5/initialization.cpp
9cee2f7b663c6f0e058eb8fe64f8e069beafa18c
[]
no_license
shamaoxiaogui/mycode
1dfd8ef6d69225c7a55d0abe9a150599ee7b7c19
b1d34eab35654137a2ba7ff48ecf51e15582b53e
refs/heads/master
2020-12-25T15:28:38.885362
2016-08-03T04:20:00
2016-08-03T04:20:00
63,694,566
0
0
null
null
null
null
UTF-8
C++
false
false
942
cpp
#include <iostream> using namespace std; class POD{ public: int _val; char _ch; }; class nonPOD{ public: nonPOD(int n=0,char ch='c'):_nval(n),_nch(ch){} private: int _nval; char _nch; }; struct Someclass{ Someclass(){cout<<"Someclass ctor"<<endl;} int x=0; }; struct Someclass2{ Someclass2(int i=0):x(i){cout<<"ctor"<<endl;} Someclass2(const Someclass2&){cout<<"copy ctor"<<endl;} int x=2; }; static int sti=0; static int sti1=1; static int sti2; POD pod; POD pod1={2,'h'}; nonPOD npod; nonPOD npod1(3,'g'); int x; // int x; // int x; int main(){ Someclass sc1; Someclass2 sc2={3}; Someclass *scp=new Someclass; POD pod3; pod1=pod3; cout<<"pod1 val ch: "<<pod1._val<<" "<<pod1._ch<<endl; cout<<sti<<endl; cout<<sti1<<endl; cout<<sti2<<endl; cout<<&pod<<endl; cout<<&pod1<<endl; cout<<&npod<<endl; cout<<&npod1<<endl; delete scp; return 0; }
[ "shamaoxiaogui@gmail.com" ]
shamaoxiaogui@gmail.com
5401fab89e4b75d0343847b5a876ddfbdbed4941
e272d18a042e6b6808bc615917b1783d53607870
/done/1149.cpp
952076d0ba64cfd60b2fb29018ff72df893cb6ca
[]
no_license
chessdroid/morbidel-timus
58656c7a62132aaae71289a20ee77baeca4ba554
b079bf3ae716d4eeb54722037ac55066f9e9da7c
refs/heads/master
2020-07-10T02:20:08.032088
2013-04-11T20:48:39
2013-04-11T20:48:39
null
0
0
null
null
null
null
MacCentralEurope
C++
false
false
703
cpp
// ACM Online // Sinus Dances - Problem 1149 // An=sin(1-sin(2+sin(3-sin(4+...sin(n))...) // Sn=(...(A1+n)A2+n-1)A3+...+2)An+1 // Print Sn for N <= 200 // asta-i problemÜ? zi mÜ? ce rÉzi asa? #include <stdio.h> int n; void print_ax(int x) { int i; char sgn; for (i = 1; i < x; i++) { sgn = (i % 2) ? '-' : '+'; printf("sin(%d%c", i, sgn); } printf("sin(%d)", x); for (i = 1; i < x; i++, printf(")")); } void print_sx(int x) { int i; for (i = 1; i < x; i++, printf("(")); for (i = 1; i < x; i++) { print_ax(i); printf("+%d)", x - i + 1); } print_ax(x); printf("+1"); } int main() { scanf("%d", &n); print_sx(n); return 0; }
[ "stefangh@gmail.com" ]
stefangh@gmail.com
4f35a89507624f308668c0c2e10d10f8f0090dbc
8107db46603a10a51db9842fe22d43ee7736c94a
/src/qt/optionsdialog.cpp
d8cac5a7fbc910c6b7609067f9d323348c95aa14
[ "MIT" ]
permissive
cryptolog/eBoost
2495e4dcf125002fc97631eb00030d31c761f823
154aa55c2d74eb60dfe6bcf1a650d943ca86ee16
refs/heads/master
2020-06-03T17:27:24.561026
2019-06-15T13:49:25
2019-06-15T13:49:25
191,667,179
0
0
MIT
2019-06-13T01:15:41
2019-06-13T01:15:41
null
UTF-8
C++
false
false
7,664
cpp
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinamountfield.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include "qvalidatedlineedit.h" #include "qvaluecombobox.h" #include <QCheckBox> #include <QDir> #include <QIntValidator> #include <QLabel> #include <QLineEdit> #include <QLocale> #include <QMessageBox> #include <QPushButton> #include <QRegExp> #include <QRegExpValidator> #include <QTabWidget> #include <QWidget> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(0, 65535, this)); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_WS_MAC ui->tabWindow->setVisible(false); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); connect(ui->lang, SIGNAL(activated(int)), this, SLOT(showRestartWarning_Lang())); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable save buttons when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableSaveButtons())); /* disable save buttons when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableSaveButtons())); /* disable/enable save buttons when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(bool)), this, SLOT(setSaveButtonState(bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); /* Window */ #ifndef Q_WS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); } void OptionsDialog::enableSaveButtons() { // prevent enabling of the save buttons when data modified, if there is an invalid proxy address present if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); ui->applyButton->setEnabled(false); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting eBoost."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting eBoost."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { // Update transactionFee with the current unit ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(object == ui->proxyIp && event->type() == QEvent::FocusOut) { // Check proxyIP for a valid IPv4/IPv6 address CService addr; if(!LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)) { ui->proxyIp->setValid(false); fProxyIpValid = false; ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); emit proxyIpValid(false); } else { fProxyIpValid = true; ui->statusLabel->clear(); emit proxyIpValid(true); } } return QDialog::eventFilter(object, event); }
[ "eboostcrypto@gmail.com" ]
eboostcrypto@gmail.com
74daf2857546b6f43ccb9bbef3669e225309ff58
47b755444e700332877d8bb432e5739045ba2c8b
/wxWidgets/include/wx/gdicmn.h
bef06b11ffb0bd9e9f97cf40dc470884ccfc3ab3
[ "MIT" ]
permissive
andr3wmac/Torque6Editor
5b30e103f0b3a81ae7a189725e25d807093bf131
0f8536ce90064adb9918f004a45aaf8165b2a343
refs/heads/master
2021-01-15T15:32:54.537291
2016-06-09T20:45:49
2016-06-09T20:45:49
39,276,153
25
14
null
null
null
null
UTF-8
C++
false
false
33,331
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/gdicmn.h // Purpose: Common GDI classes, types and declarations // Author: Julian Smart // Modified by: // Created: 01/02/97 // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_GDICMNH__ #define _WX_GDICMNH__ // --------------------------------------------------------------------------- // headers // --------------------------------------------------------------------------- #include "wx/defs.h" #include "wx/list.h" #include "wx/string.h" #include "wx/fontenc.h" #include "wx/hashmap.h" #include "wx/math.h" // --------------------------------------------------------------------------- // forward declarations // --------------------------------------------------------------------------- class WXDLLIMPEXP_FWD_CORE wxBitmap; class WXDLLIMPEXP_FWD_CORE wxBrush; class WXDLLIMPEXP_FWD_CORE wxColour; class WXDLLIMPEXP_FWD_CORE wxCursor; class WXDLLIMPEXP_FWD_CORE wxFont; class WXDLLIMPEXP_FWD_CORE wxIcon; class WXDLLIMPEXP_FWD_CORE wxPalette; class WXDLLIMPEXP_FWD_CORE wxPen; class WXDLLIMPEXP_FWD_CORE wxRegion; class WXDLLIMPEXP_FWD_BASE wxString; class WXDLLIMPEXP_FWD_CORE wxIconBundle; class WXDLLIMPEXP_FWD_CORE wxPoint; // --------------------------------------------------------------------------- // constants // --------------------------------------------------------------------------- // Bitmap flags enum wxBitmapType { wxBITMAP_TYPE_INVALID, // should be == 0 for compatibility! wxBITMAP_TYPE_BMP, wxBITMAP_TYPE_BMP_RESOURCE, wxBITMAP_TYPE_RESOURCE = wxBITMAP_TYPE_BMP_RESOURCE, wxBITMAP_TYPE_ICO, wxBITMAP_TYPE_ICO_RESOURCE, wxBITMAP_TYPE_CUR, wxBITMAP_TYPE_CUR_RESOURCE, wxBITMAP_TYPE_XBM, wxBITMAP_TYPE_XBM_DATA, wxBITMAP_TYPE_XPM, wxBITMAP_TYPE_XPM_DATA, wxBITMAP_TYPE_TIFF, wxBITMAP_TYPE_TIF = wxBITMAP_TYPE_TIFF, wxBITMAP_TYPE_TIFF_RESOURCE, wxBITMAP_TYPE_TIF_RESOURCE = wxBITMAP_TYPE_TIFF_RESOURCE, wxBITMAP_TYPE_GIF, wxBITMAP_TYPE_GIF_RESOURCE, wxBITMAP_TYPE_PNG, wxBITMAP_TYPE_PNG_RESOURCE, wxBITMAP_TYPE_JPEG, wxBITMAP_TYPE_JPEG_RESOURCE, wxBITMAP_TYPE_PNM, wxBITMAP_TYPE_PNM_RESOURCE, wxBITMAP_TYPE_PCX, wxBITMAP_TYPE_PCX_RESOURCE, wxBITMAP_TYPE_PICT, wxBITMAP_TYPE_PICT_RESOURCE, wxBITMAP_TYPE_ICON, wxBITMAP_TYPE_ICON_RESOURCE, wxBITMAP_TYPE_ANI, wxBITMAP_TYPE_IFF, wxBITMAP_TYPE_TGA, wxBITMAP_TYPE_MACCURSOR, wxBITMAP_TYPE_MACCURSOR_RESOURCE, wxBITMAP_TYPE_MAX, wxBITMAP_TYPE_ANY = 50 }; // Polygon filling mode enum wxPolygonFillMode { wxODDEVEN_RULE = 1, wxWINDING_RULE }; // Standard cursors enum wxStockCursor { wxCURSOR_NONE, // should be 0 wxCURSOR_ARROW, wxCURSOR_RIGHT_ARROW, wxCURSOR_BULLSEYE, wxCURSOR_CHAR, wxCURSOR_CROSS, wxCURSOR_HAND, wxCURSOR_IBEAM, wxCURSOR_LEFT_BUTTON, wxCURSOR_MAGNIFIER, wxCURSOR_MIDDLE_BUTTON, wxCURSOR_NO_ENTRY, wxCURSOR_PAINT_BRUSH, wxCURSOR_PENCIL, wxCURSOR_POINT_LEFT, wxCURSOR_POINT_RIGHT, wxCURSOR_QUESTION_ARROW, wxCURSOR_RIGHT_BUTTON, wxCURSOR_SIZENESW, wxCURSOR_SIZENS, wxCURSOR_SIZENWSE, wxCURSOR_SIZEWE, wxCURSOR_SIZING, wxCURSOR_SPRAYCAN, wxCURSOR_WAIT, wxCURSOR_WATCH, wxCURSOR_BLANK, #ifdef __WXGTK__ wxCURSOR_DEFAULT, // standard X11 cursor #endif #ifdef __WXMAC__ wxCURSOR_COPY_ARROW , // MacOS Theme Plus arrow #endif #ifdef __X__ // Not yet implemented for Windows wxCURSOR_CROSS_REVERSE, wxCURSOR_DOUBLE_ARROW, wxCURSOR_BASED_ARROW_UP, wxCURSOR_BASED_ARROW_DOWN, #endif // X11 wxCURSOR_ARROWWAIT, #ifdef __WXMAC__ wxCURSOR_OPEN_HAND, wxCURSOR_CLOSED_HAND, #endif wxCURSOR_MAX }; #ifndef __WXGTK__ #define wxCURSOR_DEFAULT wxCURSOR_ARROW #endif #ifndef __WXMAC__ // TODO CS supply openhand and closedhand cursors #define wxCURSOR_OPEN_HAND wxCURSOR_HAND #define wxCURSOR_CLOSED_HAND wxCURSOR_HAND #endif // ---------------------------------------------------------------------------- // Ellipsize() constants // ---------------------------------------------------------------------------- enum wxEllipsizeFlags { wxELLIPSIZE_FLAGS_NONE = 0, wxELLIPSIZE_FLAGS_PROCESS_MNEMONICS = 1, wxELLIPSIZE_FLAGS_EXPAND_TABS = 2, wxELLIPSIZE_FLAGS_DEFAULT = wxELLIPSIZE_FLAGS_PROCESS_MNEMONICS | wxELLIPSIZE_FLAGS_EXPAND_TABS }; // NB: Don't change the order of these values, they're the same as in // PangoEllipsizeMode enum. enum wxEllipsizeMode { wxELLIPSIZE_NONE, wxELLIPSIZE_START, wxELLIPSIZE_MIDDLE, wxELLIPSIZE_END }; // --------------------------------------------------------------------------- // macros // --------------------------------------------------------------------------- #if defined(__WINDOWS__) #define wxHAS_IMAGES_IN_RESOURCES #endif /* Useful macro for creating icons portably, for example: wxIcon *icon = new wxICON(sample); expands into: wxIcon *icon = new wxIcon("sample"); // On Windows wxIcon *icon = new wxIcon(sample_xpm); // On wxGTK/Linux */ #ifdef __WINDOWS__ // Load from a resource #define wxICON(X) wxIcon(wxT(#X)) #elif defined(__WXDFB__) // Initialize from an included XPM #define wxICON(X) wxIcon( X##_xpm ) #elif defined(__WXGTK__) // Initialize from an included XPM #define wxICON(X) wxIcon( X##_xpm ) #elif defined(__WXMAC__) // Initialize from an included XPM #define wxICON(X) wxIcon( X##_xpm ) #elif defined(__WXMOTIF__) // Initialize from an included XPM #define wxICON(X) wxIcon( X##_xpm ) #elif defined(__WXX11__) // Initialize from an included XPM #define wxICON(X) wxIcon( X##_xpm ) #elif defined(__WXQT__) // Initialize from an included XPM #define wxICON(X) wxIcon( X##_xpm ) #else // This will usually mean something on any platform #define wxICON(X) wxIcon(wxT(#X)) #endif // platform /* Another macro: this one is for portable creation of bitmaps. We assume that under Unix bitmaps live in XPMs and under Windows they're in ressources. */ #if defined(__WINDOWS__) #define wxBITMAP(name) wxBitmap(wxT(#name), wxBITMAP_TYPE_BMP_RESOURCE) #elif defined(__WXGTK__) || \ defined(__WXMOTIF__) || \ defined(__WXX11__) || \ defined(__WXMAC__) || \ defined(__WXDFB__) // Initialize from an included XPM #define wxBITMAP(name) wxBitmap(name##_xpm) #else // other platforms #define wxBITMAP(name) wxBitmap(name##_xpm, wxBITMAP_TYPE_XPM) #endif // platform // Macro for creating wxBitmap from in-memory PNG data. // // It reads PNG data from name_png static byte arrays that can be created using // e.g. misc/scripts/png2c.py. // // This macro exists mostly as a helper for wxBITMAP_PNG() below but also // because it's slightly more convenient to use than NewFromPNGData() directly. #define wxBITMAP_PNG_FROM_DATA(name) \ wxBitmap::NewFromPNGData(name##_png, WXSIZEOF(name##_png)) // Similar to wxBITMAP but used for the bitmaps in PNG format. // // Under Windows they should be embedded into the resource file using RT_RCDATA // resource type and under OS X the PNG file with the specified name must be // available in the resource subdirectory of the bundle. Elsewhere, this is // exactly the same thing as wxBITMAP_PNG_FROM_DATA() described above. #if defined(__WINDOWS__) || defined(__WXOSX__) #define wxBITMAP_PNG(name) wxBitmap(wxS(#name), wxBITMAP_TYPE_PNG_RESOURCE) #else #define wxBITMAP_PNG(name) wxBITMAP_PNG_FROM_DATA(name) #endif // =========================================================================== // classes // =========================================================================== // --------------------------------------------------------------------------- // wxSize // --------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxSize { public: // members are public for compatibility, don't use them directly. int x, y; // constructors wxSize() : x(0), y(0) { } wxSize(int xx, int yy) : x(xx), y(yy) { } // no copy ctor or assignment operator - the defaults are ok wxSize& operator+=(const wxSize& sz) { x += sz.x; y += sz.y; return *this; } wxSize& operator-=(const wxSize& sz) { x -= sz.x; y -= sz.y; return *this; } wxSize& operator/=(int i) { x /= i; y /= i; return *this; } wxSize& operator*=(int i) { x *= i; y *= i; return *this; } wxSize& operator/=(unsigned int i) { x /= i; y /= i; return *this; } wxSize& operator*=(unsigned int i) { x *= i; y *= i; return *this; } wxSize& operator/=(long i) { x /= i; y /= i; return *this; } wxSize& operator*=(long i) { x *= i; y *= i; return *this; } wxSize& operator/=(unsigned long i) { x /= i; y /= i; return *this; } wxSize& operator*=(unsigned long i) { x *= i; y *= i; return *this; } wxSize& operator/=(double i) { x = int(x/i); y = int(y/i); return *this; } wxSize& operator*=(double i) { x = int(x*i); y = int(y*i); return *this; } void IncTo(const wxSize& sz) { if ( sz.x > x ) x = sz.x; if ( sz.y > y ) y = sz.y; } void DecTo(const wxSize& sz) { if ( sz.x < x ) x = sz.x; if ( sz.y < y ) y = sz.y; } void DecToIfSpecified(const wxSize& sz) { if ( sz.x != wxDefaultCoord && sz.x < x ) x = sz.x; if ( sz.y != wxDefaultCoord && sz.y < y ) y = sz.y; } void IncBy(int dx, int dy) { x += dx; y += dy; } void IncBy(const wxPoint& pt); void IncBy(const wxSize& sz) { IncBy(sz.x, sz.y); } void IncBy(int d) { IncBy(d, d); } void DecBy(int dx, int dy) { IncBy(-dx, -dy); } void DecBy(const wxPoint& pt); void DecBy(const wxSize& sz) { DecBy(sz.x, sz.y); } void DecBy(int d) { DecBy(d, d); } wxSize& Scale(float xscale, float yscale) { x = (int)(x*xscale); y = (int)(y*yscale); return *this; } // accessors void Set(int xx, int yy) { x = xx; y = yy; } void SetWidth(int w) { x = w; } void SetHeight(int h) { y = h; } int GetWidth() const { return x; } int GetHeight() const { return y; } bool IsFullySpecified() const { return x != wxDefaultCoord && y != wxDefaultCoord; } // combine this size with the other one replacing the default (i.e. equal // to wxDefaultCoord) components of this object with those of the other void SetDefaults(const wxSize& size) { if ( x == wxDefaultCoord ) x = size.x; if ( y == wxDefaultCoord ) y = size.y; } // compatibility int GetX() const { return x; } int GetY() const { return y; } }; inline bool operator==(const wxSize& s1, const wxSize& s2) { return s1.x == s2.x && s1.y == s2.y; } inline bool operator!=(const wxSize& s1, const wxSize& s2) { return s1.x != s2.x || s1.y != s2.y; } inline wxSize operator+(const wxSize& s1, const wxSize& s2) { return wxSize(s1.x + s2.x, s1.y + s2.y); } inline wxSize operator-(const wxSize& s1, const wxSize& s2) { return wxSize(s1.x - s2.x, s1.y - s2.y); } inline wxSize operator/(const wxSize& s, int i) { return wxSize(s.x / i, s.y / i); } inline wxSize operator*(const wxSize& s, int i) { return wxSize(s.x * i, s.y * i); } inline wxSize operator*(int i, const wxSize& s) { return wxSize(s.x * i, s.y * i); } inline wxSize operator/(const wxSize& s, unsigned int i) { return wxSize(s.x / i, s.y / i); } inline wxSize operator*(const wxSize& s, unsigned int i) { return wxSize(s.x * i, s.y * i); } inline wxSize operator*(unsigned int i, const wxSize& s) { return wxSize(s.x * i, s.y * i); } inline wxSize operator/(const wxSize& s, long i) { return wxSize(s.x / i, s.y / i); } inline wxSize operator*(const wxSize& s, long i) { return wxSize(int(s.x * i), int(s.y * i)); } inline wxSize operator*(long i, const wxSize& s) { return wxSize(int(s.x * i), int(s.y * i)); } inline wxSize operator/(const wxSize& s, unsigned long i) { return wxSize(int(s.x / i), int(s.y / i)); } inline wxSize operator*(const wxSize& s, unsigned long i) { return wxSize(int(s.x * i), int(s.y * i)); } inline wxSize operator*(unsigned long i, const wxSize& s) { return wxSize(int(s.x * i), int(s.y * i)); } inline wxSize operator*(const wxSize& s, double i) { return wxSize(int(s.x * i), int(s.y * i)); } inline wxSize operator*(double i, const wxSize& s) { return wxSize(int(s.x * i), int(s.y * i)); } // --------------------------------------------------------------------------- // Point classes: with real or integer coordinates // --------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxRealPoint { public: double x; double y; wxRealPoint() : x(0.0), y(0.0) { } wxRealPoint(double xx, double yy) : x(xx), y(yy) { } wxRealPoint(const wxPoint& pt); // no copy ctor or assignment operator - the defaults are ok //assignment operators wxRealPoint& operator+=(const wxRealPoint& p) { x += p.x; y += p.y; return *this; } wxRealPoint& operator-=(const wxRealPoint& p) { x -= p.x; y -= p.y; return *this; } wxRealPoint& operator+=(const wxSize& s) { x += s.GetWidth(); y += s.GetHeight(); return *this; } wxRealPoint& operator-=(const wxSize& s) { x -= s.GetWidth(); y -= s.GetHeight(); return *this; } }; inline bool operator==(const wxRealPoint& p1, const wxRealPoint& p2) { return wxIsSameDouble(p1.x, p2.x) && wxIsSameDouble(p1.y, p2.y); } inline bool operator!=(const wxRealPoint& p1, const wxRealPoint& p2) { return !(p1 == p2); } inline wxRealPoint operator+(const wxRealPoint& p1, const wxRealPoint& p2) { return wxRealPoint(p1.x + p2.x, p1.y + p2.y); } inline wxRealPoint operator-(const wxRealPoint& p1, const wxRealPoint& p2) { return wxRealPoint(p1.x - p2.x, p1.y - p2.y); } inline wxRealPoint operator/(const wxRealPoint& s, int i) { return wxRealPoint(s.x / i, s.y / i); } inline wxRealPoint operator*(const wxRealPoint& s, int i) { return wxRealPoint(s.x * i, s.y * i); } inline wxRealPoint operator*(int i, const wxRealPoint& s) { return wxRealPoint(s.x * i, s.y * i); } inline wxRealPoint operator/(const wxRealPoint& s, unsigned int i) { return wxRealPoint(s.x / i, s.y / i); } inline wxRealPoint operator*(const wxRealPoint& s, unsigned int i) { return wxRealPoint(s.x * i, s.y * i); } inline wxRealPoint operator*(unsigned int i, const wxRealPoint& s) { return wxRealPoint(s.x * i, s.y * i); } inline wxRealPoint operator/(const wxRealPoint& s, long i) { return wxRealPoint(s.x / i, s.y / i); } inline wxRealPoint operator*(const wxRealPoint& s, long i) { return wxRealPoint(s.x * i, s.y * i); } inline wxRealPoint operator*(long i, const wxRealPoint& s) { return wxRealPoint(s.x * i, s.y * i); } inline wxRealPoint operator/(const wxRealPoint& s, unsigned long i) { return wxRealPoint(s.x / i, s.y / i); } inline wxRealPoint operator*(const wxRealPoint& s, unsigned long i) { return wxRealPoint(s.x * i, s.y * i); } inline wxRealPoint operator*(unsigned long i, const wxRealPoint& s) { return wxRealPoint(s.x * i, s.y * i); } inline wxRealPoint operator*(const wxRealPoint& s, double i) { return wxRealPoint(int(s.x * i), int(s.y * i)); } inline wxRealPoint operator*(double i, const wxRealPoint& s) { return wxRealPoint(int(s.x * i), int(s.y * i)); } // ---------------------------------------------------------------------------- // wxPoint: 2D point with integer coordinates // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxPoint { public: int x, y; wxPoint() : x(0), y(0) { } wxPoint(int xx, int yy) : x(xx), y(yy) { } wxPoint(const wxRealPoint& pt) : x(int(pt.x)), y(int(pt.y)) { } // no copy ctor or assignment operator - the defaults are ok //assignment operators wxPoint& operator+=(const wxPoint& p) { x += p.x; y += p.y; return *this; } wxPoint& operator-=(const wxPoint& p) { x -= p.x; y -= p.y; return *this; } wxPoint& operator+=(const wxSize& s) { x += s.GetWidth(); y += s.GetHeight(); return *this; } wxPoint& operator-=(const wxSize& s) { x -= s.GetWidth(); y -= s.GetHeight(); return *this; } // check if both components are set/initialized bool IsFullySpecified() const { return x != wxDefaultCoord && y != wxDefaultCoord; } // fill in the unset components with the values from the other point void SetDefaults(const wxPoint& pt) { if ( x == wxDefaultCoord ) x = pt.x; if ( y == wxDefaultCoord ) y = pt.y; } }; // comparison inline bool operator==(const wxPoint& p1, const wxPoint& p2) { return p1.x == p2.x && p1.y == p2.y; } inline bool operator!=(const wxPoint& p1, const wxPoint& p2) { return !(p1 == p2); } // arithmetic operations (component wise) inline wxPoint operator+(const wxPoint& p1, const wxPoint& p2) { return wxPoint(p1.x + p2.x, p1.y + p2.y); } inline wxPoint operator-(const wxPoint& p1, const wxPoint& p2) { return wxPoint(p1.x - p2.x, p1.y - p2.y); } inline wxPoint operator+(const wxPoint& p, const wxSize& s) { return wxPoint(p.x + s.x, p.y + s.y); } inline wxPoint operator-(const wxPoint& p, const wxSize& s) { return wxPoint(p.x - s.x, p.y - s.y); } inline wxPoint operator+(const wxSize& s, const wxPoint& p) { return wxPoint(p.x + s.x, p.y + s.y); } inline wxPoint operator-(const wxSize& s, const wxPoint& p) { return wxPoint(s.x - p.x, s.y - p.y); } inline wxPoint operator-(const wxPoint& p) { return wxPoint(-p.x, -p.y); } inline wxPoint operator/(const wxPoint& s, int i) { return wxPoint(s.x / i, s.y / i); } inline wxPoint operator*(const wxPoint& s, int i) { return wxPoint(s.x * i, s.y * i); } inline wxPoint operator*(int i, const wxPoint& s) { return wxPoint(s.x * i, s.y * i); } inline wxPoint operator/(const wxPoint& s, unsigned int i) { return wxPoint(s.x / i, s.y / i); } inline wxPoint operator*(const wxPoint& s, unsigned int i) { return wxPoint(s.x * i, s.y * i); } inline wxPoint operator*(unsigned int i, const wxPoint& s) { return wxPoint(s.x * i, s.y * i); } inline wxPoint operator/(const wxPoint& s, long i) { return wxPoint(s.x / i, s.y / i); } inline wxPoint operator*(const wxPoint& s, long i) { return wxPoint(int(s.x * i), int(s.y * i)); } inline wxPoint operator*(long i, const wxPoint& s) { return wxPoint(int(s.x * i), int(s.y * i)); } inline wxPoint operator/(const wxPoint& s, unsigned long i) { return wxPoint(s.x / i, s.y / i); } inline wxPoint operator*(const wxPoint& s, unsigned long i) { return wxPoint(int(s.x * i), int(s.y * i)); } inline wxPoint operator*(unsigned long i, const wxPoint& s) { return wxPoint(int(s.x * i), int(s.y * i)); } inline wxPoint operator*(const wxPoint& s, double i) { return wxPoint(int(s.x * i), int(s.y * i)); } inline wxPoint operator*(double i, const wxPoint& s) { return wxPoint(int(s.x * i), int(s.y * i)); } WX_DECLARE_LIST_WITH_DECL(wxPoint, wxPointList, class WXDLLIMPEXP_CORE); // --------------------------------------------------------------------------- // wxRect // --------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxRect { public: wxRect() : x(0), y(0), width(0), height(0) { } wxRect(int xx, int yy, int ww, int hh) : x(xx), y(yy), width(ww), height(hh) { } wxRect(const wxPoint& topLeft, const wxPoint& bottomRight); wxRect(const wxPoint& pt, const wxSize& size) : x(pt.x), y(pt.y), width(size.x), height(size.y) { } wxRect(const wxSize& size) : x(0), y(0), width(size.x), height(size.y) { } // default copy ctor and assignment operators ok int GetX() const { return x; } void SetX(int xx) { x = xx; } int GetY() const { return y; } void SetY(int yy) { y = yy; } int GetWidth() const { return width; } void SetWidth(int w) { width = w; } int GetHeight() const { return height; } void SetHeight(int h) { height = h; } wxPoint GetPosition() const { return wxPoint(x, y); } void SetPosition( const wxPoint &p ) { x = p.x; y = p.y; } wxSize GetSize() const { return wxSize(width, height); } void SetSize( const wxSize &s ) { width = s.GetWidth(); height = s.GetHeight(); } bool IsEmpty() const { return (width <= 0) || (height <= 0); } int GetLeft() const { return x; } int GetTop() const { return y; } int GetBottom() const { return y + height - 1; } int GetRight() const { return x + width - 1; } void SetLeft(int left) { x = left; } void SetRight(int right) { width = right - x + 1; } void SetTop(int top) { y = top; } void SetBottom(int bottom) { height = bottom - y + 1; } wxPoint GetTopLeft() const { return GetPosition(); } wxPoint GetLeftTop() const { return GetTopLeft(); } void SetTopLeft(const wxPoint &p) { SetPosition(p); } void SetLeftTop(const wxPoint &p) { SetTopLeft(p); } wxPoint GetBottomRight() const { return wxPoint(GetRight(), GetBottom()); } wxPoint GetRightBottom() const { return GetBottomRight(); } void SetBottomRight(const wxPoint &p) { SetRight(p.x); SetBottom(p.y); } void SetRightBottom(const wxPoint &p) { SetBottomRight(p); } wxPoint GetTopRight() const { return wxPoint(GetRight(), GetTop()); } wxPoint GetRightTop() const { return GetTopRight(); } void SetTopRight(const wxPoint &p) { SetRight(p.x); SetTop(p.y); } void SetRightTop(const wxPoint &p) { SetTopRight(p); } wxPoint GetBottomLeft() const { return wxPoint(GetLeft(), GetBottom()); } wxPoint GetLeftBottom() const { return GetBottomLeft(); } void SetBottomLeft(const wxPoint &p) { SetLeft(p.x); SetBottom(p.y); } void SetLeftBottom(const wxPoint &p) { SetBottomLeft(p); } // operations with rect wxRect& Inflate(wxCoord dx, wxCoord dy); wxRect& Inflate(const wxSize& d) { return Inflate(d.x, d.y); } wxRect& Inflate(wxCoord d) { return Inflate(d, d); } wxRect Inflate(wxCoord dx, wxCoord dy) const { wxRect r = *this; r.Inflate(dx, dy); return r; } wxRect& Deflate(wxCoord dx, wxCoord dy) { return Inflate(-dx, -dy); } wxRect& Deflate(const wxSize& d) { return Inflate(-d.x, -d.y); } wxRect& Deflate(wxCoord d) { return Inflate(-d); } wxRect Deflate(wxCoord dx, wxCoord dy) const { wxRect r = *this; r.Deflate(dx, dy); return r; } void Offset(wxCoord dx, wxCoord dy) { x += dx; y += dy; } void Offset(const wxPoint& pt) { Offset(pt.x, pt.y); } wxRect& Intersect(const wxRect& rect); wxRect Intersect(const wxRect& rect) const { wxRect r = *this; r.Intersect(rect); return r; } wxRect& Union(const wxRect& rect); wxRect Union(const wxRect& rect) const { wxRect r = *this; r.Union(rect); return r; } // return true if the point is (not strcitly) inside the rect bool Contains(int x, int y) const; bool Contains(const wxPoint& pt) const { return Contains(pt.x, pt.y); } // return true if the rectangle 'rect' is (not strictly) inside this rect bool Contains(const wxRect& rect) const; // return true if the rectangles have a non empty intersection bool Intersects(const wxRect& rect) const; // like Union() but don't ignore empty rectangles wxRect& operator+=(const wxRect& rect); // intersections of two rectrangles not testing for empty rectangles wxRect& operator*=(const wxRect& rect); // centre this rectangle in the given (usually, but not necessarily, // larger) one wxRect CentreIn(const wxRect& r, int dir = wxBOTH) const { return wxRect(dir & wxHORIZONTAL ? r.x + (r.width - width)/2 : x, dir & wxVERTICAL ? r.y + (r.height - height)/2 : y, width, height); } wxRect CenterIn(const wxRect& r, int dir = wxBOTH) const { return CentreIn(r, dir); } public: int x, y, width, height; }; // compare rectangles inline bool operator==(const wxRect& r1, const wxRect& r2) { return (r1.x == r2.x) && (r1.y == r2.y) && (r1.width == r2.width) && (r1.height == r2.height); } inline bool operator!=(const wxRect& r1, const wxRect& r2) { return !(r1 == r2); } // like Union() but don't treat empty rectangles specially WXDLLIMPEXP_CORE wxRect operator+(const wxRect& r1, const wxRect& r2); // intersections of two rectangles WXDLLIMPEXP_CORE wxRect operator*(const wxRect& r1, const wxRect& r2); // define functions which couldn't be defined above because of declarations // order inline void wxSize::IncBy(const wxPoint& pt) { IncBy(pt.x, pt.y); } inline void wxSize::DecBy(const wxPoint& pt) { DecBy(pt.x, pt.y); } // --------------------------------------------------------------------------- // Management of pens, brushes and fonts // --------------------------------------------------------------------------- typedef wxInt8 wxDash; class WXDLLIMPEXP_CORE wxGDIObjListBase { public: wxGDIObjListBase(); ~wxGDIObjListBase(); protected: wxList list; }; WX_DECLARE_STRING_HASH_MAP(wxColour*, wxStringToColourHashMap); class WXDLLIMPEXP_CORE wxColourDatabase { public: wxColourDatabase(); ~wxColourDatabase(); // find colour by name or name for the given colour wxColour Find(const wxString& name) const; wxString FindName(const wxColour& colour) const; // add a new colour to the database void AddColour(const wxString& name, const wxColour& colour); private: // load the database with the built in colour values when called for the // first time, do nothing after this void Initialize(); wxStringToColourHashMap *m_map; }; class WXDLLIMPEXP_CORE wxResourceCache: public wxList { public: wxResourceCache() { } #if !wxUSE_STD_CONTAINERS wxResourceCache(const unsigned int keyType) : wxList(keyType) { } #endif virtual ~wxResourceCache(); }; // --------------------------------------------------------------------------- // global variables // --------------------------------------------------------------------------- /* Stock objects wxStockGDI creates the stock GDI objects on demand. Pointers to the created objects are stored in the ms_stockObject array, which is indexed by the Item enum values. Platorm-specific fonts can be created by implementing a derived class with an override for the GetFont function. wxStockGDI operates as a singleton, accessed through the ms_instance pointer. By default this pointer is set to an instance of wxStockGDI. A derived class must arrange to set this pointer to an instance of itself. */ class WXDLLIMPEXP_CORE wxStockGDI { public: enum Item { BRUSH_BLACK, BRUSH_BLUE, BRUSH_CYAN, BRUSH_GREEN, BRUSH_YELLOW, BRUSH_GREY, BRUSH_LIGHTGREY, BRUSH_MEDIUMGREY, BRUSH_RED, BRUSH_TRANSPARENT, BRUSH_WHITE, COLOUR_BLACK, COLOUR_BLUE, COLOUR_CYAN, COLOUR_GREEN, COLOUR_YELLOW, COLOUR_LIGHTGREY, COLOUR_RED, COLOUR_WHITE, CURSOR_CROSS, CURSOR_HOURGLASS, CURSOR_STANDARD, FONT_ITALIC, FONT_NORMAL, FONT_SMALL, FONT_SWISS, PEN_BLACK, PEN_BLACKDASHED, PEN_BLUE, PEN_CYAN, PEN_GREEN, PEN_YELLOW, PEN_GREY, PEN_LIGHTGREY, PEN_MEDIUMGREY, PEN_RED, PEN_TRANSPARENT, PEN_WHITE, ITEMCOUNT }; wxStockGDI(); virtual ~wxStockGDI(); static void DeleteAll(); static wxStockGDI& instance() { return *ms_instance; } static const wxBrush* GetBrush(Item item); static const wxColour* GetColour(Item item); static const wxCursor* GetCursor(Item item); // Can be overridden by platform-specific derived classes virtual const wxFont* GetFont(Item item); static const wxPen* GetPen(Item item); protected: static wxStockGDI* ms_instance; static wxObject* ms_stockObject[ITEMCOUNT]; wxDECLARE_NO_COPY_CLASS(wxStockGDI); }; #define wxITALIC_FONT wxStockGDI::instance().GetFont(wxStockGDI::FONT_ITALIC) #define wxNORMAL_FONT wxStockGDI::instance().GetFont(wxStockGDI::FONT_NORMAL) #define wxSMALL_FONT wxStockGDI::instance().GetFont(wxStockGDI::FONT_SMALL) #define wxSWISS_FONT wxStockGDI::instance().GetFont(wxStockGDI::FONT_SWISS) #define wxBLACK_DASHED_PEN wxStockGDI::GetPen(wxStockGDI::PEN_BLACKDASHED) #define wxBLACK_PEN wxStockGDI::GetPen(wxStockGDI::PEN_BLACK) #define wxBLUE_PEN wxStockGDI::GetPen(wxStockGDI::PEN_BLUE) #define wxCYAN_PEN wxStockGDI::GetPen(wxStockGDI::PEN_CYAN) #define wxGREEN_PEN wxStockGDI::GetPen(wxStockGDI::PEN_GREEN) #define wxYELLOW_PEN wxStockGDI::GetPen(wxStockGDI::PEN_YELLOW) #define wxGREY_PEN wxStockGDI::GetPen(wxStockGDI::PEN_GREY) #define wxLIGHT_GREY_PEN wxStockGDI::GetPen(wxStockGDI::PEN_LIGHTGREY) #define wxMEDIUM_GREY_PEN wxStockGDI::GetPen(wxStockGDI::PEN_MEDIUMGREY) #define wxRED_PEN wxStockGDI::GetPen(wxStockGDI::PEN_RED) #define wxTRANSPARENT_PEN wxStockGDI::GetPen(wxStockGDI::PEN_TRANSPARENT) #define wxWHITE_PEN wxStockGDI::GetPen(wxStockGDI::PEN_WHITE) #define wxBLACK_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_BLACK) #define wxBLUE_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_BLUE) #define wxCYAN_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_CYAN) #define wxGREEN_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_GREEN) #define wxYELLOW_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_YELLOW) #define wxGREY_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_GREY) #define wxLIGHT_GREY_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_LIGHTGREY) #define wxMEDIUM_GREY_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_MEDIUMGREY) #define wxRED_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_RED) #define wxTRANSPARENT_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_TRANSPARENT) #define wxWHITE_BRUSH wxStockGDI::GetBrush(wxStockGDI::BRUSH_WHITE) #define wxBLACK wxStockGDI::GetColour(wxStockGDI::COLOUR_BLACK) #define wxBLUE wxStockGDI::GetColour(wxStockGDI::COLOUR_BLUE) #define wxCYAN wxStockGDI::GetColour(wxStockGDI::COLOUR_CYAN) #define wxGREEN wxStockGDI::GetColour(wxStockGDI::COLOUR_GREEN) #define wxYELLOW wxStockGDI::GetColour(wxStockGDI::COLOUR_YELLOW) #define wxLIGHT_GREY wxStockGDI::GetColour(wxStockGDI::COLOUR_LIGHTGREY) #define wxRED wxStockGDI::GetColour(wxStockGDI::COLOUR_RED) #define wxWHITE wxStockGDI::GetColour(wxStockGDI::COLOUR_WHITE) #define wxCROSS_CURSOR wxStockGDI::GetCursor(wxStockGDI::CURSOR_CROSS) #define wxHOURGLASS_CURSOR wxStockGDI::GetCursor(wxStockGDI::CURSOR_HOURGLASS) #define wxSTANDARD_CURSOR wxStockGDI::GetCursor(wxStockGDI::CURSOR_STANDARD) // 'Null' objects extern WXDLLIMPEXP_DATA_CORE(wxBitmap) wxNullBitmap; extern WXDLLIMPEXP_DATA_CORE(wxIcon) wxNullIcon; extern WXDLLIMPEXP_DATA_CORE(wxCursor) wxNullCursor; extern WXDLLIMPEXP_DATA_CORE(wxPen) wxNullPen; extern WXDLLIMPEXP_DATA_CORE(wxBrush) wxNullBrush; extern WXDLLIMPEXP_DATA_CORE(wxPalette) wxNullPalette; extern WXDLLIMPEXP_DATA_CORE(wxFont) wxNullFont; extern WXDLLIMPEXP_DATA_CORE(wxColour) wxNullColour; extern WXDLLIMPEXP_DATA_CORE(wxIconBundle) wxNullIconBundle; extern WXDLLIMPEXP_DATA_CORE(wxColourDatabase*) wxTheColourDatabase; extern WXDLLIMPEXP_DATA_CORE(const char) wxPanelNameStr[]; extern WXDLLIMPEXP_DATA_CORE(const wxSize) wxDefaultSize; extern WXDLLIMPEXP_DATA_CORE(const wxPoint) wxDefaultPosition; // --------------------------------------------------------------------------- // global functions // --------------------------------------------------------------------------- // resource management extern void WXDLLIMPEXP_CORE wxInitializeStockLists(); extern void WXDLLIMPEXP_CORE wxDeleteStockLists(); // is the display colour (or monochrome)? extern bool WXDLLIMPEXP_CORE wxColourDisplay(); // Returns depth of screen extern int WXDLLIMPEXP_CORE wxDisplayDepth(); #define wxGetDisplayDepth wxDisplayDepth // get the display size extern void WXDLLIMPEXP_CORE wxDisplaySize(int *width, int *height); extern wxSize WXDLLIMPEXP_CORE wxGetDisplaySize(); extern void WXDLLIMPEXP_CORE wxDisplaySizeMM(int *width, int *height); extern wxSize WXDLLIMPEXP_CORE wxGetDisplaySizeMM(); extern wxSize WXDLLIMPEXP_CORE wxGetDisplayPPI(); // Get position and size of the display workarea extern void WXDLLIMPEXP_CORE wxClientDisplayRect(int *x, int *y, int *width, int *height); extern wxRect WXDLLIMPEXP_CORE wxGetClientDisplayRect(); // set global cursor extern void WXDLLIMPEXP_CORE wxSetCursor(const wxCursor& cursor); #endif // _WX_GDICMNH__
[ "andrewmac@gmail.com" ]
andrewmac@gmail.com
b7c2188b607c71c52f69c70b551abcaea5448399
0749035f5d77a182155efca5aff2f1cfe1da8cc6
/TREES/mirror/mirror.cpp
681c427c33a2142c5d5e8d9774f9650ca49d6bdb
[]
no_license
anandkodnani/C-
a291025604a8d37e50bd3e9bdd99d2a95eedcd79
635e517a7ae31d70b531f611867f40fa34a4f575
refs/heads/master
2021-01-10T13:48:56.042453
2016-01-29T20:11:38
2016-01-29T20:11:38
50,384,412
0
0
null
null
null
null
UTF-8
C++
false
false
1,596
cpp
#include <iostream> #include <vector> #include <queue> using namespace std; struct Node { int val; vector<Node *> child; }; Node *newNode(int val) { Node *node = new Node; node->val = val; return node; } void printNodeLevelWise(Node *root) { queue<Node *> Q; Q.push(root); while (!Q.empty()) { Node *c = Q.front(); Q.pop(); for (auto ptr: c->child) Q.push(ptr); cout << " " << c-> val; } } void mirrorTree(Node *root) { if (!root || root->child.size() == 0) return; if (root->child.size() == 1) return mirrorTree(root->child[0]); // Reverse the roots. int i = 0, j = root->child.size() - 1; while (i < j) { swap(root->child[i], root->child[j]); ++i; --j; } for (auto ptr: root->child) mirrorTree(ptr); } // Driver program int main() { /* Let us create below tree * 10 * / / \ \ * 2 34 56 100 * | / | \ * 1 7 8 9 */ Node *root = newNode(10); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(34)); (root->child).push_back(newNode(56)); (root->child).push_back(newNode(100)); (root->child[2]->child).push_back(newNode(1)); (root->child[3]->child).push_back(newNode(7)); (root->child[3]->child).push_back(newNode(8)); (root->child[3]->child).push_back(newNode(9)); cout << "Level order traversal Before Mirroring\n"; printNodeLevelWise(root); mirrorTree(root); cout << "\nLevel order traversal After Mirroring\n"; printNodeLevelWise(root); return 0; }
[ "akodnani@codeaurora.org" ]
akodnani@codeaurora.org
4caf068474b8dc977bf110f2c14465173e22342b
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/base/crts/crtw32/iostream/strmbdbp.cpp
04e8b54bcd72e089155fbe1cc13e5bab5dcb4371
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
1,217
cpp
/*** *strmbdbp.cpp - streambuf::dbp() debug routine * * Copyright (c) 1991-2001, Microsoft Corporation. All rights reserved. * *Purpose: * Dump debug info about streambuf to stdout. * *Revision History: * * 11-13-91 KRS Created. * 01-26-95 CFW Win32s objects now exist. * 06-14-95 CFW Comment cleanup. * *******************************************************************************/ #include <cruntime.h> #include <internal.h> #include <io.h> #include <stdio.h> #include <iostream.h> #pragma hdrstop #pragma check_stack(on) // large buffer(s) void streambuf::dbp() { int olen; _WINSTATIC char obuffer[256]; if (unbuffered()) olen = sprintf(obuffer, "\nSTREAMBUF DEBUG INFO: this=%p, unbuffered\n", (void *) this); else { olen = sprintf(obuffer, "\nSTREAMBUF DEBUG INFO: this=%p, _fAlloc=%d\n" " base()=%p, ebuf()=%p, blen()=%d\n" " pbase()=%p, pptr()=%p, epptr()=%p\n" " eback()=%p, gptr()=%p, egptr()=%p\n", (void *) this, (_fAlloc), base(), ebuf(), blen(), pbase(), pptr(), epptr(), eback(), gptr(), egptr()); } _write(1,obuffer,olen); // direct write to stdout }
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
07ddd62904d2e4ec78091bc13b58cdeded5f1a89
e3c548bfa553ed3b4d9789361a04e391f5546f92
/src/test/timedata_tests.cpp
233bb84e93d3c1b9f77c284462f5376033836613
[ "MIT" ]
permissive
StorelPlatform/Storel-Platform
29201d76387b2586746a90733cecfea7b93764df
ef5c843dd5148e226b0b1d566f9b0d126a56c775
refs/heads/master
2022-01-20T07:49:43.625003
2019-07-19T16:05:16
2019-07-19T16:05:16
197,796,325
0
0
null
null
null
null
UTF-8
C++
false
false
1,018
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // #include "timedata.h" #include "test/test_storel.h" #include <boost/test/unit_test.hpp> using namespace std; BOOST_FIXTURE_TEST_SUITE(timedata_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(util_MedianFilter) { CMedianFilter<int> filter(5, 15); BOOST_CHECK_EQUAL(filter.median(), 15); filter.input(20); // [15 20] BOOST_CHECK_EQUAL(filter.median(), 17); filter.input(30); // [15 20 30] BOOST_CHECK_EQUAL(filter.median(), 20); filter.input(3); // [3 15 20 30] BOOST_CHECK_EQUAL(filter.median(), 17); filter.input(7); // [3 7 15 20 30] BOOST_CHECK_EQUAL(filter.median(), 15); filter.input(18); // [3 7 18 20 30] BOOST_CHECK_EQUAL(filter.median(), 18); filter.input(0); // [0 3 7 18 30] BOOST_CHECK_EQUAL(filter.median(), 7); } BOOST_AUTO_TEST_SUITE_END()
[ "53089347+StorelPlatform@users.noreply.github.com" ]
53089347+StorelPlatform@users.noreply.github.com
f85b1e1847b304059620d529b4fa3914fbc42c5a
fe83b3592d279a8be1c59300408b19a6a2d67c3e
/cpp/referencetest3.cpp
e393a2d5519e0d793d28644f48920fe3bd9e5496
[ "MIT" ]
permissive
MysteryPancake/Fun
ef8fa6b5f32d4bfb4fdbcffd82f0429e84eb95c6
0b8781b31357aa2d1fd3370e7ead15d6cbfd1301
refs/heads/master
2023-07-19T22:53:49.607744
2023-07-15T15:31:02
2023-07-15T15:31:02
91,234,954
37
11
MIT
2022-10-14T06:48:03
2017-05-14T10:07:18
AutoHotkey
UTF-8
C++
false
false
221
cpp
#include <iostream> using namespace std; void changeInt(int* a) { *a = 420; // changes a } int main() { int a = 5; cout << a << '\n'; // 5 changeInt(&a); cout << a << '\n'; // 420 return 0; }
[ "noreply@github.com" ]
MysteryPancake.noreply@github.com
e7285362d36e86390c3d145ef67b841d889d646a
1086e76a96c9f347d7c27bf3818554c566e5dea1
/src/components/ArduinoLite/src/Arduino.h
99b1ed076bfe7e78784bd8aa707018c1ecb118ca
[ "MIT" ]
permissive
ducalex/SolarStationR3
658a7d15a65c4033b83118df5609658ef3e90f91
9ef2fce16bf5b400c67c61837033e8ff23d4bd77
refs/heads/master
2022-05-06T03:16:45.731566
2022-04-13T14:11:39
2022-04-13T14:11:39
225,293,869
0
0
null
null
null
null
UTF-8
C++
false
false
3,606
h
#ifndef ArduinoLite_h #define ArduinoLite_h #include "esp_system.h" //#include "esp_adc_cal.h" #include "esp_timer.h" #include "esp_log.h" #include "driver/gpio.h" #include "driver/adc.h" #include "driver/dac.h" #include "stdlib.h" #include "unistd.h" #include "WString.h" #include "Stream.h" typedef bool boolean; typedef uint8_t byte; typedef unsigned int word; #define ARDUINO 100 // Some libraries need this #define F_CPU (CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ * 1000000U) #define LSBFIRST 0 #define MSBFIRST 1 #define LOW 0x0 #define HIGH 0x1 #define INPUT GPIO_MODE_INPUT|(GPIO_FLOATING << 8) #define INPUT_PULLUP GPIO_MODE_INPUT|(GPIO_PULLUP_ONLY << 8) #define INPUT_PULLDOWN GPIO_MODE_INPUT|(GPIO_PULLDOWN_ONLY << 8) #define OUTPUT GPIO_MODE_OUTPUT|(GPIO_FLOATING << 8) #define digitalPinIsValid(pin) ((pin) < 40) #define digitalPinToInterrupt(pin) (digitalPinIsValid(pin) ? (pin) : -1) #define digitalPinHasPWM(pin) ((pin) < 36) #define clockCyclesPerMicrosecond() ( F_CPU / 1000000L ) #define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() ) #define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() ) #define micros() ((unsigned long)esp_timer_get_time()) #define millis() ((unsigned long)(esp_timer_get_time() / 1000ULL)) #define delay(ms) usleep((ms) * 1000) #define delayMicroseconds(us) usleep(us) #define yield() vPortYield() #define NOP() asm volatile ("nop") #define PGM_P const char * #define PROGMEM #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) #define pgm_read_word(addr) (*(const unsigned short *)(addr)) #define pgm_read_dword(addr) (*(const unsigned long *)(addr)) #define bitRead(value, bit) (((value) >> (bit)) & 0x01) #define bitSet(value, bit) ((value) |= (1UL << (bit))) #define bitClear(value, bit) ((value) &= ~(1UL << (bit))) #define bitWrite(value, bit, bitval) (bitval ? bitSet(value, bit) : bitClear(value, bit)) #define lowByte(value) ((uint8_t)(value)) #define highByte(value) ((uint8_t)((value) >> 8)) void pinMode(uint8_t pin, uint16_t mode); uint8_t digitalRead(uint8_t pin); void digitalWrite(uint8_t pin, uint16_t val); uint16_t analogRead(uint8_t pin); void analogReadResolution(uint8_t bits); void analogWrite(uint8_t pin, uint16_t val); void attachInterrupt(int interrupt, void (*userFunc)(void), int mode, void *arg = NULL); void detachInterrupt(int interrupt); void interrupts(); void noInterrupts(); unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout); unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout); uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder); void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t value); void randomSeed(long seed); long random(long min, long max); long random(long max); #ifdef __cplusplus #include <cmath> #include <algorithm> using std::abs; using std::cos; using std::sin; using std::tan; using std::isnan; using std::isinf; using std::ceil; using std::floor; using std::pow; using std::sqrt; using ::round; #endif template <typename T, typename U, typename V> inline T constrain(T amt, U low, V high) { return max(min(amt, high), low); } template <typename T> inline T map(T x, T in_min, T in_max, T out_min, T out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } template <typename T, typename U> inline T max(T a, U b) { return std::max(a, (T)b); } template <typename T, typename U> inline T min(T a, U b) { return std::min(a, (T)b); } #endif
[ "alex@netvps.ca" ]
alex@netvps.ca
cf5bb2f4293389239287ac985f9d823829bc55a4
76e14c89fae98895f63df6e2bda10e5700000fac
/Sprites.cpp
e47ba38c81e16301cae8146a25613e3b0b25d76a
[]
no_license
GiulioRusso/Impossible-Pacman
4368a14408eee5cae89aa56716b5bc30fe84f6e1
bde64f37eaf715178f205bf45ab7fae99807b41d
refs/heads/main
2023-06-12T09:40:34.488191
2021-06-25T08:16:54
2021-06-25T08:16:54
380,161,983
0
0
null
null
null
null
UTF-8
C++
false
false
10,985
cpp
#include "Include.h" #include <QBitmap> //Ghosts static QRect red_ghosts(2, 65, 15, 15); static QRect pink_ghosts(2, 81, 15, 15); static QRect heavenly_ghosts(2, 97, 15, 15); static QRect orange_ghosts(2, 113, 15, 15); static QRect eyes_ghost(584, 81, 15, 15); //AI static QRect blinkyAi(456, 64, 15, 15); static QRect inkyAi(456, 96, 15, 15); static QRect clydeAi(456, 112, 15, 15); static QRect pinkyAi(456, 80, 15, 15); static QRect ghostVulnerableAi(584, 64, 15, 15); Sprites* Sprites::instance() { static Sprites uniqueInstance; return &uniqueInstance; } // Funzione di utilita' QRect moveBy(QRect rect, int x, int y, int dx = 15, int dy = 15, int border_x = 1, int border_y = 1) { rect.moveTo(QPoint(rect.x() + x * dx + x * border_x, rect.y() + y * dy + y * border_y)); return rect; } Sprites::Sprites() { title_screen = loadTexture(":/Sprites/title.png"); allPacman = loadTexture(":/Sprites/Allpacman.png", QColor(0, 0, 0)); pacman = loadTexture(":/Sprites/characters.png", QColor(0, 0, 0)); cher = loadTexture(":/Sprites/Cherry.png", QColor(0,0,0)); gameover = loadTexture(":/Sprites/scene-go.png"); rank = loadTexture(":/Sprites/rank.png"); ai = loadTexture(":/Sprites/ai.png", QColor(0, 0, 0)); ai3 = loadTexture(":/Sprites/ai3.png", QColor(0, 0, 0)); pause = loadTexture(":/Sprites/pause.png"); } QPixmap Sprites::get(const std::string& id) { //Schermata di gioco iniziale if (id == "title-screen") return title_screen.copy(QRect(0, 0, 224, 288)); //Box else if (id == "box") return allPacman.copy(QRect(228, 0, 224 , 248)); //Ai else if (id == "boxAi") return ai.copy(QRect(228, 0, 224, 248)); else if (id == "boxAi3") return ai3.copy(QRect(228, 0, 224, 248)); //Food else if (id == "food") return allPacman.copy(QRect(11, 11, 2, 2)); else if (id == "big-food") return allPacman.copy(QRect(8, 24, 8, 8)); //Pacman //left else if (id == "pacman-sx-0") return pacman.copy(QRect(18, 17, 15, 15)); else if (id == "pacman-sx-1") return pacman.copy(QRect(2, 17, 15, 15)); else if (id == "pacman-sx-2") return pacman.copy(QRect(34, 1, 15, 15)); else if (id == "pacman-sx-3") return pacman.copy(QRect(2, 17, 15, 15)); //right else if (id == "pacman-dx-0") return pacman.copy(QRect(18, 1, 15, 15)); else if (id == "pacman-dx-1") return pacman.copy(QRect(2, 1, 15, 15)); else if (id == "pacman-dx-2") return pacman.copy(QRect(34, 1, 15, 15)); else if (id == "pacman-dx-3") return pacman.copy(QRect(2, 1, 15, 15)); //up else if (id == "pacman-up-0") return pacman.copy(QRect(18, 33, 15, 15)); else if (id == "pacman-up-1") return pacman.copy(QRect(2, 33, 15, 15)); else if (id == "pacman-up-2") return pacman.copy(QRect(34, 1, 15, 15)); else if (id == "pacman-up-3") return pacman.copy(QRect(2, 33, 15, 15)); //down else if (id == "pacman-down-0") return pacman.copy(QRect(18, 49, 15, 15)); else if (id == "pacman-down-1") return pacman.copy(QRect(2, 49, 15, 15)); else if (id == "pacman-down-2") return pacman.copy(QRect(34, 1, 15, 15)); else if (id == "pacman-down-3") return pacman.copy(QRect(18, 49, 15, 15)); //Morte Pacman else if (id == "pacman-dead-0") return pacman.copy(QRect(50, 1, 15, 15)); else if (id == "pacman-dead-1") return pacman.copy(QRect(66, 1, 15, 15)); else if (id == "pacman-dead-2") return pacman.copy(QRect(82, 1, 15, 15)); else if (id == "pacman-dead-3") return pacman.copy(QRect(98, 1, 15, 15)); else if (id == "pacman-dead-4") return pacman.copy(QRect(114, 1, 15, 15)); else if (id == "pacman-dead-5") return pacman.copy(QRect(130, 1, 15, 15)); else if (id == "pacman-dead-6") return pacman.copy(QRect(146, 1, 15, 15)); else if (id == "pacman-dead-7") return pacman.copy(QRect(162, 1, 15, 15)); else if (id == "pacman-dead-8") return pacman.copy(QRect(178, 1, 15, 15)); else if (id == "pacman-dead-9") return pacman.copy(QRect(194, 1, 15, 15)); else if (id == "pacman-dead-10") return pacman.copy(QRect(210, 1, 15, 15)); //Fruit else if (id == "Cherry") return cher; //Ghost Spaventati else if (id == "ghost-vulnerable-0") return pacman.copy(moveBy(red_ghosts, 8, 0)); else if (id == "ghost-vulnerable-1") return pacman.copy(moveBy(red_ghosts, 9, 0)); else if (id == "ghost-finish-vulnerable-0") return pacman.copy(moveBy(red_ghosts, 10, 0)); else if (id == "ghost-finish-vulnerable-1") return pacman.copy(moveBy(red_ghosts, 11, 0)); //Ghost Spaventati Ai else if (id == "ghost-vulnerable-ai-0") return ai.copy(ghostVulnerableAi); else if (id == "ghost-vulnerable-ai-1") return ai.copy(moveBy(ghostVulnerableAi, 1, 0)); else if (id == "ghost-finish-vulnerable-ai-0") return ai.copy(moveBy(ghostVulnerableAi, 2, 0)); else if (id == "ghost-finish-vulnerable-ai-1") return ai.copy(moveBy(ghostVulnerableAi, 3, 0)); //FoodAi else if (id == "foodAi") return ai.copy(QRect(11, 11, 2, 2)); else if (id == "big-foodAi") return ai.copy(QRect(8, 24, 8, 8)); //Ghosts Eyes else if (id == "eyes-dx") return allPacman.copy(eyes_ghost); else if (id == "eyes-sx") return allPacman.copy(moveBy(eyes_ghost, 1, 0)); else if (id == "eyes-down") return allPacman.copy(moveBy(eyes_ghost, 3, 0)); else if (id == "eyes-up") return allPacman.copy(QRect(618, 81, 15, 15)); //Blinky else if (id == "red-ghost-dx-0") return pacman.copy(red_ghosts); else if (id == "red-ghost-dx-1") return pacman.copy(moveBy(red_ghosts, 1, 0)); else if (id == "red-ghost-sx-0") return pacman.copy(moveBy(red_ghosts, 2, 0)); else if (id == "red-ghost-sx-1") return pacman.copy(moveBy(red_ghosts, 3, 0)); else if (id == "red-ghost-up-0") return pacman.copy(moveBy(red_ghosts, 4, 0)); else if (id == "red-ghost-up-1") return pacman.copy(moveBy(red_ghosts, 5, 0)); else if (id == "red-ghost-down-0") return pacman.copy(moveBy(red_ghosts, 6, 0)); else if (id == "red-ghost-down-1") return pacman.copy(moveBy(red_ghosts, 7, 0)); //Pinky else if (id == "pink-ghost-dx-0") return pacman.copy(pink_ghosts); else if (id == "pink-ghost-dx-1") return pacman.copy(moveBy(pink_ghosts, 1, 0)); else if (id == "pink-ghost-sx-0") return pacman.copy(moveBy(pink_ghosts, 2, 0)); else if (id == "pink-ghost-sx-1") return pacman.copy(moveBy(pink_ghosts, 3, 0)); else if (id == "pink-ghost-up-0") return pacman.copy(moveBy(pink_ghosts, 4, 0)); else if (id == "pink-ghost-up-1") return pacman.copy(moveBy(pink_ghosts, 5, 0)); else if (id == "pink-ghost-down-0") return pacman.copy(moveBy(pink_ghosts, 6, 0)); else if (id == "pink-ghost-down-1") return pacman.copy(moveBy(pink_ghosts, 7, 0)); //Inky else if (id == "heavenly-ghost-dx-0") return pacman.copy(heavenly_ghosts); else if (id == "heavenly-ghost-dx-1") return pacman.copy(moveBy(heavenly_ghosts, 1, 0)); else if (id == "heavenly-ghost-sx-0") return pacman.copy(moveBy(heavenly_ghosts, 2, 0)); else if (id == "heavenly-ghost-sx-1") return pacman.copy(moveBy(heavenly_ghosts, 3, 0)); else if (id == "heavenly-ghost-up-0") return pacman.copy(moveBy(heavenly_ghosts, 4, 0)); else if (id == "heavenly-ghost-up-1") return pacman.copy(moveBy(heavenly_ghosts, 5, 0)); else if (id == "heavenly-ghost-down-0") return pacman.copy(moveBy(heavenly_ghosts, 6, 0)); else if (id == "heavenly-ghost-down-1") return pacman.copy(moveBy(heavenly_ghosts, 7, 0)); //Clyde else if (id == "orange-ghost-dx-0") return pacman.copy(orange_ghosts); else if (id == "orange-ghost-dx-1") return pacman.copy(moveBy(orange_ghosts, 1, 0)); else if (id == "orange-ghost-sx-0") return pacman.copy(moveBy(orange_ghosts, 2, 0)); else if (id == "orange-ghost-sx-1") return pacman.copy(moveBy(orange_ghosts, 3, 0)); else if (id == "orange-ghost-up-0") return pacman.copy(moveBy(orange_ghosts, 4, 0)); else if (id == "orange-ghost-up-1") return pacman.copy(moveBy(orange_ghosts, 5, 0)); else if (id == "orange-ghost-down-0") return pacman.copy(moveBy(orange_ghosts, 6, 0)); else if (id == "orange-ghost-down-1") return pacman.copy(moveBy(orange_ghosts, 7, 0)); //Ai Ghosts //blinky ai else if (id == "blinkydx-0") return ai.copy(blinkyAi); else if (id == "blinkydx-1") return ai.copy(moveBy(blinkyAi, 1, 0)); else if (id == "blinkysx-0") return ai.copy(moveBy(blinkyAi, 2, 0)); else if (id == "blinkysx-1") return ai.copy(moveBy(blinkyAi, 3, 0)); else if (id == "blinkyup-0") return ai.copy(moveBy(blinkyAi, 4, 0)); else if (id == "blinkyup-1") return ai.copy(moveBy(blinkyAi, 5, 0)); else if (id == "blinkydown-0") return ai.copy(moveBy(blinkyAi, 6, 0)); else if (id == "blinkydown-1") return ai.copy(moveBy(blinkyAi, 7, 0)); //clyde ai else if (id == "clydedx-0") return ai.copy(clydeAi); else if (id == "clydedx-1") return ai.copy(moveBy(clydeAi, 1, 0)); else if (id == "clydesx-0") return ai.copy(moveBy(clydeAi, 2, 0)); else if (id == "clydesx-1") return ai.copy(moveBy(clydeAi, 3, 0)); else if (id == "clydeup-0") return ai.copy(moveBy(clydeAi, 4, 0)); else if (id == "clydeup-1") return ai.copy(moveBy(clydeAi, 5, 0)); else if (id == "clydedown-0") return ai.copy(moveBy(clydeAi, 6, 0)); else if (id == "clydedown-1") return ai.copy(moveBy(clydeAi, 7, 0)); //inky ai else if (id == "inkydx-0") return ai.copy(inkyAi); else if (id == "inkydx-1") return ai.copy(moveBy(inkyAi, 1, 0)); else if (id == "inkysx-0") return ai.copy(moveBy(inkyAi, 2, 0)); else if (id == "inkysx-1") return ai.copy(moveBy(inkyAi, 3, 0)); else if (id == "inkyup-0") return ai.copy(moveBy(inkyAi, 4, 0)); else if (id == "inkyup-1") return ai.copy(moveBy(inkyAi, 5, 0)); else if (id == "inkydown-0") return ai.copy(moveBy(inkyAi, 6, 0)); else if (id == "inkydown-1") return ai.copy(moveBy(inkyAi, 7, 0)); //pinky ai else if (id == "pinkydx-0") return ai.copy(pinkyAi); else if (id == "pinkydx-1") return ai.copy(moveBy(pinkyAi, 1, 0)); else if (id == "pinkysx-0") return ai.copy(moveBy(pinkyAi, 2, 0)); else if (id == "pinkysx-1") return ai.copy(moveBy(pinkyAi, 3, 0)); else if (id == "pinkyup-0") return ai.copy(moveBy(pinkyAi, 4, 0)); else if (id == "pinkyup-1") return ai.copy(moveBy(pinkyAi, 5, 0)); else if (id == "pinkydown-0") return ai.copy(moveBy(pinkyAi, 6, 0)); else if (id == "pinkydown-1") return ai.copy(moveBy(pinkyAi, 7, 0)); //scene gameover else if (id == "title-gameover") return gameover.copy(QRect(0, 0, 224, 288)); else if (id == "title-rank") return rank.copy(QRect(0, 0, 224, 288)); else if (id == "pausa") return pause.copy(QRect(0, 0, 125, 32)); else return QPixmap(); }
[ "noreply@github.com" ]
GiulioRusso.noreply@github.com
1e3932515f9b6b8a75e1ed2003fa3c683023ad10
876b13d55068ed5c2d9367054e2ab873645c66f4
/src/main.cpp
eb1e8adcfb59739dbeeda97f0c5ecfc89ed08c94
[]
no_license
justiq/ASTS_lab2
e37ca570600467bbe7027fcc14344db1bb28dd65
89491a49ece3b7cc70c3dec63cefef2f59422869
refs/heads/main
2023-02-07T17:44:56.694091
2020-12-25T10:11:01
2020-12-25T10:11:01
324,330,697
0
0
null
null
null
null
UTF-8
C++
false
false
5,605
cpp
#include "main.h" #include <stdlib.h> #include <stdio.h> #include <inttypes.h> #include "mstn_version.h" #include "mstn_led.h" #include "mstn_clk.h" #include "mstn_usb.h" #include "morze.h" #include "rxtx.h" // StrobePin1 PORT_Pin_0 // StrobePin2 PORT_Pin_3 // RXPin PORT_Pin_1 // TXPin PORT_Pin_2 void clk_CoreConfig (uint32_t div, uint32_t mul); void button_Init (void); bool button_State (void); void PinInitA (PORT_OE_TypeDef mode, uint16_t pin); void LedInit (); void LedMorze (uint8_t *symbols); void LedWrite (bool on_off); int main() { uint8_t counter = 0, symbol_tx[8], symbol_rx[8], numbBit = 0, tempValue = 255; //clk_CoreConfig(RST_CLK_CPU_PLLsrcHSEdiv1, RST_CLK_CPU_PLLmul10); button_Init(); PinInitA(PORT_OE_OUT, TXPin); PinInitA(PORT_OE_IN, RXPin); PinInitA(PORT_OE_OUT, StrobePin1); PinInitA(PORT_OE_IN, StrobePin2); LedInit(); while(1) { if (PORT_ReadInputDataBit(MDR_PORTA, StrobePin2)) { ClearSymbol(symbol_rx); ReceiveSymbol(symbol_rx); LedMorze(symbol_rx); tempValue = MorzeToChar(symbol_rx); tempValue == 255 ? printf("Symbol is undefined! \n") : printf("Char: %c \n", tempValue); } // Read button while (!button_State()) { counter++; printf("DEBUG INFO: Counter = %d \n", counter); Delay(500); if (counter == 4) printf("DEBUG INFO: Completed char! \n"); } // Define sign if (counter > 0) { if (counter == 1) { symbol_tx[numbBit] = '.'; numbBit++; printf("DEBUG INFO: %s \n", symbol_tx); } else if (counter < 4) { symbol_tx[numbBit] = '-'; numbBit++; printf("DEBUG INFO: %s \n", symbol_tx); } else { for (numbBit; numbBit < 8; ++numbBit) symbol_tx[numbBit] = 'x'; } // If end symbol if (numbBit == 8) { numbBit = 0; TransmitSymbol(symbol_tx); tempValue = MorzeToChar(symbol_tx); tempValue == 255 ? printf("Symbol is undefined! \n") : printf("Char: %c \n", tempValue); } } if (counter != 0) { printf("numbSymb: %d \n", numbBit); } counter = 0; } } void LedMorze (uint8_t *symbols) { for (uint8_t i = 0; i < 8; ++i) { if (symbols[i] == '.') { LedWrite(1); Delay(500); } else if (symbols[i] == '-') { LedWrite(1); Delay(1500); } else { LedWrite(0); break; } LedWrite(0); Delay(500); } } void PinInitA(PORT_OE_TypeDef mode, uint16_t pin) { PORT_InitTypeDef PORT_InitStructure; PORT_InitStructure.PORT_OE = mode; PORT_InitStructure.PORT_FUNC = PORT_FUNC_PORT; PORT_InitStructure.PORT_MODE = PORT_MODE_DIGITAL; PORT_InitStructure.PORT_SPEED = PORT_SPEED_SLOW; PORT_InitStructure.PORT_Pin = (pin); PORT_Init(MDR_PORTA, &PORT_InitStructure); } void clk_CoreConfig(uint32_t div, uint32_t mul) { //Реинициализация настроек тактирования //RST_CLK_DeInit(); //Включение тактирования от внешнего источника HSE (High Speed External) RST_CLK_HSEconfig(RST_CLK_HSE_ON); //Проверка статуса HSE if (RST_CLK_HSEstatus() == ERROR) while (1); //Настройка делителя/умножителя частоты CPU_PLL(фазовая подстройка частоты) RST_CLK_CPU_PLLconfig(div, mul); //Включение CPU_PLL RST_CLK_CPU_PLLcmd(ENABLE); //Проверка статуса CPU_PLL if (RST_CLK_CPU_PLLstatus() == ERROR) while (1); //Коммутация выхода CPU_PLL на вход CPU_C3 RST_CLK_CPU_PLLuse(ENABLE); //Выбор источника тактирования ядра процессора RST_CLK_CPUclkSelection(RST_CLK_CPUclkCPU_C3); //Подача тактовой частоты на PORTC, PORTD RST_CLK_PCLKcmd(RST_CLK_PCLK_PORTC, ENABLE); RST_CLK_PCLKcmd(RST_CLK_PCLK_PORTD, ENABLE); } void button_Init(void) { //Создание структуры для инициализации порта PORT_InitTypeDef PORT_InitStructure; //Настройки порта: ввод, функция ввода/вывода, цифровой режим, минимальная скорость, Pin5 PORT_InitStructure.PORT_OE = PORT_OE_IN; PORT_InitStructure.PORT_FUNC = PORT_FUNC_PORT; PORT_InitStructure.PORT_MODE = PORT_MODE_DIGITAL; PORT_InitStructure.PORT_SPEED = PORT_SPEED_SLOW; PORT_InitStructure.PORT_Pin = (PORT_Pin_5); PORT_Init(MDR_PORTD, &PORT_InitStructure); } //Функция считывания текущего состояния кнопки SA4 bool button_State(void) { return PORT_ReadInputDataBit(MDR_PORTD, PORT_Pin_5); } void LedInit() { PORT_InitTypeDef PORT_InitStructure; PORT_InitStructure.PORT_OE = PORT_OE_OUT; PORT_InitStructure.PORT_FUNC = PORT_FUNC_PORT; PORT_InitStructure.PORT_MODE = PORT_MODE_DIGITAL; PORT_InitStructure.PORT_SPEED = PORT_SPEED_MAXFAST; PORT_InitStructure.PORT_Pin = (PORT_Pin_2); PORT_Init(MDR_PORTC, &PORT_InitStructure); } void LedWrite (bool on_off) { PORT_WriteBit(MDR_PORTC, PORT_Pin_2, on_off ? Bit_SET : Bit_RESET); }
[ "justiq.zhenya@gmail.com" ]
justiq.zhenya@gmail.com
b83a30f3c5722550af54808f8f71a24016faf10e
a78e1c5a6520c8c9965772889f58802fb26ac840
/Conch/include/common/util/JCIThreadCmdMgr.h
9d72fbe66033b7996682bebfe7e59424fbcfe802
[]
no_license
lvfulong/LayaNative-0.9.16
495c0fc4522a3dd34479e1ffd1e37c5c77b4a206
067d94a63a1917aee6802ab0675fc9efb74a5d9e
refs/heads/main
2023-03-20T05:41:38.738179
2021-03-02T02:14:10
2021-03-02T02:14:10
343,613,003
1
0
null
null
null
null
UTF-8
C++
false
false
488
h
 /** @file JCIThreadMgr.h @brief @author guo @version 1.0 @date 2016_5_19 */ #ifndef __JCIThreadMgr_H__ #define __JCIThreadMgr_H__ #include <functional> namespace laya { class IConchThreadCmdMgr { public: virtual void postToJS(const std::function<void(void)>& f) = 0; virtual void postToDownload(const std::function<void(void)>& f)=0; virtual void postToDecoder(const std::function<void(void)>& f)=0; }; } #endif //__JCIThreadMgr_H__
[ "775331175@qq.com" ]
775331175@qq.com
9a12a5d3a7ebff81747618abd917f3364740b6cc
34bdedfcfddfe090165a9072b3940604997b4843
/src_bst/bst_tree_get_max_width_probe_a.h
098d24e8544a0bbd9a175b4331c5ff17ade499ba
[]
no_license
innovatelogic/junk
84850baa589d11701b636a0f384c38f46edb1539
f6f36ac0a9cd6e0d978fe0621ddabd3f33b91638
refs/heads/master
2021-11-15T06:28:35.966336
2021-10-04T21:50:25
2021-10-04T21:56:16
63,451,848
0
0
null
null
null
null
UTF-8
C++
false
false
2,972
h
#pragma once #include <queue> #include <vector> namespace junk { namespace bst_max_width { struct Node { Node(int value) : value(value), left(nullptr), right(nullptr) {} int value; Node *left; Node *right; }; class BSTree { public: BSTree() : m_root(nullptr) {} ~BSTree() { clear(); } void insert(int value) { if (!m_root) { m_root = new Node(value); } else { Node *iter = m_root; while (iter) { if (value < iter->value) { if (!iter->left) { iter->left = new Node(value); return; } iter = iter->left; } else { if (!iter->right) { iter->right = new Node(value); return; } iter = iter->right; } } } } void clear() { std::queue<Node*> q; if (!m_root) { q.push(m_root); while (!q.empty()) { Node *top = q.front(); q.pop(); if (top->left) { q.push(top->left); } if (top->right) { q.push(top->right); } } } } size_t max_width() { size_t width = 0; if (m_root) { std::vector<Node*> v; v.push_back(m_root); while (!v.empty()) { if (v.size() > width) { width = v.size(); } std::vector<Node*> new_vec; for (size_t i = 0; i < v.size(); ++i) { if (v[i]->left) { new_vec.push_back(v[i]->left); } if (v[i]->right) { new_vec.push_back(v[i]->right); } } v = new_vec; } } return width; } private: Node *m_root; }; } }
[ "yura.gunko@gmail.com" ]
yura.gunko@gmail.com
cad7a008e9c522035d0e0a2793d7d55dde8a2f0f
7d6a7ca65e44e05104c73cc32ed72632042db123
/customview.h
c065a19c4cfeb3f3dae3fbdbfa67514fde6f48b5
[]
no_license
HeX-4pz/bugs
854349523b3f27ee2302b5beb33f27c83fe925b5
800bb3fbbafda0bec106ce0921257488b06c72e2
refs/heads/master
2020-06-27T18:56:13.382551
2019-08-01T09:52:22
2019-08-01T09:52:22
200,023,783
0
0
null
null
null
null
UTF-8
C++
false
false
498
h
#ifndef CUSTOMVIEW_H #define CUSTOMVIEW_H #include <QGraphicsView> #include <QWheelEvent> #include <QDebug> class CustomView : public QGraphicsView { Q_OBJECT public: CustomView(QWidget *parent = nullptr); CustomView(QGraphicsScene *scene, QWidget *parent = nullptr); public slots: void enterEvent(QEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void wheelEvent(QWheelEvent * event); }; #endif // CUSTOMVIEW_H
[ "shlapak4pz@gmail.com" ]
shlapak4pz@gmail.com
d394e5dbf34cbb1e6895ebc01935c11fead59748
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/FRUIncludesSoftwareFeature/UNIX_FRUIncludesSoftwareFeature_STUB.hxx
f19b9bcd588e2a9fa24d59aa3e8e86d2009766ae
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
147
hxx
#ifdef PEGASUS_OS_STUB #ifndef __UNIX_FRUINCLUDESSOFTWAREFEATURE_PRIVATE_H #define __UNIX_FRUINCLUDESSOFTWAREFEATURE_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
ba10077a149fb6ba6cd2fde6ede599d051eb2b2e
acc2f5336d768a7d86dbd2eec441283cfd11d52d
/src/Core/GCAddSlayerHandler.cpp
9e382f2961e32cdaaa047421bd185d2de5700844
[]
no_license
stevexk/server
86df9e8c2448ad97db9c3ab86820beec507ef092
4ddb6e7cfa510bb13ccd87f56db008aa1be1baad
refs/heads/master
2020-01-23T22:00:57.359964
2015-09-18T14:58:27
2015-09-18T14:58:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
634
cpp
//-------------------------------------------------------------------------------- // // Filename : GCAddSlayerHandler.cpp // Written By : Reiot // //-------------------------------------------------------------------------------- // include files #include "GCAddSlayer.h" //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- void GCAddSlayerHandler::execute (GCAddSlayer * pPacket , Player * pPlayer ) throw(Error ) { __BEGIN_TRY __BEGIN_DEBUG_EX #ifdef __GAME_CLIENT__ #endif __END_DEBUG_EX __END_CATCH }
[ "tiancaiamao@gmail.com" ]
tiancaiamao@gmail.com
a3461e3f51c57da6fdf73412f2e11593f5e3c27b
6ac39b4e919a3dce9846724039de3712d1a63060
/5th_Course/Semester1/Cryptography/Lab3/SHA-256/SHA-256/main.cpp
914245a145018497492bacf9619c88935bb7bd23
[]
no_license
egorlw26/UniversityLabs
27cf021901880f0cb7cea735e4d2ee85caff09af
b2fc21b0ac04063b0cae4573b6731f19941096e3
refs/heads/master
2021-07-14T18:26:11.427866
2021-03-02T21:25:17
2021-03-02T21:25:17
236,180,512
0
0
null
null
null
null
UTF-8
C++
false
false
271
cpp
#include "SHA_256.h" int main() { // abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq std::string msgToHash = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; SHA_256 sha = SHA_256(msgToHash); sha.showResultHash(); return 0; }
[ "egorlw26@gmail.com" ]
egorlw26@gmail.com
e5e5be8111689f050f48cbe09112b6764080aec1
dc6f3df2c3fde15d5c157e58251cdf9401d58db8
/CS148/HW/hw1/hw1_ellipse.cpp
f97f059fe42dad7efd66461a3f6d9e70ee49879c
[]
no_license
xavi1989/cs231n
1888a642dc912623f33afaa69172839c93a6cd86
be23c07888d0dc4d2b0549985f1fa5f31b725c78
refs/heads/master
2020-04-15T14:36:12.594198
2018-01-24T19:21:50
2018-01-24T19:21:50
55,452,259
0
6
null
2016-04-25T21:17:37
2016-04-04T23:17:56
Jupyter Notebook
UTF-8
C++
false
false
3,341
cpp
/******************************************************* * Homework 1: Rasterization * * CS 148 (Summer 2016), Stanford University * *-----------------------------------------------------* * Here you will implement the circle rasterization * * method you derived in the written portion of the * * homework. * * To compile this in linux: * * g++ hw1.cpp * * Then, run the program as follows: * * ./a.out 200 * * to generate a 200x200 image containing a circular * * arc. Note that the coordinate system we're using * * places pixel centers at integer coordinates and * * has the origin at the lower left. * * Your code will generate a .ppm file containing the * * final image. These images can be viewed using * * "display" in Linux or Irfanview in Mac/Windows. * *******************************************************/ #include <iostream> #include <fstream> #include <cstdio> #include <cassert> using namespace std; // We'll store image info as globals; not great programming practice // but ok for this short program. int a; int b; bool **image; void renderPixel(int x, int y) { assert(x >= 0 && y >= 0 && x <= 2*a && y <= 2*b); image[y][x] = 1; // TODO: light up the pixel's symmetric counterpart image[2*b - y][x] = 1; image[2*b - y][2*a - x] = 1; image[y][2*a - x] = 1; } void rasterizeArc() { // TODO: rasterize the arc using renderPixel to light up pixels int x = a; int y = 2*b; int d = 4*b*b+a*a-4*a*a*b; renderPixel(x, y); while((x-a)*b*b <= (y-b)*a*a) { if(d < 0) { d += (8*(x-a)+12)*b*b; // select E } else { d += (8*(x-a) + 12)*b*b - (8*(y-b)-12)*a*a; // select SE y--; } x++; renderPixel(x, y); } while((x-a)*b*b > (y-b)*a*a) { if(d < 0) { d += (8*(x-a)+8)*b*b - (8*(y-b)-12)*a*a; // select SE2 x++; } else { d += -(8*(y-b)-12)*a*a; // select SE } if(y > b+1) y--; if(x >= 2*a && y >= b) break; renderPixel(x, y); } } // You shouldn't need to change anything below this point. int main(int argc, char *argv[]) { if (argc != 3) { cout << "Usage: " << argv[0] << " a b\n"; return 0; } #ifdef _WIN32 sscanf_s(argv[1], "%d", &a); sscanf_s(argv[2], "%d", &b); #else sscanf(argv[1], "%d", &a); sscanf(argv[2], "%d", &b); #endif if (a <= 0 || b<=0) { cout << "Image must be of positive size.\n"; return 0; } if(a <= b) { cout << "specify ellipse with a > b\n"; return 0; } // reserve image as 2d array image = new bool*[2*a+1]; for (int i = 0; i <= 2*b; i++) image[i] = new bool[2*a+1]; rasterizeArc(); char filename[50]; #ifdef _WIN32 sprintf_s(filename, 50, "ellispe%dx%d.ppm", a, b); #else sprintf(filename, "circle%dx%d.ppm", a, b); #endif ofstream outfile(filename); outfile << "P3\n# " << filename << "\n"; outfile << 2*a+1 << ' ' << 2*b+1 << ' ' << 1 << endl; for (int i = 0; i <= 2*b; i++) for (int j = 0; j <= 2*a; j++) { outfile << image[2*b-i][j] << " 0 0\n"; } // delete image data for (int i = 0; i <= 2*b; i++) delete [] image[i]; delete [] image; return 0; }
[ "wei.xia1989@gmail.com" ]
wei.xia1989@gmail.com
9f544a11c3cedc764eeb7da3aecaac020a1ea140
a867ee960d327175709cbaf305031ec966daa5b0
/ModelCPlusPLus/ModelCPlusPLus.cpp
beecef71b09634696562551ade6b6a1084cfb502
[]
no_license
adrianmo14857/projektKPSS
07aa5ca4568097972fc483e664ebe0fa97794b15
a23d402a912d54a8e55baae76d2c16323f48e6e3
refs/heads/master
2020-09-08T19:40:01.050122
2019-11-08T10:49:56
2019-11-08T10:49:56
221,227,508
0
0
null
2019-11-12T13:43:11
2019-11-12T13:43:10
null
UTF-8
C++
false
false
1,223
cpp
// ModelCPlusPLus.cpp : Ten plik zawiera funkcję „main”. W nim rozpoczyna się i kończy wykonywanie programu. // #include "pch.h" #include <iostream> int main() { int Fzm = 25; //Strumien ogrzanej wody od 0 do ok. 22 int To = 5; //Temperatura zewnetrzna int Tpm = 5; //woda wracajaca do elektrowni int Tzco = 46.25; //woda idąca do budynku while (1) { } } // Uruchomienie programu: Ctrl + F5 lub menu Debugowanie > Uruchom bez debugowania // Debugowanie programu: F5 lub menu Debugowanie > Rozpocznij debugowanie // Porady dotyczące rozpoczynania pracy: // 1. Użyj okna Eksploratora rozwiązań, aby dodać pliki i zarządzać nimi // 2. Użyj okna programu Team Explorer, aby nawiązać połączenie z kontrolą źródła // 3. Użyj okna Dane wyjściowe, aby sprawdzić dane wyjściowe kompilacji i inne komunikaty // 4. Użyj okna Lista błędów, aby zobaczyć błędy // 5. Wybierz pozycję Projekt > Dodaj nowy element, aby utworzyć nowe pliki kodu, lub wybierz pozycję Projekt > Dodaj istniejący element, aby dodać istniejące pliku kodu do projektu // 6. Aby w przyszłości ponownie otworzyć ten projekt, przejdź do pozycji Plik > Otwórz > Projekt i wybierz plik sln
[ "cz.piotreek@gmail.com" ]
cz.piotreek@gmail.com
16f1a8b6f65b712abd021936881359d2168b9943
baddd2f9e568a74844d95c1ac80d722c962417e9
/auxlib.cpp
be214c8429deb102922f350ade06ed97739fc6e0
[]
no_license
HUOd/Compiler-Design
388297745d2e3e00dd918aaa1543120aa90f0fe0
4ccabba3dd5030177cd3bf3b2b771984d5652603
refs/heads/master
2020-03-19T19:20:41.010362
2018-06-10T23:19:14
2018-06-10T23:19:14
136,851,049
0
0
null
null
null
null
UTF-8
C++
false
false
2,973
cpp
// $Id: auxlib.cpp,v 1.3 2017-10-11 14:28:14-07 - - $ #include <assert.h> #include <errno.h> #include <libgen.h> #include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wait.h> #include "auxlib.h" string exec::execname; int exec::exit_status = EXIT_SUCCESS; const char* debugflags = ""; bool alldebugflags = false; static void eprint_signal (const char* kind, int signal) { eprintf (", %s %d", kind, signal); const char* sigstr = strsignal (signal); if (sigstr != nullptr) fprintf (stderr, " %s", sigstr); } void eprint_status (const char* command, int status) { if (status == 0) return; eprintf ("%s: status 0x%04X", command, status); if (WIFEXITED (status)) { eprintf (", exit %d", WEXITSTATUS (status)); } if (WIFSIGNALED (status)) { eprint_signal ("Terminated", WTERMSIG (status)); #ifdef WCOREDUMP if (WCOREDUMP (status)) eprintf (", core dumped"); #endif } if (WIFSTOPPED (status)) { eprint_signal ("Stopped", WSTOPSIG (status)); } if (WIFCONTINUED (status)) { eprintf (", Continued"); } eprintf ("\n"); } void veprintf (const char* format, va_list args) { //assert (exec::execname.size() != 0); assert (format != nullptr); fflush (nullptr); if (strstr (format, "%:") == format) { fprintf (stderr, "%s: ", exec::execname.c_str()); format += 2; } vfprintf (stderr, format, args); fflush (nullptr); } void eprintf (const char* format, ...) { va_list args; va_start (args, format); veprintf (format, args); va_end (args); } void errprintf (const char* format, ...) { va_list args; va_start (args, format); veprintf (format, args); va_end (args); exec::exit_status = EXIT_FAILURE; } void syserrprintf (const char* object) { errprintf ("%:%s: %s\n", object, strerror (errno)); } void __stubprintf (const char* file, int line, const char* func, const char* format, ...) { va_list args; fflush (nullptr); printf ("%s: %s[%d] %s: ", exec::execname.c_str(), file, line, func); va_start (args, format); vprintf (format, args); va_end (args); fflush (nullptr); } void set_debugflags (const char* flags) { debugflags = flags; assert (debugflags != nullptr); if (strchr (debugflags, '@') != nullptr) alldebugflags = true; DEBUGF ('x', "Debugflags = \"%s\", all = %d\n", debugflags, alldebugflags); } bool is_debugflag (char flag) { return alldebugflags or strchr (debugflags, flag) != nullptr; } void __debugprintf (char flag, const char* file, int line, const char* func, const char* format, ...) { va_list args; if (not is_debugflag (flag)) return; fflush (nullptr); va_start (args, format); fprintf (stderr, "DEBUGF(%c): %s[%d] %s():\n", flag, file, line, func); vfprintf (stderr, format, args); va_end (args); fflush (nullptr); }
[ "hrd2017ce@gmail.com" ]
hrd2017ce@gmail.com
4c8f5b4d427ba32b68a09be27163033bd11f8873
527739ed800e3234136b3284838c81334b751b44
/include/RED4ext/Types/generated/work/WorkspotAnimsetEntry.hpp
f4180e18f6f7ef35860cd97bdb12548a9273d84c
[ "MIT" ]
permissive
0xSombra/RED4ext.SDK
79ed912e5b628ef28efbf92d5bb257b195bfc821
218b411991ed0b7cb7acd5efdddd784f31c66f20
refs/heads/master
2023-07-02T11:03:45.732337
2021-04-15T16:38:19
2021-04-15T16:38:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
825
hpp
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/DynArray.hpp> #include <RED4ext/Types/SimpleTypes.hpp> #include <RED4ext/Types/generated/anim/AnimSetup.hpp> namespace RED4ext { namespace anim { struct AnimSet; } namespace anim { struct Rig; } namespace work { struct WorkspotAnimsetEntry { static constexpr const char* NAME = "workWorkspotAnimsetEntry"; static constexpr const char* ALIAS = NAME; uint8_t unk00[0x8 - 0x0]; // 0 RaRef<anim::Rig> rig; // 08 anim::AnimSetup animations; // 10 DynArray<Ref<anim::AnimSet>> loadingHandles; // 30 uint8_t unk40[0x70 - 0x40]; // 40 }; RED4EXT_ASSERT_SIZE(WorkspotAnimsetEntry, 0x70); } // namespace work } // namespace RED4ext
[ "expired6978@gmail.com" ]
expired6978@gmail.com
c379043e1fd48ea0ce46da58d3731addcc5e21d4
6e69eaf63109c10d434e5c8dcd4ffa16df26e2eb
/.old/engine/include/StateInput.h
5eed9960b3a5a046fe364fe1e5ff3833e19d2397
[]
no_license
UIKit0/dont-stop-running
5e390473f6130724a0a9989d90c8376e00ef1fbd
89635714375234dc3365b468ad27a9f76295d7fb
refs/heads/master
2021-01-15T21:29:18.999842
2015-01-31T13:35:38
2015-01-31T13:35:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,212
h
#pragma clang diagnostic push #pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection" #pragma once #include "Constants.h" #include "Memory.h" namespace engine { class Vec2; class InputEventHandler; // todo: add support for gamepads struct StateInput { StateInput(); ~StateInput(); /** * Returns the current mouse position. */ Vec2 getMousePosition(); /** * Returns true if the argument key was pressed this frame */ bool keyWasPressed(Key key); /** * Returns true if the argument key was released this frame */ bool keyWasReleased(Key key); /** * Returns true if the argument key is pressed */ bool keyIsDown(Key key); /** * Returns true if the argument mouse button is pressed */ bool mouseButtonIsDown(MouseButton button); /** * Register this event handler with the input system to sync the */ InputEventHandler *getEventHandler(); private: struct Implementation; std::unique_ptr<Implementation> impl; }; } #pragma clang diagnostic pop
[ "astronothing@gmail.com" ]
astronothing@gmail.com
d1c604da6f715babc7a810691f5aed5c81663172
fce0d1bf8e69505c67be0f929194e1d8a7475ebf
/Analyzer/BDT/Trial/v03_RemovePairSel/TreeMaker/BDTInputTreeProducer.h
c8f68a4203c7c88b62a17a64d229bac1d35d0159
[]
no_license
KyeongPil-Lee/DYScouting
e86ccfbb8fad60554f4e5a152ced9db9d013a162
9150e3aa82ef5dc11de83728f65ebc62304c472b
refs/heads/master
2021-12-19T08:53:46.435674
2021-12-06T18:29:09
2021-12-06T18:29:09
214,085,816
0
0
null
null
null
null
UTF-8
C++
false
false
5,928
h
#include <TChain.h> #include <TFile.h> #include <TH1D.h> #include <TH2D.h> #include <TLorentzVector.h> #include <TStopwatch.h> #include <TTimeStamp.h> #include <TString.h> #include <TLegend.h> #include <THStack.h> #include <TPad.h> #include <TCanvas.h> #include <TColor.h> #include <TAttMarker.h> #include <TF1.h> #include <TStyle.h> #include <TEfficiency.h> #include <vector> #include <Include/DYTool.h> class TreeProducer: public DYTool::ClassTemplate { public: TreeProducer(): ClassTemplate() { } void Run() { CheckSampleInfo(); StartTimer(); InitSetup(); TChain *chain = new TChain("DYTree/ntuple"); DYTool::AddNtupleToChain(chain, sampleInfo_.ntuplePathFile); DYTool::DYTree *ntuple = new DYTool::DYTree( chain ); Int_t nEvent = chain->GetEntries(); cout << "\t[Total Events: " << nEvent << "]" << endl; for(Int_t i=0; i<nEvent; i++) { DYTool::loadBar(i+1, nEvent, 100, 100); ntuple->GetEvent(i); // -- only DY->mumu or DY->ee events according to its name -- // if( DYTool::SelectGenEventBySampleType(sampleInfo_.type, ntuple) ) { Bool_t isDYEvent = kFALSE; vector<DYTool::MuPair> vec_DYMuPair = DYTool::EventSelection_BDTInput_Loose_noPairSel(ntuple, isDYEvent); if( isDYEvent ) { for( auto& DYMuPair: vec_DYMuPair ) // -- fill all pairs { if( DYMuPair.mass > 50.0 ) continue; // -- because the DY sample is truncated at M=50 GeV if( sampleInfo_.type.Contains("DYMuMu") && !DYTool::GenRecoMatching(DYMuPair, ntuple) ) continue; // -- for the signal, only pair passing gen-reco matching is used (1 pair per event) diMuM_ = DYMuPair.mass; diMuRap_ = DYMuPair.rap; diMuPt_ = DYMuPair.pt; diMuNormVtxChi2_ = DYMuPair.normVtxChi2; diMuDEta_ = DYMuPair.dEta; diMuDPhi_ = DYMuPair.dPhi; diMuOS_ = (Int_t)DYMuPair.isOS; caloMET_pt_ = ntuple->caloMET_pt; caloMET_phi_ = ntuple->caloMET_phi; nMuonHit_lead_ = DYMuPair.first_.nMuonHit; nMatchedStation_lead_ = DYMuPair.first_.nMatchedStation; nPixelHit_lead_ = DYMuPair.first_.nPixelHit; nTrackerLayer_lead_ = DYMuPair.first_.nTrackerLayer; normChi2_lead_ = DYMuPair.first_.normChi2; relTrkIso_lead_ = DYMuPair.first_.relTrkIso; nMuonHit_sub_ = DYMuPair.second_.nMuonHit; nMatchedStation_sub_ = DYMuPair.second_.nMatchedStation; nPixelHit_sub_ = DYMuPair.second_.nPixelHit; nTrackerLayer_sub_ = DYMuPair.second_.nTrackerLayer; normChi2_sub_ = DYMuPair.second_.normChi2; relTrkIso_sub_ = DYMuPair.second_.relTrkIso; tree_->Fill(); } } } } TString fileName = "ROOTFile_BDTInputTree_"+sampleInfo_.type+".root"; TFile *f_output = TFile::Open(fileName, "RECREATE"); f_output->cd(); tree_->Write(); f_output->Close(); PrintRunTime(); } private: TTree *tree_; Double_t diMuM_; Double_t diMuRap_; Double_t diMuPt_; Double_t diMuNormVtxChi2_; Double_t diMuDEta_; Double_t diMuDPhi_; Int_t diMuOS_; Double_t caloMET_pt_; Double_t caloMET_phi_; // -- single muon variables // -- leading muon Int_t nMuonHit_lead_; Int_t nMatchedStation_lead_; Int_t nPixelHit_lead_; Int_t nTrackerLayer_lead_; Double_t normChi2_lead_; Double_t relTrkIso_lead_; // -- sub-leading muon Int_t nMuonHit_sub_; Int_t nMatchedStation_sub_; Int_t nPixelHit_sub_; Int_t nTrackerLayer_sub_; Double_t normChi2_sub_; Double_t relTrkIso_sub_; void InitSetup() { InitVar(); tree_ = new TTree("BDTInput", "BDT input tree"); tree_->Branch("diMuM", &diMuM_, "diMuM/D"); tree_->Branch("diMuRap", &diMuRap_, "diMuRap/D"); tree_->Branch("diMuPt", &diMuPt_, "diMuPt/D"); tree_->Branch("diMuNormVtxChi2", &diMuNormVtxChi2_, "diMuNormVtxChi2/D"); tree_->Branch("diMuDEta", &diMuDEta_, "diMuDEta/D"); tree_->Branch("diMuDPhi", &diMuDPhi_, "diMuDPhi/D"); tree_->Branch("diMuOS", &diMuOS_, "diMuOS/I"); tree_->Branch("caloMET_pt", &caloMET_pt_, "caloMET_pt/D"); tree_->Branch("caloMET_phi", &caloMET_phi_, "caloMET_phi/D"); tree_->Branch("nMuonHit_lead", &nMuonHit_lead_, "nMuonHit_lead/I"); tree_->Branch("nMatchedStation_lead", &nMatchedStation_lead_, "nMatchedStation_lead/I"); tree_->Branch("nPixelHit_lead", &nPixelHit_lead_, "nPixelHit_lead/I"); tree_->Branch("nTrackerLayer_lead", &nTrackerLayer_lead_, "nTrackerLayer_lead/I"); tree_->Branch("normChi2_lead", &normChi2_lead_, "normChi2_lead/D"); tree_->Branch("relTrkIso_lead", &relTrkIso_lead_, "relTrkIso_lead/D"); tree_->Branch("nMuonHit_sub", &nMuonHit_sub_, "nMuonHit_sub/I"); tree_->Branch("nMatchedStation_sub", &nMatchedStation_sub_, "nMatchedStation_sub/I"); tree_->Branch("nPixelHit_sub", &nPixelHit_sub_, "nPixelHit_sub/I"); tree_->Branch("nTrackerLayer_sub", &nTrackerLayer_sub_, "nTrackerLayer_sub/I"); tree_->Branch("normChi2_sub", &normChi2_sub_, "normChi2_sub/D"); tree_->Branch("relTrkIso_sub", &relTrkIso_sub_, "relTrkIso_sub/D"); } void InitVar() { diMuM_ = 0; diMuRap_ = 0; diMuPt_ = 0; diMuNormVtxChi2_ = 0; diMuDEta_ = 0; diMuDPhi_ = 0; diMuOS_ = 0; caloMET_pt_ = 0; caloMET_phi_ = 0; // -- single muon variables // -- leading muon nMuonHit_lead_ = 0; nMatchedStation_lead_ = 0; nPixelHit_lead_ = 0; nTrackerLayer_lead_ = 0; normChi2_lead_ = 0; relTrkIso_lead_ = 0; // -- sub-leading muon nMuonHit_sub_ = 0; nMatchedStation_sub_ = 0; nPixelHit_sub_ = 0; nTrackerLayer_sub_ = 0; normChi2_sub_ = 0; relTrkIso_sub_ = 0; } };
[ "kplee@cern.ch" ]
kplee@cern.ch
7982e371b315ba77afaa87758a94c385a414ef28
d3d1d7d99054b8684ed5fc784421024050a95c79
/spoj/pt07x.cpp
c1afa09b1f62f6d31f08a487f0bc486b363c11fc
[]
no_license
rishabhSharmaOfficial/CompetitiveProgramming
76e7ac3f8fe8c53599e600fc2df2520451b39710
85678a6dc1ee437d917adde8ec323a55a340375e
refs/heads/master
2023-04-28T05:51:18.606350
2021-05-15T07:04:33
2021-05-15T07:04:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,978
cpp
#include<bits/stdc++.h> #define ll long long int #define ld long double #define pi pair<int,int> #define all(x) x.begin(), x.end() #define allr(x) x.rbegin(), x.rend() #define sz(x) ((int)x.size()) #define ln(x) ((int)x.length()) #define mp make_pair #define pb push_back #define ff first #define ss second #define endl '\n' #define dbg(x) cout << #x << ": " << x << endl #define clr(x,v) memset(x, v, sizeof(x)) #define dblout(x) cout << setprecision(x) << fixed; #define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; const double eps = 1e-9; const double PI = acos(-1.0); const ll mod = 1e9 + 7; const int MAXN = 1e5 + 5; int dp[MAXN][2]; int dfs(int u, int par, int have_choice, vector<vector<int>> &adj) { int &ret = dp[u][have_choice]; if(~ret) return ret; int ans = 2 * MAXN; if(have_choice) { //choose to include me, have_choice for children int c1 = 1; for(int v : adj[u]) if(v != par) c1 += dfs(v, u, 1, adj); //dont include me, no choice but to include children int c2 = 0; for(int v : adj[u]) if(v != par) c2 += dfs(v, u, 0, adj); ans = min(c1, c2); } else { //no choice but to include me, have choice for children ans = 1; for(int v : adj[u]) if(v != par) ans += dfs(v, u, 1, adj); } return ret = ans; } void cp() { int n; cin >> n; vector<vector<int>> adj(n + 1); for(int i = 0, u, v; i < n - 1; i++) cin >> u >> v, adj[u].pb(v), adj[v].pb(u); int root = -1; for(int i = 1; i <= n; i++) if(sz(adj[i]) <= 1) root = i; clr(dp, -1); int ans = min(dfs(root, root, 0, adj), dfs(root, root, 1, adj)); cout << ans << endl; } int main() { FASTIO; int t; t = 1; // cin >> t; while(t--) { cp(); } return 0; }
[ "pranav.sindura@gmail.com" ]
pranav.sindura@gmail.com
ac0b3d5597a5bb47882a108ffbe7be166e75880c
a18362424d796737ba13f6279f68dd078170d13a
/leetcode/p851.cpp
95670a996ccc7200695d0ac78ffc971ac3c949c1
[]
no_license
liaobnb/Byteme
d11195f8ce3d615a34dfad31fe0867a38d7a7f59
9b6391b15d6ec241299704e06ac085d3ab632294
refs/heads/master
2020-04-14T15:23:31.868867
2019-01-03T01:22:06
2019-01-03T01:22:06
163,924,954
1
0
null
2019-01-03T04:56:17
2019-01-03T04:56:17
null
UTF-8
C++
false
false
973
cpp
#include <bits/stdc++.h> using namespace std; vi quiet; unordered_map<int, vi> mp; int cache[520]; int dfs(int x) { // If we can not make sure which person has more money. if (!mp.count(x)) return x; if (cache[x]) return cache[x]; vi g = mp[x]; int least = quiet[x]; int least_idx = x; fori(i, 0, sz(g)) { int t = dfs(g[i]); cache[g[i]] = t; if (quiet[t] < least) { least = quiet[t]; least_idx = t; } } return least_idx; } class Solution { public: vector<int> loudAndRich(vvi& richer, vi& q) { quiet = q; int n = sz(q); mp.clear(); mst(cache, 0); fora (v, richer) { int lo = v[1], hi = v[0]; mp[lo].pb(hi); } fora(it, mp) { vi g = it.se; cout << it.fi << ": "; pvi(g); } vi res; fori(i, 0, sz(q)) { int r; if (cache[i] > 0) r = cache[i]; else r = dfs(i); res.pb(r); } return res; } }; int main() { return 0; }
[ "landcold7@gmail.com" ]
landcold7@gmail.com