text
stringlengths 8
6.88M
|
|---|
#include "stdafx.h"
#include "Game.h"
#include "Engine.h"
#include "NewGame.h"
//#define OLDGAME
int main(int argc, char *argv[])
{
if ( gEngine.Init() )
{
#ifdef OLDGAME
gGame.Init();
#else
NewGame game;
game.Init();
#endif
while ( !gEngine.IsExit() )
{
gEngine.Update();
#ifdef OLDGAME
gGame.Update(gEngine.GetDeltaTime());
#else
game.Update(gEngine.GetDeltaTime());
#endif
gEngine.BeginFrame();
#ifdef OLDGAME
gGame.Render();
#else
game.Draw();
#endif
gEngine.EndFrame();
}
#ifndef OLDGAME
game.Close();
#endif
}
gEngine.Close();
return 0;
}
|
#include <UECS/EntityFilter.h>
using namespace Ubpa::UECS;
EntityFilter::EntityFilter()
:
allHashCode{ TypeID<EntityFilter> },
anyHashCode{ TypeID<EntityFilter> },
noneHashCode{ TypeID<EntityFilter> },
combinedHashCode{ hash_combine(std::array<size_t, 3>{TypeID<EntityFilter>, TypeID<EntityFilter>, TypeID<EntityFilter>}) }
{
}
EntityFilter::EntityFilter(
std::set<CmptType> allCmptTypes,
std::set<CmptType> anyCmptTypes,
std::set<CmptType> noneCmptTypes)
:
allCmptTypes{ move(allCmptTypes) },
anyCmptTypes{ move(anyCmptTypes) },
noneCmptTypes{ move(noneCmptTypes) },
allHashCode{ GenAllHashCode() },
anyHashCode{ GenAnyHashCode() },
noneHashCode{ GenNoneHashCode() },
combinedHashCode{ GenCombinedHashCode()}
{
}
void EntityFilter::InsertAll(const CmptType* types, size_t num) {
assert(types != nullptr);
for (size_t i = 0; i < num; i++)
allCmptTypes.insert(types[i]);
allHashCode = GenAllHashCode();
combinedHashCode = GenCombinedHashCode();
}
void EntityFilter::InsertAny(const CmptType* types, size_t num) {
assert(types != nullptr);
for (size_t i = 0; i < num; i++)
anyCmptTypes.insert(types[i]);
anyHashCode = GenAnyHashCode();
combinedHashCode = GenCombinedHashCode();
}
void EntityFilter::InsertNone(const CmptType* types, size_t num) {
assert(types != nullptr);
for (size_t i = 0; i < num; i++)
noneCmptTypes.insert(types[i]);
noneHashCode = GenNoneHashCode();
combinedHashCode = GenCombinedHashCode();
}
void EntityFilter::EraseAll(const CmptType* types, size_t num) {
assert(types != nullptr);
for (size_t i = 0; i < num; i++)
allCmptTypes.erase(types[i]);
allHashCode = GenAllHashCode();
combinedHashCode = GenCombinedHashCode();
}
void EntityFilter::EraseAny(const CmptType* types, size_t num) {
assert(types != nullptr);
for (size_t i = 0; i < num; i++)
anyHashCode = GenAnyHashCode();
combinedHashCode = GenCombinedHashCode();
}
void EntityFilter::EraseNone(const CmptType* types, size_t num) {
assert(types != nullptr);
for (size_t i = 0; i < num; i++)
noneCmptTypes.erase(types[i]);
noneHashCode = GenNoneHashCode();
combinedHashCode = GenCombinedHashCode();
}
size_t EntityFilter::GenAllHashCode() const noexcept {
size_t rst = TypeID<EntityFilter>;
for (auto type : allCmptTypes) {
rst = hash_combine(rst, type.HashCode());
}
return rst;
}
size_t EntityFilter::GenAnyHashCode() const noexcept {
size_t rst = TypeID<EntityFilter>;
for (auto type : anyCmptTypes) {
rst = hash_combine(rst, type.HashCode());
}
return rst;
}
size_t EntityFilter::GenNoneHashCode() const noexcept {
size_t rst = TypeID<EntityFilter>;
for (auto type : noneCmptTypes) {
rst = hash_combine(rst, type.HashCode());
}
return rst;
}
size_t EntityFilter::GenCombinedHashCode() const noexcept {
return hash_combine(std::array<size_t, 3>{allHashCode, anyHashCode, noneHashCode});
}
bool EntityFilter::operator==(const EntityFilter& filter) const noexcept {
return allCmptTypes == filter.allCmptTypes
&& anyCmptTypes == filter.anyCmptTypes
&& noneCmptTypes == filter.noneCmptTypes;
}
|
#pragma once
#include <map>
#include <string>
class SensorParameter {
public:
enum class SensorType {
PHONE_GYROSCOPE,
PHONE_ACCELEROMETER,
AX3_ACCELEROMETER,
LOCATION,
GPS_LOC };
static std::map<std::string, SensorType> mapping;
static constexpr const char* DEFAULT_TYPE_STRING = "ax3";
protected:
SensorParameter(const std::string& type);
private:
SensorType type;
static auto generateMapping() -> void;
public:
SensorParameter(SensorType type);
virtual ~SensorParameter() = default;
static auto knownSensors() -> std::string;
auto isGyro() const -> bool;
auto isLocation() const -> bool;
auto isAcceleration() const -> bool;
auto getType() const { return type; }
};
|
// I write a code that cannot slove the unique issue.
// If I use a set to filter the result, then it cause time out. The attached is my code without "unique" property
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
vector<int> container;
helper(res, container, nums, 0);
return res;
}
void helper(vector<vector<int>>& res, vector<int>& container, vector<int> nums, int cur)
{
if(container.size() == 3)
{
if(container[0] + container[1] + container[2] == 0)
res.push_back(container);
return;
}
for(int i = cur; i < nums.size(); i++)
{
container.push_back(nums[i]);
helper(res, container, nums, i + 1);
container.pop_back();
}
}
};
// Acturally we do not need the recurive solution, simply brute force it. The code is as attached.
// The trick is we do not need N^3 solutoin, we can use two iterators to go in both sides.
// A thinking is whenever we have value problems, we can always sort and then go in both sides.
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i++)
{
if(i != 0 && nums[i] == nums[i - 1])
continue;
int target = 0 - nums[i];
int j = i + 1; int k = nums.size() - 1;
while(j < k)
{
vector<int> container;
if(j != i + 1 && nums[j] == nums[j - 1])
{
j++;
continue;
}
else if(k != nums.size() - 1 && nums[k] == nums[k + 1])
{
k--;
continue;
}
else if(nums[j] + nums[k] == target)
{
container.push_back(nums[i]);
container.push_back(nums[j]);
container.push_back(nums[k]);
res.push_back(container);
j++;
k--;
}
else if(nums[j] + nums[k] + nums[i] < 0)
j++;
else
k--;
}
}
return res;
}
};
|
#include <Arduino.h>
#include <WiFi.h>
// #include "wolfssl/wolfcrypt/srp.h"
// #include <Crypto.h>
#include <os.h>
#include "utils/srp.h"
#include "utils/tlv.h"
#include "mdns.h"
#include "esp_wifi.h"
//this include is in gitignore, store security credentials there
#include "access/access.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "hap/hap_defines.h"
#include "accessory/accessory.hpp"
// #include "Ed25519.h"
// #include "utils/mongoose.h"
#include "utils/httpd.h"
#include "security/ed25519/src/ed25519.h"
// #include "hap/src/hap.h"
#define PORT 811
//SERVICE
#define HAP_SERVICE "_hap"
#define HAP_PROTO "_tcp"
#define DEVICE_NAME "RGBLight"
static const char *header_fmt =
"HTTP/1.1 200 OK\r\n"
"Content-Length: %d\r\n"
"Content-Type: application/pairing+tlv8\r\n"
"\r\n";
#define SRP_SALT_LENGTH 16
#include "stdio.h"
const int WIFI_CONNECTED_BIT = BIT0;
static EventGroupHandle_t wifi_event_group;
void *bindb;
srp_context_t serverSrp;
srp_context_t clientSrp;
WiFiServer server(PORT);
mg_connection *newNC;
void mdns_setup()
{
esp_err_t status = mdns_init();
// delay(2000);
if (status) {
Serial.println("Error mdns_init");
}
else {
Serial.println("mdns_init ok...");
}
status = mdns_hostname_set("led");
// delay(1000);
if (status) {
Serial.println("Error mdns_hostname_set");
}
else {
Serial.println("mdns_hostname_set ok...");
}
// delay(1000);
status = mdns_instance_name_set(DEVICE_NAME);
if (status) {
Serial.println("Error mdns_instance_name_set");
}
else {
Serial.println("mdns_instance_name_set ok...");
}
// delay(1000);
status = mdns_service_add(DEVICE_NAME, HAP_SERVICE, HAP_PROTO, PORT, NULL, 0);
if (status) {
Serial.println("Error mdns_service_add");
}
else {
Serial.println("mdns_service_add ok...");
}
uint8_t mac[6];
esp_wifi_get_mac(ESP_IF_WIFI_STA, mac);
char accessory_id[32] = {0,};
sprintf(accessory_id, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
Serial.print("Accessory ID: ");
Serial.print(accessory_id);
Serial.println("");
char pairState[4];
char category[4];
memset(pairState, 0, sizeof(pairState));
sprintf(pairState, "%d", 1);
memset(category, 0, sizeof(category));
sprintf(category, "%d", HAP_ACCESSORY_CATEGORY_LIGHTBULB);
mdns_txt_item_t hap_service_txt[8] = {
{(char *)"c#", (char *)"1.0"},
{(char *)"ff", (char *)"0"},
{(char *)"pv", (char *)"1.0"},
{(char *)"id", (char *)accessory_id},
{(char *)"md", (char *)DEVICE_NAME},
{(char *)"s#", (char *)"1"},
{(char *)"sf", (char *)pairState},
{(char *)"ci", (char *)category},
};
// delay(1000);
status = mdns_service_txt_set(HAP_SERVICE, HAP_PROTO, hap_service_txt, 8);
if (status)
{
Serial.println("Error mdns_service_txt_set");
}
else
{
Serial.println("mdns_service_txt_set ok...");
}
}
void wifi_setup() {
delay(1000);
Serial.println("Connecting to network");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(100);
}
WiFi.enableIpV6();
delay(2000);
Serial.println("");
Serial.print("Connected to ");
Serial.print(WIFI_SSID);
Serial.print(" with IPv4: ");
Serial.print(WiFi.localIP());
Serial.print(" with IPv6: ");
Serial.print(WiFi.localIPv6());
Serial.println("");
}
static int _verify() {
}
void create_srp() {
srp_init(NULL, 0);
// mbedtls_mpi *salt;
Serial.println("srp_set_username");
serverSrp = srp_new_server(SRP_TYPE_3072, SRP_CRYPTO_HASH_ALGORITHM_SHA512);
srp_set_username(serverSrp, "Pair-Setup");
Serial.println("srp_set_auth_password");
// srp_set_params(serverSrp, NULL, NULL, salt);
const unsigned char *t = reinterpret_cast<const unsigned char *>(LIGHTS_CODE);
srp_set_auth_password(serverSrp, t, strlen(LIGHTS_CODE));
// srp_set_params(serverSrp, NULL, NULL, tlv_salt);
Serial.println("srp_gen_pub");
srp_gen_pub(serverSrp);
}
static int _setup_m2(struct pair_setup *ps,
uint8_t *device_msg, int device_msg_length,
uint8_t** acc_msg, int* acc_msg_length)
{
Serial.println("init SRP");
Serial.println("srp_get_public_key");
mbedtls_mpi *public_k = srp_get_public_key(serverSrp);
mbedtls_mpi *salt = srp_get_salt(serverSrp);
int bodySize = 0;
uint8_t state[] = {0x02};
bodySize += tlv_encode_length(sizeof(state));
bodySize += tlv_encode_length(SRP_PUBLIC_KEY_LENGTH);
bodySize += tlv_encode_length(SRP_SALT_LENGTH);
Serial.print(public_k->n);
Serial.print("-");
Serial.print(SRP_PUBLIC_KEY_LENGTH);
Serial.println("");
Serial.print(salt->n);
Serial.print("-");
Serial.print(SRP_SALT_LENGTH);
Serial.println("");
Serial.println("malloc acc_msg");
*acc_msg = (uint8_t *)(malloc(bodySize));
Serial.println("malloc acc_msg success");
uint8_t* tlv_encode_ptr = *acc_msg;
tlv_encode_ptr += tlv_encode(HAP_TLV_TYPE_SALT, SRP_SALT_LENGTH, (uint8_t *)(salt->p), *acc_msg);
Serial.println("tlv_encode HAP_TLV_TYPE_SALT success");
tlv_encode_ptr += tlv_encode(HAP_TLV_TYPE_PUBLICKEY, public_k->n, (uint8_t *)public_k->p, *acc_msg);
Serial.println("tlv_encode HAP_TLV_TYPE_PUBLICKEY success");
tlv_encode_ptr += tlv_encode(HAP_TLV_TYPE_STATE, sizeof(state), state, *acc_msg);
Serial.println("tlv_encode HAP_TLV_TYPE_STATE success");
*acc_msg_length = bodySize;
return 0;
}
static int _setup_m4(struct pair_setup* ps,
uint8_t* device_msg, int device_msg_length,
uint8_t** acc_msg, int* acc_msg_length)
{
struct tlv* ios_srp_public_key = tlv_decode(device_msg, device_msg_length,
HAP_TLV_TYPE_PUBLICKEY);
if (ios_srp_public_key == NULL) {
Serial.println("failed to get HAP_TLV_TYPE_PUBLICKEY");
return 1;
}
// ios_srp_public_key->
mbedtls_mpi *mpi;
mbedtls_mpi_init(mpi);
mbedtls_mpi_write_binary(mpi, ios_srp_public_key->value, ios_srp_public_key->length);
if (mpi == NULL) {
Serial.println("error to set HAP_TLV_TYPE_PUBLICKEY");
return 1;
}
// srp_compute_key()
return 0;
}
int pair_setup_do(void* _ps, char* req_body, int req_body_len, char** res_body, int* res_body_len) {
return _setup_m2(NULL, (uint8_t*)req_body, req_body_len, (uint8_t**)res_body, res_body_len);
}
static void _msg_recv(void *connection, struct mg_connection *nc, char *msg, int len)
{
Serial.println(heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
Serial.println("_msg_recv");
struct http_message shm, *hm = &shm;
char *http_raw_msg = msg;
int http_raw_msg_len = len;
mg_parse_http(http_raw_msg, http_raw_msg_len, hm, 1);
char addr[32];
mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr),
MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
// printf("HTTP request from %s: %.*s %.*s %.*s", addr, (int)hm->method.len,
// hm->method.p, (int)hm->uri.len, hm->uri.p, (int)hm->body.len, hm->body.p);
if (strncmp(hm->uri.p, "/pair-setup", strlen("/pair-setup")) == 0)
{
Serial.println("want to pair");
struct tlv *state_tlv = tlv_decode((uint8_t *)hm->body.p, hm->body.len,
HAP_TLV_TYPE_STATE);
if (state_tlv == NULL)
{
printf("tlv_decode failed. type:%d\n", HAP_TLV_TYPE_STATE);
}
uint8_t state = ((uint8_t *)&state_tlv->value)[0];
char *res_header = NULL;
int res_header_len = 0;
char *res_body = NULL;
int body_len = 0;
char *req_body = strdup(hm->body.p);
switch (state)
{
case 0x01:
{
if (pair_setup_do(NULL, req_body, (int)hm->body.len, &res_body, &body_len))
{
Serial.println("test fail");
}
if (res_body == NULL)
{
Serial.println("ERROR");
}
res_header = (char *)malloc(strlen(header_fmt));
sprintf(res_header, header_fmt, body_len);
res_header_len = sizeof(res_header);
Serial.println("send to ios");
if (res_body)
{
// mg_printf(nc, header_fmt, body_len);
// mg_send_head(nc, 200, body_len, "Content-Type: application/pairing+tlv8\r\n");
char *sendFull = (char *)malloc(res_header_len + body_len);
strcpy(sendFull, res_header);
strcat(sendFull, res_body);
mg_send(nc, sendFull, res_header_len + body_len);
// mg_send(nc, res_header, res_header_len);
// mg_send(nc, res_body, body_len);
} else {
Serial.println("no body");
}
break;
}
case 0x03:
Serial.println("0x03");
if (_setup_m4(NULL, (uint8_t*)req_body, (int)hm->body.len, (uint8_t**)res_body, &body_len)) {
Serial.println("0x03 fail");
return;
}
// error = _setup_m4(ps, (uint8_t*)req_body, req_body_len, (uint8_t**)res_body, res_body_len);
break;
// case 0x05:
// Serial.println("0x05");
// // error = _setup_m6(ps, (uint8_t*)req_body, req_body_len, (uint8_t**)res_body, res_body_len);
// break;
default:
printf("[PAIR-SETUP][ERR] Invalid state number. %d\n", state);
break;
}
// tlv_decoded_item_free(state_tlv);
} else {
Serial.println("want something else");
}
// struct hap_connection* hc = connection;
// if (hc->pair_verified) {
// _encrypted_msg_recv(connection, nc, msg, len);
// }
// else {
// _plain_msg_recv(connection, nc, msg, len);
// }
}
static void _hap_connection_close(void *connection, struct mg_connection *nc)
{
Serial.println("_hap_connection_close");
// srp_free(serverSrp);
}
static void _hap_connection_accept(void *accessory, struct mg_connection *nc)
{
newNC = nc;
Serial.println("_hap_connection_accept");
}
void setup()
{
wifi_event_group = xEventGroupCreate();
Serial.begin(115200);
delay(1000);
wifi_setup();
mdns_setup();
create_srp();
struct httpd_ops httpd_ops = {
.accept = _hap_connection_accept,
.close = _hap_connection_close,
.recv = _msg_recv,
};
delay(10000);
char *t = (char *)malloc(8);
strcpy(t, "1234");
httpd_init(&httpd_ops);
delay(10000);
Serial.println("httpd_init");
bindb = httpd_bind(PORT, t);
// server.begin();
}
void loop()
{
// WiFiClient client = server.available();
// if (!client) {
// return;
// }
}
|
#pragma once
#include <tudocomp/config.h>
#ifdef STXXL_FOUND
#include <tudocomp_stat/StatPhaseExtension.hpp>
#include <stxxl/bits/io/iostats.h>
namespace tdc {
class STXXLStatExtension : public StatPhaseExtension {
private:
static stxxl::stats* s_stats;
static inline stxxl::stats_data sample() {
return stxxl::stats_data(*s_stats);
}
stxxl::stats_data m_begin;
public:
inline STXXLStatExtension() : m_begin(sample()) {
}
virtual inline void write(json& data) override {
auto stats = sample() - m_begin;
// TODO: once the charter supports displaying objects,
// organize these into an "stxxl" object
data["cached_read_volume"] = stats.get_cached_read_volume();
data["cached_reads"] = stats.get_cached_reads();
data["cached_writes"] = stats.get_cached_writes();
data["cached_written_volume"] = stats.get_cached_written_volume();
data["io_wait_time"] = stats.get_io_wait_time();
data["pio_time"] = stats.get_pio_time();
data["pread_time"] = stats.get_pread_time();
data["pwrite_time"] = stats.get_pwrite_time();
data["read_time"] = stats.get_read_time();
data["read_volume"] = stats.get_read_volume();
data["reads"] = stats.get_reads();
data["wait_read_time"] = stats.get_wait_read_time();
data["wait_write_time"] = stats.get_wait_write_time();
data["write_time"] = stats.get_write_time();
data["writes"] = stats.get_writes();
data["written_volume"] = stats.get_written_volume();
}
};
}
#endif // STXXL_FOUND
|
/*!
* \file KaiXinApp_GardenList.cpp
* \author GoZone
* \date
* \brief 解析与UI: 偷菜
*
* \ref CopyRight
* =======================================================================<br>
* Copyright ? 2010-2012 GOZONE <br>
* All Rights Reserved.<br>
* The file is generated by Kaixin_Component Wizard for Tranzda Mobile Platform <br>
* =======================================================================<br>
*/
#include "KaiXinAPICommon.h"
#if(LCD_SIZE == LCD_HVGA )
#define OFFSET_X (10)
#elif(LCD_SIZE == LCD_WVGA )
#define OFFSET_X (20)
#endif
void* KaiXinAPI_GardenList_JsonParse(char *text)
{
cJSON *json;
cJSON *pTemp0;
tResponseGardenList* Response = new tResponseGardenList;
memset(Response, 0 , sizeof(tResponseGardenList));
json = cJSON_Parse(text);
pTemp0 = cJSON_GetObjectItem(json,"ret");
if (pTemp0)
{
Response->ret = pTemp0->valueint;
}
//Success
if(Response->ret == 1)
{
pTemp0 = cJSON_GetObjectItem(json, "uid");
if(pTemp0)
{
STRCPY_Ex(Response->uid, pTemp0->valuestring);
}
pTemp0 = cJSON_GetObjectItem(json, "friends");
if(pTemp0)
{
int nSize1 = 0, i = 0;
nSize1 = cJSON_GetArraySize(pTemp0);
Response->nSize_friends = nSize1;
if( nSize1 != 0 )
{
Response->friends = NULL;
Response->friends = (GardenList_friends*) malloc(sizeof( GardenList_friends ) * nSize1 );
memset(Response->friends, 0 , sizeof(GardenList_friends) * nSize1 );
}
for ( i = 0; i < nSize1; i++ )
{
cJSON *Item1 = NULL, *pTemp1 = NULL;
Item1 = cJSON_GetArrayItem(pTemp0,i);
pTemp1 = cJSON_GetObjectItem(Item1, "flogo");
if(pTemp1)
{
STRCPY_Ex(Response->friends[i].flogo, pTemp1->valuestring);
}
pTemp1 = cJSON_GetObjectItem(Item1, "fuid");
if(pTemp1)
{
Response->friends[i].fuid = pTemp1->valueint;
}
pTemp1 = cJSON_GetObjectItem(Item1, "fname");
if(pTemp1)
{
STRCPY_Ex(Response->friends[i].fname, pTemp1->valuestring);
}
pTemp1 = cJSON_GetObjectItem(Item1, "mature");
if(pTemp1)
{
STRCPY_Ex(Response->friends[i].mature, pTemp1->valuestring);
}
pTemp1 = cJSON_GetObjectItem(Item1, "mtime");
if(pTemp1)
{
STRCPY_Ex(Response->friends[i].mtime, pTemp1->valuestring);
}
}
}
}
//Failue
else
{
//pTemp0 = cJSON_GetObjectItem(json,"msg");
//if (pTemp0)
//{
// strcpy(Response->msg, pTemp0 ->valuestring);
//}
}
cJSON_Delete(json);
return Response;
}
// 构造函数
TGardenListForm::TGardenListForm(TApplication* pApp):TWindow(pApp)
{
Create(APP_KA_ID_GardenListForm);
}
// 析构函数
TGardenListForm::~TGardenListForm(void)
{
if( Response )
{
delete Response;
}
}
// 窗口事件处理
Boolean TGardenListForm::EventHandler(TApplication * pApp, EventType * pEvent)
{
Boolean bHandled = FALSE;
switch (pEvent->eType)
{
case EVENT_WinInit:
{
_OnWinInitEvent(pApp, pEvent);
bHandled = TRUE;
break;
}
case EVENT_WinClose:
{
_OnWinClose(pApp, pEvent);
break;
}
case EVENT_CtrlSelect:
{
bHandled = _OnCtrlSelectEvent(pApp, pEvent);
break;
}
case EVENT_WinEraseClient:
{
TDC dc(this);
WinEraseClientEventType *pEraseEvent = reinterpret_cast< WinEraseClientEventType* >( pEvent );
TRectangle rc(pEraseEvent->rc);
TRectangle rcBack(5, 142, 310, 314);
this->GetBounds(&rcBack);
// 刷主窗口背景色
dc.SetBackColor(RGB_COLOR_WHITE);
// 擦除
dc.EraseRectangle(&rc, 0);
dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_title_bg), 0, 0, SCR_W,
GUI_API_STYLE_ALIGNMENT_LEFT);
//dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_bottom_bg), 0, rcBack.Bottom()-68,
//320, GUI_API_STYLE_ALIGNMENT_LEFT|GUI_API_STYLE_ALIGNMENT_TOP);
pEraseEvent->result = 1;
bHandled = TRUE;
}
break;
case EVENT_KeyCommand:
{
// 抓取右软键事件
if (pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_UP
|| pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_LONG)
{
// 模拟退出按钮选中消息
HitControl(m_BackBtn);
bHandled = TRUE;
}
}
break;
default:
break;
}
if (!bHandled)
{
bHandled = TWindow::EventHandler(pApp, pEvent);
}
return bHandled;
}
// 窗口初始化
Boolean TGardenListForm::_OnWinInitEvent(TApplication * pApp, EventType * pEvent)
{
int iRet = eFailed;
int nIndex = 0;
TBarRowList *lpRowList = NULL;
TRectangle Rc_CoolBarList;
nListItems =0;
Response = NULL;
iRet = KaiXinAPI_JsonParse(KX_GardenList, (void **)&Response);
m_BackBtn = SetAppBackButton(this);
SetAppTilte(this, APP_KA_ID_STRING_Garden);
if(iRet == 1)
{
TBarRow *lpRow = NULL;
TCoolBarList* pCoolBarList = static_cast<TCoolBarList*>(GetControlPtr(APP_KA_ID_GardenListForm_GardenListCoolBarList));
if (pCoolBarList)
{
TBarListItem* lpItem = NULL;
pCoolBarList->SetBounds(RC_LIST_LARGE);
pCoolBarList->GetBounds(&Rc_CoolBarList);
lpRowList = pCoolBarList->Rows();
//add row
if (lpRowList)
{
lpRowList->BeginUpdate();
lpRowList->Clear();
lpRow = lpRowList->AppendRow();
lpRowList->EndUpdate();
if(lpRow)
{
//Title
lpItem = lpRow->AppendItem();
if(lpItem)
{
TFont objFontType;
Int32 ItemHeight = 0;
TRectangle rect;
TRectangle Rc_Temp;
TUChar pszSubTitle[64] = {0};
lpItem->GetBounds(rect);
lpItem->SetCaption(NULL);
lpItem->SetIndicatorType(itNone);
ItemHeight = ItemHeight + 30;
TUString::StrPrintF(pszSubTitle, TResource::LoadConstString(APP_KA_ID_STRING_SubTitleGarden),TResource::LoadConstString(APP_KA_ID_STRING_Friend));
Int32 nTitlelabelId = lpItem->AddCtrl(CTL_CLASS_LABEL, 20, 5);
TLabel* pTitlelabel = static_cast<TLabel*>(GetControlPtr(nTitlelabelId));
TRectangle Rc_Titlelabel(OFFSET_X, ItemHeight, SCR_W - 20, 20);
pTitlelabel->SetBounds(&Rc_Titlelabel);
objFontType = pTitlelabel->GetFont();
objFontType.Create(FONT_CONTENT, FONT_CONTENT);
pTitlelabel->SetFont(objFontType);
pTitlelabel->SetCaption(pszSubTitle,FALSE);
pTitlelabel->GetBounds(&Rc_Temp);
ItemHeight = ItemHeight + Rc_Temp.Height() + 30;
lpItem->SetHeight(ItemHeight);
}
// 好友列表
nListItems = Response->nSize_friends;
if(nListItems == 0)
{
lpItem = lpRow->AppendItem();
if(lpItem)
{
TFont objFontType;
TUChar pszFriendName[32] = {0};
Int32 ItemHeight = 0;
TRectangle rect;
TRectangle Rc_Temp;
lpItem->GetBounds(rect);
lpItem->SetCaption(NULL);
lpItem->SetIndicatorType(itNone);
ItemHeight = ItemHeight + rect.Y() + 15;
//好友的花园里还没有成熟的果实
Int32 nNoneHarvestId = lpItem->AddCtrl(CTL_CLASS_LABEL, 20, 5);
TLabel* pNoneHarvest = static_cast<TLabel*>(GetControlPtr(nNoneHarvestId));
TRectangle Rc_NoneHarvest(OFFSET_X, ItemHeight, SCR_W - 40 , 20);
pNoneHarvest->SetBounds(&Rc_NoneHarvest);
objFontType = pNoneHarvest->GetFont();
objFontType.Create(FONT_CONTENT_DETAIL, FONT_CONTENT_DETAIL);
pNoneHarvest->SetFont(objFontType);
pNoneHarvest->SetColor(CTL_COLOR_TYPE_FORE,RGB_COLOR_GRAY);
pNoneHarvest->SetCaption(TResource::LoadConstString(APP_KA_ID_STRING_NoneHarvestGarden),FALSE);
pNoneHarvest->GetBounds(&Rc_Temp);
ItemHeight = ItemHeight + Rc_Temp.Height() + 10;
lpItem->SetHeight(ItemHeight - (rect.Y() - Rc_CoolBarList.Y()) + 10 );
}
}
else
{
for( nIndex = 0; nIndex < nListItems; nIndex++)
{
lpItem = lpRow->AppendItem();
if(lpItem)
{
TFont objFontType;
TUChar pszFriendName[32] = {0};
Int32 ItemHeight = 0;
TRectangle rect;
TRectangle Rc_Temp;
lpItem->GetBounds(rect);
lpItem->SetCaption(NULL);
lpItem->SetIndicatorType(itNone);
ItemHeight = ItemHeight + rect.Y() + 15;
//好友名字
TUString::StrUtf8ToStrUnicode(pszFriendName, (const Char *)Response->friends[nIndex].fname);
nFriendNameId[nIndex] = lpItem->AddCtrl(CTL_CLASS_RICHVIEW, 20, 5);
TRichView* pFriendName = static_cast<TRichView*>(GetControlPtr(nFriendNameId[nIndex]));
TRectangle Rc_FriendName(OFFSET_X, ItemHeight, SCR_W - 40 , 20);
pFriendName->SetBounds(&Rc_FriendName);
objFontType = pFriendName->GetFont();
objFontType.Create(FONT_CONTENT_DETAIL, FONT_CONTENT_DETAIL);
pFriendName->SetFont(objFontType);
//pFriendName->SetColor(CTL_COLOR_TYPE_FORE,RGB_COLOR_BLUE);
pFriendName->SetWordWrapAttr(TRUE);
pFriendName->SetTransparent(TRUE);
pFriendName->SetEnabled(TRUE);
pFriendName->SetScrollBarMode(CTL_SCL_MODE_NONE);
pFriendName->SetMaxVisibleLines(1, TRUE);
pFriendName->SetCaption(pszFriendName,FALSE);
pFriendName->GetBounds(&Rc_Temp);
ItemHeight = ItemHeight + Rc_Temp.Height() + 5;
lpItem->SetHeight(ItemHeight - (rect.Y() - Rc_CoolBarList.Y()) + 10 );
}
}
}
}
//:TODO:Add subject info
lpRowList->BeginUpdate();
lpRow = lpRowList->AppendRow();
lpRowList->EndUpdate();
//add Item
if(lpRow)
{
//nothing to do
}
}
}
}
return TRUE;
}
// 关闭窗口时,保存设置信息
Boolean TGardenListForm::_OnWinClose(TApplication * pApp, EventType * pEvent)
{
return TRUE;
}
// 控件点击事件处理
Boolean TGardenListForm::_OnCtrlSelectEvent(TApplication * pApp, EventType * pEvent)
{
Boolean bHandled;
bHandled = FALSE;
Int32 nCtrlID = pEvent->sParam1;
if(m_BackBtn == nCtrlID)
{
bHandled = TRUE;
this->CloseWindow();
return bHandled;
}
for( int nIndex = 0; nIndex < nListItems; nIndex++)
{
if(nFriendNameId[nIndex] == nCtrlID)
{
if(strcmp(Response->friends[nIndex].mature, "1") == 0)//可收获
{
TUChar szFUid[32]={0};
Char sFUid[32]={0};
TUString::StrIToA(szFUid, Response->friends[nIndex].fuid);
TUString::StrUnicodeToStrUtf8(sFUid, szFUid);
Set_Url_Params(KX_GardenDetail, "fuid", (char*)sFUid);
KaiXinAPICommon_Download(KX_GardenDetail, this->GetWindowHwndId());
this->CloseWindow();
bHandled = TRUE;
}
}
}
return bHandled;
}
|
//#define NDEBUG
#include <cassert>
#include <utilities.h>
#include "MP3Tasks.h"
int main(void) {
/// This "stack" memory is enough for each task to run properly (512 * 32-bit (4 bytes)) = 2Kbytes stack
const uint32_t STACK_SIZE_WORDS = 0x00000200;
assert(sd->Init() && audio->Init() && Init_MP3_GPIO_Interrupts() && oled->Init());
/// command line queue handles
sdFileCmdTaskHandle = xQueueCreate(1, sizeof(uint8_t *));
mp3CmdTaskHandle = xQueueCreate(2, sizeof(uint8_t *));
txtCmdTaskHandle = xQueueCreate(2, sizeof(uint8_t *));
/// isr queue handles
mp3QueueHandle = xQueueCreate(2, sizeof(uint8_t *));
scheduler_add_task(new terminalTask(PRIORITY_HIGH));
/// command line handled tasks
xTaskCreate(vPlayMp3FilesFromCmd, "cmp3cmd", STACK_SIZE_WORDS, nullptr, PRIORITY_HIGH, nullptr);
xTaskCreate(vPlayTxtFilesFromCmd, "ctxtcmd", STACK_SIZE_WORDS, nullptr, PRIORITY_HIGH, nullptr);
xTaskCreate(vSendFilesFromCmd, "pmp3cmd", STACK_SIZE_WORDS, nullptr, PRIORITY_LOW, nullptr);
/// isr handled tasks
xTaskCreate(vPlayMp3Files, "cmp3", STACK_SIZE_WORDS, nullptr, PRIORITY_HIGH, nullptr);
xTaskCreate(vSendMp3Files, "pmp3", STACK_SIZE_WORDS, nullptr, PRIORITY_LOW, nullptr);
xTaskCreate(vIncrVolumeOrList, "incVL", STACK_SIZE_WORDS, nullptr, PRIORITY_HIGH, nullptr);
xTaskCreate(vDecrVolumeOrList, "decVL", STACK_SIZE_WORDS, nullptr, PRIORITY_HIGH, nullptr);
xTaskCreate(vFastForwardOrSelect, "ffs", STACK_SIZE_WORDS, nullptr, PRIORITY_HIGH, nullptr);
xTaskCreate(vNextOrPrevious, "ns", STACK_SIZE_WORDS, nullptr, PRIORITY_HIGH, nullptr);
/// init oled display of song lists & Volume
updateSongList(TOP);
oled->initVolume(4);
scheduler_start();
for (;;); /* endless loop - retain code execution */
}
|
//$Id: GmatODType.cpp 1398 2013-06-04 20:39:37Z tdnguyen $
//------------------------------------------------------------------------------
// GmatODType
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002-2011 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG06CA54C
//
// Author: Tuan Dang Nguyen, NASA/GSFC
// Created: 2013/06/04
//
/**
* ObType class used for the GMAT Internal observation data
*/
//------------------------------------------------------------------------------
#include "GmatODType.hpp"
#include "MessageInterface.hpp"
#include "GmatConstants.hpp"
#include "FileManager.hpp"
#include "StringUtil.hpp"
#include "MeasurementException.hpp"
#include <sstream>
//#define DEBUG_ODTYPE_CREATION_INITIALIZATION
//#define DEBUG_FILE_WRITE
//#define DEBUG_FILE_READ
//#define DEBUG_FILE_ACCESS
//-----------------------------------------------------------------------------
// GmatODType(const std::string withName)
//-----------------------------------------------------------------------------
/**
* Default constructor
*
* @param withName The name of the new object
*/
//-----------------------------------------------------------------------------
GmatODType::GmatODType(const std::string withName) :
ObType ("GMAT_OD", withName),
epochPrecision (16),
dataPrecision (6)
{
#ifdef DEBUG_ODTYPE_CREATION_INITIALIZATION
MessageInterface::ShowMessage("GmatODType default constructor (a GMAT_OD obtype) <%s,%p>\n", GetName().c_str(), this);
#endif
header = "% GMAT OD Measurement Data File\n\n";
}
//-----------------------------------------------------------------------------
// ~GmatODType()
//-----------------------------------------------------------------------------
/**
* Destructor
*/
//-----------------------------------------------------------------------------
GmatODType::~GmatODType()
{
}
//-----------------------------------------------------------------------------
// GmatODType(const GmatODType& ot) :
//-----------------------------------------------------------------------------
/**
* Copy constructor
*
* @param ot The GmatODType that gets copied to this one
*/
//-----------------------------------------------------------------------------
GmatODType::GmatODType(const GmatODType& ot) :
ObType (ot),
epochPrecision (ot.epochPrecision),
dataPrecision (ot.dataPrecision)
{
#ifdef DEBUG_ODTYPE_CREATION_INITIALIZATION
MessageInterface::ShowMessage("GmatODType copy constructor (a GMAT_OD obtype) from <%s,%p> to <%s,%p>\n", ot.GetName().c_str(), &ot, GetName().c_str(), this);
#endif
}
//-----------------------------------------------------------------------------
// GmatODType& operator=(const GmatODType& ot)
//-----------------------------------------------------------------------------
/**
* Assignment operator
*
* @param ot The GmatODType that gets copied to this one
*
* @return This GmatODType, configured to match ot
*/
//-----------------------------------------------------------------------------
GmatODType& GmatODType::operator=(const GmatODType& ot)
{
#ifdef DEBUG_ODTYPE_CREATION_INITIALIZATION
MessageInterface::ShowMessage("Assigning one GMAT_OD obtype to another\n");
#endif
if (this != &ot)
{
epochPrecision = ot.epochPrecision;
dataPrecision = ot.dataPrecision;
}
return *this;
}
//-----------------------------------------------------------------------------
// GmatBase* Clone() const
//-----------------------------------------------------------------------------
/**
* Cloning method used to create a GmatODType from a GmatBase pointer
*
* @return A new GmatODType object matching this one
*/
//-----------------------------------------------------------------------------
GmatBase* GmatODType::Clone() const
{
#ifdef DEBUG_ODTYPE_CREATION_INITIALIZATION
MessageInterface::ShowMessage("Cloning a GMAT_OD obtype\n");
#endif
return new GmatODType(*this);
}
//-----------------------------------------------------------------------------
// bool Initialize()
//-----------------------------------------------------------------------------
/**
* Prepares this GmatObType for use
*
* @return true on success, false on failure
*/
//-----------------------------------------------------------------------------
bool GmatODType::Initialize()
{
#ifdef DEBUG_ODTYPE_CREATION_INITIALIZATION
MessageInterface::ShowMessage("GmatODType::Initialize() Executing\n");
#endif
ObType::Initialize();
return true;
}
//-----------------------------------------------------------------------------
// bool Open(bool forRead, bool forWrite, bool append)
//-----------------------------------------------------------------------------
/**
* Opens a GmatODType stream for processing
*
* The method manages GmatODType path and file extension defaults in addition to
* performing the basic open operations.
*
* @param forRead True to open for reading, false otherwise
* @param forWrite True to open for writing, false otherwise
* @param append True if data being written should be appended, false if not
*
* @return true if the the stream was opened, false if not
*/
//-----------------------------------------------------------------------------
bool GmatODType::Open(bool forRead, bool forWrite, bool append)
{
#ifdef DEBUG_FILE_ACCESS
MessageInterface::ShowMessage("GmatODType::Open(%s, %s, %s) Executing\n",
(forRead ? "true" : "false"),
(forWrite ? "true" : "false"),
(append ? "true" : "false") );
#endif
// when theStream open twice the content in theStream is always empty string. Therefore, it needs this verification.
if (theStream.is_open())
return true;
bool retval = false;
// temporary
retval = true;
std::ios_base::openmode mode = std::fstream::in;
if (forRead && forWrite)
mode = std::fstream::in | std::fstream::out;
else
{
if (forRead)
mode = std::fstream::in;
if (forWrite)
mode = std::fstream::out;
}
if (append)
mode = mode | std::fstream::app;
#ifdef DEBUG_FILE_ACCESS
MessageInterface::ShowMessage(" Opening the stream %s, mode = %d\n",
streamName.c_str(), mode);
#endif
if (streamName != "")
{
std::string fullPath = "";
// If no path designation slash character is found, add the default path
if ((streamName.find('/') == std::string::npos) &&
(streamName.find('\\') == std::string::npos))
{
FileManager *fm = FileManager::Instance();
fullPath = fm->GetPathname(FileManager::MEASUREMENT_PATH);
}
fullPath += streamName;
// Add the .gmd extension if there is no extension in the file
size_t dotLoc = fullPath.find_last_of('.'); // change from std::string::size_type to size_t in order to compatible with C++98 and C++11
size_t slashLoc = fullPath.find_last_of('/'); // change from std::string::size_type to size_t in order to compatible with C++98 and C++11
if (slashLoc == std::string::npos)
slashLoc = fullPath.find_last_of('\\');
if ((dotLoc == std::string::npos) ||
(dotLoc < slashLoc))
{
fullPath += ".gmd";
}
#ifdef DEBUG_FILE_ACCESS
MessageInterface::ShowMessage(" Full path is %s, mode = %d\n",
fullPath.c_str(), mode);
#endif
theStream.open(fullPath.c_str(), mode);
}
retval = theStream.is_open();
if (retval && forWrite)
theStream << header;
if (retval == false)
{
// MessageInterface::ShowMessage(
// "GMAT_OD Data File %s could not be opened\n",
// streamName.c_str());
throw MeasurementException("GMAT_OD Data File " + streamName + " could not be opened\n");
}
return retval;
}
//-----------------------------------------------------------------------------
// bool IsOpen()
//-----------------------------------------------------------------------------
/**
* Tests to see if the GmatODType data file has been opened
*
* @return true if the file is open, false if not.
*/
//-----------------------------------------------------------------------------
bool GmatODType::IsOpen()
{
#ifdef DEBUG_FILE_WRITE
MessageInterface::ShowMessage("GmatODType::IsOpen() Executing\n");
#endif
return theStream.is_open();
}
//-----------------------------------------------------------------------------
// bool AddMeasurement(MeasurementData *md)
//-----------------------------------------------------------------------------
/**
* Adds a new measurement to the GmatODType data file
*
* This method takes the raw observation data passed in and formats it into a
* string compatible with GmatInternal data files, and then writes that string
* to the open data stream.
*
* @param md The measurement data containing the observation.
*
* @return true on success, false on failure
*/
//-----------------------------------------------------------------------------
bool GmatODType::AddMeasurement(MeasurementData *md)
{
#ifdef DEBUG_FILE_WRITE
MessageInterface::ShowMessage("GmatODType::AddMeasurement() Executing\n");
#endif
bool retval = false;
std::stringstream dataLine;
char databuffer[200];
char epochbuffer[200];
Real taiEpoch = (md->epochSystem == TimeConverterUtil::TAIMJD ? md->epoch :
TimeConverterUtil::ConvertToTaiMjd(md->epochSystem, md->epoch,
GmatTimeConstants::JD_NOV_17_1858));
sprintf(epochbuffer, "%18.12lf", taiEpoch);
dataLine << epochbuffer << " " << md->typeName
<< " " << md->type << " ";
for (UnsignedInt j = 0; j < md->participantIDs.size(); ++j)
dataLine << md->participantIDs[j] << " ";
for (UnsignedInt k = 0; k < md->value.size(); ++k)
{
Real dsnRange = GmatMathUtil::Mod(md->value[k],md->rangeModulo); // value of observation has to be mod(fullrange, M)
sprintf(databuffer, "%20.8lf", dsnRange); // increasing 6 decimal places to 8
dataLine << databuffer;
if (k < md->value.size()-1)
dataLine << " ";
}
//sprintf(databuffer, " %d %.15le %.15le", md->uplinkBand, md->uplinkFreq, md->rangeModulo);
sprintf(databuffer, " %d %.15le %.15le", md->uplinkBand, md->uplinkFreqAtRecei, md->rangeModulo);
dataLine << databuffer;
theStream << dataLine.str() << "\n";
#ifdef DEBUG_FILE_WRITE
MessageInterface::ShowMessage("GmatODType::WriteMeasurement: \"%s\"\n",
dataLine.str().c_str());
#endif
// temporary
retval = true;
return retval;
}
//-----------------------------------------------------------------------------
// ObservationData* ReadObservation()
//-----------------------------------------------------------------------------
/**
* Retrieves an observation record
*
* This method reads an observation data set from a GmatOD data stream and
* returns the data to the caller.
*
* @return The observation data from the stream. If there is no more data in
* the stream, a NULL pointer is returned.
*/
//-----------------------------------------------------------------------------
ObservationData* GmatODType::ReadObservation()
{
#ifdef DEBUG_FILE_READ
MessageInterface::ShowMessage("GmatODType::READObservation() Executing\n");
#endif
std::string str;
std::stringstream theLine;
Integer participantSize;
Integer dataSize;
Real defaultNoiseCovariance = 0.1;
// Do nothing when it is at the end of file
if (theStream.eof())
return NULL;
// Read a line when it is not end of file
std::getline (theStream, str);
// Skip header and comment lines or empty lines
while ((str[0] == '%') || (GmatStringUtil::RemoveAllBlanks(str) == "") ||
(str.length() < 2))
{
std::getline(theStream, str);
// Do nothing when it is at the end of file
if (theStream.eof())
return NULL;
}
// Processing data in the line
theLine << str;
currentObs.Clear();
currentObs.dataFormat = "GMAT_OD";
// old format: 21545.05439854615 Range 7000 GS2ID ODSatID 2713.73185
// new format: 21545.05439854615 DSNRange 7050 GS2ID ODSatID 2713.73185 Uplink Band Uplink Frequency Range Modulo
Real value;
GmatEpoch taiEpoch;
theLine >> taiEpoch;
currentObs.epoch = (currentObs.epochSystem == TimeConverterUtil::TAIMJD ?
taiEpoch :
TimeConverterUtil::ConvertFromTaiMjd(currentObs.epochSystem, taiEpoch,
GmatTimeConstants::JD_NOV_17_1858));
theLine >> currentObs.typeName;
Integer type;
theLine >> type;
currentObs.type = (Gmat::MeasurementType)type;
//switch (currentObs.type)
//{
// case Gmat::GEOMETRIC_RANGE:
// case Gmat::GEOMETRIC_RANGE_RATE:
// case Gmat::USN_TWOWAYRANGE:
// case Gmat::USN_TWOWAYRANGERATE:
// case Gmat::DSN_TWOWAYRANGE:
// case Gmat::DSN_TWOWAYDOPPLER:
// participantSize = 2;
// dataSize = 1;
// break;
// case Gmat::TDRSS_TWOWAYRANGE:
// case Gmat::TDRSS_TWOWAYRANGERATE:
// participantSize = 3;
// dataSize = 1;
// break;
// case Gmat::GEOMETRIC_AZ_EL:
// case Gmat::GEOMETRIC_RA_DEC:
// case Gmat::OPTICAL_AZEL:
// case Gmat::OPTICAL_RADEC:
// participantSize = 2;
// dataSize = 2;
// defaultNoiseCovariance = 0.1;
// break;
// default:
// participantSize = 0;
// dataSize = 0;
// break;
//}
// Set measurement unit
currentObs.unit = "RU";
participantSize = 2;
dataSize = 1;
for (Integer i = 0; i < participantSize; ++i)
{
theLine >> str;
currentObs.participantIDs.push_back(str);
}
for (Integer i = 0; i < dataSize; ++i)
{
theLine >> value;
currentObs.value.push_back(value);
currentObs.value_orig.push_back(value);
if (value == -1.0)
break;
}
if (value != -1.0)
{
// Read uplink band, uplink frequency, and range modulo:
Integer uplinkBand;
// Real uplinkFreq;
Real uplinkFreqAtRecei;
Real rangeModulo;
theLine >> uplinkBand;
// theLine >> uplinkFreq;
theLine >> uplinkFreqAtRecei;
theLine >> rangeModulo;
currentObs.uplinkBand = uplinkBand;
// currentObs.uplinkFreq = uplinkFreq;
currentObs.uplinkFreqAtRecei = uplinkFreqAtRecei;
currentObs.rangeModulo = rangeModulo;
}
// Covariance *noise = new Covariance();
// noise->SetDimension(dataSize);
// for (Integer i = 0; i < dataSize; ++i)
// {
// /// @todo Measurement noise covariance is hard-coded; this must be fixed
// (*noise)(i,i) = defaultNoiseCovariance;
// }
// currentObs.noiseCovariance = noise;
#ifdef DEBUG_FILE_READ
MessageInterface::ShowMessage(" %.12lf %s %d ", currentObs.epoch, currentObs.typeName.c_str(), currentObs.type);
for (Integer i = 0; i < participantSize; ++i)
MessageInterface::ShowMessage("%s ", currentObs.participantIDs.at(i).c_str());
for (Integer i = 0; i < dataSize; ++i)
MessageInterface::ShowMessage("%.12lf ", currentObs.value.at(i));
MessageInterface::ShowMessage(" %d %.12le %.12le\n",currentObs.uplinkBand, currentObs.uplinkFreq, currentObs.rangeModulo);
MessageInterface::ShowMessage("GmatODType::READObservation() End\n");
#endif
return ¤tObs;
}
//-----------------------------------------------------------------------------
// bool Close()
//-----------------------------------------------------------------------------
/**
* Closes the data stream
*
* This method flushes the data stream, and then closes it.
*
* @return true on success, false on failure
*/
//-----------------------------------------------------------------------------
bool GmatODType::Close()
{
#ifdef DEBUG_FILE_WRITE
MessageInterface::ShowMessage("GmatODType::Close() Executing\n");
#endif
bool retval = false;
if (theStream.is_open())
{
theStream.flush();
theStream.close();
retval = !(theStream.is_open());
}
return retval;
}
//-----------------------------------------------------------------------------
// bool GmatODType::Finalize()
//-----------------------------------------------------------------------------
/**
* Completes operations on this GmatODType.
*
* @return true always -- there is no GmatObType specific finalization needed.
*/
//-----------------------------------------------------------------------------
bool GmatODType::Finalize()
{
#ifdef DEBUG_FILE_WRITE
MessageInterface::ShowMessage("GmatODType::Finalize() Executing\n");
#endif
bool retval = true;
return retval;
}
|
#ifndef SOXIPNEHE3DWORLDLOADER_H
#define SOXIPNEHE3DWORLDLOADER_H
#include <Inventor/engines/SoSubEngine.h>
#include <Inventor/fields/SoSFString.h>
#include <Inventor/fields/SoMFVec3f.h>
#include <Inventor/fields/SoMFvec2f.h>
#include <Inventor/fields/SoMFUInt32.h>
#include <string>
#include <vector>
class SoXipNehe3DWorldLoader : public SoEngine
{
SO_ENGINE_HEADER(SoXipNehe3DWorldLoader);
public:
SoXipNehe3DWorldLoader();
// Initialization
static void initClass();
SoSFString fileName;
SoEngineOutput verticesCoords;
SoEngineOutput textCoords;
SoEngineOutput numVertices; // number of vertices to use for each triangle strip in the set
private:
std::vector<SbVec3f> _verticesCoords;
std::vector<SbVec2f> _textCoords;
std::vector<int> _numVertices;
virtual void inputChanged(SoField *which);
bool loadNehe3DWorld(const std::string filename);
virtual void evaluate();
};
#endif //SOXIPNEHEWORLDLOADER_H
|
#pragma once
#include <mutex>
#include <list>
#include "misc.h"
#include "notification.h"
#include "team.h"
#include "network.h"
struct User
{
static const uint32_t kNotificationQueueSize = 32;
User() = delete;
User(const std::string& name, const std::string& password, Team* team);
Team* GetTeam();
const std::string& GetName() const;
IPAddr GetIPAddr() const;
bool AddNotification(Notification* n);
Notification* GetNotification();
uint32_t GetNotificationsInQueue();
void SetSocket(Socket* socket);
Socket* GetSocket();
void DumpStats(std::string& out, IPAddr hwConsoleIp) const;
static EUserErrorCodes Add(const std::string& name, const std::string& password, Team* team);
static User* Get(const std::string& name);
static EUserErrorCodes Authorize(const std::string& name, const std::string& password, IPAddr ipAddr, AuthKey& authKey);
static EUserErrorCodes ChangePassword(const std::string& userName, const std::string& newPassword);
static EUserErrorCodes ChangePassword(AuthKey authKey, const std::string& newPassword, Team* team);
static User* Get(AuthKey authKey);
static void GetUsers(std::vector<User*>& users);
static void BroadcastNotification(Notification* n, User* sourceUser);
static void Start();
private:
Team* m_team = nullptr;
std::string m_name;
// guarded by GUsersGuard
std::string m_password;
IPAddr m_ipAddr = ~0u;
AuthKey m_authKey = kInvalidAuthKey;
mutable std::mutex m_notificationMutex;
std::list<Notification*> m_notifications;
Socket* m_socket = nullptr;
float m_lastUserNotifyTime = 0.0f;
void NotifyUser();
static void DumpStorage();
static void ReadStorage();
static void ChangePassword(User* user, const std::string& newPassword);
};
|
/**
* @file ResourceZipFile.h
*/
#pragma once
#include "IResourceFile.h"
#include "Compression/ZipFile.h"
namespace liman {
class ResourceZipFile : public IResourceFile {
ZipFile* m_pZipFile;
std::string m_fileName;
public:
explicit ResourceZipFile(std::string &resFileName) {
m_pZipFile = nullptr;
m_fileName = resFileName;
}
~ResourceZipFile() override = default;
bool Open() override;
int GetRawResourceSize(const Resource &resource) override;
int GetRawResource(const Resource &resource, char* buffer) override;
int GetNumResources() const override;
std::string GetResourceName(int num) const override;
};
}
|
#include "startTimer.h"
void startTimer::Timer(const uint16_t duration)
{
// mode CTC du timer 1 avec horloge divisée par 1024
// interruption après la durée spécifiée
TCNT1 = 0; // initialise le timer a 0
OCR1A = duration; // La valeur TOP jusque laquelle le TCNT1 doit compter
TCCR1A = (1<< WGM12); // Timer/Counter 1 control register A en mode CTC
TCCR1B = (1 << CS12) | (1 << CS10); // divise l'horloge par 1024
TCCR1C = 0;
TIMSK1 |= (1 << OCIE1A); // On active ici le bit output compare interrupts enable A
} // du time/counter interrupt mask register
|
#pragma once
#include "core/RayHitStructs.h"
#include "core/Shape.h"
#include "math/geometry.h"
namespace rt {
class Sphere : public Shape {
public:
//
// Constructors
//
Sphere(Vec3f center, float radius);
~Sphere();
//
// Functions that need to be implemented, since Sphere is a subclass of
// Shape
//
Hit intersect(Ray ray) override;
private:
Vec3f center;
float radius;
};
} // namespace rt
|
#include "iterator.h"
void Iterator::init(void* ptr)
{
}
void Iterator::init(void* ptr, int(*compare)(unsigned char* key, int key_size, unsigned char* value, int value_size), unsigned char* key, int key_size, std::string data_path)
{
}
|
#ifndef _HS_SFM_BUNDLE_ADJUSTMENT_CAMERA_SHARED_NOISED_Y_GENERATOR_HPP_
#define _HS_SFM_BUNDLE_ADJUSTMENT_CAMERA_SHARED_NOISED_Y_GENERATOR_HPP_
#include <cmath>
#include "hs_math/random/normal_random_var.hpp"
#include "hs_sfm/bundle_adjustment/camera_shared_vector_function.hpp"
#include "hs_sfm/bundle_adjustment/camera_shared_y_covariance_inverse.hpp"
namespace hs
{
namespace sfm
{
namespace ba
{
template <typename _Scalar>
class CameraSharedNoisedYGenerator
{
public:
typedef _Scalar Scalar;
typedef int Err;
typedef CameraSharedVectorFunction<Scalar> VectorFunction;
typedef typename VectorFunction::YVector YVector;
typedef CameraSharedYCovarianceInverse<Scalar> YCovarianceInverse;
private:
typedef typename VectorFunction::Index Index;
typedef EIGEN_VECTOR(Scalar, VectorFunction::params_per_key_) Key;
typedef EIGEN_VECTOR(Scalar, Eigen::Dynamic) Constraint;
typedef typename YCovarianceInverse::KeyBlock KeyBlock;
typedef hs::math::random::NormalRandomVar<Scalar,
VectorFunction::params_per_key_>
KeyGenerator;
typedef hs::math::random::NormalRandomVar<Scalar, 1>
ConstraintGenerator;
public:
Err operator() (const YVector& true_y,
const YCovarianceInverse& y_covariance_inverse,
YVector& noised_y) const
{
Index y_size = y_covariance_inverse.GetYSize();
if (y_size != true_y.rows())
{
return -1;
}
noised_y.resize(y_size);
size_t number_of_keys = y_covariance_inverse.NumberOfKeys();
for (size_t i = 0; i < number_of_keys; i++)
{
Key true_key = true_y.segment(i * VectorFunction::params_per_key_,
VectorFunction::params_per_key_);
KeyBlock key_covariance = y_covariance_inverse.GetKeyBlock(i).inverse();
Key noised_key;
KeyGenerator::Generate(true_key, key_covariance, noised_key);
noised_y.segment(i * VectorFunction::params_per_key_,
VectorFunction::params_per_key_) = noised_key;
}
Index constraints_size = y_covariance_inverse.GetConstraintsSize();
Index key_params_size = y_covariance_inverse.GetKeyParamsSize();
for (Index constraint_id = 0; constraint_id < constraints_size;
constraint_id++)
{
Scalar sigma =
1 / std::sqrt(y_covariance_inverse.GetConstraint(constraint_id));
Scalar mean = true_y[key_params_size + constraint_id];
ConstraintGenerator::Generate(
mean, sigma, noised_y[key_params_size + constraint_id]);
}
return 0;
}
};
}
}
}
#endif
|
// inspired by http://www.lighthouse3d.com/tutorials/view-frustum-culling/
#include "FrustumCull.h"
void FrustumCull::setCamInternals(float angle, float ratio, float nearD, float farD) {
this->ratio = ratio;
this->angle = angle;
this->nearD = nearD;
this->farD = farD;
tang = (float)tan(glm::radians(angle) * 0.5);
nh = nearD * tang;
nw = nh * ratio;
fh = farD * tang;
fw = fh * ratio;
}
void FrustumCull::setCamDef(const glm::vec3 &p, const glm::vec3 &l, const glm::vec3 &u) {
glm::vec3 dir, nc, fc, X, Y, Z;
Z = glm::normalize(p - l);
X = glm::normalize(glm::cross(u, Z));
Y = glm::cross(Z, X);
nc = p - Z * nearD;
fc = p - Z * farD;
glm::vec3 Xnw = X * nw;
glm::vec3 Xfw = X * fw;
glm::vec3 Ynh = Y * nh;
glm::vec3 Yfh = Y * fh;
ntl = nc + Ynh - Xnw;
ntr = nc + Ynh + Xnw;
nbl = nc - Ynh - Xnw;
nbr = nc - Ynh + Xnw;
ftl = fc + Yfh - Xfw;
ftr = fc + Yfh + Xfw;
fbl = fc - Yfh - Xfw;
fbr = fc - Yfh + Xfw;
pl[TOP].set3Points(ntr, ntl, ftl);
pl[BOTTOM].set3Points(nbl, nbr, fbr);
pl[LEFT].set3Points(ntl, nbl, fbl);
pl[RIGHT].set3Points(nbr, ntr, fbr);
pl[NEARP].set3Points(ntl, ntr, nbr);
pl[FARP].set3Points(ftr, ftl, fbl);
}
FrustumCull::Classification FrustumCull::pointInFrustum(const glm::vec3 &p) const {
Classification result = INSIDE;
for (int i = 0; i < 6; i++) {
if (pl[i].distance(p) < 0)
return OUTSIDE;
}
return result;
}
FrustumCull::Classification FrustumCull::sphereInFrustum(const glm::vec3 &p, float raio) const {
Classification result = INSIDE;
float distance;
for(int i=0; i < 6; i++) {
distance = pl[i].distance(p);
if (distance < -raio)
return OUTSIDE;
else if (distance < raio)
result = INTERSECT;
}
return(result);
}
|
#include "common/Compiler.h"
#include "common/FastRand.h"
#include "common/WorkloadSim.h"
#include <benchmark/benchmark.h>
#include <sstream>
#include <system_error>
namespace FwdVoidErrorCode {
template <int N>
ATTRIBUTE_NOINLINE std::error_code IMPL_FwdVoidErrorCode(int gt10) noexcept {
gt10 = workload(gt10);
if (std::error_code ec = IMPL_FwdVoidErrorCode<N - 1>(gt10))
return ec; // never happens
workload(0);
return std::error_code();
}
template <>
ATTRIBUTE_NOINLINE std::error_code IMPL_FwdVoidErrorCode<1>(int gt10) noexcept {
if (workload(gt10) < 10)
return std::error_code(9, std::system_category()); // never happens
workload(0);
return std::error_code();
}
template <int N>
void BM_FwdVoidErrorCode(benchmark::State &state) {
std::ostringstream nulls;
int gt10 = fastrand() % 10 + 100;
while (state.KeepRunning()) {
if (std::error_code ec = IMPL_FwdVoidErrorCode<N>(gt10)) {
nulls << "[never happens]" << ec;
}
}
}
BENCHMARK_TEMPLATE1(BM_FwdVoidErrorCode, 1);
BENCHMARK_TEMPLATE1(BM_FwdVoidErrorCode, 2);
BENCHMARK_TEMPLATE1(BM_FwdVoidErrorCode, 4);
BENCHMARK_TEMPLATE1(BM_FwdVoidErrorCode, 8);
}
|
#ifndef TXPacket_hpp
#define TXPacket_hpp
#include <stdint.h>
#include <mutex>
#include <bitset>
class TXPacket {
public:
TXPacket();
uint16_t get_header();
void set_vel_x(int8_t vel_x);
int8_t get_vel_x();
void set_vel_y(int8_t vel_y);
int8_t get_vel_y();
void set_vel_z(int8_t vel_z);
int8_t get_vel_z();
void set_rot_z(int8_t rot_z);
int8_t get_rot_z();
void set_torpedo_ctl(std::bitset < 8 > torpedo_ctl);
std::bitset < 8 > get_torpedo_ctl();
void set_servo_ctl(std::bitset < 8 > servo_ctl);
std::bitset < 8 > get_servo_ctl();
void set_led_ctl(std::bitset < 8 > led_ctl);
std::bitset < 8 > get_led_ctl();
void set_mode(std::bitset < 16 > mode);
std::bitset < 16 > get_mode();
size_t size();
bool valid();
bool read_buffer(unsigned char buffer[]);
void get_buffer(unsigned char buffer[]);
private:
uint16_t compute_checksum();
typedef struct {
uint16_t header;
int8_t vel_x;
int8_t vel_y;
int8_t vel_z;
int8_t rot_z;
uint8_t torpedo_ctl;
uint8_t servo_ctl;
uint8_t led_ctl;
uint16_t mode;
uint16_t checksum;
} __attribute__ ((__packed__)) tx_packet_t;
tx_packet_t tx_packet;
std::mutex tx_packet_mtx;
size_t tx_packet_size;
bool is_valid;
};
#endif // TXPacket_hpp
|
#include <iostream>
#include <algorithm>
#include <ctime>
using namespace std;
std::string deleteMarks(string& des, char x) {
des.erase(remove(des.begin(), des.end(), x), des.end());
return des;
}
bool checkDateIsExpired(std::string date, std::string startDate, std::string endDate)
{
int diffStart = 0, diffEnd = 0;
int date_year = std::stoi(date.substr(0, 4));
int date_month = std::stoi(date.substr(5, 2));
int date_day = std::stoi(date.substr(8, 2));
int startDate_year = std::stoi(startDate.substr(0, 4));
int startDate_month = std::stoi(startDate.substr(5, 2));
int startDate_day = std::stoi(startDate.substr(8, 2));
int endDate_year = std::stoi(endDate.substr(0, 4));
int endDate_month = std::stoi(endDate.substr(5, 2));
int endDate_day = std::stoi(endDate.substr(8, 2));
diffStart = (date_year - startDate_year) * 12 + date_month - startDate_month;
diffEnd = (endDate_year - date_year) * 12 + endDate_month - date_month;
if (diffStart > 0 && diffEnd > 0)
return true;
else if (diffStart == 0 && diffEnd > 0)
{
if ((date_day - startDate_day) >= 0)
return true;
}
else if (diffStart > 0 && diffEnd == 0)
{
if ((endDate_day - date_day) >= 0)
return true;
}
else if (diffStart == 0 && diffEnd == 0)
{
if ((date_day - startDate_day) >= 0 && (endDate_day - date_day) >= 0)
return true;
}
return false;
}
std::string getDangTianRiQi()
{
std::string nowTime;
std::time_t t = std::time(NULL);
std::tm *st = std::localtime(&t);
char tmpArray[64] = { 0 };
sprintf(tmpArray, "%d-%02d-%02d", st->tm_year + 1900, st->tm_mon + 1, st->tm_mday);
nowTime = tmpArray;
return nowTime;
}
static unsigned short const wCRC16Table[256] = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040};
void Crc16(const uint8_t* pDataIn, int iLenIn, uint16_t* pCRCOut)
{
uint16_t wResult = 0;
uint16_t wTableNo = 0;
int i = 0;
for( i = 0; i < iLenIn; i++)
{
wTableNo = ((wResult & 0xff) ^ (pDataIn[i] & 0xff));
wResult = ((wResult >> 8) & 0xff) ^ wCRC16Table[wTableNo];
}
*pCRCOut = wResult;
}
std::string Crc16String(const uint8_t* pDataIn, int iLenIn)
{
uint16_t wResult = 0;
uint16_t wTableNo = 0;
int i = 0;
for( i = 0; i < iLenIn; i++)
{
wTableNo = ((wResult & 0xff) ^ (pDataIn[i] & 0xff));
wResult = ((wResult >> 8) & 0xff) ^ wCRC16Table[wTableNo];
}
return std::to_string(wResult);
}
int main() {
string curDate = getDangTianRiQi();
cout << "curDate is " << curDate << endl;
string startDate = "2021-03-17";
string endDate = "2022-03-17";
cout << checkDateIsExpired(curDate, startDate, endDate) << endl;
//string hel = "hello world china ! ";
//cout << "res = " << deleteMarks(hel, ' ') << endl;
//cout << "hel len = " << hel.length() << endl;
cout << "--------------" << endl;
string res = Crc16String((uint8_t*)"5ffbad9ba78786429905036d", string("5ffbad9ba78786429905036d").length());
cout << "++++++ " << res << endl;
return 0;
}
|
/**
* \file ChildView.cpp
*
* \author PaulaRed
*/
#include "pch.h"
#include "DoubleBufferDC.h"
#include "framework.h"
#include "Towers2020.h"
#include "ChildView.h"
#include "Game.h"
#include "Level.h"
#include "ImageMap.h"
#include <memory>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
using namespace Gdiplus;
using namespace std;
using namespace xmlnode;
/// Maximum amount of time to allow for elapsed
const double MaxElapsed = 0.050;
/// Frame duration in milliseconds
const int FrameDuration = 30;
/// Level 0 filename
wstring Level0 = L"levels/level0.xml";
/// Level 1 filename
wstring Level1 = L"levels/level1.xml";
/// Level 2 filename
wstring Level2 = L"levels/level2.xml";
/// Level 3 filename
wstring Level3 = L"levels/level3.xml";
// CChildView
CChildView::CChildView()
{
}
CChildView::~CChildView()
{
}
BEGIN_MESSAGE_MAP(CChildView, CWnd)
ON_WM_PAINT()
ON_WM_TIMER()
ON_WM_ERASEBKGND()
ON_COMMAND(ID_LEVEL_LEVEL0, &CChildView::OnLevelLevel0)
ON_COMMAND(ID_LEVEL_LEVEL1, &CChildView::OnLevelLevel1)
ON_COMMAND(ID_LEVEL_LEVEL2, &CChildView::OnLevelLevel2)
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_COMMAND(ID_LEVEL_LEVEL3, &CChildView::OnLevelLevel3)
END_MESSAGE_MAP()
// CChildView message handlers
BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs)
{
if (!CWnd::PreCreateWindow(cs))
return FALSE;
cs.dwExStyle |= WS_EX_CLIENTEDGE;
cs.style &= ~WS_BORDER;
cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,
::LoadCursor(nullptr, IDC_ARROW), reinterpret_cast<HBRUSH>(COLOR_WINDOW+1), nullptr);
return TRUE;
}
/**
* This function is called for everytime there is a screen update.
This is where all drawing starts.
*/
void CChildView::OnPaint()
{
if (mFirstDraw)
{
mFirstDraw = false;
SetTimer(1, FrameDuration, nullptr);
/*
* Initialize the elapsed time system
*/
LARGE_INTEGER time, freq;
QueryPerformanceCounter(&time);
QueryPerformanceFrequency(&freq);
mLastTime = time.QuadPart;
mTimeFreq = double(freq.QuadPart);
}
/*
* Compute the elapsed time since the last draw
*/
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
long long diff = time.QuadPart - mLastTime;
double elapsed = double(diff) / mTimeFreq;
mLastTime = time.QuadPart;
//
// Prevent tunnelling
//
while (elapsed > MaxElapsed)
{
mGame.Update(MaxElapsed);
elapsed -= MaxElapsed;
}
// Consume any remaining time
if (elapsed > 0)
{
mGame.Update(elapsed);
}
CPaintDC paintDC(this);
CDoubleBufferDC dc(&paintDC); // device context for painting
Graphics graphics(dc.m_hDC);
// get the client's rectangle viewing box
CRect rect;
GetClientRect(&rect);
mGame.OnDraw(&graphics, rect.Width(), rect.Height());
}
/**
* Handle timer events
* \param nIDEvent The timer event ID
*/
void CChildView::OnTimer(UINT_PTR nIDEvent)
{
Invalidate();
CWnd::OnTimer(nIDEvent);
}
/**
* Erase the background
*
* This is disabled to eliminate flicker
* \param pDC Device context
* \returns FALSE
*/
BOOL CChildView::OnEraseBkgnd(CDC* pDC)
{
return FALSE;
}
/**
* Handler for loading Level0
*/
void CChildView::OnLevelLevel0()
{
auto newLevel = make_shared<CLevel>(&mGame, Level0);
int levelNumber = 0;
mGame.SetLevel(newLevel, levelNumber);
}
/**
* Handler for loading Level1
*/
void CChildView::OnLevelLevel1()
{
auto newLevel = make_shared<CLevel>(&mGame, Level1);
int levelNumber = 1;
mGame.SetLevel(newLevel, levelNumber);
}
/**
* Handler for loading Level2
*/
void CChildView::OnLevelLevel2()
{
auto newLevel = make_shared<CLevel>(&mGame, Level2);
int levelNumber = 2;
mGame.SetLevel(newLevel, levelNumber);
}
/**
* Handler for loading Level3
*/
void CChildView::OnLevelLevel3()
{
auto newLevel = make_shared<CLevel>(&mGame, Level3);
int levelNumber = 3;
mGame.SetLevel(newLevel, levelNumber);
}
/**
* Called when there is a left mouse button press
* \param nFlags Flags associated with the mouse button press
* \param point Where the button was pressed
*/
void CChildView::OnLButtonDown(UINT nFlags, CPoint point)
{
mGame.OnLButtonDown(point.x, point.y);
}
/**
* Called when the left mouse button is released
* \param nFlags Flags associated with the mouse button release
* \param point Where the button was pressed
*/
void CChildView::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
OnMouseMove(nFlags, point);
}
/**
* Called when the mouse is moved
* \param nFlags Flags associated with the mouse movement
* \param point Where the button was pressed
*/
void CChildView::OnMouseMove(UINT nFlags, CPoint point)
{
mGame.OnMouseMove(point.x, point.y, nFlags);
}
|
#include "AppContext.h"
std::string AppContext::get_current_space_name() {
return current_space_name;
}
void AppContext::set_current_space_name(std::string &value) {
current_space_name = value;
}
std::string AppContext::get_current_variable_name() {
return current_variable_name;
}
void AppContext::set_current_variable_name(std::string &value) {
current_variable_name = value;
}
std::string AppContext::getCommunicate() {
return communicate;
}
void AppContext::setCommunicate(std::string &value) {
communicate = value;
}
void AppContext::setCommunicate(const char *value) {
communicate = std::string(value);
}
void AppContext::clearCommunicate() {
communicate.clear();
}
const std::unique_ptr<AbstractView> &AppContext::get_current_view() {
if (currentView == nullptr) {
currentView = std::make_unique<SpaceView>();
}
return currentView;
}
void AppContext::setViewToPrevious() {
if (!(previousView == nullptr)) {
currentView = std::move(previousView);
current_input_index = 0;
inputs_list.clear();
}
}
void AppContext::invalidate_last_input() {
current_input_index = 0;
inputs_list.pop_back();
}
bool AppContext::get_is_closing() {
return is_closing;
}
void AppContext::add_input(std::string &input) {
current_input_index++;
inputs_list.push_back(input);
}
unsigned long AppContext::get_current_input_index() {
return current_input_index;
}
void AppContext::increment_current_input_index() {
current_input_index++;
}
void AppContext::clear_current_input_index() {
current_input_index = 0;
}
void AppContext::safe_exit_program() {
is_closing = true;
}
std::vector<std::string> &AppContext::get_inputs_list() {
return inputs_list;
}
std::string AppContext::current_space_name;
std::string AppContext::current_variable_name;
std::string AppContext::communicate;
std::unique_ptr<AbstractView> AppContext::currentView;
std::unique_ptr<AbstractView> AppContext::previousView;
std::vector<std::string> AppContext::inputs_list;
unsigned long AppContext::current_input_index;
bool AppContext::is_closing = false;
|
// Include required header files from OpenCV directory
#include "opencv2/core.hpp"
#include "opencv2/face.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <regex>
#include "/usr/local/include/opencv2/objdetect.hpp"
#include "/usr/local/include/opencv2/highgui.hpp"
#include "/usr/local/include/opencv2/imgproc.hpp"
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <vector>
/// when run on PC not on arm , turn this on
#define PC
#define HO_Label 2
using namespace cv;
using namespace cv::face;
using namespace std;
void showFeatureAndSaveInformation(Ptr<FisherFaceRecognizer> model, int argc, int height, string output_folder);
static Mat norm_0_255(InputArray _src)
{
Mat src = _src.getMat();
// Create and return normalized image:
Mat dst;
switch (src.channels())
{
case 1:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
break;
case 3:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
break;
default:
src.copyTo(dst);
break;
}
return dst;
}
static void read_csv(const string &filename, vector<Mat> &images, vector<int> &labels, char separator = ';')
{
std::ifstream file(filename.c_str(), ifstream::in);
if (!file)
{
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(Error::StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line))
{
//cout << "line " << line << endl;
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
//cout << "path " << path << endl;
//cout << imread(path,0) << endl;
if (!path.empty() && !classlabel.empty())
{
images.push_back(imread(path, 0));
labels.push_back(atoi(classlabel.c_str()));
}
}
}
string cascadeName, nestedCascadeName;
struct framebuffer_info
{
uint32_t bits_per_pixel; // depth of framebuffer
uint32_t xres_virtual; // how many pixel in a row in virtual screen
uint32_t yres_virtual;
};
struct framebuffer_info get_framebuffer_info(const char *framebuffer_device_path)
{
struct framebuffer_info info;
struct fb_var_screeninfo screen_info;
int fd = -1;
fd = open(framebuffer_device_path, O_RDWR);
if (fd >= 0)
{
if (!ioctl(fd, FBIOGET_VSCREENINFO, &screen_info))
{
info.xres_virtual = screen_info.xres_virtual; // ¤@¦æ¦³¦h¤ÖÓpixel
info.yres_virtual = screen_info.yres_virtual; // ¤@¦æ¦³¦h¤ÖÓpixel
info.bits_per_pixel = screen_info.bits_per_pixel; //¨CÓpixelªº¦ì¼Æ
}
}
return info;
};
namespace patch
{
template <typename T>
std::string to_string(const T &n)
{
std::ostringstream stm;
stm << n;
return stm.str();
}
} // namespace patch
/*
this class read old Feature which are projections of old face to model eigenvectors
than do MSE on these feature with our current face
if MSE is small , we predict its label
if MSE is not small to all fecture,we label it as unknown
*/
class oldFeaturePredict
{
public:
vector<int> label_list;
vector<cv::Mat> old_projection_list;
string projectionFileName = "record/faceProjection.txt";
cv::Mat model_eigenvectors;
cv::Mat model_mean;
int threshold = 400;
oldFeaturePredict(cv::Mat model_eigenvectors, cv::Mat model_mean) : model_eigenvectors(model_eigenvectors), model_mean(model_mean)
{
readProjectionFromFile();
}
void readProjectionFromFile()
{
ifstream file(projectionFileName, ios::in);
if (!file.is_open())
{
cout << " can't open file for readProjectionFromFile" << endl;
}
cout << " start readProjectionFromFile -----" << endl;
fflush(stdout);
string line;
regex re("(\\d),\\[([+-]?[0-9]*[.][0-9]+), ([+-]?[0-9]*[.][0-9]+), ([+-]?[0-9]*[.][0-9]+)\\]");
//regex re("((\\d)),\\[([+-]?([0-9]*[.])?[0-9]+)+\\]");
//regex re("((\\d)),\\[([+-]?([0-9]*[.])?[0-9]+)");
smatch sm;
int count = 0;
map<int, int> eachClassOccureCount;
while (getline(file, line))
{
//cout << "line" << line << endl;
regex_search(line, sm, re);
//cout << "sm======" << endl;
//for (auto tmp : sm)
//{
//cout << tmp << endl;
//}
int label = stoi(sm[1].str());
if (eachClassOccureCount[label]++ > 15)
{
continue;
}
if (count++ > 50)
{
break;
}
label_list.push_back(label);
Mat old_projection_item = Mat(1, 3, CV_64F);
//cout << "old_projection_item size" << old_projection_item.size() << endl;
old_projection_item.at<double>(0, 0) = stod(sm[2].str());
old_projection_item.at<double>(0, 1) = stod(sm[3].str());
old_projection_item.at<double>(0, 2) = stod(sm[4].str());
//cout << "old_projection item" << old_projection_item << endl;
old_projection_list.push_back(old_projection_item);
}
cout << "saved projection values" << endl;
for (auto item : label_list)
{
cout << item << endl;
}
for (auto item : old_projection_list)
{
cout << item << endl;
}
}
void predict(InputArray _src, int &label, double &confidence) const
{
// get data
Mat src = _src.getMat();
// project into PCA subspace
Mat q = LDA::subspaceProject(model_eigenvectors, model_mean, src.reshape(1, 1));
for (size_t sampleIdx = 0; sampleIdx < old_projection_list.size(); sampleIdx++)
{
//cout << "***old_projection_list["<<sampleIdx << "]" << old_projection_list[sampleIdx] << endl;
//cout << "---q" << q << endl;
double dist = norm(old_projection_list[sampleIdx], q, NORM_L2);
int tmp_label = label_list[sampleIdx];
label = tmp_label;
confidence = dist;
if (label != 2 && label !=3)
{
if (dist < 600)
{
cout << "****saved Feature predict label:unknown(" << label << ") confidence:" << confidence << endl;
return;
}
}
else
{
if (dist < 600)
{
cout << "****saved Feature predict label:" << label << " confidence:" << confidence << endl;
return;
}
}
}
cout << "**** saved Feature predict label : Unknow" << endl;
label = -1;
}
};
int main(int argc, const char *argv[])
{
// ----------------------------------
// Initialization
// ----------------------------------
Mat frame, image;
double scale = 1;
CascadeClassifier cascade, nestedCascade;
nestedCascade.load("haarcascades/haarcascade_eye_tree_eyeglasses.xml");
cascade.load("haarcascades/haarcascade_frontalface_alt2.xml");
cout << "Load CascadeClassifier Done" << endl;
// ----------------------------------
// Prepare Face Recognition Model
// ----------------------------------
if (argc < 1)
{
cout << "usage: " << argv[0] << " <csv.ext> " << endl;
exit(1);
}
string output_folder = ".";
if (argc == 3)
{
output_folder = string(argv[2]);
}
string fn_csv = string(argv[1]);
vector<Mat> images;
vector<int> labels;
try
{
read_csv(fn_csv, images, labels);
}
catch (const cv::Exception &e)
{
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
// nothing more we can do
exit(1);
}
if (images.size() <= 1)
{
string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
CV_Error(Error::StsError, error_message);
}
cout << "Training EigenFaceRecognizer..." << endl;
Ptr<FisherFaceRecognizer> model = FisherFaceRecognizer::create();
model->train(images, labels);
Mat eigenvalues = model->getEigenValues();
// And we can do the same to display the Eigenvectors (read Eigenfaces):
Mat eigenVectors = model->getEigenVectors();
// Get the sample mean from the training data
Mat mean = model->getMean();
// build old projection class
oldFeaturePredict oldFeaturePredict_obj(eigenVectors, mean);
// ----------------------------------
// open camera device
// ----------------------------------
const int frame_rate = 10;
#if defined(PC)
cv::VideoCapture camera(0);
#else
cv::VideoCapture camera(2);
#endif
framebuffer_info fb_info = get_framebuffer_info("/dev/fb0");
std::ofstream ofs("/dev/fb0");
if (!camera.isOpened())
{
std::cerr << "Could not open video device." << std::endl;
return 1;
}
int framebuffer_width = fb_info.xres_virtual;
int framebuffer_height = fb_info.yres_virtual;
int framebuffer_depth = fb_info.bits_per_pixel;
//camera.set(CAP_PROP_FRAME_HEIGHT, framebuffer_height);
//camera.set(CAP_PROP_FPS, frame_rate);
// streaming
cout << "Get Webcam, Start Streaming and Face Detection..." << endl;
int height = images[0].rows;
showFeatureAndSaveInformation(model, argc, height, output_folder);
ofstream saveProjectionFile(output_folder + "/faceProjection.txt", ios::out | ios::app);
fflush(stdout);
while (true)
{
camera >> frame;
if (frame.empty())
break;
Mat img = frame.clone();
// ----------------------------------
// Face Detection
// ----------------------------------
vector<Rect> faces, faces2;
Mat gray, smallImg;
cvtColor(img, gray, COLOR_BGR2GRAY); // Convert to Gray Scale
double fx = 1 / scale;
// Resize the Grayscale Image
resize(gray, smallImg, Size(), fx, fx, INTER_LINEAR);
equalizeHist(smallImg, smallImg);
// Detect faces of different sizes using cascade classifier
cascade.detectMultiScale(smallImg, faces, 1.3, 3, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
// Draw circles around the faces
for (size_t i = 0; i < faces.size(); i++)
{
Rect r = faces[i];
Mat smallImgROI;
vector<Rect> nestedObjects;
Point center;
Scalar color = Scalar(0, 255, 0); // Color for Drawing tool
int radius;
double aspect_ratio = (double)r.width / r.height;
rectangle(img, cv::Point(cvRound(r.x * scale), cvRound(r.y * scale)),
cv::Point(cvRound((r.x + r.width - 1) * scale),
cvRound((r.y + r.height - 1) * scale)),
color, 3, 8, 0);
if (nestedCascade.empty())
continue;
smallImgROI = smallImg(r);
Mat resized;
resize(gray(r), resized, Size(92, 112), 0, 0, INTER_CUBIC);
// ----------------------------------
// Face Recognition
// ----------------------------------
int predictedLabel = -1;
double confidence = 0.0;
//cout << "Get Face! Start Face Recognition..." << endl;
model->predict(resized, predictedLabel, confidence);
/// show current face projection to eigenvector
Mat projection = LDA::subspaceProject(eigenVectors, mean, resized.reshape(1, 1));
cout << "current Face Projection to eigenvetors space:" << projection << endl;
// save current face feature ,let we can load this feature after to predict face
if (confidence < 800)
{
saveProjectionFile << predictedLabel << "," << projection << endl;
}
else
{
//saveProjectionFile << "0"<< "," << projection << endl;
}
/////////////use saved Feature to prediction
int oldProjectionPredictLabel = -1;
double oldProjectionConfidence = 0.0;
oldFeaturePredict_obj.predict(resized, oldProjectionPredictLabel, oldProjectionConfidence);
string result_message = format("!!!!Predicted class = %d, Confidence = %f", predictedLabel, confidence);
cout << result_message << endl;
string name = "";
if (confidence > 1000)
name = "Unknown";
else if (predictedLabel == 2)
name = "309551111";
else if (predictedLabel == 3)
name = "409551005";
else
name = "Unknown";
// Draw name on image
int font_face = cv::FONT_HERSHEY_COMPLEX;
double font_scale = 1;
int thickness = 1;
int baseline;
cv::Size text_size = cv::getTextSize(name, font_face, font_scale, thickness, &baseline);
cv::Point origin;
origin.x = cvRound(r.x * scale);
origin.y = cvRound(r.y * scale) - text_size.height / 2;
cv::putText(img, name, origin, font_face, font_scale, cv::Scalar(0, 255, 255), thickness, 8, 0);
// Detect and draw eyes on image
nestedCascade.detectMultiScale(smallImgROI, nestedObjects, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
for (size_t j = 0; j < nestedObjects.size(); j++)
{
Rect nr = nestedObjects[j];
center.x = cvRound((r.x + nr.x + nr.width * 0.5) * scale);
center.y = cvRound((r.y + nr.y + nr.height * 0.5) * scale);
radius = cvRound((nr.width + nr.height) * 0.25 * scale);
circle(img, center, radius, color, 3, 8, 0);
}
}
// press to exit
char c = (char)waitKey(10);
if (c == 27 || c == 'q' || c == 'Q')
{
//saveProjectionFile.close();
break;
}
// Display with imshow
#if defined(PC)
imshow("FaceDetection", img);
// Display with frame buffer
#else
cv::Size2f frame_size = img.size();
cv::Mat framebuffer_compat;
cv::cvtColor(img, framebuffer_compat, cv::COLOR_BGR2BGR565);
for (int y = 0; y < frame_size.height; y++)
{
ofs.seekp(y * fb_info.xres_virtual * fb_info.bits_per_pixel / 8);
ofs.write(reinterpret_cast<char *>(framebuffer_compat.ptr(y)), frame_size.width * fb_info.bits_per_pixel / 8);
}
#endif
}
camera.release();
return 0;
}
void showFeatureAndSaveInformation(Ptr<FisherFaceRecognizer> model, int argc, int height, string output_folder)
{
Mat eigenvalues = model->getEigenValues();
// And we can do the same to display the Eigenvectors (read Eigenfaces):
Mat W = model->getEigenVectors();
// Get the sample mean from the training data
Mat mean = model->getMean();
// Display or save the image reconstruction at some predefined steps:
ofstream saveEigenValueFile(output_folder + "/eigenValue.txt", ios::out);
for (int i = 0; i < min(16, W.cols); i++)
{
saveEigenValueFile << "eigenValue:" << endl;
saveEigenValueFile << eigenvalues.at<double>(i) << endl;
string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
cout << msg << endl;
// get eigenvector #i
Mat ev = W.col(i).clone();
// Reshape to original size & normalize to [0...255] for imshow.
Mat grayscale = norm_0_255(ev.reshape(1, height));
// Show the image & apply a Bone colormap for better sensing.
Mat cgrayscale;
applyColorMap(grayscale, cgrayscale, COLORMAP_BONE);
// Display or save:
#if defined(PC)
if (argc == 2)
{
imshow(format("fisherface_%d", i), cgrayscale);
}
else
{
imwrite(format("%s/fisherface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
}
#else
if (argc == 2)
{
}
else
{
imwrite(format("%s/fisherface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
}
#endif
}
saveEigenValueFile.close();
/// save model
model->write(output_folder + "/model.xml");
}
|
#include <ESP8266WiFi.h>
#include <mDNSResolver.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <PubSubClient.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <EEPROM.h>
#include <math.h>
#include <vector>
#define UNUSED(x) (void)x
//#define SERIAL_OUT
#ifdef SERIAL_OUT
#define SERIAL(x) Serial.x
#else
#define SERIAL(x)
#endif
//Secrets
#define OTA_PASSWORD ""
#define OTA_HOSTNAME ""
const String ssid = "";//SET THIS
const String password = "";//SET THIS
const String domain = "local";
//MQTT SETUP (set these)
#define MQTT_CLIENT_NAME ""
#define MQTT_HOSTNAME ""
#define MQTT_IP ""
#define MQTT_PORT 1883 // use 8883 for SSL
const char* MQTT_ORDERS = "";
bool mqtt_led = false;
Adafruit_SSD1306 oled = Adafruit_SSD1306();
//WIFI SETUP
WiFiClient wifi;
WiFiUDP udp;
IPAddress mqtt_ip;
bool wifi_connect() {
delay(10);
oled.printf("Connecting to %s", ssid.c_str());
oled.display();
SERIAL(printf("Connecting to %s", ssid.c_str()));
WiFi.begin(ssid.c_str(), password.c_str());
while (WiFi.status() != WL_CONNECTED) {
delay(500);
oled.print(".");
oled.display();
SERIAL(print("."));
}
oled.print("\n");
oled.println(WiFi.localIP());
oled.display();
SERIAL(print(WiFi.localIP()));
SERIAL(print(" ("));
SERIAL(print(WiFi.subnetMask()));
SERIAL(print(")\n"));
delay(500);
oled.clearDisplay();
return wifi.connected();
}
// $ per minute
// $ today
typedef struct {
uint32_t cost;
uint32_t expire_time;
} order;
float total_money = 0.0f;
float display_money = 0.0f;
std::vector<order> past_orders;
const uint32_t expire_seconds = 5;
const float max_lagtime = 2000.0f;
const float max_discrepancy = 10000.0f;
uint32_t time_counter = 0;
StaticJsonBuffer<2048> jsonBuffer;
void update_display() {
float discrepancy = (total_money - display_money);
uint32_t t = millis() - time_counter;
float pressure = (float)t / max_lagtime;
if (pressure >= 1.0f)
display_money = total_money;
else
display_money += discrepancy * pressure;
oled.clearDisplay();
oled.setCursor(0, 0);
char money_str[17];
char postfix;
if (display_money < 100000.00f) {
dtostrf(display_money, 8, 2, money_str);
postfix = ' ';
} else if (display_money >= 100000.0f && display_money < 100000000.0f) {
dtostrf(display_money/1000.0f, 8, 2, money_str);
postfix = 'K';
} else if (display_money >= 100000000.0f && display_money < 100000000000.0f) {
dtostrf(display_money/1000000, 8, 2, money_str);
postfix = 'M';
} else if (display_money >= 100000000000.0f && display_money < 100000000000000.0f) {
dtostrf(display_money/1000000000, 8, 2, money_str);
postfix = 'B';
}
uint32_t money_per_second = 0;
std::vector<order>::iterator i = past_orders.begin();
while(i != past_orders.end()) {
if (i->expire_time > millis()) {
money_per_second += i->cost;
++i;
} else {
i = past_orders.erase(i);
}
}
SERIAL(printf("$%s%c\n", &money_str[0], postfix));
oled.printf("$%s%c", &money_str[0], postfix);
SERIAL(printf("A$ps %d\n", money_per_second));
oled.printf("$%5d/sec", money_per_second);
oled.display();
}
//MQTT
PubSubClient client(wifi);
String clientId;
void mqtt_connect() {
while (!client.connected()) {
if (client.connect(clientId.c_str())) {
client.subscribe(MQTT_ORDERS, 1);
SERIAL(println("MQTT Connected"));
} else {
delay(5000);
SERIAL(printf("MQTT Failure %d\n", client.state()));
}
}
}
bool is_topic(const char* t, const char *tt) {
return strcmp(t, tt) == 0;
}
uint32_t write_timer = 0;
const uint32_t write_rate = 360000;
void mqtt_callback(char *topic, uint8_t* payload, uint32_t len) {
UNUSED(payload);
UNUSED(len);
if (is_topic(topic, MQTT_ORDERS)) {
digitalWrite(0, mqtt_led ? HIGH : LOW);
mqtt_led = !mqtt_led;
JsonObject& root = jsonBuffer.parseObject((char*)payload);
if(!root.containsKey("spend_amount") || !root.containsKey("tip_amount")) return;
time_counter = millis();
float money = (((float)atoi(root["spend_amount"])) + ((float)atoi(root["tip_amount"])))/100.0f;
past_orders.push_back({((uint32_t)money)/expire_seconds, millis()+(1000 * expire_seconds)});
total_money += money;
if (millis() - write_timer > write_rate) {
write_totals();
write_timer = millis();
}
update_display();
jsonBuffer.clear();
}
}
//OTA setup
void setup_ota() {
// Port defaults to 8266
ArduinoOTA.setPort(8266);
// Hostname defaults to esp8266-[ChipID]
ArduinoOTA.setHostname(OTA_HOSTNAME);
// No authentication by default
ArduinoOTA.setPassword((const char *)OTA_PASSWORD);
ArduinoOTA.onStart([]() {
oled.clearDisplay();
oled.println("Start");
oled.display();
});
ArduinoOTA.onEnd([]() {
oled.clearDisplay();
oled.println("\nEnd");
oled.display();
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
oled.clearDisplay();
oled.printf("Progress: %u%%\r", (progress / (total / 100)));
oled.display();
});
ArduinoOTA.onError([](ota_error_t error) {
oled.clearDisplay();
oled.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) oled.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) oled.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) oled.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) oled.println("Receive Failed");
else if (error == OTA_END_ERROR) oled.println("End Failed");
oled.display();
});
ArduinoOTA.begin();
}
//==ENTRY==
void setup_connections() {
wifi_connect();
while (udp.parsePacket() > 0);
int res = WiFi.hostByName(MQTT_HOSTNAME, mqtt_ip);
if (res != 1) {
mDNSResolver::Resolver resolver(udp);
resolver.setLocalIP(WiFi.localIP());
mqtt_ip = resolver.search(MQTT_HOSTNAME);
if (mqtt_ip == INADDR_NONE) {
//HARDCODED IP
oled.println("MQTT:Hardcoded");
oled.display();
SERIAL(println("Using hardcoded IP"));
mqtt_ip.fromString(MQTT_IP);
}
}
clientId = MQTT_CLIENT_NAME;
clientId += String(random(0xffff), HEX);
SERIAL(printf("Client: %s\n", clientId.c_str()));
oled.clearDisplay();
oled.setCursor(0, 3);
oled.printf("%s:", clientId.c_str());
oled.print(mqtt_ip);
oled.println("");
client.setServer(mqtt_ip, MQTT_PORT);
client.setCallback(mqtt_callback);
udp.stop();
}
int address = 0;
byte value;
//Total money and last average value
void read_totals() {
EEPROM.get(0, total_money);
}
void write_totals() {
EEPROM.put(0, total_money);
EEPROM.commit();
}
void setup() {
#ifdef SERIAL_OUT
Serial.begin(115200);
#endif
pinMode(0, OUTPUT);
digitalWrite(0, LOW);
oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
oled.clearDisplay();
oled.setCursor(0, 0);
oled.setTextSize(1);
oled.setTextColor(WHITE);
oled.println("Booting");
oled.display();
SERIAL(println("Booting"));
setup_connections();
setup_ota();
time_counter = millis();
EEPROM.begin(512);
read_totals();
if (isnan(total_money))
total_money = 0.0f;
oled.setCursor(0, 1);
oled.println("System Up");
oled.display();
oled.setCursor(0, 0);
SERIAL(println("System Up"));
oled.setTextSize(2);
delay(1000);
}
void loop() {
ArduinoOTA.handle();
mqtt_connect();
client.loop();
update_display();
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::ApplicationModel::SocialInfo {
struct ISocialFeedChildItem;
struct ISocialFeedContent;
struct ISocialFeedItem;
struct ISocialFeedSharedItem;
struct ISocialItemThumbnail;
struct ISocialUserInfo;
struct SocialFeedChildItem;
struct SocialFeedContent;
struct SocialFeedItem;
struct SocialFeedSharedItem;
struct SocialItemThumbnail;
struct SocialUserInfo;
}
namespace Windows::ApplicationModel::SocialInfo {
struct ISocialFeedChildItem;
struct ISocialFeedContent;
struct ISocialFeedItem;
struct ISocialFeedSharedItem;
struct ISocialItemThumbnail;
struct ISocialUserInfo;
struct SocialFeedChildItem;
struct SocialFeedContent;
struct SocialFeedItem;
struct SocialFeedSharedItem;
struct SocialItemThumbnail;
struct SocialUserInfo;
}
namespace Windows::ApplicationModel::SocialInfo {
template <typename T> struct impl_ISocialFeedChildItem;
template <typename T> struct impl_ISocialFeedContent;
template <typename T> struct impl_ISocialFeedItem;
template <typename T> struct impl_ISocialFeedSharedItem;
template <typename T> struct impl_ISocialItemThumbnail;
template <typename T> struct impl_ISocialUserInfo;
}
namespace Windows::ApplicationModel::SocialInfo {
enum class [[deprecated("SocialFeedItemStyle is deprecated and might not work on all platforms. For more info, see MSDN.")]] SocialFeedItemStyle
{
Default = 0,
Photo = 1,
};
enum class [[deprecated("SocialFeedKind is deprecated and might not work on all platforms. For more info, see MSDN.")]] SocialFeedKind
{
HomeFeed = 0,
ContactFeed = 1,
Dashboard = 2,
};
enum class [[deprecated("SocialFeedUpdateMode is deprecated and might not work on all platforms. For more info, see MSDN.")]] SocialFeedUpdateMode
{
Append = 0,
Replace = 1,
};
enum class [[deprecated("SocialItemBadgeStyle is deprecated and might not work on all platforms. For more info, see MSDN.")]] SocialItemBadgeStyle
{
Hidden = 0,
Visible = 1,
VisibleWithCount = 2,
};
}
}
|
#pragma once
#include<string>
#include<iostream>
class Student {
private:
std::string name;
int score;
public:
Student(std::string name="", int score=0)
{
this->name = name;
this->score = score;
}
friend std::ostream& operator<<(std::ostream& out, Student& student) {
out << "name : " << student.name << ", " << " score : " << student.score;
return out;
}
};
|
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include "easyfind.hpp"
int main(void)
{
//vector
std::vector<int> vect(10);
int value = 2;
std::fill(vect.begin(), vect.end(), value);
std::vector<int>::iterator found = easyfind(vect, 2);
if (found == vect.end())
std::cout << "[+]Vector[+] Eror 404 Dont found" << std::endl;
else
std::cout << "[+]Vector[+] Yeah " << *found << " is inside me in " << found - vect.begin() << std::endl;
if (easyfind(vect, 666) == vect.end())
std::cout << "[+]Vector[+] Eror 404 Dont found" << std::endl;
//map
std::map<int, int> map;
map.insert(std::pair<int,int>( 2, 30 ));
map.insert(std::pair<int,int>( 1, 42 ));
map.insert(std::pair<int,int>( 3, 42 ));
std::map<int, int>::iterator foundMap = easyfind(map, 42);
if (foundMap == map.end())
std::cout << "[+]Map[+] Eror 404 Dont found" << std::endl;
else
std::cout << "[+]Map[+] Yeah " << foundMap->second << " is inside me in " << foundMap->first << std::endl;
if (easyfind(map, 666) == map.end())
std::cout << "[+]Map[+] Eror 404 Dont found" << std::endl;
//multimap
std::multimap<int, int> multimap;
multimap.insert(std::pair<int,int>( 2, 30 ));
multimap.insert(std::pair<int,int>( 33, 9 ));
std::multimap<int, int>::iterator foundMP = easyfind(multimap, 9);
if (foundMP == multimap.end())
std::cout << "[+]MultiMap[+] Eror 404 Dont found" << std::endl;
else
std::cout << "[+]MultiMap[+] Yeah " << foundMP->second <<" is inside me in " << foundMP->first << std::endl;
if (easyfind(multimap, 666) == multimap.end())
std::cout << "[+]MultiMap[+] Eror 404 Dont found" << std::endl;
return (0);
}
|
#pragma once
#include <cryptopp/osrng.h>
#include <array>
#include "Network.h"
typedef std::array<byte, CryptoPP::AES::DEFAULT_KEYLENGTH> AESKey;
AESKey generateKey(CryptoPP::AutoSeededRandomPool& rng);
void save_key(AESKey& aes_key, PublicKey& publicKey, CryptoPP::AutoSeededRandomPool& rng);
void encrypt_file(const std::string& filename, std::array<byte, CryptoPP::AES::DEFAULT_KEYLENGTH>& aes_key, CryptoPP::AutoSeededRandomPool& rng);
void decrypt_file(const std::string& filename, std::array<byte, CryptoPP::AES::DEFAULT_KEYLENGTH>& aes_key);
AESKey loadKey(PrivateKey& privateKey, CryptoPP::AutoSeededRandomPool& rng);
|
#include <cstring>
#include "Utility.hpp"
bool shiku::Utility::IsEndsWith(const char *str, const char *suffix)
{
int len1 = strlen(str);
int len2 = strlen(suffix);
if(len1 < len2)
return false;
for(int i = 1; i <= len2; ++i)
if(str[len1 - i] != suffix[len2 - i])
return false;
return true;
}
uint32_t shiku::Utility::BkdrHash(const char *str)
{
static uint32_t seed = 131;
uint32_t hash = 0;
while(*str)
hash = hash * seed + (*str++);
return hash & 0x7FFFFFFF;
}
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
using namespace std;
using namespace __gnu_pbds;
using ll = long long int;
typedef pair <int,int> PII;
typedef pair <ll,ll> PLL;
#define F first
#define S second
#define all(v) (v).begin(),(v).end()
typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
//find_by_order(k) --> returns iterator to the kth largest element counting from 0
//order_of_key(val) --> returns the number of items in a set that are strictly smaller than our item
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// to generate a uniform random integer over a range [l,r], use
// int x = uniform_int_distribution<int>(l,r)(rng);
// unordered map
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
struct chash { /// use most bits rather than just the lowest ones
const uint64_t C = ll(2e18*acos((long double)-1))+71; // large odd number
const int RANDOM = rng();
ll operator()(ll x) const { /// https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
return __builtin_bswap64((x^RANDOM)*C); }
};
template<class K,class V> using ht = gp_hash_table<K,V,chash>;
// declare map of <int,PLL> as
// ht<int, PLL> mp;
ll const MOD = 1e9 + 7;
#define L(x) (x) << 1
#define R(x) (x) << 1 | 1
using ll = long long int;
struct Node { // change
ll lv, rv, tot = 0, ending = 0, starting = 0, sz;
Node(){
tot = 0, ending = 0, starting = sz = 0;
}
Node(ll v){
sz = tot = ending = starting = (v != 0);
lv = rv = v;
}
// bool operator==(const Node &node) const { return val == node.val; }
};
const Node QUERY_IDENTITY(0); // change
const Node LAZY_IDENTITY(0); // change
int const N = 2e5 + 10;
Node t[4 * N]; ll a[N];
// Node lazy[4 * N];
Node merge(const Node &a, const Node &b) {
Node tmp;
tmp.tot = a.tot + b.tot;
tmp.lv = a.lv ? a.lv : b.lv;
tmp.rv = b.rv ? b.rv : a.rv;
tmp.starting = a.starting;
tmp.ending = b.ending;
tmp.sz = a.sz + b.sz;
if (a.rv <= b.lv){
tmp.tot += a.ending * b.starting;
}
if (a.starting == a.sz && a.rv <= b.lv) {
tmp.starting += b.starting;
}
if (b.ending == b.sz && a.rv <= b.lv) tmp.ending += a.ending;
return tmp;
} // change
/**
* Given the lazy in the node, and a new operation,
* update the lazy value.
**/
// void assignLazy(int p, Node op) { lazy[p].val += op.val; } // change
/**
* Given the lazy in for a node, calculate its value,
* and push the lazy down to the childs
**/
void push(int p, int l, int r) { // change
return;
// if (lazy[p] == LAZY_IDENTITY) {
// auto last = lazy[p];
// if (l != r) { for (auto ch : {L(p), R(p)}) { assignLazy(ch, last); } }
// t[p].val += (r - l + 1) * last.val;
// }
// lazy[p] = LAZY_IDENTITY;
}
void build(int p, int l, int r) {
if (l == r) {
t[p] = a[l]; return;
}
int mid = (l + r) / 2;
build(L(p), l, mid); build(R(p), mid + 1, r);
t[p] = merge(t[L(p)], t[R(p)]);
}
void update(int p, int l, int r, int ul, int ur, ll val) {
push(p, l, r); // The order matters
if (l > ur || r < ul) return;
if (ul <= l && r <= ur) {
t[p] = val;
// assignLazy(p, op);
return;
}
int mid = (l + r) / 2;
update(L(p), l, mid, ul, ur, val); update(R(p), mid + 1, r, ul, ur, val);
t[p] = merge(t[L(p)], t[R(p)]);
}
Node query(int p, int l, int r, int ql, int qr) {
push(p, l, r); // The order matters
if (l > qr || r < ql) return QUERY_IDENTITY;
if (ql <= l && r <= qr) return t[p];
int mid = (l + r) / 2;
return merge(query(L(p), l, mid, ql, qr), query(R(p), mid + 1, r, ql, qr));
}
void solve(int t){
int n, q;
cin >> n >> q;
for (int i = 1; i <= n; i++) cin >> a[i];
build(1, 1, n);
// cout << "hello" << endl;
while (q--){
int tp, x, y;
cin >> tp >> x >> y;
if (tp == 1){
update(1, 1, n, x, x, y);
}
if (tp == 2) {
cout << query(1, 1, n, x, y).tot << "\n";
}
}
}
int main(){
ios::sync_with_stdio(false); cin.tie(0);
int t = 1;
// cin >> t; // if no testcase, comment this out
for (int i = 1; i <= t; i++) solve(t);
return 0;
}
|
#include "hierarchy_node.hh"
#include <unistdx/base/make_object>
std::ostream&
bsc::operator<<(std::ostream& out, const hierarchy_node& rhs) {
return out << sys::make_object(
"socket_address", rhs.socket_address(),
"weight", rhs.weight()
);
}
|
#include<iostream>
#include<cstring>
using namespace std;
const int MAX_SIDE_NUMBER=100000;
const int MAX_POINT_NUMBER=100000;
class node
{
public:
int id;
node *side[MAX_SIDE_NUMBER];
double cost[MAX_SIDE_NUMBER];
int sideCount;
};
node *points[MAX_POINT_NUMBER];
int n,m;
void CreatePoint(int id)
{
points[id]=new node();
points[id]->id=id;
points[id]->sideCount=0;
}
void CreateLink(int a,int b,double cost)
{
if(points[a]==null)CreatePoint(a);
if(points[b]==null)CreatePoint(b);
points[a].cost[points[a].sideCount]=cost;
points[a].side[points[a].sideCount++]=b;
points[b].cost[points[b].sideCount]=cost;
points[b].side[points[b].sideCount++]=a;
}
int PointConnected[MAX_POINT_NUMBER];
bool CheckPointConnect(int a,int b)
{
}
void PrimInitialize()
{
memset(PointConnected,0,sizeof(PointConnected));
}
void prim()
{
while(true)
{
for(int i=0;i<n;i++)
{
}
}
}
int main()
{
int a,b;
double c;
cin >>n>>m;
for(int i=0;i<m;i++)
{
cin >>a>>b>>c;
CreateLink(a,b,c);
}
}
|
#ifndef DeviceNTP_h
#define DeviceNTP_h
#include "Arduino.h"
#include "../ArduinoJson/ArduinoJson.h"
#include "RemoteDebug.h"
#include "Udp.h"
#include "WiFiUdp.h"
#define SEVENZYYEARS 2208988800UL
#define NTP_PACKET_SIZE 48
#define DEVICE_NTP_SET_UPDATE_CALLBACK_SIGNATURE std::function<void(bool, bool)>
#define DEVICE_NTP_GET_BY_KEY_TOPIC_PUB "DeviceNTP/GetAllByKeyIoT"
#define DEVICE_NTP_GET_BY_KEY_COMPLETED_TOPIC_SUB "DeviceNTP/GetAllByKeyCompletedIoT"
#define DEVICE_NTP_SET_UTC_TIME_OFF_SET_IN_SECOND_TOPIC_SUB "DeviceNTP/SetUtcTimeOffsetInSecondIoT"
#define DEVICE_NTP_SET_UPDATE_INTERVAL_IN_MILLI_SECOND_TOPIC_SUB "DeviceNTP/SetUpdateIntervalInMilliSecondIoT"
namespace ART
{
class ESPDevice;
class DeviceNTP
{
public:
DeviceNTP(ESPDevice* espDevice);
~DeviceNTP();
void load(JsonObject& jsonObject);
char* getHost() const;
int getPort();
int getUtcTimeOffsetInSecond();
long getUpdateIntervalInMilliSecond();
/**
* Starts the underlying UDP client with the default local port
*/
void begin();
void getByKeyPub();
void getByKeySub(const char* json);
/**
* This should be called in the main loop of your application. By default an update from the NTP Server is only
* made every 60 seconds. This can be configured in the DeviceNTP constructor.
*
* @return true on success, false on failure
*/
bool update();
/**
* This will force the update from the NTP Server.
*
* @return true on success, false on failure
*/
bool forceUpdate();
int getDay();
int getHours();
int getMinutes();
int getSeconds();
/**
* @return time formatted like `hh:mm:ss`
*/
String getFormattedTimeOld();
String getFormattedTime();
/**
* @return time in seconds since Jan. 1, 1970
*/
unsigned long getEpochTime();
unsigned long getEpochTimeUTC();
/**
* Stops the underlying UDP client
*/
void end();
DeviceNTP& setUpdateCallback(DEVICE_NTP_SET_UPDATE_CALLBACK_SIGNATURE callback);
private:
ESPDevice * _espDevice;
char* _host;
int _port;
int _utcTimeOffsetInSecond;
long _updateIntervalInMilliSecond;
UDP* _udp;
bool _udpSetup = false;
unsigned long _currentEpoc = 0; // In s
unsigned long _lastUpdate = 0; // In ms
byte _packetBuffer[NTP_PACKET_SIZE];
void sendNTPPacket();
DEVICE_NTP_SET_UPDATE_CALLBACK_SIGNATURE _updateCallback;
bool _loaded = false;
void setUtcTimeOffsetInSecond(const char* json);
void setUpdateIntervalInMilliSecond(const char* json);
void onDeviceMQSubscribeDeviceInApplication();
void onDeviceMQUnSubscribeDeviceInApplication();
bool onDeviceMQSubscription(const char* topicKey, const char* json);
};
}
#endif
|
#include <iostream>
#include <algorithm>
#include <vector>
long long modul = 1e7 + 7;
long long result = 0;
void dfs(std::pair<long long, long long> pair, std::vector<std::pair<long long, long long>> *g, long long *sum, long long *temp)
{
temp[pair.first] = 1;
for (size_t i = 0; i < g[pair.first].size(); i++)
{
std::pair<long long, long long> node = g[pair.first][i];
if (node.first != pair.second)
{
dfs(std::make_pair(node.first, pair.first), g, sum, temp);
temp[pair.first] = (temp[pair.first] + temp[node.first]) % modul;
sum[pair.first] = (sum[pair.first] + (sum[node.first] + temp[node.first] * node.second) % modul) % modul;
}
}
for (size_t i = 0; i < g[pair.first].size(); i++)
{
std::pair<long long, long long> node = g[pair.first][i];
if (node.first != pair.second)
{
result += node.second * (temp[node.first]) % modul * (temp[pair.first] - temp[node.first]) % modul;
result %= modul;
result += sum[node.first] * (temp[pair.first] - temp[node.first]) % modul;
result %= modul;
}
}
}
int main()
{
long long N;
std::cin >> N;
std::vector<std::pair<long long, long long>> g[N];
long long A, B, C;
long long *temp = new long long[N];
long long *temp2 = new long long[N];
for (size_t i = 0; i < N - 1; i++)
{
std::cin >> A >> B >> C;
g[A - 1].push_back(std::make_pair(B - 1, C));
g[B - 1].push_back(std::make_pair(A - 1, C));
}
dfs(std::make_pair(0, -1), g, temp, temp2);
result = (result * 2) % modul;
std::cout << result << std::endl;
return 0;
}
|
/*
* Copyright 2016-2017 Flatiron Institute, Simons Foundation
*
* 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 QPROCESSMANAGER_H
#define QPROCESSMANAGER_H
#include <QMutex>
#include <QProcess>
#include <QSet>
#include <QSharedPointer>
#include <QStack>
class QProcessManager : public QObject {
Q_OBJECT
Q_PROPERTY(int count READ count NOTIFY countChanged)
public:
explicit QProcessManager(QObject* parent = 0);
~QProcessManager();
int count() const;
QSharedPointer<QProcess> start(const QString& program, const QStringList& arguments, QIODevice::OpenMode mode = QIODevice::ReadWrite);
QSharedPointer<QProcess> start(const QString& command, QIODevice::OpenMode mode = QIODevice::ReadWrite);
QSharedPointer<QProcess> start(QProcess* process, QIODevice::OpenMode mode = QIODevice::ReadWrite);
void remove(const QSharedPointer<QProcess>& ptr);
signals:
void countChanged(int);
public slots:
void closeAll();
QSharedPointer<QProcess> closeLast();
private slots:
void processDestroyed(QObject*);
void processFinished();
private:
QSharedPointer<QProcess> registerProcess(QProcess*);
void unregisterProcess(QProcess*);
QStack<QSharedPointer<QProcess> > m_stack;
mutable QMutex m_lock;
};
#endif // QPROCESSMANAGER_H
|
#ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#include "ofxSyphon.h"
class testApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void serverAnnounced(ofxSyphonServerDirectoryEventArgs &arg);
void serverUpdated(ofxSyphonServerDirectoryEventArgs &args);
void serverRetired(ofxSyphonServerDirectoryEventArgs &arg);
ofxSyphonClient mClient;
ofxSyphonServerDirectory dir;
bool serverAvailable;
};
#endif
|
#pragma once
#include <vector>
#include <iostream>
#include <list>
#include <memory>
#include <random>
#include <exception>
#include <algorithm>
#include <fstream>
using namespace std;
string createRandomString(int64_t len, int64_t alphabetSize, int64_t seed);
bool addBit(vector<bool> &bits);
string toString(vector<bool> &bits);
void createStringPermutation(uint64_t len, vector<string> &output);
string createDeBruijnSequence(uint64_t n);
string createFibonacciWord(int length);
namespace stool
{
template <class X>
bool equalCheck(vector<X> &item1, vector<X> &item2)
{
if (item1.size() != item2.size())
{
return false;
}
else
{
for (uint64_t i = 0; i < item1.size(); i++)
{
if (item1[i] != item2[i])
return false;
}
return true;
}
}
} // namespace stool
|
#ifndef INSTRUCOES_H
#define INSTRUCOES_H
#include <allegro.h>
class Instrucoes
{
private:
BITMAP* buffer;
BITMAP* bmp;
float pos_x;
float pos_y;
public:
Instrucoes();
virtual ~Instrucoes();
void Set_instrucoes(BITMAP* buffer, BITMAP* bmp);
void Executar();
void Print();
protected:
private:
};
#endif // INSTRUCOES_H
|
#include "thread.h"
#include <iostream>
#include <Windows.h>
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
extern bool test_mode;
base::thread::thread()
: _handle(0)
{}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
base::thread::~thread()
{}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void base::thread::start(const base::source_location &loc)
{
_handle = CreateThread(
0,
0,
(LPTHREAD_START_ROUTINE)thread::thread_fnc,
this,
0,
0);
if(_handle==0) {
throw base::exception(loc.to_str())
<< "thread::start failed! (err: "
<< GetLastError()
<< ")\n";
}
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void base::thread::stop(const base::source_location &loc)
{
loc;
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void* base::thread::thread_fnc(void* data)
{
try {
reinterpret_cast<thread*>(data)->run();
}
catch(const base::exception &e) {
std::cout << e.text();
if (!test_mode)
{
MessageBoxA(0, e.text().c_str(), "Error...", MB_APPLMODAL);
}
PostQuitMessage(-1);
return (void*)-1;
}
PostQuitMessage(-1);
return 0;
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
bool base::thread::wait_for_end(const unsigned int time /* = -1 */)
{
return WAIT_OBJECT_0 == WaitForSingleObject((HANDLE)_handle, time);
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void base::thread::terminate()
{
TerminateThread((HANDLE)_handle, DWORD(-1));
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
|
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial SIM900(3, 5); // configure software serial port
int SittingRoom = 8;
int Bedroom = 10;
int Security = 11;
char buffer[80];
byte pos = 0;
//resetting the buffer here
void resetBuffer() {
memset(buffer, 0, sizeof(buffer));
pos = 0;
}
void setup() {
pinMode(SittingRoom, OUTPUT);
pinMode(Bedroom, OUTPUT);
pinMode(Security, OUTPUT);
SIM900.begin(9600);
Serial.begin(9600);
Serial.println("power up" );
delay(15000);
}
void loop()
{
Serial.println("SubmitHttpRequest - started" );
SubmitHttpRequest();
Serial.println("SubmitHttpRequest - finished" );
delay(1000);
}
void SubmitHttpRequest()
{
SIM900.println("AT+CSQ"); // Signal quality check
delay(2000);
ShowSerialData();// this code is to show the data from gprs shield, in order to easily see the process of how the gprs shield submit a http request, and the following is for this purpose too.
SIM900.println("AT+CGATT?"); //Attach or Detach from GPRS Support
delay(2000);
ShowSerialData();
SIM900.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR, the connection type is using gprs
delay(2000);
ShowSerialData();
SIM900.println("AT+SAPBR=3,1,\"APN\",\"internet\"");//setting the APN, Access point name string
delay(2000);
ShowSerialData();
SIM900.println("AT+SAPBR=1,1");//setting the SAPBR
delay(10000);
ShowSerialData();
SIM900.println("AT+SAPBR=2,1");//getting ip address assigned
delay(1000);
ShowSerialData();
SIM900.println("AT+HTTPINIT"); //init the HTTP request
delay(2000);
ShowSerialData();
SIM900.println("AT+HTTPPARA=\"CID\",1"); //init the HTTP request
delay(2000);
ShowSerialData();
SIM900.println("AT+HTTPPARA=\"URL\",\"http://www.home-system.cynaut-tech.com/all-settings?username=engdave\"");
//SIM900.println("AT+HTTPPARA=REDIR,1");
delay(2000);
ShowSerialData();
SIM900.println("AT+HTTPACTION=0");//submit the request
delay(5000);
ShowSerialData();
SIM900.println("AT+HTTPREAD");// read the data from the website you access
delay(300);
ShowSerialData();
SIM900.println("AT+HTTPTERM");
ShowSerialData();
delay(300);
/*
SIM900.println("AT+SAPBR=0,1");
delay(5000);
ShowSerialData();
delay(5000);
*/
//SIM900.println("");
//delay(100);
}
void ShowSerialData() {
while (SIM900.available() != 0) {
Serial.write(char (SIM900.read()));
resetBuffer();
}
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "hlist.h"
#include "components.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
bool explore(S_expr* list1, S_expr* list2, string & result){
HList hlist;
if(!list1 && !list2)
return true;
if(!list1 || !list2)
return false;
if(hlist.isAtom(list1) && hlist.isAtom(list2)){
result.append("Found atoms.\n");
result+=list1->getNode().element;
result+='\t';
result+=list2->getNode().element;
result+='\n';
if(list1->getNode().element == list2->getNode().element){
result.append("Atoms are identical.\n");
return true;
}
else
result.append("Atoms are different.\n");
}
if(!hlist.isAtom(list1) && !hlist.isAtom(list2)){
result.append("Found hierarchical lists.\n");
if(!explore(list1->getNode().pair.getHead(), list2->getNode().pair.getHead(), result))
return false;
else
return explore(list1->getNode().pair.getTail(), list2->getNode().pair.getTail(), result);
}
return false;
}
void MainWindow::on_checkButton_clicked()
{
checkLists();
}
void MainWindow::checkLists(){
HList hlist;
S_expr* list1, *list2;
QString input1 = ui->list1->text();
QString input2 = ui->list2->text();
string result;
int i=0, k=0;
if(hlist.read_s_expr(list1, input1.toUtf8().constData(), result, i)){
ui->resultWindow->setText(QString::fromStdString(result));
}
else if(hlist.read_s_expr(list2, input2.toUtf8().constData(), result, k)){
ui->resultWindow->setText(QString::fromStdString(result));
}
else if(explore(list1, list2, result)){
result.append("These two lists are identical.");
ui->resultWindow->setText(QString::fromStdString(result));
hlist.destroy(list1, result);
hlist.destroy(list2, result);
}
else{
result.append("These two lists are different.\n");
ui->resultWindow->setText(QString::fromStdString(result));
hlist.destroy(list1, result);
hlist.destroy(list2, result);
}
this->resize(482, 600);
this->resize(481, 599);
}
void MainWindow::on_fileButtonForList1_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open TXT File"), QDir::homePath(),
tr("TXT text (*.txt);;All Files (*)"));
ifstream sourceFile(fileName.toUtf8().constData());
string input;
sourceFile >> input;
ui->list1->setText(QString::fromStdString(input));
}
void MainWindow::on_fileButtonForList2_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open TXT File"), QDir::homePath(),
tr("TXT text (*.txt);;All Files (*)"));
ifstream sourceFile(fileName.toUtf8().constData());
string input;
sourceFile >> input;
ui->list2->setText(QString::fromStdString(input));
}
void MainWindow::on_saveToFile_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open TXT File"), QDir::homePath(),
tr("TXT text (*.txt);;All Files (*)"));
ofstream sourceFile(fileName.toUtf8().constData());
sourceFile << ui->resultWindow->toPlainText().toUtf8().constData();
}
|
#include <iostream>
#include <string>
#define M 34943
using namespace std;
int main() //本题处理 的数太大了,不可以直接处理,需要用大数的处理方法
{
string s;
int len;
long long ans;
while(getline(cin,s))
{
ans=0;
len=s.length();
if(len == 0)
{
cout << "00 00" << endl;
continue;
}
if(s[0] == '#')
break;
for(int i = 0; i < len; i++)
{
ans = ((ans<<8)+s[i])%M; //大数除法
}
ans =(ans<<16)%M;
ans=M-ans%M;
s="0000";
int i = 3;
while(ans != 0)
{
int res;
res = ans % 16;
ans /= 16;
if(res < 10)
s[i--] = res + '0';
else
s[i--] = res - 10 + 'A';
}
cout << s[0] << s[1] << " " << s[2] << s[3] << endl;
}
return 0;
}
|
#include <jni.h>
#include <string>
#include "opencv2/opencv.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <cstddef>
using namespace cv;
extern "C" JNIEXPORT void
Java_com_example_ndktest2_MainActivity_StereomMatching(JNIEnv *env,jobject, jint width, jint height, jbyteArray yuv) {
Mat undisort_img;
Mat dispaty_data;
Mat disparty_map;
double min, max;
jbyte *bytes;
jint a;
int disp = 32;
int minDisparity = 0;
int numDisparities = 32;
int SADWindowSize = 3;//3
int P1 = 0;
int P2 = 0;
int disp12MaxDiff = 0;
int preFilterCap = 0;
int uniquenessRatio = 0;
int speckleWindowSize = 0;
int speckleRange = 0;
bool fullDp = false;
jbyte* _yuv = env->GetByteArrayElements(yuv, 0);
Mat myuv(height + height/2, width, CV_8UC1, (unsigned char *)_yuv);
Mat mgray(height, width, CV_8UC1, (unsigned char *)_yuv);
fastNlMeansDenoising(mgray, undisort_img);
normalize(undisort_img, undisort_img, 0, 255, NORM_MINMAX, -1, Mat());
Ptr<StereoSGBM> sgbm = StereoSGBM::create(0,6,11);
sgbm->setPreFilterCap(32);
sgbm->setBlockSize(SADWindowSize);
int cn = undisort_img.channels();
sgbm->setP1(8 * cn*SADWindowSize*SADWindowSize);
sgbm->setP2(32 * cn*SADWindowSize*SADWindowSize);
sgbm->setMinDisparity(0);
sgbm->setNumDisparities(numDisparities);
sgbm->setUniquenessRatio(10);
sgbm->setSpeckleWindowSize(100);
sgbm->setSpeckleRange(32);
sgbm->setDisp12MaxDiff(1);
sgbm->setMode(StereoSGBM::MODE_SGBM);
sgbm->compute(undisort_img, undisort_img, dispaty_data);
minMaxLoc(dispaty_data, &min, &max);
dispaty_data.convertTo(disparty_map,CV_8UC1,255/(max-min),-255*min/(max-min));
return env->ReleaseByteArrayElements(yuv, _yuv, 0);;
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** 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.
//**
//** This program 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
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
//**
//** This file deals with the parsing and definition of shaders.
//**
//**************************************************************************
#include "../cinematic/public.h"
#include "shader.h"
#include "main.h"
#include "backend.h"
#include "commands.h"
#include "sky.h"
#include "surfaces.h"
#include "cvars.h"
#include "state.h"
#include "../../common/Common.h"
#include "../../common/common_defs.h"
#include "../../common/strings.h"
#include "../../common/command_buffer.h"
#include "../../common/content_types.h"
#include "../hexen2clientdefs.h"
#include "../../common/file_formats/bsp47.h"
#define SHADER_HASH_SIZE 4096
#define MAX_SHADERTEXT_HASH 2048
#define MAX_SHADER_FILES 4096
#define MAX_SHADER_STRING_POINTERS 100000
struct infoParm_t {
const char* name;
int clearSolid;
int surfaceFlags;
int contents;
};
struct collapse_t {
int blendA;
int blendB;
int multitextureEnv;
int multitextureBlend;
};
// Ridah
// Table containing string indexes for each shader found in the scripts, referenced by their checksum
// values.
struct shaderStringPointer_t {
const char* pStr;
shaderStringPointer_t* next;
};
//bani - dynamic shader list
struct dynamicshader_t {
char* shadertext;
dynamicshader_t* next;
};
static shader_t* ShaderHashTable[ SHADER_HASH_SIZE ];
// the shader is parsed into these global variables, then copied into
// dynamically allocated memory if it is valid.
static shader_t shader;
static shaderStage_t stages[ MAX_SHADER_STAGES ];
static texModInfo_t texMods[ MAX_SHADER_STAGES ][ TR_MAX_TEXMODS ];
// ydnar: these are here because they are only referenced while parsing a shader
static char implicitMap[ MAX_QPATH ];
static unsigned implicitStateBits;
static cullType_t implicitCullType;
static char* s_shaderText;
static const char** shaderTextHashTable[ MAX_SHADERTEXT_HASH ];
static shaderStringPointer_t shaderChecksumLookup[ SHADER_HASH_SIZE ];
static shaderStringPointer_t shaderStringPointerList[ MAX_SHADER_STRING_POINTERS ];
static dynamicshader_t* dshader = NULL;
// Ridah, shader caching
static int numBackupShaders = 0;
static shader_t* backupShaders[ MAX_SHADERS ];
static shader_t* backupHashTable[ SHADER_HASH_SIZE ];
static bool purgeallshaders = false;
// this table is also present in q3map
static infoParm_t infoParms[] =
{
// server relevant contents
{"water", 1, 0, BSP46CONTENTS_WATER },
{"slime", 1, 0, BSP46CONTENTS_SLIME }, // mildly damaging
{"slag", 1, 0, BSP46CONTENTS_SLIME }, // uses the BSP46CONTENTS_SLIME flag, but the shader reference is changed to 'slag'
// to idendify that this doesn't work the same as 'slime' did.
// (slime hurts instantly, slag doesn't)
{"lava", 1, 0, BSP46CONTENTS_LAVA }, // very damaging
{"playerclip", 1, 0, BSP46CONTENTS_PLAYERCLIP },
{"monsterclip", 1, 0, BSP46CONTENTS_MONSTERCLIP },
{"clipmissile", 1, 0, BSP47CONTENTS_MISSILECLIP}, // impact only specific weapons (rl, gl)
{"nodrop", 1, 0, BSP46CONTENTS_NODROP }, // don't drop items or leave bodies (death fog, lava, etc)
{"nonsolid", 1, BSP46SURF_NONSOLID, 0}, // clears the solid flag
{"ai_nosight", 1, 0, BSP47CONTENTS_AI_NOSIGHT },
{"clipshot", 1, 0, BSP47CONTENTS_CLIPSHOT }, // stops bullets
// utility relevant attributes
{"origin", 1, 0, BSP46CONTENTS_ORIGIN }, // center of rotating brushes
{"trans", 0, 0, BSP46CONTENTS_TRANSLUCENT }, // don't eat contained surfaces
{"detail", 0, 0, BSP46CONTENTS_DETAIL }, // don't include in structural bsp
{"structural", 0, 0, BSP46CONTENTS_STRUCTURAL }, // force into structural bsp even if trnas
{"areaportal", 1, 0, BSP46CONTENTS_AREAPORTAL }, // divides areas
{"clusterportal", 1,0, BSP46CONTENTS_CLUSTERPORTAL }, // for bots
{"donotenter", 1, 0, BSP46CONTENTS_DONOTENTER }, // for bots
{"donotenterlarge", 1, 0, BSP47CONTENTS_DONOTENTER_LARGE }, // for larger bots
{"fog", 1, 0, BSP46CONTENTS_FOG}, // carves surfaces entering
{"sky", 0, BSP46SURF_SKY, 0 }, // emit light from an environment map
{"lightfilter", 0, BSP46SURF_LIGHTFILTER, 0 }, // filter light going through it
{"alphashadow", 0, BSP46SURF_ALPHASHADOW, 0 }, // test light on a per-pixel basis
{"hint", 0, BSP46SURF_HINT, 0 }, // use as a primary splitter
// server attributes
{"slick", 0, BSP46SURF_SLICK, 0 },
{"monsterslick", 0, BSP47SURF_MONSTERSLICK, 0 }, // surf only slick for monsters
{"monsterslicknorth", 0, BSP47SURF_MONSLICK_N, 0 },
{"monsterslickeast", 0, BSP47SURF_MONSLICK_E, 0 },
{"monsterslicksouth", 0, BSP47SURF_MONSLICK_S, 0 },
{"monsterslickwest", 0, BSP47SURF_MONSLICK_W, 0 },
{"noimpact", 0, BSP46SURF_NOIMPACT, 0 }, // don't make impact explosions or marks
{"nomarks", 0, BSP46SURF_NOMARKS, 0 }, // don't make impact marks, but still explode
{"ladder", 0, BSP46SURF_LADDER, 0 },
{"nodamage", 0, BSP46SURF_NODAMAGE, 0 },
{"glass", 0, BSP47SURF_GLASS, 0 },
{"ceramic", 0, BSP47SURF_CERAMIC, 0 },
{"rubble", 0, BSP47SURF_RUBBLE, 0 },
// steps
{"metalsteps", 0, BSP46SURF_METALSTEPS,0 },
{"flesh", 0, BSP46SURF_FLESH, 0 },
{"nosteps", 0, BSP46SURF_NOSTEPS, 0 },
{"metal", 0, BSP46SURF_METALSTEPS, 0 },
{"woodsteps", 0, BSP47SURF_WOOD, 0 },
{"grasssteps", 0, BSP47SURF_GRASS, 0 },
{"gravelsteps", 0, BSP47SURF_GRAVEL, 0 },
{"carpetsteps", 0, BSP47SURF_CARPET, 0 },
{"snowsteps", 0, BSP47SURF_SNOW, 0 },
{"roofsteps", 0, BSP47SURF_ROOF, 0 }, // tile roof
// drawsurf attributes
{"nodraw", 0, BSP46SURF_NODRAW, 0 }, // don't generate a drawsurface (or a lightmap)
{"pointlight", 0, BSP46SURF_POINTLIGHT, 0 }, // sample lighting at vertexes
{"nolightmap", 0, BSP46SURF_NOLIGHTMAP,0 }, // don't generate a lightmap
{"nodlight", 0, BSP46SURF_NODLIGHT, 0 }, // don't ever add dynamic lights
{"dust", 0, BSP46SURF_DUST, 0} // leave a dust trail when walking on this surface
};
static collapse_t collapse[] =
{
{ 0, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO,
GL_MODULATE, 0 },
{ 0, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR,
GL_MODULATE, 0 },
{ GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR,
GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR },
{ GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR,
GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR },
{ GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO,
GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR },
{ GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO,
GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR },
{ 0, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE,
GL_ADD, 0 },
{ GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE,
GL_ADD, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE },
#if 0
{ 0, GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_SRCBLEND_SRC_ALPHA,
GL_DECAL, 0 },
#endif
{ -1 }
};
static bool ParseVector( const char** text, int count, float* v ) {
// FIXME: spaces are currently required after parens, should change parseext...
char* token = String::ParseExt( text, false );
if ( String::Cmp( token, "(" ) ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name );
return false;
}
for ( int i = 0; i < count; i++ ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing vector element in shader '%s'\n", shader.name );
return false;
}
v[ i ] = String::Atof( token );
}
token = String::ParseExt( text, false );
if ( String::Cmp( token, ")" ) ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name );
return false;
}
return true;
}
static unsigned NameToAFunc( const char* funcname ) {
if ( !String::ICmp( funcname, "GT0" ) ) {
return GLS_ATEST_GT_0;
} else if ( !String::ICmp( funcname, "LT128" ) ) {
return GLS_ATEST_LT_80;
} else if ( !String::ICmp( funcname, "GE128" ) ) {
return GLS_ATEST_GE_80;
}
common->Printf( S_COLOR_YELLOW "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", funcname, shader.name );
return 0;
}
static int NameToSrcBlendMode( const char* name ) {
if ( !String::ICmp( name, "GL_ONE" ) ) {
return GLS_SRCBLEND_ONE;
} else if ( !String::ICmp( name, "GL_ZERO" ) ) {
return GLS_SRCBLEND_ZERO;
} else if ( !String::ICmp( name, "GL_DST_COLOR" ) ) {
return GLS_SRCBLEND_DST_COLOR;
} else if ( !String::ICmp( name, "GL_ONE_MINUS_DST_COLOR" ) ) {
return GLS_SRCBLEND_ONE_MINUS_DST_COLOR;
} else if ( !String::ICmp( name, "GL_SRC_ALPHA" ) ) {
return GLS_SRCBLEND_SRC_ALPHA;
} else if ( !String::ICmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) {
return GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA;
} else if ( !String::ICmp( name, "GL_DST_ALPHA" ) ) {
return GLS_SRCBLEND_DST_ALPHA;
} else if ( !String::ICmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) {
return GLS_SRCBLEND_ONE_MINUS_DST_ALPHA;
} else if ( !String::ICmp( name, "GL_SRC_ALPHA_SATURATE" ) ) {
return GLS_SRCBLEND_ALPHA_SATURATE;
}
common->Printf( S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name );
return GLS_SRCBLEND_ONE;
}
static int NameToDstBlendMode( const char* name ) {
if ( !String::ICmp( name, "GL_ONE" ) ) {
return GLS_DSTBLEND_ONE;
} else if ( !String::ICmp( name, "GL_ZERO" ) ) {
return GLS_DSTBLEND_ZERO;
} else if ( !String::ICmp( name, "GL_SRC_ALPHA" ) ) {
return GLS_DSTBLEND_SRC_ALPHA;
} else if ( !String::ICmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) {
return GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
} else if ( !String::ICmp( name, "GL_DST_ALPHA" ) ) {
return GLS_DSTBLEND_DST_ALPHA;
} else if ( !String::ICmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) {
return GLS_DSTBLEND_ONE_MINUS_DST_ALPHA;
} else if ( !String::ICmp( name, "GL_SRC_COLOR" ) ) {
return GLS_DSTBLEND_SRC_COLOR;
} else if ( !String::ICmp( name, "GL_ONE_MINUS_SRC_COLOR" ) ) {
return GLS_DSTBLEND_ONE_MINUS_SRC_COLOR;
}
common->Printf( S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name );
return GLS_DSTBLEND_ONE;
}
static genFunc_t NameToGenFunc( const char* funcname ) {
if ( !String::ICmp( funcname, "sin" ) ) {
return GF_SIN;
} else if ( !String::ICmp( funcname, "square" ) ) {
return GF_SQUARE;
} else if ( !String::ICmp( funcname, "triangle" ) ) {
return GF_TRIANGLE;
} else if ( !String::ICmp( funcname, "sawtooth" ) ) {
return GF_SAWTOOTH;
} else if ( !String::ICmp( funcname, "inversesawtooth" ) ) {
return GF_INVERSE_SAWTOOTH;
} else if ( !String::ICmp( funcname, "noise" ) ) {
return GF_NOISE;
}
common->Printf( S_COLOR_YELLOW "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name );
return GF_SIN;
}
static void ParseWaveForm( const char** text, waveForm_t* wave ) {
char* token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name );
return;
}
wave->func = NameToGenFunc( token );
// BASE, AMP, PHASE, FREQ
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name );
return;
}
wave->base = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name );
return;
}
wave->amplitude = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name );
return;
}
wave->phase = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name );
return;
}
wave->frequency = String::Atof( token );
}
static void ParseTexMod( const char* _text, shaderStage_t* stage ) {
const char** text = &_text;
if ( stage->bundle[ 0 ].numTexMods == TR_MAX_TEXMODS ) {
common->Error( "ERROR: too many tcMod stages in shader '%s'\n", shader.name );
}
texModInfo_t* tmi = &stage->bundle[ 0 ].texMods[ stage->bundle[ 0 ].numTexMods ];
stage->bundle[ 0 ].numTexMods++;
const char* token = String::ParseExt( text, false );
//
// turb
//
if ( !String::ICmp( token, "turb" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name );
return;
}
tmi->wave.base = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name );
return;
}
tmi->wave.amplitude = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name );
return;
}
tmi->wave.phase = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name );
return;
}
tmi->wave.frequency = String::Atof( token );
tmi->type = TMOD_TURBULENT;
}
//
// scale
//
else if ( !String::ICmp( token, "scale" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name );
return;
}
tmi->scale[ 0 ] = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name );
return;
}
tmi->scale[ 1 ] = String::Atof( token );
tmi->type = TMOD_SCALE;
}
//
// scroll
//
else if ( !String::ICmp( token, "scroll" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name );
return;
}
tmi->scroll[ 0 ] = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name );
return;
}
tmi->scroll[ 1 ] = String::Atof( token );
tmi->type = TMOD_SCROLL;
}
//
// stretch
//
else if ( !String::ICmp( token, "stretch" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name );
return;
}
tmi->wave.func = NameToGenFunc( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name );
return;
}
tmi->wave.base = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name );
return;
}
tmi->wave.amplitude = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name );
return;
}
tmi->wave.phase = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name );
return;
}
tmi->wave.frequency = String::Atof( token );
tmi->type = TMOD_STRETCH;
}
//
// transform
//
else if ( !String::ICmp( token, "transform" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name );
return;
}
tmi->matrix[ 0 ][ 0 ] = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name );
return;
}
tmi->matrix[ 0 ][ 1 ] = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name );
return;
}
tmi->matrix[ 1 ][ 0 ] = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name );
return;
}
tmi->matrix[ 1 ][ 1 ] = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name );
return;
}
tmi->translate[ 0 ] = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name );
return;
}
tmi->translate[ 1 ] = String::Atof( token );
tmi->type = TMOD_TRANSFORM;
}
//
// rotate
//
else if ( !String::ICmp( token, "rotate" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name );
return;
}
tmi->rotateSpeed = String::Atof( token );
tmi->type = TMOD_ROTATE;
}
//
// entityTranslate
//
else if ( !String::ICmp( token, "entityTranslate" ) ) {
tmi->type = TMOD_ENTITY_TRANSLATE;
}
//
// swap
//
else if ( !String::ICmp( token, "swap" ) ) {
// swap S/T coords (rotate 90d)
tmi->type = TMOD_SWAP;
} else {
common->Printf( S_COLOR_YELLOW "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name );
}
}
static bool ParseStage( shaderStage_t* stage, const char** text ) {
int depthMaskBits = GLS_DEPTHMASK_TRUE, blendSrcBits = 0, blendDstBits = 0, atestBits = 0, depthFuncBits = 0;
qboolean depthMaskExplicit = false;
stage->active = true;
while ( 1 ) {
const char* token = String::ParseExt( text, true );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: no matching '}' found\n" );
return false;
}
if ( token[ 0 ] == '}' ) {
break;
}
// check special case for map16/map32/mapcomp/mapnocomp (compression enabled)
if ( !String::ICmp( token, "map16" ) ) {
// only use this texture if 16 bit color depth
if ( glConfig.colorBits <= 16 ) {
token = "map"; // use this map
} else {
String::ParseExt( text, false ); // ignore the map
continue;
}
} else if ( !String::ICmp( token, "map32" ) ) {
// only use this texture if 16 bit color depth
if ( glConfig.colorBits > 16 ) {
token = "map"; // use this map
} else {
String::ParseExt( text, false ); // ignore the map
continue;
}
} else if ( !String::ICmp( token, "mapcomp" ) ) {
// only use this texture if compression is enabled
if ( glConfig.textureCompression && r_ext_compressed_textures->integer ) {
token = "map"; // use this map
} else {
String::ParseExt( text, false ); // ignore the map
continue;
}
} else if ( !String::ICmp( token, "mapnocomp" ) ) {
// only use this texture if compression is not available or disabled
if ( !glConfig.textureCompression ) {
token = "map"; // use this map
} else {
String::ParseExt( text, false ); // ignore the map
continue;
}
} else if ( !String::ICmp( token, "animmapcomp" ) ) {
// only use this texture if compression is enabled
if ( glConfig.textureCompression && r_ext_compressed_textures->integer ) {
token = "animmap"; // use this map
} else {
while ( token[ 0 ] ) {
String::ParseExt( text, false ); // ignore the map
}
continue;
}
} else if ( !String::ICmp( token, "animmapnocomp" ) ) {
// only use this texture if compression is not available or disabled
if ( !glConfig.textureCompression ) {
token = "animmap"; // use this map
} else {
while ( token[ 0 ] ) {
String::ParseExt( text, false ); // ignore the map
}
continue;
}
}
//
// map <name>
//
if ( !String::ICmp( token, "map" ) ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name );
return false;
}
// Fixes startup error and allows polygon shadows to work again
if ( !String::ICmp( token, "$whiteimage" ) || !String::ICmp( token, "*white" ) ) {
stage->bundle[ 0 ].image[ 0 ] = tr.whiteImage;
continue;
} else if ( !String::ICmp( token, "$dlight" ) ) {
stage->bundle[ 0 ].image[ 0 ] = tr.dlightImage;
continue;
} else if ( !String::ICmp( token, "$lightmap" ) ) {
stage->bundle[ 0 ].isLightmap = true;
if ( shader.lightmapIndex < 0 ) {
stage->bundle[ 0 ].image[ 0 ] = tr.whiteImage;
} else {
stage->bundle[ 0 ].image[ 0 ] = tr.lightmaps[ shader.lightmapIndex ];
}
continue;
} else {
stage->bundle[ 0 ].image[ 0 ] = R_FindImageFile( token, !shader.noMipMaps, !shader.noPicMip, GL_REPEAT, IMG8MODE_Normal, shader.characterMip );
if ( !stage->bundle[ 0 ].image[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name );
return false;
}
}
}
//
// clampmap <name>
//
else if ( !String::ICmp( token, "clampmap" ) ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parameter for 'clampmap' keyword in shader '%s'\n", shader.name );
return false;
}
stage->bundle[ 0 ].image[ 0 ] = R_FindImageFile( token, !shader.noMipMaps, !shader.noPicMip, GL_CLAMP, IMG8MODE_Normal, shader.characterMip );
if ( !stage->bundle[ 0 ].image[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name );
return false;
}
}
//
// lightmap <name>
//
else if ( !String::ICmp( token, "lightmap" ) ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parameter for 'lightmap' keyword in shader '%s'\n", shader.name );
return false;
}
// Fixes startup error and allows polygon shadows to work again
if ( !String::ICmp( token, "$whiteimage" ) || !String::ICmp( token, "*white" ) ) {
stage->bundle[ 0 ].image[ 0 ] = tr.whiteImage;
continue;
} else if ( !String::ICmp( token, "$dlight" ) ) {
stage->bundle[ 0 ].image[ 0 ] = tr.dlightImage;
continue;
} else if ( !String::ICmp( token, "$lightmap" ) ) {
stage->bundle[ 0 ].isLightmap = true;
if ( shader.lightmapIndex < 0 ) {
stage->bundle[ 0 ].image[ 0 ] = tr.whiteImage;
} else {
stage->bundle[ 0 ].image[ 0 ] = tr.lightmaps[ shader.lightmapIndex ];
}
continue;
} else {
stage->bundle[ 0 ].image[ 0 ] = R_FindImageFile( token, false, false, GL_CLAMP, IMG8MODE_Normal, false, true );
if ( !stage->bundle[ 0 ].image[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name );
return false;
}
stage->bundle[ 0 ].isLightmap = true;
}
}
//
// animMap <frequency> <image1> .... <imageN>
//
else if ( !String::ICmp( token, "animMap" ) ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parameter for 'animMmap' keyword in shader '%s'\n", shader.name );
return false;
}
stage->bundle[ 0 ].imageAnimationSpeed = String::Atof( token );
// parse up to MAX_IMAGE_ANIMATIONS animations
while ( 1 ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
break;
}
int num = stage->bundle[ 0 ].numImageAnimations;
if ( num < MAX_IMAGE_ANIMATIONS ) {
stage->bundle[ 0 ].image[ num ] = R_FindImageFile( token, !shader.noMipMaps, !shader.noPicMip, GL_REPEAT, IMG8MODE_Normal, shader.characterMip );
if ( !stage->bundle[ 0 ].image[ num ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name );
return false;
}
stage->bundle[ 0 ].numImageAnimations++;
}
}
} else if ( !String::ICmp( token, "videoMap" ) ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parameter for 'videoMmap' keyword in shader '%s'\n", shader.name );
return false;
}
stage->bundle[ 0 ].videoMapHandle = CIN_PlayCinematicStretched( token, 0, 0, 256, 256, ( CIN_loop | CIN_silent | CIN_shader ) );
if ( stage->bundle[ 0 ].videoMapHandle != -1 ) {
stage->bundle[ 0 ].isVideoMap = true;
stage->bundle[ 0 ].image[ 0 ] = tr.scratchImage[ stage->bundle[ 0 ].videoMapHandle ];
}
}
//
// alphafunc <func>
//
else if ( !String::ICmp( token, "alphaFunc" ) ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name );
return false;
}
atestBits = NameToAFunc( token );
}
//
// depthFunc <func>
//
else if ( !String::ICmp( token, "depthfunc" ) ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name );
return false;
}
if ( !String::ICmp( token, "lequal" ) ) {
depthFuncBits = 0;
} else if ( !String::ICmp( token, "equal" ) ) {
depthFuncBits = GLS_DEPTHFUNC_EQUAL;
} else {
common->Printf( S_COLOR_YELLOW "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name );
continue;
}
}
//
// detail
//
else if ( !String::ICmp( token, "detail" ) ) {
stage->isDetail = true;
}
//
// fog
//
else if ( !String::ICmp( token, "fog" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parm for fog in shader '%s'\n", shader.name );
continue;
}
if ( !String::ICmp( token, "on" ) ) {
stage->isFogged = true;
} else {
stage->isFogged = false;
}
}
//
// blendfunc <srcFactor> <dstFactor>
// or blendfunc <add|filter|blend>
//
else if ( !String::ICmp( token, "blendfunc" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name );
continue;
}
// check for "simple" blends first
if ( !String::ICmp( token, "add" ) ) {
blendSrcBits = GLS_SRCBLEND_ONE;
blendDstBits = GLS_DSTBLEND_ONE;
} else if ( !String::ICmp( token, "filter" ) ) {
blendSrcBits = GLS_SRCBLEND_DST_COLOR;
blendDstBits = GLS_DSTBLEND_ZERO;
} else if ( !String::ICmp( token, "blend" ) ) {
blendSrcBits = GLS_SRCBLEND_SRC_ALPHA;
blendDstBits = GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
} else {
// complex double blends
blendSrcBits = NameToSrcBlendMode( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name );
continue;
}
blendDstBits = NameToDstBlendMode( token );
}
// clear depth mask for blended surfaces
if ( !depthMaskExplicit ) {
depthMaskBits = 0;
}
}
//
// rgbGen
//
else if ( !String::ICmp( token, "rgbGen" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name );
continue;
}
if ( !String::ICmp( token, "wave" ) ) {
ParseWaveForm( text, &stage->rgbWave );
stage->rgbGen = CGEN_WAVEFORM;
} else if ( !String::ICmp( token, "const" ) ) {
vec3_t color;
ParseVector( text, 3, color );
stage->constantColor[ 0 ] = 255 * color[ 0 ];
stage->constantColor[ 1 ] = 255 * color[ 1 ];
stage->constantColor[ 2 ] = 255 * color[ 2 ];
stage->rgbGen = CGEN_CONST;
} else if ( !String::ICmp( token, "identity" ) ) {
stage->rgbGen = CGEN_IDENTITY;
} else if ( !String::ICmp( token, "identityLighting" ) ) {
stage->rgbGen = CGEN_IDENTITY_LIGHTING;
} else if ( !String::ICmp( token, "entity" ) ) {
stage->rgbGen = CGEN_ENTITY;
} else if ( !String::ICmp( token, "oneMinusEntity" ) ) {
stage->rgbGen = CGEN_ONE_MINUS_ENTITY;
} else if ( !String::ICmp( token, "vertex" ) ) {
stage->rgbGen = CGEN_VERTEX;
if ( stage->alphaGen == 0 ) {
stage->alphaGen = AGEN_VERTEX;
}
} else if ( !String::ICmp( token, "exactVertex" ) ) {
stage->rgbGen = CGEN_EXACT_VERTEX;
} else if ( !String::ICmp( token, "lightingDiffuse" ) ) {
stage->rgbGen = CGEN_LIGHTING_DIFFUSE;
} else if ( !String::ICmp( token, "oneMinusVertex" ) ) {
stage->rgbGen = CGEN_ONE_MINUS_VERTEX;
} else {
common->Printf( S_COLOR_YELLOW "WARNING: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name );
continue;
}
}
//
// alphaGen
//
else if ( !String::ICmp( token, "alphaGen" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name );
continue;
}
if ( !String::ICmp( token, "wave" ) ) {
ParseWaveForm( text, &stage->alphaWave );
stage->alphaGen = AGEN_WAVEFORM;
} else if ( !String::ICmp( token, "const" ) ) {
token = String::ParseExt( text, false );
stage->constantColor[ 3 ] = 255 * String::Atof( token );
stage->alphaGen = AGEN_CONST;
} else if ( !String::ICmp( token, "identity" ) ) {
stage->alphaGen = AGEN_IDENTITY;
} else if ( !String::ICmp( token, "entity" ) ) {
stage->alphaGen = AGEN_ENTITY;
} else if ( !String::ICmp( token, "oneMinusEntity" ) ) {
stage->alphaGen = AGEN_ONE_MINUS_ENTITY;
} else if ( !String::ICmp( token, "normalzfade" ) ) {
stage->alphaGen = AGEN_NORMALZFADE;
token = String::ParseExt( text, false );
if ( token[ 0 ] ) {
stage->constantColor[ 3 ] = 255 * String::Atof( token );
} else {
stage->constantColor[ 3 ] = 255;
}
token = String::ParseExt( text, false );
if ( token[ 0 ] ) {
stage->zFadeBounds[ 0 ] = String::Atof( token ); // lower range
token = String::ParseExt( text, false );
stage->zFadeBounds[ 1 ] = String::Atof( token ); // upper range
} else {
stage->zFadeBounds[ 0 ] = -1.0; // lower range
stage->zFadeBounds[ 1 ] = 1.0; // upper range
}
} else if ( !String::ICmp( token, "vertex" ) ) {
stage->alphaGen = AGEN_VERTEX;
} else if ( !String::ICmp( token, "lightingSpecular" ) ) {
stage->alphaGen = AGEN_LIGHTING_SPECULAR;
} else if ( !String::ICmp( token, "oneMinusVertex" ) ) {
stage->alphaGen = AGEN_ONE_MINUS_VERTEX;
} else if ( !String::ICmp( token, "portal" ) ) {
stage->alphaGen = AGEN_PORTAL;
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
shader.portalRange = 256;
common->Printf( S_COLOR_YELLOW "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name );
} else {
shader.portalRange = String::Atof( token );
}
} else {
common->Printf( S_COLOR_YELLOW "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name );
continue;
}
}
//
// tcGen <function>
//
else if ( !String::ICmp( token, "texgen" ) || !String::ICmp( token, "tcGen" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing texgen parm in shader '%s'\n", shader.name );
continue;
}
if ( !String::ICmp( token, "environment" ) ) {
stage->bundle[ 0 ].tcGen = TCGEN_ENVIRONMENT_MAPPED;
} else if ( !String::ICmp( token, "firerisenv" ) ) {
stage->bundle[ 0 ].tcGen = TCGEN_FIRERISEENV_MAPPED;
} else if ( !String::ICmp( token, "lightmap" ) ) {
stage->bundle[ 0 ].tcGen = TCGEN_LIGHTMAP;
} else if ( !String::ICmp( token, "texture" ) || !String::ICmp( token, "base" ) ) {
stage->bundle[ 0 ].tcGen = TCGEN_TEXTURE;
} else if ( !String::ICmp( token, "vector" ) ) {
ParseVector( text, 3, stage->bundle[ 0 ].tcGenVectors[ 0 ] );
ParseVector( text, 3, stage->bundle[ 0 ].tcGenVectors[ 1 ] );
stage->bundle[ 0 ].tcGen = TCGEN_VECTOR;
} else {
common->Printf( S_COLOR_YELLOW "WARNING: unknown texgen parm in shader '%s'\n", shader.name );
}
}
//
// tcMod <type> <...>
//
else if ( !String::ICmp( token, "tcMod" ) ) {
char buffer[ 1024 ] = "";
while ( 1 ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
break;
}
String::Cat( buffer, sizeof ( buffer ), token );
String::Cat( buffer, sizeof ( buffer ), " " );
}
ParseTexMod( buffer, stage );
continue;
}
//
// depthmask
//
else if ( !String::ICmp( token, "depthwrite" ) ) {
depthMaskBits = GLS_DEPTHMASK_TRUE;
depthMaskExplicit = true;
continue;
} else {
common->Printf( S_COLOR_YELLOW "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name );
return false;
}
}
//
// if cgen isn't explicitly specified, use either identity or identitylighting
//
if ( stage->rgbGen == CGEN_BAD ) {
if ( blendSrcBits == 0 ||
blendSrcBits == GLS_SRCBLEND_ONE ||
blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) {
stage->rgbGen = CGEN_IDENTITY_LIGHTING;
} else {
stage->rgbGen = CGEN_IDENTITY;
}
}
// ydnar: if shader stage references a lightmap, but no lightmap is present
// (vertex-approximated surfaces), then set cgen to vertex
if ( GGameType & GAME_ET && stage->bundle[ 0 ].isLightmap && shader.lightmapIndex < 0 &&
stage->bundle[ 0 ].image[ 0 ] == tr.whiteImage ) {
stage->rgbGen = CGEN_EXACT_VERTEX;
}
//
// implicitly assume that a GL_ONE GL_ZERO blend mask disables blending
//
if ( blendSrcBits == GLS_SRCBLEND_ONE && blendDstBits == GLS_DSTBLEND_ZERO ) {
blendDstBits = blendSrcBits = 0;
depthMaskBits = GLS_DEPTHMASK_TRUE;
}
// decide which agens we can skip
//JL was CGEN_IDENTITY which is equal to AGEN_ENTITY
if ( stage->alphaGen == AGEN_IDENTITY ) {
if ( stage->rgbGen == CGEN_IDENTITY || stage->rgbGen == CGEN_LIGHTING_DIFFUSE ) {
stage->alphaGen = AGEN_SKIP;
}
}
//
// compute state bits
//
stage->stateBits = depthMaskBits |
blendSrcBits | blendDstBits |
atestBits |
depthFuncBits;
return true;
}
// deformVertexes wave <spread> <waveform> <base> <amplitude> <phase> <frequency>
// deformVertexes normal <frequency> <amplitude>
// deformVertexes move <vector> <waveform> <base> <amplitude> <phase> <frequency>
// deformVertexes bulge <bulgeWidth> <bulgeHeight> <bulgeSpeed>
// deformVertexes projectionShadow
// deformVertexes autoSprite
// deformVertexes autoSprite2
// deformVertexes text[0-7]
static void ParseDeform( const char** text ) {
char* token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing deform parm in shader '%s'\n", shader.name );
return;
}
if ( shader.numDeforms == MAX_SHADER_DEFORMS ) {
common->Printf( S_COLOR_YELLOW "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name );
return;
}
deformStage_t* ds = &shader.deforms[ shader.numDeforms ];
shader.numDeforms++;
if ( !String::ICmp( token, "projectionShadow" ) ) {
ds->deformation = DEFORM_PROJECTION_SHADOW;
return;
}
if ( !String::ICmp( token, "autosprite" ) ) {
ds->deformation = DEFORM_AUTOSPRITE;
return;
}
if ( !String::ICmp( token, "autosprite2" ) ) {
ds->deformation = DEFORM_AUTOSPRITE2;
return;
}
if ( !String::NICmp( token, "text", 4 ) ) {
int n = token[ 4 ] - '0';
if ( n < 0 || n > 7 ) {
n = 0;
}
ds->deformation = ( deform_t )( DEFORM_TEXT0 + n );
return;
}
if ( !String::ICmp( token, "bulge" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name );
return;
}
ds->bulgeWidth = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name );
return;
}
ds->bulgeHeight = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name );
return;
}
ds->bulgeSpeed = String::Atof( token );
ds->deformation = DEFORM_BULGE;
return;
}
if ( !String::ICmp( token, "wave" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name );
return;
}
if ( String::Atof( token ) != 0 ) {
ds->deformationSpread = 1.0f / String::Atof( token );
} else {
ds->deformationSpread = 100.0f;
common->Printf( S_COLOR_YELLOW "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name );
}
ParseWaveForm( text, &ds->deformationWave );
ds->deformation = DEFORM_WAVE;
return;
}
if ( !String::ICmp( token, "normal" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name );
return;
}
ds->deformationWave.amplitude = String::Atof( token );
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name );
return;
}
ds->deformationWave.frequency = String::Atof( token );
ds->deformation = DEFORM_NORMALS;
return;
}
if ( !String::ICmp( token, "move" ) ) {
for ( int i = 0; i < 3; i++ ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name );
return;
}
ds->moveVector[ i ] = String::Atof( token );
}
ParseWaveForm( text, &ds->deformationWave );
ds->deformation = DEFORM_MOVE;
return;
}
common->Printf( S_COLOR_YELLOW "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name );
}
// skyParms <outerbox> <cloudheight> <innerbox>
static void ParseSkyParms( const char** text ) {
static const char* suf[ 6 ] = {"rt", "bk", "lf", "ft", "up", "dn"};
// outerbox
char* token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name );
return;
}
if ( String::Cmp( token, "-" ) ) {
for ( int i = 0; i < 6; i++ ) {
char pathname[ MAX_QPATH ];
String::Sprintf( pathname, sizeof ( pathname ), "%s_%s.tga", token, suf[ i ] );
shader.sky.outerbox[ i ] = R_FindImageFile( pathname, true, true, GL_CLAMP );
if ( !shader.sky.outerbox[ i ] ) {
shader.sky.outerbox[ i ] = tr.defaultImage;
}
}
}
// cloudheight
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name );
return;
}
shader.sky.cloudHeight = String::Atof( token );
if ( !shader.sky.cloudHeight ) {
shader.sky.cloudHeight = 512;
}
R_InitSkyTexCoords( shader.sky.cloudHeight );
// innerbox
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name );
return;
}
if ( String::Cmp( token, "-" ) ) {
for ( int i = 0; i < 6; i++ ) {
char pathname[ MAX_QPATH ];
String::Sprintf( pathname, sizeof ( pathname ), "%s_%s.tga", token, suf[ i ] );
shader.sky.innerbox[ i ] = R_FindImageFile( pathname, true, true, GL_CLAMP );
if ( !shader.sky.innerbox[ i ] ) {
shader.sky.innerbox[ i ] = tr.defaultImage;
}
}
}
shader.isSky = true;
}
static void ParseSort( const char** text ) {
char* token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing sort parameter in shader '%s'\n", shader.name );
return;
}
if ( !String::ICmp( token, "portal" ) ) {
shader.sort = SS_PORTAL;
} else if ( !String::ICmp( token, "sky" ) ) {
shader.sort = SS_ENVIRONMENT;
} else if ( !String::ICmp( token, "opaque" ) ) {
shader.sort = SS_OPAQUE;
} else if ( !String::ICmp( token, "decal" ) ) {
shader.sort = SS_DECAL;
} else if ( !String::ICmp( token, "seeThrough" ) ) {
shader.sort = SS_SEE_THROUGH;
} else if ( !String::ICmp( token, "banner" ) ) {
shader.sort = SS_BANNER;
} else if ( !String::ICmp( token, "additive" ) ) {
shader.sort = SS_BLEND1;
} else if ( !String::ICmp( token, "nearest" ) ) {
shader.sort = SS_NEAREST;
} else if ( !String::ICmp( token, "underwater" ) ) {
shader.sort = SS_UNDERWATER;
} else {
shader.sort = String::Atof( token );
}
}
// surfaceparm <name>
static void ParseSurfaceParm( const char** text ) {
int numInfoParms = sizeof ( infoParms ) / sizeof ( infoParms[ 0 ] );
char* token = String::ParseExt( text, false );
for ( int i = 0; i < numInfoParms; i++ ) {
if ( !String::ICmp( token, infoParms[ i ].name ) ) {
shader.surfaceFlags |= infoParms[ i ].surfaceFlags;
shader.contentFlags |= infoParms[ i ].contents;
break;
}
}
}
// The current text pointer is at the explicit text definition of the
// shader. Parse it into the global shader variable. Later functions
// will optimize it.
static bool ParseShader( const char** text ) {
int s;
s = 0;
if ( GGameType & GAME_ET ) {
tr.allowCompress = true; // Arnout: allow compression by default
}
char* token = String::ParseExt( text, true );
if ( token[ 0 ] != '{' ) {
common->Printf( S_COLOR_YELLOW "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name );
return false;
}
while ( 1 ) {
token = String::ParseExt( text, true );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: no concluding '}' in shader %s\n", shader.name );
return false;
}
// end of shader definition
if ( token[ 0 ] == '}' ) {
if ( GGameType & GAME_ET ) {
tr.allowCompress = true; // Arnout: allow compression by default
}
break;
}
// stage definition
else if ( token[ 0 ] == '{' ) {
if ( !ParseStage( &stages[ s ], text ) ) {
return false;
}
stages[ s ].active = true;
s++;
continue;
}
// skip stuff that only the QuakeEdRadient needs
else if ( !String::NICmp( token, "qer", 3 ) ) {
String::SkipRestOfLine( text );
continue;
}
// sun parms
else if ( !String::ICmp( token, "q3map_sun" ) ) {
float a, b;
token = String::ParseExt( text, false );
tr.sunLight[ 0 ] = String::Atof( token );
token = String::ParseExt( text, false );
tr.sunLight[ 1 ] = String::Atof( token );
token = String::ParseExt( text, false );
tr.sunLight[ 2 ] = String::Atof( token );
VectorNormalize( tr.sunLight );
token = String::ParseExt( text, false );
a = String::Atof( token );
VectorScale( tr.sunLight, a, tr.sunLight );
token = String::ParseExt( text, false );
a = String::Atof( token );
a = DEG2RAD( a );
token = String::ParseExt( text, false );
b = String::Atof( token );
b = DEG2RAD( b );
tr.sunDirection[ 0 ] = cos( a ) * cos( b );
tr.sunDirection[ 1 ] = sin( a ) * cos( b );
tr.sunDirection[ 2 ] = sin( b );
} else if ( !String::ICmp( token, "deformVertexes" ) ) {
ParseDeform( text );
continue;
} else if ( !String::ICmp( token, "tesssize" ) ) {
String::SkipRestOfLine( text );
continue;
} else if ( !String::ICmp( token, "clampTime" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] ) {
shader.clampTime = String::Atof( token );
}
}
// skip stuff that only the q3map needs
else if ( !String::NICmp( token, "q3map", 5 ) ) {
String::SkipRestOfLine( text );
continue;
}
// skip stuff that only q3map or the server needs
else if ( !String::ICmp( token, "surfaceParm" ) ) {
ParseSurfaceParm( text );
continue;
}
// no mip maps
else if ( !String::ICmp( token, "nomipmaps" ) || !String::ICmp( token,"nomipmap" ) ) {
shader.noMipMaps = true;
shader.noPicMip = true;
continue;
}
// no picmip adjustment
else if ( !String::ICmp( token, "nopicmip" ) ) {
shader.noPicMip = true;
continue;
}
// character picmip adjustment
else if ( !String::ICmp( token, "picmip2" ) ) {
shader.characterMip = true;
continue;
}
// polygonOffset
else if ( !String::ICmp( token, "polygonOffset" ) ) {
shader.polygonOffset = true;
continue;
}
// entityMergable, allowing sprite surfaces from multiple entities
// to be merged into one batch. This is a savings for smoke
// puffs and blood, but can't be used for anything where the
// shader calcs (not the surface function) reference the entity color or scroll
else if ( !String::ICmp( token, "entityMergable" ) ) {
shader.entityMergable = true;
continue;
}
// fogParms
else if ( !String::ICmp( token, "fogParms" ) ) {
if ( !ParseVector( text, 3, shader.fogParms.color ) ) {
return false;
}
shader.fogParms.colorInt = ColorBytes4( shader.fogParms.color[ 0 ] * tr.identityLight,
shader.fogParms.color[ 1 ] * tr.identityLight,
shader.fogParms.color[ 2 ] * tr.identityLight, 1.0 );
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name );
continue;
}
shader.fogParms.depthForOpaque = String::Atof( token );
shader.fogParms.depthForOpaque = shader.fogParms.depthForOpaque < 1 ? 1 : shader.fogParms.depthForOpaque;
shader.fogParms.tcScale = 1.0f / shader.fogParms.depthForOpaque;
// skip any old gradient directions
String::SkipRestOfLine( text );
continue;
}
// portal
else if ( !String::ICmp( token, "portal" ) ) {
shader.sort = SS_PORTAL;
continue;
}
// skyparms <cloudheight> <outerbox> <innerbox>
else if ( !String::ICmp( token, "skyparms" ) ) {
ParseSkyParms( text );
continue;
}
// This is fixed fog for the skybox/clouds determined solely by the shader
// it will not change in a level and will not be necessary
// to force clients to use a sky fog the server says to.
// skyfogvars <(r,g,b)> <dist>
else if ( !String::ICmp( token, "skyfogvars" ) ) {
vec3_t fogColor;
if ( !ParseVector( text, 3, fogColor ) ) {
return false;
}
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing density value for sky fog\n" );
continue;
}
if ( String::Atof( token ) > 1 ) {
common->Printf( S_COLOR_YELLOW "WARNING: last value for skyfogvars is 'density' which needs to be 0.0-1.0\n" );
continue;
}
if ( GGameType & ( GAME_WolfSP | GAME_WolfMP | GAME_ET ) ) {
R_SetFog( FOG_SKY, 0, 5, fogColor[ 0 ], fogColor[ 1 ], fogColor[ 2 ], String::Atof( token ) );
}
continue;
} else if ( !String::ICmp( token, "sunshader" ) ) {
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing shader name for 'sunshader'\n" );
continue;
}
tr.sunShaderName = new char[ String::Length( token ) + 1 ];
String::Cpy( tr.sunShaderName, token );
} else if ( !String::ICmp( token, "lightgridmulamb" ) ) {
// ambient multiplier for lightgrid
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing value for 'lightgrid ambient multiplier'\n" );
continue;
}
if ( String::Atof( token ) > 0 ) {
tr.lightGridMulAmbient = String::Atof( token );
}
} else if ( !String::ICmp( token, "lightgridmuldir" ) ) {
// directional multiplier for lightgrid
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing value for 'lightgrid directional multiplier'\n" );
continue;
}
if ( String::Atof( token ) > 0 ) {
tr.lightGridMulDirected = String::Atof( token );
}
} else if ( !String::ICmp( token, "waterfogvars" ) ) {
vec3_t watercolor;
if ( !ParseVector( text, 3, watercolor ) ) {
return false;
}
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing density/distance value for water fog\n" );
continue;
}
float fogvar = String::Atof( token );
//----(SA) right now allow one water color per map. I'm sure this will need
// to change at some point, but I'm not sure how to track fog parameters
// on a "per-water volume" basis yet.
if ( GGameType & GAME_WolfSP ) {
char fogString[ 64 ];
if ( fogvar == 0 ) {
// '0' specifies "use the map values for everything except the fog color
// TODO
fogString[ 0 ] = 0;
} else if ( fogvar > 1 ) {
// distance "linear" fog
String::Sprintf( fogString, sizeof ( fogString ), "0 %d 1.1 %f %f %f 200", ( int )fogvar, watercolor[ 0 ], watercolor[ 1 ], watercolor[ 2 ] );
} else { // density "exp" fog
String::Sprintf( fogString, sizeof ( fogString ), "0 5 %f %f %f %f 200", fogvar, watercolor[ 0 ], watercolor[ 1 ], watercolor[ 2 ] );
}
Cvar_Set( "r_waterFogColor", fogString );
} else if ( GGameType & ( GAME_WolfMP | GAME_ET ) ) {
if ( fogvar == 0 ) {
// '0' specifies "use the map values for everything except the fog color
// TODO
} else if ( fogvar > 1 ) {
// distance "linear" fog
R_SetFog( FOG_WATER, 0, fogvar, watercolor[ 0 ], watercolor[ 1 ], watercolor[ 2 ], 1.1 );
} else {
// density "exp" fog
R_SetFog( FOG_WATER, 0, 5, watercolor[ 0 ], watercolor[ 1 ], watercolor[ 2 ], fogvar );
}
}
continue;
}
// fogvars
else if ( !String::ICmp( token, "fogvars" ) ) {
vec3_t fogColor;
if ( !ParseVector( text, 3, fogColor ) ) {
return false;
}
token = String::ParseExt( text, false );
if ( !token[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing density value for the fog\n" );
continue;
}
//----(SA) NOTE: fogFar > 1 means the shader is setting the farclip, < 1 means setting
// density (so old maps or maps that just need softening fog don't have to care about farclip)
float fogDensity = String::Atof( token );
int fogFar = fogDensity > 1 ? fogDensity : 5;
if ( GGameType & GAME_WolfSP ) {
Cvar_Set( "r_mapFogColor", va( "0 %d %f %f %f %f 0", fogFar, fogDensity, fogColor[ 0 ], fogColor[ 1 ], fogColor[ 2 ] ) );
} else if ( GGameType & ( GAME_WolfMP | GAME_ET ) ) {
R_SetFog( FOG_MAP, 0, fogFar, fogColor[ 0 ], fogColor[ 1 ], fogColor[ 2 ], fogDensity );
R_SetFog( FOG_CMD_SWITCHFOG, FOG_MAP, 50, 0, 0, 0, 0 );
}
continue;
}
// Ridah, allow disable fog for some shaders
else if ( !String::ICmp( token, "nofog" ) ) {
shader.noFog = true;
continue;
}
// RF, allow each shader to permit compression if available
else if ( !String::ICmp( token, "allowcompress" ) ) {
tr.allowCompress = 1;
continue;
} else if ( !String::ICmp( token, "nocompress" ) ) {
tr.allowCompress = -1;
continue;
}
// light <value> determines flaring in q3map, not needed here
else if ( !String::ICmp( token, "light" ) ) {
token = String::ParseExt( text, false );
continue;
}
// cull <face>
else if ( !String::ICmp( token, "cull" ) ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing cull parms in shader '%s'\n", shader.name );
continue;
}
if ( !String::ICmp( token, "none" ) || !String::ICmp( token, "twosided" ) || !String::ICmp( token, "disable" ) ) {
shader.cullType = CT_TWO_SIDED;
} else if ( !String::ICmp( token, "back" ) || !String::ICmp( token, "backside" ) || !String::ICmp( token, "backsided" ) ) {
shader.cullType = CT_BACK_SIDED;
} else {
common->Printf( S_COLOR_YELLOW "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name );
}
continue;
}
// ydnar: distancecull <opaque distance> <transparent distance> <alpha threshold>
else if ( !String::ICmp( token, "distancecull" ) ) {
for ( int i = 0; i < 3; i++ ) {
token = String::ParseExt( text, false );
if ( token[ 0 ] == 0 ) {
common->Printf( S_COLOR_YELLOW "WARNING: missing distancecull parms in shader '%s'\n", shader.name );
} else {
shader.distanceCull[ i ] = String::Atof( token );
}
}
if ( shader.distanceCull[ 1 ] - shader.distanceCull[ 0 ] > 0 ) {
// distanceCull[ 3 ] is an optimization
shader.distanceCull[ 3 ] = 1.0 / ( shader.distanceCull[ 1 ] - shader.distanceCull[ 0 ] );
} else {
shader.distanceCull[ 0 ] = 0;
shader.distanceCull[ 1 ] = 0;
shader.distanceCull[ 2 ] = 0;
shader.distanceCull[ 3 ] = 0;
}
continue;
}
// sort
else if ( !String::ICmp( token, "sort" ) ) {
ParseSort( text );
continue;
}
// ydnar: implicit default mapping to eliminate redundant/incorrect explicit shader stages
else if ( !String::NICmp( token, "implicit", 8 ) ) {
// set implicit mapping state
if ( !String::ICmp( token, "implicitBlend" ) ) {
implicitStateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
implicitCullType = CT_TWO_SIDED;
} else if ( !String::ICmp( token, "implicitMask" ) ) {
implicitStateBits = GLS_DEPTHMASK_TRUE | GLS_ATEST_GE_80;
implicitCullType = CT_TWO_SIDED;
} else { // "implicitMap"
implicitStateBits = GLS_DEPTHMASK_TRUE;
implicitCullType = CT_FRONT_SIDED;
}
// get image
token = String::ParseExt( text, false );
if ( token[ 0 ] != '\0' ) {
String::NCpyZ( implicitMap, token, sizeof ( implicitMap ) );
} else {
implicitMap[ 0 ] = '-';
implicitMap[ 1 ] = '\0';
}
continue;
} else {
common->Printf( S_COLOR_YELLOW "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name );
return false;
}
}
//
// ignore shaders that don't have any stages, unless it is a sky or fog
// ydnar: or have implicit mapping
//
if ( s == 0 && !shader.isSky && !( shader.contentFlags & BSP46CONTENTS_FOG ) && implicitMap[ 0 ] == '\0' ) {
return false;
}
shader.explicitlyDefined = true;
return true;
}
/*
========================================================================================
SHADER OPTIMIZATION AND FOGGING
========================================================================================
*/
// If vertex lighting is enabled, only render a single pass, trying to guess
// which is the correct one to best aproximate what it is supposed to look like.
static void VertexLightingCollapse() {
// if we aren't opaque, just use the first pass
if ( shader.sort == SS_OPAQUE ) {
// pick the best texture for the single pass
shaderStage_t* bestStage = &stages[ 0 ];
int bestImageRank = -999999;
for ( int stage = 0; stage < MAX_SHADER_STAGES; stage++ ) {
shaderStage_t* pStage = &stages[ stage ];
if ( !pStage->active ) {
break;
}
int rank = 0;
if ( pStage->bundle[ 0 ].isLightmap ) {
rank -= 100;
}
if ( pStage->bundle[ 0 ].tcGen != TCGEN_TEXTURE ) {
rank -= 5;
}
if ( pStage->bundle[ 0 ].numTexMods ) {
rank -= 5;
}
if ( pStage->rgbGen != CGEN_IDENTITY && pStage->rgbGen != CGEN_IDENTITY_LIGHTING ) {
rank -= 3;
}
if ( rank > bestImageRank ) {
bestImageRank = rank;
bestStage = pStage;
}
}
stages[ 0 ].bundle[ 0 ] = bestStage->bundle[ 0 ];
stages[ 0 ].stateBits &= ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS );
stages[ 0 ].stateBits |= GLS_DEPTHMASK_TRUE;
if ( shader.lightmapIndex == LIGHTMAP_NONE ) {
stages[ 0 ].rgbGen = CGEN_LIGHTING_DIFFUSE;
} else {
stages[ 0 ].rgbGen = CGEN_EXACT_VERTEX;
}
stages[ 0 ].alphaGen = AGEN_SKIP;
} else {
// don't use a lightmap (tesla coils)
if ( stages[ 0 ].bundle[ 0 ].isLightmap ) {
stages[ 0 ] = stages[ 1 ];
}
// if we were in a cross-fade cgen, hack it to normal
if ( stages[ 0 ].rgbGen == CGEN_ONE_MINUS_ENTITY || stages[ 1 ].rgbGen == CGEN_ONE_MINUS_ENTITY ) {
stages[ 0 ].rgbGen = CGEN_IDENTITY_LIGHTING;
}
if ( ( stages[ 0 ].rgbGen == CGEN_WAVEFORM && stages[ 0 ].rgbWave.func == GF_SAWTOOTH ) &&
( stages[ 1 ].rgbGen == CGEN_WAVEFORM && stages[ 1 ].rgbWave.func == GF_INVERSE_SAWTOOTH ) ) {
stages[ 0 ].rgbGen = CGEN_IDENTITY_LIGHTING;
}
if ( ( stages[ 0 ].rgbGen == CGEN_WAVEFORM && stages[ 0 ].rgbWave.func == GF_INVERSE_SAWTOOTH ) &&
( stages[ 1 ].rgbGen == CGEN_WAVEFORM && stages[ 1 ].rgbWave.func == GF_SAWTOOTH ) ) {
stages[ 0 ].rgbGen = CGEN_IDENTITY_LIGHTING;
}
}
for ( int stage = 1; stage < MAX_SHADER_STAGES; stage++ ) {
shaderStage_t* pStage = &stages[ stage ];
if ( !pStage->active ) {
break;
}
Com_Memset( pStage, 0, sizeof ( *pStage ) );
}
}
// Attempt to combine two stages into a single multitexture stage
// FIXME: I think modulated add + modulated add collapses incorrectly
static bool CollapseMultitexture() {
if ( !qglActiveTextureARB ) {
return false;
}
// make sure both stages are active
if ( !stages[ 0 ].active || !stages[ 1 ].active ) {
return false;
}
int abits = stages[ 0 ].stateBits;
int bbits = stages[ 1 ].stateBits;
// make sure that both stages have identical state other than blend modes
if ( ( abits & ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE ) ) !=
( bbits & ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE ) ) ) {
return false;
}
abits &= ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS );
bbits &= ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS );
// search for a valid multitexture blend function
int i;
for ( i = 0; collapse[ i ].blendA != -1; i++ ) {
if ( abits == collapse[ i ].blendA && bbits == collapse[ i ].blendB ) {
break;
}
}
// nothing found
if ( collapse[ i ].blendA == -1 ) {
return false;
}
// GL_ADD is a separate extension
if ( collapse[ i ].multitextureEnv == GL_ADD && !glConfig.textureEnvAddAvailable ) {
return false;
}
// make sure waveforms have identical parameters
if ( ( stages[ 0 ].rgbGen != stages[ 1 ].rgbGen ) ||
( stages[ 0 ].alphaGen != stages[ 1 ].alphaGen ) ) {
return false;
}
// an add collapse can only have identity colors
if ( collapse[ i ].multitextureEnv == GL_ADD && stages[ 0 ].rgbGen != CGEN_IDENTITY ) {
return false;
}
if ( stages[ 0 ].rgbGen == CGEN_WAVEFORM ) {
if ( memcmp( &stages[ 0 ].rgbWave, &stages[ 1 ].rgbWave, sizeof ( stages[ 0 ].rgbWave ) ) ) {
return false;
}
}
if ( stages[ 0 ].alphaGen == AGEN_WAVEFORM ) {
if ( memcmp( &stages[ 0 ].alphaWave, &stages[ 1 ].alphaWave, sizeof ( stages[ 0 ].alphaWave ) ) ) {
return false;
}
}
// make sure that lightmaps are in bundle 1 for 3dfx
if ( stages[ 0 ].bundle[ 0 ].isLightmap ) {
stages[ 0 ].bundle[ 1 ] = stages[ 0 ].bundle[ 0 ];
stages[ 0 ].bundle[ 0 ] = stages[ 1 ].bundle[ 0 ];
} else {
stages[ 0 ].bundle[ 1 ] = stages[ 1 ].bundle[ 0 ];
}
// set the new blend state bits
shader.multitextureEnv = collapse[ i ].multitextureEnv;
stages[ 0 ].stateBits &= ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS );
stages[ 0 ].stateBits |= collapse[ i ].multitextureBlend;
//
// move down subsequent shaders
//
memmove( &stages[ 1 ], &stages[ 2 ], sizeof ( stages[ 0 ] ) * ( MAX_SHADER_STAGES - 2 ) );
Com_Memset( &stages[ MAX_SHADER_STAGES - 1 ], 0, sizeof ( stages[ 0 ] ) );
return true;
}
// See if we can use on of the simple fastpath stage functions, otherwise
// set to the generic stage function
static void ComputeStageIteratorFunc() {
shader.optimalStageIteratorFunc = RB_StageIteratorGeneric;
//
// see if this should go into the sky path
//
if ( shader.isSky ) {
shader.optimalStageIteratorFunc = RB_StageIteratorSky;
return;
}
if ( r_ignoreFastPath->integer ) {
return;
}
// ydnar: stages with tcMods can't be fast-pathed
if ( stages[ 0 ].bundle[ 0 ].numTexMods != 0 ||
stages[ 0 ].bundle[ 1 ].numTexMods != 0 ) {
return;
}
//
// see if this can go into the vertex lit fast path
//
if ( shader.numUnfoggedPasses == 1 ) {
if ( stages[ 0 ].rgbGen == CGEN_LIGHTING_DIFFUSE ) {
if ( stages[ 0 ].alphaGen == AGEN_IDENTITY ) {
if ( stages[ 0 ].bundle[ 0 ].tcGen == TCGEN_TEXTURE ) {
if ( !shader.polygonOffset ) {
if ( !shader.multitextureEnv ) {
if ( !shader.numDeforms ) {
shader.optimalStageIteratorFunc = RB_StageIteratorVertexLitTexture;
return;
}
}
}
}
}
}
}
//
// see if this can go into an optimized LM, multitextured path
//
if ( shader.numUnfoggedPasses == 1 ) {
if ( ( stages[ 0 ].rgbGen == CGEN_IDENTITY ) && ( stages[ 0 ].alphaGen == AGEN_IDENTITY ) ) {
if ( stages[ 0 ].bundle[ 0 ].tcGen == TCGEN_TEXTURE &&
stages[ 0 ].bundle[ 1 ].tcGen == TCGEN_LIGHTMAP ) {
if ( !shader.polygonOffset ) {
if ( !shader.numDeforms ) {
if ( shader.multitextureEnv ) {
shader.optimalStageIteratorFunc = RB_StageIteratorLightmappedMultitexture;
return;
}
}
}
}
}
}
}
// Arnout: this is a nasty issue. Shaders can be registered after drawsurfaces
// are generated but before the frame is rendered. This will, for the duration
// of one frame, cause drawsurfaces to be rendered with bad shaders. To fix this,
// need to go through all render commands and fix sortedIndex.
static void FixRenderCommandList( int newShader ) {
if ( !backEndData[ tr.smpFrame ] ) {
return;
}
const void* curCmd = backEndData[ tr.smpFrame ]->commands.cmds;
while ( 1 ) {
switch ( *( const int* )curCmd ) {
case RC_SET_COLOR:
{
const setColorCommand_t* sc_cmd = ( const setColorCommand_t* )curCmd;
curCmd = ( const void* )( sc_cmd + 1 );
break;
}
case RC_STRETCH_PIC:
case RC_STRETCH_PIC_GRADIENT:
case RC_ROTATED_PIC:
{
const stretchPicCommand_t* sp_cmd = ( const stretchPicCommand_t* )curCmd;
curCmd = ( const void* )( sp_cmd + 1 );
break;
}
case RC_2DPOLYS:
{
const poly2dCommand_t* sp_cmd = ( const poly2dCommand_t* )curCmd;
curCmd = ( const void* )( sp_cmd + 1 );
break;
}
case RC_DRAW_SURFS:
{
const drawSurfsCommand_t* ds_cmd = ( const drawSurfsCommand_t* )curCmd;
drawSurf_t* drawSurf = ds_cmd->drawSurfs;
for ( int i = 0; i < ds_cmd->numDrawSurfs; i++, drawSurf++ ) {
int entityNum;
shader_t* shader;
int fogNum;
int dlightMap;
int frontFace;
int atiTess;
R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &fogNum, &dlightMap, &frontFace, &atiTess );
int sortedIndex = ( ( drawSurf->sort >> QSORT_SHADERNUM_SHIFT ) & ( MAX_SHADERS - 1 ) );
if ( sortedIndex >= newShader ) {
sortedIndex++;
drawSurf->sort = ( sortedIndex << QSORT_SHADERNUM_SHIFT ) |
( entityNum << QSORT_ENTITYNUM_SHIFT ) |
( atiTess << QSORT_ATI_TESS_SHIFT ) |
( fogNum << QSORT_FOGNUM_SHIFT ) |
( frontFace << QSORT_FRONTFACE_SHIFT ) |
dlightMap;
}
}
curCmd = ( const void* )( ds_cmd + 1 );
break;
}
case RC_DRAW_BUFFER:
{
const drawBufferCommand_t* db_cmd = ( const drawBufferCommand_t* )curCmd;
curCmd = ( const void* )( db_cmd + 1 );
break;
}
case RC_SWAP_BUFFERS:
{
const swapBuffersCommand_t* sb_cmd = ( const swapBuffersCommand_t* )curCmd;
curCmd = ( const void* )( sb_cmd + 1 );
break;
}
case RC_RENDERTOTEXTURE:
{
const renderToTextureCommand_t* sb_cmd = ( const renderToTextureCommand_t* )curCmd;
curCmd = ( const void* )( sb_cmd + 1 );
break;
}
case RC_FINISH:
{
const renderFinishCommand_t* sb_cmd = ( const renderFinishCommand_t* )curCmd;
curCmd = ( const void* )( sb_cmd + 1 );
break;
}
case RC_SCREENSHOT:
{
const screenshotCommand_t* sb_cmd = ( const screenshotCommand_t* )curCmd;
curCmd = ( const void* )( sb_cmd + 1 );
break;
}
case RC_END_OF_LIST:
default:
return;
}
}
}
// Positions the most recently created shader in the tr.sortedShaders[]
// array so that the shader->sort key is sorted reletive to the other
// shaders.
//
// Sets shader->sortedIndex
static void SortNewShader() {
shader_t* newShader = tr.shaders[ tr.numShaders - 1 ];
float sort = newShader->sort;
int i;
for ( i = tr.numShaders - 2; i >= 0; i-- ) {
if ( tr.sortedShaders[ i ]->sort <= sort ) {
break;
}
tr.sortedShaders[ i + 1 ] = tr.sortedShaders[ i ];
tr.sortedShaders[ i + 1 ]->sortedIndex++;
}
// Arnout: fix rendercommandlist
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493
FixRenderCommandList( i + 1 );
newShader->sortedIndex = i + 1;
tr.sortedShaders[ i + 1 ] = newShader;
}
static int GenerateShaderHashValue( const char* fname, const int size ) {
int hash = 0;
int i = 0;
while ( fname[ i ] != '\0' ) {
char letter = String::ToLower( fname[ i ] );
if ( letter == '.' ) {
break; // don't include extension
}
if ( letter == '\\' ) {
letter = '/'; // damn path names
}
if ( letter == PATH_SEP ) {
letter = '/'; // damn path names
}
hash += ( long )( letter ) * ( i + 119 );
i++;
}
hash = ( hash ^ ( hash >> 10 ) ^ ( hash >> 20 ) );
hash &= ( size - 1 );
return hash;
}
static shader_t* GeneratePermanentShader() {
if ( tr.numShaders == MAX_SHADERS ) {
common->Printf( S_COLOR_YELLOW "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n" );
return tr.defaultShader;
}
shader_t* newShader = new shader_t;
*newShader = shader;
// this allows grates to be fogged
if ( shader.sort <= ( GGameType & GAME_ET ? SS_SEE_THROUGH : SS_OPAQUE ) ) {
newShader->fogPass = FP_EQUAL;
} else if ( shader.contentFlags & BSP46CONTENTS_FOG ) {
newShader->fogPass = FP_LE;
}
tr.shaders[ tr.numShaders ] = newShader;
newShader->index = tr.numShaders;
tr.sortedShaders[ tr.numShaders ] = newShader;
newShader->sortedIndex = tr.numShaders;
tr.numShaders++;
for ( int i = 0; i < newShader->numUnfoggedPasses; i++ ) {
if ( !stages[ i ].active ) {
break;
}
newShader->stages[ i ] = new shaderStage_t;
*newShader->stages[ i ] = stages[ i ];
for ( int b = 0; b < NUM_TEXTURE_BUNDLES; b++ ) {
int size = newShader->stages[ i ]->bundle[ b ].numTexMods * sizeof ( texModInfo_t );
newShader->stages[ i ]->bundle[ b ].texMods = new texModInfo_t[ newShader->stages[ i ]->bundle[ b ].numTexMods ];
Com_Memcpy( newShader->stages[ i ]->bundle[ b ].texMods, stages[ i ].bundle[ b ].texMods, size );
}
}
SortNewShader();
int hash = GenerateShaderHashValue( newShader->name, SHADER_HASH_SIZE );
newShader->next = ShaderHashTable[ hash ];
ShaderHashTable[ hash ] = newShader;
return newShader;
}
// Returns a freshly allocated shader with all the needed info from the
// current global working shader
static shader_t* FinishShader() {
int stage;
qboolean hasLightmapStage;
qboolean vertexLightmap;
hasLightmapStage = false;
vertexLightmap = false;
//
// set sky stuff appropriate
//
if ( shader.isSky ) {
shader.sort = SS_ENVIRONMENT;
}
//
// set polygon offset
//
if ( shader.polygonOffset && !shader.sort ) {
shader.sort = SS_DECAL;
}
//
// set appropriate stage information
//
for ( stage = 0; stage < MAX_SHADER_STAGES; stage++ ) {
shaderStage_t* pStage = &stages[ stage ];
if ( !pStage->active ) {
break;
}
// check for a missing texture
if ( !pStage->bundle[ 0 ].image[ 0 ] ) {
common->Printf( S_COLOR_YELLOW "Shader %s has a stage with no image\n", shader.name );
pStage->active = false;
continue;
}
//
// ditch this stage if it's detail and detail textures are disabled
//
if ( pStage->isDetail && !r_detailTextures->integer ) {
if ( GGameType & ( GAME_WolfSP | GAME_WolfMP | GAME_ET ) ) {
if ( stage < ( MAX_SHADER_STAGES - 1 ) ) {
memmove( pStage, pStage + 1, sizeof ( *pStage ) * ( MAX_SHADER_STAGES - stage - 1 ) );
// kill the last stage, since it's now a duplicate
for ( int i = MAX_SHADER_STAGES - 1; i > stage; i-- ) {
if ( stages[ i ].active ) {
Com_Memset( &stages[ i ], 0, sizeof ( *pStage ) );
break;
}
}
stage--; // the next stage is now the current stage, so check it again
} else {
Com_Memset( pStage, 0, sizeof ( *pStage ) );
}
} else {
pStage->active = false;
if ( stage < ( MAX_SHADER_STAGES - 1 ) ) {
memmove( pStage, pStage + 1, sizeof ( *pStage ) * ( MAX_SHADER_STAGES - stage - 1 ) );
Com_Memset( pStage + 1, 0, sizeof ( *pStage ) );
}
}
continue;
}
//
// default texture coordinate generation
//
if ( pStage->bundle[ 0 ].isLightmap ) {
if ( pStage->bundle[ 0 ].tcGen == TCGEN_BAD ) {
pStage->bundle[ 0 ].tcGen = TCGEN_LIGHTMAP;
}
hasLightmapStage = true;
} else {
if ( pStage->bundle[ 0 ].tcGen == TCGEN_BAD ) {
pStage->bundle[ 0 ].tcGen = TCGEN_TEXTURE;
}
}
//
// determine sort order and fog color adjustment
//
if ( ( pStage->stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) &&
( stages[ 0 ].stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) ) {
int blendSrcBits = pStage->stateBits & GLS_SRCBLEND_BITS;
int blendDstBits = pStage->stateBits & GLS_DSTBLEND_BITS;
// fog color adjustment only works for blend modes that have a contribution
// that aproaches 0 as the modulate values aproach 0 --
// GL_ONE, GL_ONE
// GL_ZERO, GL_ONE_MINUS_SRC_COLOR
// GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
// modulate, additive
if ( ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE ) ) ||
( ( blendSrcBits == GLS_SRCBLEND_ZERO ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR ) ) ) {
pStage->adjustColorsForFog = ACFF_MODULATE_RGB;
}
// strict blend
else if ( ( blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) {
pStage->adjustColorsForFog = ACFF_MODULATE_ALPHA;
}
// premultiplied alpha
else if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) {
pStage->adjustColorsForFog = ACFF_MODULATE_RGBA;
}
// ydnar: zero + blended alpha, one + blended alpha
//JL this makes no sense to me
else if ( GGameType & GAME_ET && ( blendSrcBits == GLS_SRCBLEND_SRC_ALPHA || blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) {
pStage->adjustColorsForFog = ACFF_MODULATE_ALPHA;
} else {
// we can't adjust this one correctly, so it won't be exactly correct in fog
}
// don't screw with sort order if this is a portal or environment
if ( !shader.sort ) {
// see through item, like a grill or grate
if ( pStage->stateBits & GLS_DEPTHMASK_TRUE ) {
shader.sort = SS_SEE_THROUGH;
} else {
shader.sort = SS_BLEND0;
}
}
}
}
// there are times when you will need to manually apply a sort to
// opaque alpha tested shaders that have later blend passes
if ( !shader.sort ) {
shader.sort = SS_OPAQUE;
}
//
// if we are in r_vertexLight mode, never use a lightmap texture
//
if ( !( GGameType & ( GAME_WolfMP | GAME_ET ) ) && stage > 1 && r_vertexLight->integer && !r_uiFullScreen->integer ) {
VertexLightingCollapse();
stage = 1;
hasLightmapStage = false;
}
//
// look for multitexture potential
//
if ( stage > 1 && CollapseMultitexture() ) {
stage--;
}
if ( shader.lightmapIndex >= 0 && !hasLightmapStage ) {
if ( vertexLightmap ) {
common->DPrintf( S_COLOR_RED "WARNING: shader '%s' has VERTEX forced lightmap!\n", shader.name );
} else {
common->DPrintf( S_COLOR_RED "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name );
shader.lightmapIndex = LIGHTMAP_NONE;
}
}
//
// compute number of passes
//
shader.numUnfoggedPasses = stage;
// fogonly shaders don't have any normal passes
if ( stage == 0 ) {
shader.sort = SS_FOG;
}
// determine which stage iterator function is appropriate
ComputeStageIteratorFunc();
// RF default back to no compression for next shader
if ( r_ext_compressed_textures->integer == 2 ) {
tr.allowCompress = false;
}
return GeneratePermanentShader();
}
// Scans the combined text description of all the shader files for the
// given shader name.
//
// return NULL if not found
//
// If found, it will return a valid shader
static const char* FindShaderInShaderText( const char* shadername ) {
if ( !s_shaderText ) {
return NULL;
}
//bani - if we have any dynamic shaders loaded, check them first
if ( dshader ) {
dynamicshader_t* dptr = dshader;
int i = 0;
while ( dptr ) {
if ( !dptr->shadertext || !String::Length( dptr->shadertext ) ) {
common->Printf( S_COLOR_YELLOW "WARNING: dynamic shader %s(%d) has no shadertext\n", shadername, i );
} else {
const char* q = dptr->shadertext;
const char* token = String::ParseExt( &q, true );
if ( ( token[ 0 ] != 0 ) && !String::ICmp( token, shadername ) ) {
return q;
}
}
i++;
dptr = dptr->next;
}
}
if ( GGameType & ( GAME_WolfSP | GAME_WolfMP | GAME_ET ) ) {
// Ridah, optimized shader loading
if ( GGameType & GAME_WolfSP || r_cacheShaders->integer ) {
unsigned short int checksum = GenerateShaderHashValue( shadername, SHADER_HASH_SIZE );
// if it's known, skip straight to it's position
shaderStringPointer_t* pShaderString = &shaderChecksumLookup[ checksum ];
while ( pShaderString && pShaderString->pStr ) {
const char* p = pShaderString->pStr;
const char* token = String::ParseExt( &p, true );
if ( ( token[ 0 ] != 0 ) && !String::ICmp( token, shadername ) ) {
return p;
}
pShaderString = pShaderString->next;
}
// it's not even in our list, so it mustn't exist
return NULL;
}
} else {
int hash = GenerateShaderHashValue( shadername, MAX_SHADERTEXT_HASH );
for ( int i = 0; shaderTextHashTable[ hash ][ i ]; i++ ) {
const char* p = shaderTextHashTable[ hash ][ i ];
char* token = String::ParseExt( &p, true );
if ( !String::ICmp( token, shadername ) ) {
return p;
}
}
}
if ( GGameType & GAME_WolfMP ) {
const char* p = s_shaderText;
// look for label
// note that this could get confused if a shader name is used inside
// another shader definition
while ( 1 ) {
char* token = String::ParseExt( &p, true );
if ( token[ 0 ] == 0 ) {
break;
}
if ( token[ 0 ] == '{' ) {
// skip the definition
String::SkipBracedSection( &p );
} else if ( !String::ICmp( token, shadername ) ) {
return p;
} else {
// skip to end of line
String::SkipRestOfLine( &p );
}
}
} else if ( !( GGameType & GAME_WolfSP ) ) {
const char* p = s_shaderText;
// look for label
while ( 1 ) {
char* token = String::ParseExt( &p, true );
if ( token[ 0 ] == 0 ) {
break;
}
if ( !String::ICmp( token, shadername ) ) {
return p;
} else {
// skip the definition
String::SkipBracedSection( &p );
}
}
}
return NULL;
}
// given a (potentially erroneous) lightmap index, attempts to load
// an external lightmap image and/or sets the index to a valid number
static void R_FindLightmap( int* lightmapIndex ) {
if ( !( GGameType & GAME_ET ) ) {
// use (fullbright) vertex lighting if the bsp file doesn't have
// lightmaps
if ( *lightmapIndex >= 0 && *lightmapIndex >= tr.numLightmaps ) {
*lightmapIndex = LIGHTMAP_BY_VERTEX;
}
return;
}
// don't fool with bogus lightmap indexes
if ( *lightmapIndex < 0 ) {
return;
}
// does this lightmap already exist?
if ( *lightmapIndex < tr.numLightmaps && tr.lightmaps[ *lightmapIndex ] != NULL ) {
return;
}
// bail if no world dir
if ( tr.worldDir == NULL ) {
*lightmapIndex = LIGHTMAP_BY_VERTEX;
return;
}
// sync up render thread, because we're going to have to load an image
R_SyncRenderThread();
// attempt to load an external lightmap
char fileName[ MAX_QPATH ];
sprintf( fileName, "%s/lm_%04d.tga", tr.worldDir, *lightmapIndex );
image_t* image = R_FindImageFile( fileName, false, false, GL_CLAMP, IMG8MODE_Normal, false, true );
if ( image == NULL ) {
*lightmapIndex = LIGHTMAP_BY_VERTEX;
return;
}
// add it to the lightmap list
if ( *lightmapIndex >= tr.numLightmaps ) {
tr.numLightmaps = *lightmapIndex + 1;
}
tr.lightmaps[ *lightmapIndex ] = image;
}
// Make sure all images that belong to this shader remain valid
static bool R_RegisterShaderImages( shader_t* sh ) {
if ( sh->isSky ) {
return false;
}
for ( int i = 0; i < sh->numUnfoggedPasses; i++ ) {
if ( sh->stages[ i ] && sh->stages[ i ]->active ) {
for ( int b = 0; b < NUM_TEXTURE_BUNDLES; b++ ) {
for ( int j = 0; sh->stages[ i ]->bundle[ b ].image[ j ] && j < MAX_IMAGE_ANIMATIONS; j++ ) {
if ( !R_TouchImage( sh->stages[ i ]->bundle[ b ].image[ j ] ) ) {
return false;
}
}
}
}
}
return true;
}
// look for the given shader in the list of backupShaders
static shader_t* R_FindCachedShader( const char* name, int lightmapIndex, int hash ) {
if ( !r_cacheShaders->integer ) {
return NULL;
}
if ( !numBackupShaders ) {
return NULL;
}
if ( !name ) {
return NULL;
}
shader_t* sh = backupHashTable[ hash ];
shader_t* shPrev = NULL;
while ( sh ) {
if ( sh->lightmapIndex == lightmapIndex && !String::ICmp( sh->name, name ) ) {
if ( tr.numShaders == MAX_SHADERS ) {
common->Printf( S_COLOR_YELLOW "WARNING: R_FindCachedShader - MAX_SHADERS hit\n" );
return NULL;
}
// make sure the images stay valid
if ( !R_RegisterShaderImages( sh ) ) {
return NULL;
}
// this is the one, so move this shader into the current list
if ( !shPrev ) {
backupHashTable[ hash ] = sh->next;
} else {
shPrev->next = sh->next;
}
sh->next = ShaderHashTable[ hash ];
ShaderHashTable[ hash ] = sh;
backupShaders[ sh->index ] = NULL; // make sure we don't try and free it
// set the index up, and add it to the current list
tr.shaders[ tr.numShaders ] = sh;
sh->index = tr.numShaders;
tr.sortedShaders[ tr.numShaders ] = sh;
sh->sortedIndex = tr.numShaders;
tr.numShaders++;
numBackupShaders--;
sh->remappedShader = NULL; // Arnout: remove any remaps
SortNewShader(); // make sure it renders in the right order
return sh;
}
shPrev = sh;
sh = sh->next;
}
return NULL;
}
static void SetImplicitShaderStages( image_t* image ) {
// set implicit cull type
if ( implicitCullType && !shader.cullType ) {
shader.cullType = implicitCullType;
}
if ( shader.lightmapIndex == LIGHTMAP_NONE ) {
// dynamic colors at vertexes
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 0 ].active = true;
stages[ 0 ].rgbGen = CGEN_LIGHTING_DIFFUSE;
stages[ 0 ].stateBits = implicitStateBits;
} else if ( shader.lightmapIndex == LIGHTMAP_BY_VERTEX ||
( GGameType & GAME_ET && shader.lightmapIndex == LIGHTMAP_WHITEIMAGE ) ) {
// explicit colors at vertexes
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 0 ].active = true;
stages[ 0 ].rgbGen = CGEN_EXACT_VERTEX;
stages[ 0 ].alphaGen = AGEN_SKIP;
stages[ 0 ].stateBits = implicitStateBits;
} else if ( shader.lightmapIndex == LIGHTMAP_2D ) {
// GUI elements
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 0 ].active = true;
stages[ 0 ].rgbGen = CGEN_VERTEX;
stages[ 0 ].alphaGen = AGEN_VERTEX;
stages[ 0 ].stateBits = GLS_DEPTHTEST_DISABLE |
GLS_SRCBLEND_SRC_ALPHA |
GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
} else if ( shader.lightmapIndex == LIGHTMAP_WHITEIMAGE ) {
// fullbright level
stages[ 0 ].bundle[ 0 ].image[ 0 ] = tr.whiteImage;
stages[ 0 ].active = true;
stages[ 0 ].rgbGen = CGEN_IDENTITY_LIGHTING;
stages[ 0 ].stateBits = GLS_DEFAULT;
stages[ 1 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 1 ].active = true;
stages[ 1 ].rgbGen = CGEN_IDENTITY;
stages[ 1 ].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO;
} else if ( implicitStateBits & ( GLS_ATEST_BITS | GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) {
// masked or blended implicit shaders need texture first
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 0 ].active = true;
stages[ 0 ].rgbGen = CGEN_IDENTITY;
stages[ 0 ].stateBits = implicitStateBits;
stages[ 1 ].bundle[ 0 ].image[ 0 ] = tr.lightmaps[ shader.lightmapIndex ];
stages[ 1 ].bundle[ 0 ].isLightmap = true;
stages[ 1 ].active = true;
stages[ 1 ].rgbGen = CGEN_IDENTITY;
stages[ 1 ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO | GLS_DEPTHFUNC_EQUAL;
}
// otherwise do standard lightmap + texture
else {
// two pass lightmap
stages[ 0 ].bundle[ 0 ].image[ 0 ] = tr.lightmaps[ shader.lightmapIndex ];
stages[ 0 ].bundle[ 0 ].isLightmap = true;
stages[ 0 ].active = true;
stages[ 0 ].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation
// for identitylight
stages[ 0 ].stateBits = GLS_DEFAULT;
stages[ 1 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 1 ].active = true;
stages[ 1 ].rgbGen = CGEN_IDENTITY;
if ( GGameType & GAME_ET ) {
stages[ 1 ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO;
} else {
stages[ 1 ].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO;
}
}
}
static shader_t* R_FindLoadedShader( const char* name, int lightmapIndex ) {
int hash = GenerateShaderHashValue( name, SHADER_HASH_SIZE );
//
// see if the shader is already loaded
//
for ( shader_t* sh = ShaderHashTable[ hash ]; sh; sh = sh->next ) {
// NOTE: if there was no shader or image available with the name strippedName
// then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we
// have to check all default shaders otherwise for every call to R_FindShader
// with that same strippedName a new default shader is created.
if ( ( sh->lightmapIndex == lightmapIndex || sh->defaultShader ) &&
!String::ICmp( sh->name, name ) ) {
// match found
return sh;
}
}
// make sure the render thread is stopped, because we are probably
// going to have to upload an image
if ( r_smp->integer ) {
R_SyncRenderThread();
}
// Ridah, check the cache
// ydnar: don't cache shaders using lightmaps
if ( lightmapIndex < 0 ) {
shader_t* sh = R_FindCachedShader( name, lightmapIndex, hash );
if ( sh != NULL ) {
return sh;
}
}
return NULL;
}
static void R_ClearGlobalShader() {
Com_Memset( &shader, 0, sizeof ( shader ) );
Com_Memset( &stages, 0, sizeof ( stages ) );
for ( int i = 0; i < MAX_SHADER_STAGES; i++ ) {
stages[ i ].bundle[ 0 ].texMods = texMods[ i ];
}
// ydnar: default to no implicit mappings
implicitMap[ 0 ] = '\0';
implicitStateBits = GLS_DEFAULT;
implicitCullType = CT_FRONT_SIDED;
}
// Will always return a valid shader, but it might be the default shader if
// the real one can't be found.
//
// In the interest of not requiring an explicit shader text entry to be
// defined for every single image used in the game, three default shader
// behaviors can be auto-created for any image:
//
// If lightmapIndex == LIGHTMAP_NONE, then the image will have dynamic
// diffuse lighting applied to it, as apropriate for most entity skin
// surfaces.
//
// If lightmapIndex == LIGHTMAP_2D, then the image will be used for 2D
// rendering unless an explicit shader is found
//
// If lightmapIndex == LIGHTMAP_BY_VERTEX, then the image will use the
// vertex rgba modulate values, as apropriate for misc_model pre-lit surfaces.
//
// Other lightmapIndex values will have a lightmap stage created and src*dest
// blending applied with the texture, as apropriate for most world
// construction surfaces.
shader_t* R_FindShader( const char* name, int lightmapIndex, bool mipRawImage ) {
if ( name[ 0 ] == 0 ) {
return tr.defaultShader;
}
R_FindLightmap( &lightmapIndex );
char strippedName[ MAX_QPATH ];
String::StripExtension2( name, strippedName, sizeof ( strippedName ) );
String::FixPath( strippedName );
shader_t* loadedShader = R_FindLoadedShader( strippedName, lightmapIndex );
if ( loadedShader ) {
return loadedShader;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, strippedName, sizeof ( shader.name ) );
shader.lightmapIndex = lightmapIndex;
//
// attempt to define shader from an explicit parameter file
//
const char* shaderText = FindShaderInShaderText( strippedName );
if ( shaderText ) {
// enable this when building a pak file to get a global list
// of all explicit shaders
if ( r_printShaders->integer ) {
common->Printf( "*SHADER* %s\n", name );
}
if ( !ParseShader( &shaderText ) ) {
// had errors, so use default shader
shader.defaultShader = true;
shader_t* sh = FinishShader();
return sh;
}
// ydnar: allow implicit mappings
if ( implicitMap[ 0 ] == '\0' ) {
shader_t* sh = FinishShader();
return sh;
}
}
//
// if not defined in the in-memory shader descriptions,
// look for a single TGA, BMP, or PCX
//
char fileName[ MAX_QPATH ];
// ydnar: allow implicit mapping ('-' = use shader name)
if ( implicitMap[ 0 ] == '\0' || implicitMap[ 0 ] == '-' ) {
String::NCpyZ( fileName, name, sizeof ( fileName ) );
} else {
String::NCpyZ( fileName, implicitMap, sizeof ( fileName ) );
}
String::DefaultExtension( fileName, sizeof ( fileName ), ".tga" );
// ydnar: implicit shaders were breaking nopicmip/nomipmaps
if ( !mipRawImage ) {
shader.noMipMaps = true;
shader.noPicMip = true;
}
image_t* image = R_FindImageFile( fileName, !shader.noMipMaps, !shader.noPicMip, mipRawImage ? GL_REPEAT : GL_CLAMP );
if ( !image ) {
//common->DPrintf(S_COLOR_RED "Couldn't find image for shader %s\n", name);
common->Printf( S_COLOR_YELLOW "WARNING: Couldn't find image for shader %s\n", name );
shader.defaultShader = true;
return FinishShader();
}
//
// create the default shading commands
//
SetImplicitShaderStages( image );
return FinishShader();
}
shader_t* R_Build2DShaderFromImage( image_t* image ) {
char strippedName[ MAX_QPATH ];
String::StripExtension2( image->imgName, strippedName, sizeof ( strippedName ) );
String::FixPath( strippedName );
shader_t* loadedShader = R_FindLoadedShader( strippedName, LIGHTMAP_2D );
if ( loadedShader ) {
return loadedShader;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, strippedName, sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_2D;
shader.originalWidth = image->width;
shader.originalHeight = image->height;
SetImplicitShaderStages( image );
return FinishShader();
}
qhandle_t R_RegisterShaderFromImage( const char* name, int lightmapIndex, image_t* image, bool mipRawImage ) {
shader_t* loadedShader = R_FindLoadedShader( name, lightmapIndex );
if ( loadedShader ) {
return loadedShader->index;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, name, sizeof ( shader.name ) );
shader.lightmapIndex = lightmapIndex;
//
// create the default shading commands
//
SetImplicitShaderStages( image );
shader_t* sh = FinishShader();
return sh->index;
}
// This is the exported shader entry point for the rest of the system
// It will always return an index that will be valid.
//
// This should really only be used for explicit shaders, because there is no
// way to ask for different implicit lighting modes (vertex, lightmap, etc)
qhandle_t R_RegisterShader( const char* name ) {
if ( String::Length( name ) >= MAX_QPATH ) {
common->Printf( "Shader name exceeds MAX_QPATH\n" );
return 0;
}
shader_t* sh = R_FindShader( name, LIGHTMAP_2D, true );
// we want to return 0 if the shader failed to
// load for some reason, but R_FindShader should
// still keep a name allocated for it, so if
// something calls RE_RegisterShader again with
// the same name, we don't try looking for it again
if ( sh->defaultShader ) {
return 0;
}
return sh->index;
}
// For menu graphics that should never be picmiped
qhandle_t R_RegisterShaderNoMip( const char* name ) {
if ( String::Length( name ) >= MAX_QPATH ) {
common->Printf( "Shader name exceeds MAX_QPATH\n" );
return 0;
}
shader_t* sh = R_FindShader( name, LIGHTMAP_2D, false );
// we want to return 0 if the shader failed to
// load for some reason, but R_FindShader should
// still keep a name allocated for it, so if
// something calls RE_RegisterShader again with
// the same name, we don't try looking for it again
if ( sh->defaultShader ) {
return 0;
}
return sh->index;
}
static shader_t* R_RegisterShaderLightMap( const char* name, int lightmapIndex ) {
if ( String::Length( name ) >= MAX_QPATH ) {
common->Printf( "Shader name exceeds MAX_QPATH\n" );
return 0;
}
shader_t* sh = R_FindShader( name, lightmapIndex, true );
// we want to return 0 if the shader failed to
// load for some reason, but R_FindShader should
// still keep a name allocated for it, so if
// something calls RE_RegisterShader again with
// the same name, we don't try looking for it again
if ( sh->defaultShader ) {
return tr.defaultShader;
}
return sh;
}
// Will always return a valid shader, but it might be the default shader if
// the real one can't be found.
static shader_t* R_FindShaderByName( const char* name ) {
if ( ( name == NULL ) || ( name[ 0 ] == 0 ) ) {
// bk001205
return tr.defaultShader;
}
char strippedName[ MAX_QPATH ];
String::StripExtension2( name, strippedName, sizeof ( strippedName ) );
String::FixPath( strippedName );
int hash = GenerateShaderHashValue( strippedName, SHADER_HASH_SIZE );
//
// see if the shader is already loaded
//
for ( shader_t* sh = ShaderHashTable[ hash ]; sh; sh = sh->next ) {
// NOTE: if there was no shader or image available with the name strippedName
// then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we
// have to check all default shaders otherwise for every call to R_FindShader
// with that same strippedName a new default shader is created.
if ( String::ICmp( sh->name, strippedName ) == 0 ) {
// match found
return sh;
}
}
return tr.defaultShader;
}
void R_RemapShader( const char* shaderName, const char* newShaderName, const char* timeOffset ) {
shader_t* sh = R_FindShaderByName( shaderName );
if ( sh == NULL || sh == tr.defaultShader ) {
sh = R_RegisterShaderLightMap( shaderName, 0 );
}
if ( sh == NULL || sh == tr.defaultShader ) {
common->Printf( S_COLOR_YELLOW "WARNING: R_RemapShader: shader %s not found\n", shaderName );
return;
}
shader_t* sh2 = R_FindShaderByName( newShaderName );
if ( sh2 == NULL || sh2 == tr.defaultShader ) {
sh2 = R_RegisterShaderLightMap( newShaderName, 0 );
}
if ( sh2 == NULL || sh2 == tr.defaultShader ) {
common->Printf( S_COLOR_YELLOW "WARNING: R_RemapShader: new shader %s not found\n", newShaderName );
return;
}
// remap all the shaders with the given name
// even tho they might have different lightmaps
char strippedName[ MAX_QPATH ];
String::StripExtension2( shaderName, strippedName, sizeof ( strippedName ) );
int hash = GenerateShaderHashValue( strippedName, SHADER_HASH_SIZE );
for ( sh = ShaderHashTable[ hash ]; sh; sh = sh->next ) {
if ( String::ICmp( sh->name, strippedName ) == 0 ) {
if ( sh != sh2 ) {
sh->remappedShader = sh2;
} else {
sh->remappedShader = NULL;
}
}
}
if ( timeOffset ) {
sh2->timeOffset = String::Atof( timeOffset );
}
}
static void R_CreateColourShadeShader() {
R_ClearGlobalShader();
String::NCpyZ( shader.name, "colorShade", sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.sort = SS_SEE_THROUGH;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = tr.whiteImage;
stages[ 0 ].active = true;
stages[ 0 ].stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ 0 ].rgbGen = CGEN_ENTITY;
stages[ 0 ].alphaGen = AGEN_ENTITY;
tr.colorShadeShader = FinishShader();
}
static void R_CreateColourShellShader() {
R_ClearGlobalShader();
String::NCpyZ( shader.name, "colorShell", sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.sort = SS_BLEND0;
shader.deforms[0].deformation = DEFORM_WAVE;
shader.deforms[0].deformationWave.base = 4.0f;
shader.deforms[0].deformationWave.func = GF_SIN;
shader.numDeforms = 1;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = tr.whiteImage;
stages[ 0 ].active = true;
stages[ 0 ].stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ 0 ].rgbGen = CGEN_ENTITY;
stages[ 0 ].alphaGen = AGEN_ENTITY;
tr.colorShellShader = FinishShader();
}
static void R_CreateSkyBoxShader() {
if ( !( GGameType & GAME_Quake2 ) ) {
return;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, "*sky", sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.isSky = true;
tr.skyboxShader = FinishShader();
}
static void CreateInternalShaders() {
tr.numShaders = 0;
// init the default shader
R_ClearGlobalShader();
String::NCpyZ( shader.name, "<default>", sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = tr.defaultImage;
stages[ 0 ].active = true;
stages[ 0 ].stateBits = GLS_DEFAULT;
tr.defaultShader = FinishShader();
// shadow shader is just a marker
String::NCpyZ( shader.name, "<stencil shadow>", sizeof ( shader.name ) );
shader.sort = SS_STENCIL_SHADOW;
tr.shadowShader = FinishShader();
R_CreateColourShadeShader();
R_CreateColourShellShader();
R_CreateSkyBoxShader();
}
static void BuildShaderChecksumLookup() {
// initialize the checksums
memset( shaderChecksumLookup, 0, sizeof ( shaderChecksumLookup ) );
const char* p = s_shaderText;
if ( !p ) {
return;
}
// loop for all labels
int numShaderStringPointers = 0;
while ( 1 ) {
const char* pOld = p;
const char* token = String::ParseExt( &p, true );
if ( !*token ) {
break;
}
if ( !( GGameType & GAME_ET ) && !String::ICmp( token, "{" ) ) {
// skip braced section
String::SkipBracedSection( &p );
continue;
}
// get it's checksum
unsigned short int checksum = GenerateShaderHashValue( token, SHADER_HASH_SIZE );
// if it's not currently used
if ( !shaderChecksumLookup[ checksum ].pStr ) {
shaderChecksumLookup[ checksum ].pStr = pOld;
} else {
// create a new list item
shaderStringPointer_t* newStrPtr;
if ( numShaderStringPointers >= MAX_SHADER_STRING_POINTERS ) {
common->Error( "MAX_SHADER_STRING_POINTERS exceeded, too many shaders" );
}
newStrPtr = &shaderStringPointerList[ numShaderStringPointers++ ];
newStrPtr->pStr = pOld;
newStrPtr->next = shaderChecksumLookup[ checksum ].next;
shaderChecksumLookup[ checksum ].next = newStrPtr;
}
if ( GGameType & GAME_ET ) {
// Gordon: skip the actual shader section
String::SkipBracedSection( &p );
}
}
}
// Finds and loads all .shader files, combining them into a single large
// text block that can be scanned for shader names
static void ScanAndLoadShaderFiles() {
long sum = 0;
// scan for shader files
int numShaders;
char** shaderFiles;
shaderFiles = FS_ListFiles( "scripts", ".shader", &numShaders );
if ( !shaderFiles || !numShaders ) {
if ( GGameType & GAME_Tech3 ) {
common->Printf( S_COLOR_YELLOW "WARNING: no shader files found\n" );
}
return;
}
if ( numShaders > MAX_SHADER_FILES ) {
numShaders = MAX_SHADER_FILES;
}
// load and parse shader files
char* buffers[ MAX_SHADER_FILES ];
int buffersize[ MAX_SHADER_FILES ];
for ( int i = 0; i < numShaders; i++ ) {
char filename[ MAX_QPATH ];
String::Sprintf( filename, sizeof ( filename ), "scripts/%s", shaderFiles[ i ] );
common->Printf( "...loading '%s'\n", filename );
buffersize[ i ] = FS_ReadFile( filename, ( void** )&buffers[ i ] );
sum += buffersize[ i ];
if ( !buffers[ i ] ) {
common->Error( "Couldn't load %s", filename );
}
}
// build single large buffer
s_shaderText = new char[ sum + numShaders * 2 ];
s_shaderText[ 0 ] = 0;
// Gordon: optimised to not use strcat/String::Length which can be VERY slow for the large strings we're using here
char* p = s_shaderText;
// free in reverse order, so the temp files are all dumped
for ( int i = numShaders - 1; i >= 0; i-- ) {
if ( GGameType & GAME_ET ) {
String::Cpy( p++, "\n" );
String::Cpy( p, buffers[ i ] );
} else {
String::Cat( s_shaderText, sum + numShaders * 2, "\n" );
p = &s_shaderText[ String::Length( s_shaderText ) ];
String::Cat( s_shaderText, sum + numShaders * 2, buffers[ i ] );
}
FS_FreeFile( buffers[ i ] );
buffers[ i ] = p;
if ( GGameType & GAME_ET ) {
p += buffersize[ i ];
} else if ( !( GGameType & ( GAME_WolfSP | GAME_WolfMP ) ) ) {
String::Compress( p );
}
}
// ydnar: unixify all shaders
String::FixPath( s_shaderText );
// free up memory
FS_FreeFileList( shaderFiles );
if ( GGameType & ( GAME_WolfSP | GAME_WolfMP | GAME_ET ) ) {
// Ridah, optimized shader loading (18ms on a P3-500 for sfm1.bsp)
if ( GGameType & GAME_WolfSP || r_cacheShaders->integer ) {
BuildShaderChecksumLookup();
}
return;
}
int shaderTextHashTableSizes[ MAX_SHADERTEXT_HASH ];
Com_Memset( shaderTextHashTableSizes, 0, sizeof ( shaderTextHashTableSizes ) );
int size = 0;
//
for ( int i = 0; i < numShaders; i++ ) {
// pointer to the first shader file
const char* p = buffers[ i ];
// look for label
while ( 1 ) {
char* token = String::ParseExt( &p, true );
if ( token[ 0 ] == 0 ) {
break;
}
int hash = GenerateShaderHashValue( token, MAX_SHADERTEXT_HASH );
shaderTextHashTableSizes[ hash ]++;
size++;
String::SkipBracedSection( &p );
// if we passed the pointer to the next shader file
if ( i < numShaders - 1 ) {
if ( p > buffers[ i + 1 ] ) {
break;
}
}
}
}
size += MAX_SHADERTEXT_HASH;
const char** hashMem = new const char*[ size ];
Com_Memset( hashMem, 0, sizeof ( char* ) * size );
for ( int i = 0; i < MAX_SHADERTEXT_HASH; i++ ) {
shaderTextHashTable[ i ] = hashMem;
hashMem = hashMem + ( shaderTextHashTableSizes[ i ] + 1 );
}
Com_Memset( shaderTextHashTableSizes, 0, sizeof ( shaderTextHashTableSizes ) );
//
for ( int i = 0; i < numShaders; i++ ) {
// pointer to the first shader file
const char* p = buffers[ i ];
// look for label
while ( 1 ) {
const char* oldp = p;
char* token = String::ParseExt( &p, true );
if ( token[ 0 ] == 0 ) {
break;
}
int hash = GenerateShaderHashValue( token, MAX_SHADERTEXT_HASH );
shaderTextHashTable[ hash ][ shaderTextHashTableSizes[ hash ]++ ] = oldp;
String::SkipBracedSection( &p );
// if we passed the pointer to the next shader file
if ( i < numShaders - 1 ) {
if ( p > buffers[ i + 1 ] ) {
break;
}
}
}
}
}
static shader_t* CreateProjectionShader() {
R_ClearGlobalShader();
String::NCpyZ( shader.name, "projectionShadow", sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.cullType = CT_FRONT_SIDED;
shader.polygonOffset = true;
shader.numDeforms = 1;
shader.deforms[ 0 ].deformation = DEFORM_PROJECTION_SHADOW;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = tr.whiteImage;
stages[ 0 ].bundle[ 0 ].tcGen = TCGEN_IDENTITY;
stages[ 0 ].active = true;
stages[ 0 ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ 0 ].rgbGen = CGEN_CONST;
stages[ 0 ].alphaGen = AGEN_CONST;
stages[ 0 ].constantColor[ 3 ] = 127;
return FinishShader();
}
static void R_CreateParticleShader( image_t* image ) {
R_ClearGlobalShader();
String::NCpyZ( shader.name, "particle", sizeof ( shader.name ) );
shader.cullType = CT_FRONT_SIDED;
shader.lightmapIndex = LIGHTMAP_NONE;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = tr.particleImage;
stages[ 0 ].bundle[ 0 ].numImageAnimations = 1;
stages[ 0 ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ 0 ].stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; // no z buffering
stages[ 0 ].rgbGen = CGEN_VERTEX;
stages[ 0 ].alphaGen = AGEN_VERTEX;
stages[ 0 ].active = true;
tr.particleShader = FinishShader();
}
static void CreateExternalShaders() {
if ( GGameType & GAME_Tech3 ) {
if ( !( GGameType & GAME_WolfSP ) ) {
tr.projectionShadowShader = R_FindShader( "projectionShadow", LIGHTMAP_NONE, true );
}
tr.flareShader = R_FindShader( "flareShader", LIGHTMAP_NONE, true );
if ( GGameType & GAME_Quake3 ) {
tr.sunShader = R_FindShader( "sun", LIGHTMAP_NONE, true );
} else {
tr.sunflareShader = R_FindShader( "sunflare1", LIGHTMAP_NONE, true );
}
if ( GGameType & GAME_WolfSP ) {
tr.spotFlareShader = R_FindShader( "spotLight", LIGHTMAP_NONE, true );
}
} else {
tr.projectionShadowShader = CreateProjectionShader();
tr.flareShader = tr.defaultShader;
tr.sunShader = tr.defaultShader;
R_CreateParticleShader( tr.particleImage );
}
}
//JL This is almost identical to loading of models cache. Totaly useless.
static void R_LoadCacheShaders() {
if ( !r_cacheShaders->integer ) {
return;
}
// don't load the cache list in between level loads, only on startup, or after a vid_restart
if ( numBackupShaders > 0 ) {
return;
}
char* buf;
int len = FS_ReadFile( "shader.cache", ( void** )&buf );
if ( len <= 0 ) {
return;
}
const char* pString = buf;
char* token;
while ( ( token = String::ParseExt( &pString, true ) ) && token[ 0 ] ) {
char name[ MAX_QPATH ];
String::NCpyZ( name, token, sizeof ( name ) );
R_RegisterModel( name );
}
FS_FreeFile( buf );
}
void R_InitShaders() {
common->Printf( "Initializing Shaders\n" );
glfogNum = FOG_NONE;
if ( GGameType & GAME_WolfSP ) {
Cvar_Set( "r_waterFogColor", "0" );
Cvar_Set( "r_mapFogColor", "0" );
Cvar_Set( "r_savegameFogColor", "0" );
}
Com_Memset( ShaderHashTable, 0, sizeof ( ShaderHashTable ) );
CreateInternalShaders();
ScanAndLoadShaderFiles();
CreateExternalShaders();
// Ridah
R_LoadCacheShaders();
}
void R_FreeShaders() {
for ( int i = 0; i < tr.numShaders; i++ ) {
shader_t* sh = tr.shaders[ i ];
for ( int j = 0; j < MAX_SHADER_STAGES; j++ ) {
if ( !sh->stages[ j ] ) {
break;
}
for ( int b = 0; b < NUM_TEXTURE_BUNDLES; b++ ) {
delete[] sh->stages[ j ]->bundle[ b ].texMods;
}
delete sh->stages[ j ];
}
delete sh;
}
if ( s_shaderText ) {
delete[] shaderTextHashTable[ 0 ];
delete[] s_shaderText;
s_shaderText = NULL;
}
}
// When a handle is passed in by another module, this range checks it and
// returns a valid (possibly default) shader_t to be used internally.
shader_t* R_GetShaderByHandle( qhandle_t hShader ) {
if ( hShader < 0 ) {
common->Printf( S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader );
return tr.defaultShader;
}
if ( hShader >= tr.numShaders ) {
common->Printf( S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader );
return tr.defaultShader;
}
return tr.shaders[ hShader ];
}
// Dump information on all valid shaders to the console. A second parameter
// will cause it to print in sorted order
void R_ShaderList_f() {
shader_t* shader;
common->Printf( "-----------------------\n" );
int count = 0;
for ( int i = 0; i < tr.numShaders; i++ ) {
if ( Cmd_Argc() > 1 ) {
shader = tr.sortedShaders[ i ];
} else {
shader = tr.shaders[ i ];
}
common->Printf( "%i ", shader->numUnfoggedPasses );
if ( shader->lightmapIndex >= 0 ) {
common->Printf( "L " );
} else {
common->Printf( " " );
}
if ( shader->multitextureEnv == GL_ADD ) {
common->Printf( "MT(a) " );
} else if ( shader->multitextureEnv == GL_MODULATE ) {
common->Printf( "MT(m) " );
} else if ( shader->multitextureEnv == GL_DECAL ) {
common->Printf( "MT(d) " );
} else {
common->Printf( " " );
}
if ( shader->explicitlyDefined ) {
common->Printf( "E " );
} else {
common->Printf( " " );
}
if ( shader->optimalStageIteratorFunc == RB_StageIteratorGeneric ) {
common->Printf( "gen " );
} else if ( shader->optimalStageIteratorFunc == RB_StageIteratorSky ) {
common->Printf( "sky " );
} else if ( shader->optimalStageIteratorFunc == RB_StageIteratorLightmappedMultitexture ) {
common->Printf( "lmmt" );
} else if ( shader->optimalStageIteratorFunc == RB_StageIteratorVertexLitTexture ) {
common->Printf( "vlt " );
} else {
common->Printf( " " );
}
if ( shader->defaultShader ) {
common->Printf( ": %s (DEFAULTED)\n", shader->name );
} else {
common->Printf( ": %s\n", shader->name );
}
count++;
}
common->Printf( "%i total shaders\n", count );
common->Printf( "------------------\n" );
}
static bool R_ShaderCanBeCached( shader_t* sh ) {
if ( purgeallshaders ) {
return false;
}
if ( sh->isSky ) {
return false;
}
for ( int i = 0; i < sh->numUnfoggedPasses; i++ ) {
if ( sh->stages[ i ] && sh->stages[ i ]->active ) {
for ( int b = 0; b < NUM_TEXTURE_BUNDLES; b++ ) {
for ( int j = 0; j < MAX_IMAGE_ANIMATIONS && sh->stages[ i ]->bundle[ b ].image[ j ]; j++ ) {
if ( sh->stages[ i ]->bundle[ b ].image[ j ]->imgName[ 0 ] == '*' ) {
return false;
}
}
}
}
}
return true;
}
static void R_PurgeLightmapShaders() {
for ( size_t i = 0; i < sizeof ( backupHashTable ) / sizeof ( backupHashTable[ 0 ] ); i++ ) {
shader_t* sh = backupHashTable[ i ];
shader_t* shPrev = NULL;
shader_t* next = NULL;
while ( sh ) {
if ( sh->lightmapIndex >= 0 || !R_ShaderCanBeCached( sh ) ) {
next = sh->next;
if ( !shPrev ) {
backupHashTable[ i ] = sh->next;
} else {
shPrev->next = sh->next;
}
backupShaders[ sh->index ] = NULL; // make sure we don't try and free it
numBackupShaders--;
for ( int j = 0; j < sh->numUnfoggedPasses; j++ ) {
if ( !sh->stages[ j ] ) {
break;
}
for ( int b = 0; b < NUM_TEXTURE_BUNDLES; b++ ) {
if ( sh->stages[ j ]->bundle[ b ].texMods ) {
delete[] sh->stages[ j ]->bundle[ b ].texMods;
}
}
delete sh->stages[ j ];
}
delete sh;
sh = next;
continue;
}
shPrev = sh;
sh = sh->next;
}
}
}
void R_PurgeShaders() {
if ( !numBackupShaders ) {
return;
}
purgeallshaders = true;
R_PurgeLightmapShaders();
purgeallshaders = false;
numBackupShaders = 0;
}
void R_BackupShaders() {
if ( !r_cache->integer ) {
return;
}
if ( !r_cacheShaders->integer ) {
return;
}
// copy each model in memory across to the backupModels
memcpy( backupShaders, tr.shaders, sizeof ( backupShaders ) );
// now backup the ShaderHashTable
memcpy( backupHashTable, ShaderHashTable, sizeof ( ShaderHashTable ) );
numBackupShaders = tr.numShaders;
tr.numShaders = 0;
// Gordon: ditch all lightmapped shaders
R_PurgeLightmapShaders();
}
// bani - load a new dynamic shader
//
// if shadertext is NULL, looks for matching shadername and removes it
//
// returns true if request was successful, false if the gods were angered
bool R_LoadDynamicShader( const char* shadername, const char* shadertext ) {
const char* func_err = "WARNING: R_LoadDynamicShader";
if ( !shadername && shadertext ) {
common->Printf( S_COLOR_YELLOW "%s called with NULL shadername and non-NULL shadertext:\n%s\n", func_err, shadertext );
return false;
}
if ( shadername && String::Length( shadername ) >= MAX_QPATH ) {
common->Printf( S_COLOR_YELLOW "%s shadername %s exceeds MAX_QPATH\n", func_err, shadername );
return false;
}
//empty the whole list
if ( !shadername && !shadertext ) {
dynamicshader_t* dptr = dshader;
while ( dptr ) {
dynamicshader_t* lastdptr = dptr->next;
delete[] dptr->shadertext;
delete dptr;
dptr = lastdptr;
}
dshader = NULL;
return true;
}
//walk list for existing shader to delete, or end of the list
dynamicshader_t* dptr = dshader;
dynamicshader_t* lastdptr = NULL;
while ( dptr ) {
const char* q = dptr->shadertext;
char* token = String::ParseExt( &q, true );
if ( ( token[ 0 ] != 0 ) && !String::ICmp( token, shadername ) ) {
//request to nuke this dynamic shader
if ( !shadertext ) {
if ( !lastdptr ) {
dshader = NULL;
} else {
lastdptr->next = dptr->next;
}
delete[] dptr->shadertext;
delete dptr;
return true;
}
common->Printf( S_COLOR_YELLOW "%s shader %s already exists!\n", func_err, shadername );
return false;
}
lastdptr = dptr;
dptr = dptr->next;
}
//cant add a new one with empty shadertext
if ( !shadertext || !String::Length( shadertext ) ) {
common->Printf( S_COLOR_YELLOW "%s new shader %s has NULL shadertext!\n", func_err, shadername );
return false;
}
//create a new shader
dptr = new dynamicshader_t;
if ( lastdptr ) {
lastdptr->next = dptr;
}
dptr->shadertext = new char[ String::Length( shadertext ) + 1 ];
String::NCpyZ( dptr->shadertext, shadertext, String::Length( shadertext ) + 1 );
dptr->next = NULL;
if ( !dshader ) {
dshader = dptr;
}
return true;
}
int R_GetShaderWidth( qhandle_t shader ) {
return R_GetShaderByHandle( shader )->originalWidth;
}
int R_GetShaderHeight( qhandle_t shader ) {
return R_GetShaderByHandle( shader )->originalHeight;
}
void R_CacheTranslatedPic( const idStr& name, const idSkinTranslation& translation,
qhandle_t& image, qhandle_t& imageTop, qhandle_t& imageBottom ) {
char strippedName[ MAX_QPATH ];
String::StripExtension2( name.CStr(), strippedName, sizeof ( strippedName ) );
String::FixPath( strippedName );
idStr nameTop = idStr( strippedName ) + "*top";
idStr nameBottom = idStr( strippedName ) + "*bottom";
//
// see if the image is already loaded
//
shader_t* shaderBase = R_FindLoadedShader( strippedName, LIGHTMAP_2D );
shader_t* shaderTop = R_FindLoadedShader( nameTop.CStr(), LIGHTMAP_2D );
shader_t* shaderBottom = R_FindLoadedShader( nameBottom.CStr(), LIGHTMAP_2D );
if ( shaderBase && shaderTop && shaderBottom ) {
image = shaderBase->index;
imageTop = shaderTop->index;
imageBottom = shaderBottom->index;
return;
}
//
// load the pic from disk
//
byte* pic = NULL;
byte* picTop = NULL;
byte* picBottom = NULL;
int width = 0;
int height = 0;
R_LoadPICTranslated( name.CStr(), translation, &pic, &picTop, &picBottom, &width, &height, IMG8MODE_Normal );
if ( pic == NULL ) {
// If we dont get a successful load copy the name and try upper case
// extension for unix systems, if that fails bail.
idStr altname = name;
int len = altname.Length();
altname[ len - 3 ] = String::ToUpper( altname[ len - 3 ] );
altname[ len - 2 ] = String::ToUpper( altname[ len - 2 ] );
altname[ len - 1 ] = String::ToUpper( altname[ len - 1 ] );
common->Printf( "trying %s...\n", altname.CStr() );
R_LoadPICTranslated( altname.CStr(), translation, &pic, &picTop, &picBottom, &width, &height, IMG8MODE_Normal );
if ( pic == NULL ) {
common->FatalError( "R_CacheTranslatedPic: failed to load %s", name.CStr() );
}
}
image = R_Build2DShaderFromImage( R_CreateImage( name.CStr(), pic, width, height, false, false, GL_CLAMP, false ) )->index;
imageTop = R_Build2DShaderFromImage( R_CreateImage( nameTop.CStr(), picTop, width, height, false, false, GL_CLAMP, false ) )->index;
imageBottom = R_Build2DShaderFromImage( R_CreateImage( nameBottom.CStr(), picBottom, width, height, false, false, GL_CLAMP, false ) )->index;
delete[] pic;
delete[] picTop;
delete[] picBottom;
}
qhandle_t R_CreateWhiteShader() {
R_ClearGlobalShader();
String::NCpyZ( shader.name, "white", sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_2D;
SetImplicitShaderStages( tr.whiteImage );
return FinishShader()->index;
}
shader_t* R_BuildSprShader( image_t* image ) {
R_ClearGlobalShader();
String::NCpyZ( shader.name, image->imgName, sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.cullType = CT_FRONT_SIDED;
stages[ 0 ].active = true;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 0 ].rgbGen = CGEN_IDENTITY;
stages[ 0 ].alphaGen = AGEN_ENTITY_CONDITIONAL_TRANSLUCENT;
stages[ 0 ].stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
return FinishShader();
}
shader_t* R_BuildSp2Shader( image_t* image ) {
char shaderName[ MAX_QPATH ];
String::StripExtension2( image->imgName, shaderName, sizeof ( shaderName ) );
String::FixPath( shaderName );
shader_t* loadedShader = R_FindLoadedShader( shaderName, LIGHTMAP_NONE );
if ( loadedShader ) {
return loadedShader;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, shaderName, sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.cullType = CT_FRONT_SIDED;
stages[ 0 ].active = true;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 0 ].rgbGen = CGEN_IDENTITY;
stages[ 0 ].alphaGen = AGEN_ENTITY_CONDITIONAL_TRANSLUCENT;
stages[ 0 ].stateBits = GLS_DEFAULT | GLS_ATEST_GE_80;
stages[ 0 ].translucentStateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
return FinishShader();
}
shader_t* R_BuildQuakeWorldCustomSkin( const char* name, image_t* image, image_t* topImage, image_t* bottomImage, image_t* fullBrightImage ) {
char shaderName[ MAX_QPATH ];
String::StripExtension2( name, shaderName, sizeof ( shaderName ) );
String::FixPath( shaderName );
shader_t* loadedShader = R_FindLoadedShader( shaderName, LIGHTMAP_NONE );
if ( loadedShader ) {
return loadedShader;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, shaderName, sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.cullType = CT_FRONT_SIDED;
int i = 0;
stages[ i ].active = true;
stages[ i ].bundle[ 0 ].image[ 0 ] = image;
stages[ i ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ i ].rgbGen = CGEN_LIGHTING_DIFFUSE;
if ( GGameType & GAME_Hexen2 ) {
stages[ i ].alphaGen = AGEN_ENTITY_CONDITIONAL_TRANSLUCENT;
stages[ i ].stateBits = GLS_DEPTHMASK_TRUE;
stages[ i ].translucentStateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
} else {
stages[ i ].alphaGen = AGEN_IDENTITY;
stages[ i ].stateBits = GLS_DEFAULT;
}
i++;
if ( r_drawOverBrights->integer ) {
stages[ i ].active = true;
stages[ i ].bundle[ 0 ].image[ 0 ] = image;
stages[ i ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ i ].isOverbright = true;
stages[ i ].rgbGen = CGEN_LIGHTING_DIFFUSE_OVER_BRIGHT;
stages[ i ].alphaGen = AGEN_IDENTITY;
stages[ i ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE;
i++;
}
stages[ i ].active = true;
stages[ i ].bundle[ 0 ].image[ 0 ] = topImage;
stages[ i ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ i ].rgbGen = CGEN_LIGHTING_DIFFUSE_ENTITY_TOP_COLOUR;
stages[ i ].alphaGen = AGEN_IDENTITY;
stages[ i ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
i++;
stages[ i ].active = true;
stages[ i ].bundle[ 0 ].image[ 0 ] = bottomImage;
stages[ i ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ i ].rgbGen = CGEN_LIGHTING_DIFFUSE_ENTITY_BOTTOM_COLOUR;
stages[ i ].alphaGen = AGEN_IDENTITY;
stages[ i ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
i++;
if ( fullBrightImage ) {
stages[ i ].active = true;
stages[ i ].bundle[ 0 ].image[ 0 ] = fullBrightImage;
stages[ i ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ i ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ i ].rgbGen = CGEN_IDENTITY;
stages[ i ].alphaGen = AGEN_IDENTITY;
i++;
}
return FinishShader();
}
shader_t* R_BuildMdlShader( const char* modelName, int skinIndex, int numImages, image_t** images,
image_t** fullBrightImages, image_t* topImage, image_t* bottomImage, int flags ) {
char shaderName[ MAX_QPATH ];
String::StripExtension2( modelName, shaderName, sizeof ( shaderName ) );
String::FixPath( shaderName );
String::Cat( shaderName, sizeof( shaderName ), va( "_%d", skinIndex ) );
shader_t* loadedShader = R_FindLoadedShader( shaderName, LIGHTMAP_NONE );
if ( loadedShader ) {
return loadedShader;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, shaderName, sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.cullType = CT_FRONT_SIDED;
bool doOverBright = !!r_drawOverBrights->integer;
stages[ 0 ].active = true;
for ( int i = 0; i < numImages; i++ ) {
stages[ 0 ].bundle[ 0 ].image[ i ] = images[ i ];
stages[ 1 ].bundle[ 0 ].image[ i ] = images[ i ];
}
stages[ 0 ].bundle[ 0 ].numImageAnimations = numImages;
stages[ 1 ].bundle[ 0 ].numImageAnimations = numImages;
stages[ 0 ].bundle[ 0 ].imageAnimationSpeed = 10;
stages[ 1 ].bundle[ 0 ].imageAnimationSpeed = 10;
stages[ 0 ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ 1 ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ 0 ].rgbGen = CGEN_LIGHTING_DIFFUSE;
if ( GGameType & GAME_Hexen2 ) {
if ( flags & H2MDLEF_SPECIAL_TRANS ) {
shader.cullType = CT_TWO_SIDED;
stages[ 0 ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ 0 ].rgbGen = CGEN_IDENTITY;
stages[ 0 ].alphaGen = AGEN_IDENTITY;
doOverBright = false;
} else {
stages[ 0 ].alphaGen = AGEN_ENTITY_CONDITIONAL_TRANSLUCENT;
if ( flags & ( H2MDLEF_TRANSPARENT | H2MDLEF_HOLEY ) ) {
stages[ 0 ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
doOverBright = false;
} else {
stages[ 0 ].stateBits = GLS_DEPTHMASK_TRUE;
}
stages[ 0 ].translucentStateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
}
} else {
stages[ 0 ].stateBits = GLS_DEFAULT;
stages[ 0 ].alphaGen = AGEN_IDENTITY;
}
int idx = 1;
if ( doOverBright ) {
stages[ 1 ].active = true;
stages[ 1 ].rgbGen = CGEN_LIGHTING_DIFFUSE_OVER_BRIGHT;
stages[ 1 ].alphaGen = AGEN_IDENTITY;
stages[ 1 ].isOverbright = true;
stages[ 1 ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE;
idx++;
}
if ( topImage ) {
stages[ idx ].active = true;
stages[ idx ].bundle[ 0 ].image[ 0 ] = topImage;
stages[ idx ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ idx ].rgbGen = CGEN_LIGHTING_DIFFUSE_ENTITY_TOP_COLOUR;
stages[ idx ].alphaGen = AGEN_IDENTITY;
stages[ idx ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
idx++;
}
if ( bottomImage ) {
stages[ idx ].active = true;
stages[ idx ].bundle[ 0 ].image[ 0 ] = bottomImage;
stages[ idx ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ idx ].rgbGen = CGEN_LIGHTING_DIFFUSE_ENTITY_BOTTOM_COLOUR;
stages[ idx ].alphaGen = AGEN_IDENTITY;
stages[ idx ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
idx++;
}
if ( fullBrightImages[ 0 ] ) {
stages[ idx ].active = true;
for ( int i = 0; i < numImages; i++ ) {
stages[ idx ].bundle[ 0 ].image[ i ] = fullBrightImages[ i ];
}
stages[ idx ].bundle[ 0 ].numImageAnimations = numImages;
stages[ idx ].bundle[ 0 ].imageAnimationSpeed = 10;
stages[ idx ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ idx ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ idx ].rgbGen = CGEN_IDENTITY;
stages[ idx ].alphaGen = AGEN_IDENTITY;
idx++;
}
return FinishShader();
}
shader_t* R_BuildHexen2CustomSkinShader( image_t* image ) {
char shaderName[ MAX_QPATH ];
String::StripExtension2( image->imgName, shaderName, sizeof ( shaderName ) );
String::FixPath( shaderName );
shader_t* loadedShader = R_FindLoadedShader( shaderName, LIGHTMAP_NONE );
if ( loadedShader ) {
return loadedShader;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, shaderName, sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.cullType = CT_FRONT_SIDED;
stages[ 0 ].active = true;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 0 ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ 0 ].rgbGen = CGEN_LIGHTING_DIFFUSE;
stages[ 0 ].alphaGen = AGEN_ENTITY_CONDITIONAL_TRANSLUCENT;
stages[ 0 ].stateBits = GLS_DEPTHMASK_TRUE;
stages[ 0 ].translucentStateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
if ( r_drawOverBrights->integer ) {
stages[ 1 ].active = true;
stages[ 1 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 1 ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ 1 ].rgbGen = CGEN_LIGHTING_DIFFUSE_OVER_BRIGHT;
stages[ 1 ].alphaGen = AGEN_IDENTITY;
stages[ 1 ].stateBits = GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE;
stages[ 1 ].isOverbright = true;
}
return FinishShader();
}
shader_t* R_BuildMd2Shader( image_t* image ) {
char shaderName[ MAX_QPATH ];
String::StripExtension2( image->imgName, shaderName, sizeof ( shaderName ) );
String::FixPath( shaderName );
shader_t* loadedShader = R_FindLoadedShader( shaderName, LIGHTMAP_NONE );
if ( loadedShader ) {
return loadedShader;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, shaderName, sizeof ( shader.name ) );
shader.lightmapIndex = LIGHTMAP_NONE;
shader.cullType = CT_FRONT_SIDED;
stages[ 0 ].active = true;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 0 ].rgbGen = CGEN_LIGHTING_DIFFUSE;
stages[ 0 ].alphaGen = AGEN_ENTITY_CONDITIONAL_TRANSLUCENT;
stages[ 0 ].stateBits = GLS_DEFAULT;
stages[ 0 ].translucentStateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
return FinishShader();
}
shader_t* R_BuildBsp29Shader( mbrush29_texture_t* texture, int lightMapIndex ) {
shader_t* loadedShader = R_FindLoadedShader( texture->name, lightMapIndex );
if ( loadedShader ) {
return loadedShader;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, texture->name, sizeof ( shader.name ) );
shader.cullType = CT_FRONT_SIDED;
shader.lightmapIndex = lightMapIndex;
stages[ 0 ].active = true;
R_TextureAnimationQ1( texture, &stages[ 0 ].bundle[ 0 ] );
stages[ 0 ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
if ( GGameType & GAME_Hexen2 ) {
stages[ 0 ].rgbGen = CGEN_ENTITY_ABSOLUTE_LIGHT;
stages[ 0 ].alphaGen = AGEN_ENTITY_CONDITIONAL_TRANSLUCENT;
} else {
stages[ 0 ].rgbGen = CGEN_IDENTITY;
stages[ 0 ].alphaGen = AGEN_IDENTITY;
}
stages[ 0 ].stateBits = GLS_DEFAULT;
stages[ 0 ].translucentStateBits = GLS_DEFAULT | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ 1 ].active = true;
stages[ 1 ].rgbGen = CGEN_IDENTITY;
stages[ 1 ].alphaGen = AGEN_IDENTITY;
stages[ 1 ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_SRC_COLOR;
stages[ 1 ].bundle[ 0 ].image[ 0 ] = tr.lightmaps[ lightMapIndex ];
stages[ 1 ].bundle[ 0 ].isLightmap = true;
stages[ 1 ].bundle[ 0 ].tcGen = TCGEN_LIGHTMAP;
int i = 2;
if ( r_drawOverBrights->integer ) {
stages[ i ].active = true;
R_TextureAnimationQ1( texture, &stages[ i ].bundle[ 0 ] );
stages[ i ].isOverbright = true;
stages[ i ].rgbGen = CGEN_IDENTITY;
stages[ i ].alphaGen = AGEN_IDENTITY;
stages[ i ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE;
shader.multitextureEnv = GL_MODULATE;
stages[ i ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ i ].bundle[ 1 ].image[ 0 ] = tr.lightmaps[ lightMapIndex + MAX_LIGHTMAPS / 2 ];
stages[ i ].bundle[ 1 ].tcGen = TCGEN_LIGHTMAP;
i++;
}
if ( R_TextureFullbrightAnimationQ1( texture, &stages[ i ].bundle[ 0 ] ) ) {
stages[ i ].active = true;
stages[ i ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ i ].rgbGen = CGEN_IDENTITY;
stages[ i ].alphaGen = AGEN_IDENTITY;
stages[ i ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
}
return FinishShader();
}
shader_t* R_BuildBsp29WarpShader( const char* name, image_t* image ) {
R_ClearGlobalShader();
String::NCpyZ( shader.name, name, sizeof ( shader.name ) );
shader.cullType = CT_FRONT_SIDED;
shader.lightmapIndex = LIGHTMAP_NONE;
stages[ 0 ].active = true;
stages[ 0 ].rgbGen = CGEN_IDENTITY;
if ( GGameType & GAME_Quake && r_wateralpha->value < 1 ) {
stages[ 0 ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ 0 ].alphaGen = AGEN_CONST;
stages[ 0 ].constantColor[ 3 ] = r_wateralpha->value * 255;
} else if ( ( GGameType & GAME_Hexen2 ) &&
( !String::NICmp( name, "*rtex078", 8 ) ||
!String::NICmp( name, "*lowlight", 9 ) ) ) {
stages[ 0 ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ 0 ].alphaGen = AGEN_CONST;
stages[ 0 ].constantColor[ 3 ] = 102;
} else {
stages[ 0 ].stateBits = GLS_DEFAULT;
stages[ 0 ].alphaGen = AGEN_IDENTITY;
}
texMods[ 0 ][ 0 ].type = TMOD_TURBULENT_OLD;
texMods[ 0 ][ 0 ].wave.frequency = 1.0f / idMath::TWO_PI;
texMods[ 0 ][ 0 ].wave.amplitude = 1.0f / 8.0f;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
stages[ 0 ].bundle[ 0 ].numImageAnimations = 1;
stages[ 0 ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
stages[ 0 ].bundle[ 0 ].numTexMods = 1;
return FinishShader();
}
shader_t* R_BuildBsp29SkyShader( const char* name, image_t* imageSolid, image_t* imageAlpha ) {
R_ClearGlobalShader();
String::NCpyZ( shader.name, name, sizeof ( shader.name ) );
shader.cullType = CT_FRONT_SIDED;
shader.lightmapIndex = LIGHTMAP_NONE;
stages[ 0 ].active = true;
stages[ 0 ].bundle[ 0 ].image[ 0 ] = imageSolid;
stages[ 0 ].bundle[ 0 ].tcGen = TCGEN_QUAKE_SKY;
texMods[ 0 ][ 0 ].type = TMOD_SCROLL;
texMods[ 0 ][ 0 ].scroll[ 0 ] = 8 / 128.0f;
texMods[ 0 ][ 0 ].scroll[ 1 ] = 8 / 128.0f;
stages[ 0 ].bundle[ 0 ].numTexMods = 1;
stages[ 0 ].stateBits = GLS_DEFAULT;
stages[ 0 ].rgbGen = CGEN_IDENTITY;
stages[ 0 ].alphaGen = AGEN_IDENTITY;
stages[ 1 ].active = true;
stages[ 1 ].bundle[ 0 ].image[ 0 ] = imageAlpha;
stages[ 1 ].bundle[ 0 ].tcGen = TCGEN_QUAKE_SKY;
texMods[ 1 ][ 0 ].type = TMOD_SCROLL;
texMods[ 1 ][ 0 ].scroll[ 0 ] = 16 / 128.0f;
texMods[ 1 ][ 0 ].scroll[ 1 ] = 16 / 128.0f;
stages[ 1 ].bundle[ 0 ].numTexMods = 1;
stages[ 1 ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
stages[ 1 ].rgbGen = CGEN_IDENTITY;
stages[ 1 ].alphaGen = AGEN_IDENTITY;
return FinishShader();
}
shader_t* R_BuildBsp38Shader( image_t* image, int flags, int lightMapIndex ) {
if ( flags & BSP38SURF_SKY ) {
return tr.skyboxShader;
}
char shaderName[ MAX_QPATH ];
String::StripExtension2( image->imgName, shaderName, sizeof ( shaderName ) );
String::FixPath( shaderName );
if ( flags & BSP38SURF_WARP ) {
String::Cat( shaderName, sizeof ( shaderName ), "*warp" );
}
if ( flags & BSP38SURF_FLOWING ) {
String::Cat( shaderName, sizeof ( shaderName ), "*flowing" );
}
if ( flags & BSP38SURF_TRANS33 ) {
String::Cat( shaderName, sizeof ( shaderName ), "*trans33" );
} else if ( flags & BSP38SURF_TRANS66 ) {
String::Cat( shaderName, sizeof ( shaderName ), "*trans66" );
}
shader_t* loadedShader = R_FindLoadedShader( shaderName, lightMapIndex );
if ( loadedShader ) {
return loadedShader;
}
R_ClearGlobalShader();
String::NCpyZ( shader.name, shaderName, sizeof ( shader.name ) );
shader.cullType = CT_FRONT_SIDED;
shader.lightmapIndex = lightMapIndex;
stages[ 0 ].active = true;
stages[ 0 ].bundle[ 0 ].numImageAnimations = 1;
stages[ 0 ].bundle[ 0 ].tcGen = TCGEN_TEXTURE;
if ( flags & BSP38SURF_WARP ) {
texMods[ 0 ][ 0 ].type = TMOD_TURBULENT_OLD;
texMods[ 0 ][ 0 ].wave.frequency = 1.0f / idMath::TWO_PI;
texMods[ 0 ][ 0 ].wave.amplitude = 1.0f / 16.0f;
stages[ 0 ].bundle[ 0 ].numTexMods = 1;
}
// Hmmm, no flowing on translucent non-turbulent surfaces
if ( flags & BSP38SURF_FLOWING &&
( !( flags & ( BSP38SURF_TRANS33 | BSP38SURF_TRANS66 ) ) || flags & BSP38SURF_WARP ) ) {
int i = stages[ 0 ].bundle[ 0 ].numTexMods;
texMods[ 0 ][ i ].type = TMOD_SCROLL;
if ( flags & BSP38SURF_WARP ) {
texMods[ 0 ][ i ].scroll[ 0 ] = -0.5;
} else {
texMods[ 0 ][ i ].scroll[ 0 ] = -1.6;
}
stages[ 0 ].bundle[ 0 ].numTexMods++;
}
if ( flags & BSP38SURF_WARP ) {
stages[ 0 ].rgbGen = CGEN_IDENTITY_LIGHTING;
} else {
stages[ 0 ].rgbGen = CGEN_IDENTITY;
}
stages[ 0 ].bundle[ 0 ].image[ 0 ] = image;
if ( flags & ( BSP38SURF_TRANS33 | BSP38SURF_TRANS66 ) ) {
stages[ 0 ].alphaGen = AGEN_CONST;
if ( flags & BSP38SURF_TRANS33 ) {
stages[ 0 ].constantColor[ 3 ] = 84;
} else {
stages[ 0 ].constantColor[ 3 ] = 168;
}
stages[ 0 ].stateBits = GLS_DEFAULT | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
} else {
stages[ 0 ].alphaGen = AGEN_IDENTITY;
stages[ 0 ].stateBits = GLS_DEFAULT;
}
if ( lightMapIndex != LIGHTMAP_NONE ) {
stages[ 1 ].bundle[ 0 ].image[ 0 ] = tr.lightmaps[ lightMapIndex ];
stages[ 1 ].bundle[ 0 ].numImageAnimations = 1;
stages[ 1 ].bundle[ 0 ].tcGen = TCGEN_LIGHTMAP;
stages[ 1 ].bundle[ 0 ].isLightmap = true;
stages[ 1 ].rgbGen = CGEN_IDENTITY;
stages[ 1 ].alphaGen = AGEN_IDENTITY;
stages[ 1 ].stateBits = GLS_SRCBLEND_ZERO | GLS_DSTBLEND_SRC_COLOR;
stages[ 1 ].active = true;
}
return FinishShader();
}
|
#include <Arduino.h>
/**
* @name Stepper by hand
* @desc How to drive a stepper motor without library.
*
* @package Arduino Basics
* @author Michael <michael@zenbox.de>
* @since 2017/01/05
* @version v1.0.0
* @copyright (c) 2017 Michael Reichart
* @license MIT License <http://opensource.org/licenses/MIT>
*/
/**
* @desc Stepper 28BYJ-48 without library.
* Motor pins: 1-Blue, 2-Pink, 3-Yellow, 4-Orange
* Red - VCC. The motor shield pins IN1, IN2, IN3, IN4
* are for the electromagnetic coils in the stepper.
* The motorshield power supply and ground can be connected
* to the arduino power and ground, for testing.
* Test some speed limitations. It depends on the
* used power supply, how fast a stepper can be driven.
*
* @link https://grahamwideman.wikispaces.com/Motors-+28BYJ-48+Stepper+motor+notes
*/
const byte NUM_STEPPER_PINS = 4;
int stepperPins[NUM_STEPPER_PINS] = {7,6,5,4};
boolean stepperPinState = false;
int speedMax = 120;
int speedMin = 4000;
int speed = 0;
/**
* @desc the data sequence for the electromagnetic coils.
* We need 8 steps for one full rotation. The steps
* are easily binary noted.
*
*/
// Anzahl der Schritte für einen Umdrehungszyklus
const int NUM_DATA = 8;
byte dataLeft[NUM_DATA];
// declare a pin for the onboard led
const byte PIN = 13;
void setup() {
// init a serial port
Serial.begin(9600);
Serial.println("Everything seems fine ...");
// init the led pin
pinMode(PIN, OUTPUT);
digitalWrite(PIN, LOW);
pinMode(PIN, LOW);
/**
* @desc init the stepper pins
*/
for ( byte i = 0; i < NUM_STEPPER_PINS; i++) {
pinMode(stepperPins[i], OUTPUT );
}
speed = 1000;
/**
* @desc the eight step sequence for a left rotation
*/
dataLeft[0] = 0b00001000; // decimal: 8
dataLeft[1] = 0b00001100; // decimal: 12
dataLeft[2] = 0b00000100; // ...
dataLeft[3] = 0b00000110;
dataLeft[4] = 0b00000010;
dataLeft[5] = 0b00000011;
dataLeft[6] = 0b00000001;
dataLeft[7] = 0b00001001;
}
void stop() {
for (int stepperPin = 0; stepperPin < NUM_STEPPER_PINS; stepperPin++) {
digitalWrite(stepperPins[stepperPin], LOW);
}
}
void turnRight(){
/**
* @desc the stepper rotation leftward
*/
for (int i = 0; i < NUM_DATA; i+=1) {
for (int stepperPin = 0; stepperPin < NUM_STEPPER_PINS; stepperPin+=1) {
stepperPinState = bitRead(dataLeft[i], stepperPin);
// Serial.print(stepperPinState);
digitalWrite(stepperPins[stepperPin], stepperPinState);
delayMicroseconds(100);
}
}
}
void turnLeft () {
/**
* @desc the stepper rotation rightward
*/
for (int i = NUM_DATA - 1; i >= 0; i--) {
for (int stepperPin = 0; stepperPin < NUM_STEPPER_PINS; stepperPin++) {
stepperPinState = bitRead(dataLeft[i], stepperPin); // 1 = HIGH, 0 = LOW
digitalWrite(stepperPins[stepperPin], stepperPinState);
delayMicroseconds(speed);
}
}
}
void loop() {
turnRight();
}
|
#include <cstdio>
int main(void){
for (int i = 1; i <= 32; ++i){
printf("%d\n", (i & (i - 1)) == 0);
}
return 0;
}
|
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
printf("\n");
char p[10], q[10];
printf(".......................Welcome to Tic Tac Toe game:.....................\n\n");
printf("Player 1 enter your name : ");
scanf("%s", p);
printf("Player 2 enter your name : ");
scanf("%s", q);
printf("\n");
int a[3][3] = { 0, };
int i, j, x, y;
int count = 0;
for (i = 1; i <= 9; i++)
{
if (count % 2 == 0)
{
printf("It's your turn %s : ", p);
scanf("%d%d", &x, &y);
a[x][y] = 'X';
count++;
}
else
{
printf("It's your turn %s : ", q);
scanf("%d%d", &x, &y);
a[x][y] = 'O';
count++;
}
printf("\n");
for (i = 0; i<3; i++)
{
for (j = 0; j<3; j++)
{
if (a[i][j]=='\0')
printf("\t_\t");
else
printf("\t%c\t", a[i][j]);
}
printf("\n\n");
}
if (a[0][0] == 'X'&&a[0][1] == 'X'&&a[0][2] == 'X')
{
printf("%s wins\n", p);
break;
}
if (a[1][0] == 'X'&&a[1][1] == 'X'&&a[1][2] == 'X')
{
printf("%s wins\n", p);
break;
}
if (a[2][0] == 'X'&&a[2][1] == 'X'&&a[2][2] == 'X')
{
printf("%s wins\n", p);
break;
}
if (a[0][0] == 'X'&&a[1][0] == 'X'&&a[2][0] == 'X')
{
printf("%s wins\n", p);
break;
}
if (a[0][1] == 'X'&&a[1][1] == 'X'&&a[2][1] == 'X')
{
printf("%s wins\n", p);
break;
}
if (a[0][2] == 'X'&&a[1][2] == 'X'&&a[2][2] == 'X')
{
printf("%s wins\n", p);
break;
}
if (a[0][0] == 'X'&&a[1][1] == 'X'&&a[2][2] == 'X')
{
printf("%s wins\n", p);
break;
}
if (a[0][2] == 'X'&&a[1][1] == 'X'&&a[2][0] == 'X')
{
printf("%s wins\n", p);
break;
}
if (a[0][0] == 'O'&&a[0][1] == 'O'&&a[0][2] == 'O')
{
printf("%s wins\n", q);
break;
}
if (a[1][0] == 'O'&&a[1][1] == 'O'&&a[1][2] == 'O')
{
printf("%s wins\n", q);
break;
}
if (a[2][0] == 'O'&&a[2][1] == 'O'&&a[2][2] == 'O')
{
printf("%s wins\n", q);
break;
}
if (a[0][0] == 'O'&&a[1][0] == 'O'&&a[2][0] == 'O')
{
printf("%s wins\n", q);
break;
}
if (a[0][1] == 'O'&&a[1][1] == 'O'&&a[2][1] == 'O')
{
printf("%s wins\n", q);
break;
}
if (a[0][2] == 'O'&&a[1][2] == 'O'&&a[2][2] == 'O')
{
printf("%s wins\n", q);
break;
}
if (a[0][0] == 'O'&&a[1][1] == 'O'&&a[2][2] == 'O')
{
printf("%s wins\n", q);
break;
}
if (a[0][2] == 'O'&&a[1][1] == 'O'&&a[2][0] == 'O')
{
printf("%s wins\n", q);
break;
}
if (count == 9)
{
printf("This is a tie");
break;
}
}
_getch();
}
|
#include "qmlclientstate.h"
using namespace secure_voice_call;
QMLClientState::QMLClientState(QObject *parent) : QObject(parent)
{
}
QMLClientState::ClientStates QMLClientState::getState() const { return mClientState; }
QMLClientState &QMLClientState::getInstance() {
static QMLClientState instance;
return instance;
}
QString QMLClientState::callerName() const
{
return mCallerName;
}
QString QMLClientState::authorizatedAs() const
{
return mAuthorizatedAs;
}
QString QMLClientState::status() const
{
return mStatus;
}
void QMLClientState::setState(QMLClientState::ClientStates clientState)
{
if (mClientState == clientState)
return;
mClientState = clientState;
emit stateChanged(mClientState);
}
void QMLClientState::setCallerName(QString callerName)
{
if (mCallerName == callerName)
return;
mCallerName = callerName;
emit callerNameChanged(mCallerName);
}
void QMLClientState::setAuthorizatedAs(QString authorizatedAs)
{
if (mAuthorizatedAs == authorizatedAs)
return;
mAuthorizatedAs = authorizatedAs;
emit authorizatedAsChanged(mAuthorizatedAs);
}
void QMLClientState::setStatus(QString status)
{
mStatus = status;
emit statusChanged(mStatus);
}
|
#ifndef __LOADSHADER_MAT_H__
#define __LOADSHADER_MAT_H__
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
static char* readShaderSource(const char* shaderFile);
int loadShader(const char* vShaderFile, const char* fShaderFile);
#endif
|
//Visitor.cpp
#include "Visitor.h"
Visitor::Visitor() {
}
Visitor::~Visitor() {
}
Visitor::Visitor(const Visitor& source) {
}
Visitor& Visitor::operator=(const Visitor& source) {
return *this;
}
void Visitor::Visit(Page *page) {
}
void Visitor::Visit(Memo *memo) {
}
void Visitor::Visit(Line *line) {
}
void Visitor::Visit(Character *character) {
}
void Visitor::Visit(SingleCharacter *singleCharacter) {
}
void Visitor::Visit(DoubleCharacter *doubleCharacter) {
}
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include <signal.h>
#include <flux/SignalMaster>
namespace flux {
Ref<SignalMaster> SignalMaster::create(SignalSet *listenSet, SignalSet *terminationSet)
{
return new SignalMaster(listenSet, terminationSet);
}
SignalMaster::SignalMaster(SignalSet *listenSet, SignalSet *terminationSet):
listenSet_(listenSet),
terminationSet_(terminationSet),
receivedSignals_(SignalChannel::create())
{
if (!listenSet_) listenSet_ = SignalSet::createFull();
if (!terminationSet_) {
terminationSet_ = SignalSet::createEmpty();
terminationSet_->insert(SIGINT);
terminationSet_->insert(SIGTERM);
}
}
void SignalMaster::run()
{
int signal = 0;
while (true) {
int error = ::sigwait(listenSet_->rawSet(), &signal);
if (error != 0) FLUX_SYSTEM_DEBUG_ERROR(error);
receivedSignals_->pushBack(signal);
if (terminationSet_->contains(signal)) break;
}
}
} // namespace flux
|
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set wordSet(wordDict.begin(), wordDict.end());
vector<int> memo(s.size(), -1); // initial memo[]
return wordBreak(s, wordSet, 0, memo);
}
bool wordBreak(string s, unordered_set<string> & wordSet, int start, vector<int> & memo) {
if (start >= s.size()) return true;
if (memo[start] != -1) return memo[start];
for (int i = start + 1; i <= s.size(); ++i) {
if (wordSet.count(s.substr(start, i - start)) && wordBreak(s, wordSet, i, memo))
return memo[start] = 1;
}
return memo[start] = 0;
}
};
|
// github.com/andy489
#include <iostream>
using namespace std;
void merge(int *arr, int l, int mid, int r) {
unique_ptr<int[]> l_arr(new int[mid - l + 1]);
unique_ptr<int[]> r_arr(new int[r - mid]);
memcpy(l_arr.get(), arr + l, sizeof(int) * (mid - l + 1));
memcpy(r_arr.get(), arr + mid + 1, sizeof(int) * (r - mid));
int l_ind = 0, r_ind = 0, i(l);
for (; i <= r; ++i) {
if (r_ind == r - mid || (l_ind != mid - l + 1 && l_arr[l_ind] < r_arr[r_ind]))
arr[i] = l_arr[l_ind++];
else
arr[i] = r_arr[r_ind++];
}
}
void mergeSort(int *arr, int l, int r) {
if (l == r)
return;
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
int main() {
int n, i(0);
cin >> n;
int *arr = new int[n];
for (; i < n; ++i)
cin >> arr[i];
mergeSort(arr, 0, n - 1);
for (i = 0; i < n; ++i)
cout << arr[i] << ' ';
return 0;
}
|
#pragma once
#include "MenuPage.hpp"
class MenuPageError : public MenuPage {
private:
std::string message;
public:
MenuPageError(StateManager& manager, nk_context* nk);
MenuPageError(const MenuPageError& orig) = delete;
virtual ~MenuPageError();
virtual void updateContent();
void setMessage(const std::string &message_) {
message = message_;
}
};
|
#pragma once
#include <iostream>
#include <stdint.h>
#include <fstream>
#include <sstream>
#include <vector>
#include <limits>
#include <stack>
#include <map>
#include <set>
#include "IOperand.h"
#include "Creator.h"
#define MAX_PRECISION 308
#define COUNT_NUM_INT 15
#define MAX_COUNT_NUM 800
#define MIN_SIZE_FOR_OPERATION 2
#define SUCCESS_CODE 0
#define ERROR_CODE -1
template <typename T>
class Type
{
public:
T val;
Type(const T& val);
operator T();
T operator=(const T& val);
};
class IOperandCreator
{
protected:
IOperand const* createInt8(std::string const& value) const;
IOperand const* createInt16(std::string const& value) const;
IOperand const* createInt32(std::string const& value) const;
IOperand const* createFloat(std::string const& value) const;
IOperand const* createDouble(std::string const& value) const;
using Fptr = IOperand const* (IOperandCreator::*)(std::string const&) const;
std::vector<Fptr> associater
{
&IOperandCreator::createInt8,
&IOperandCreator::createInt16,
&IOperandCreator::createInt32,
&IOperandCreator::createFloat,
&IOperandCreator::createDouble
};
public:
IOperand const* createOperand(eOperandType type, std::string const& value) const;
};
class Operand : public IOperand, public IOperandCreator
{
int precision;
eOperandType type;
std::string StringVal;
bool checkOtherDigits(const std::string& num);
bool checkAlpha(const std::string& num);
int countDigitAfterDot(const std::string& value);
public:
Operand(const std::string& value, eOperandType type);
int getPrecision(void) const override;
eOperandType getType(void) const override;
IOperand const* operator+(IOperand const& rhs) const override;
IOperand const* operator-(IOperand const& rhs) const override;
IOperand const* operator*(IOperand const& rhs) const override;
IOperand const* operator/(IOperand const& rhs) const override;
IOperand const* operator%(IOperand const& rhs) const override;
std::string const& toString(void) const override;
};
const IOperand* Creator(const std::string& value, eOperandType type);
template <typename T>
T printAndExit(const T& whatReturn, const std::string& message)
{
std::cout << message << std::endl;
return whatReturn;
}
template <typename T>
Type<T>::Type(const T& val) { this->val = val; }
template <typename T>
Type<T>::operator T() { return val; }
template <typename T>
T Type<T>::operator=(const T& val) { this->val = val; }
|
/**
* Network server
*/
#ifndef FISHY_NET_SERVER_H
#define FISHY_NET_SERVER_H
#include "net_common.h"
#include <CORE/BASE/status.h>
#include <CORE/MEMORY/blob.h>
#include <CORE/UTIL/noncopyable.h>
namespace core {
namespace net {
class iNetServer;
/**
* Data handler called from {@link iNetServer#update}
*/
class iServerConnectionHandler {
public:
virtual ~iServerConnectionHandler() {}
/**
* Called to process incomming data from a single client.
*
* @param server server to send responses with.
* @param connectionId identifier for the connection who sent the data.
* @param data data to be processed. Caller owns the blob.
*/
virtual bool process(
iNetServer &server,
const tConnectionId connectionId,
const core::memory::ConstBlob &data) = 0;
/**
* Called when a new client connects
*
* @param connectionId the identifier for the new client
*/
virtual void open(const tConnectionId connectionId) = 0;
/**
* Called when an existing client disconnects
*
* @param connectionId the identifier for the old client
*/
virtual void close(const tConnectionId connectionId) = 0;
/**
* Called after all calls to process before {@link iNetServer#update} returns.
* Allows the connection handler to clean out temporary data and compact
* partially completed packets.
*/
virtual void cleanup() = 0;
};
/**
* Networking server interface
*/
class iNetServer : util::noncopyable {
public:
virtual ~iNetServer(){};
/**
* Try to start a server.
*/
virtual Status start(const core::net::ServerDef &def) = 0;
/**
* Gracefully disconnect all clients and shut down.
*/
virtual void stop() = 0;
/**
* Poll for client connection data.
*
* @param handler the {@link iServerConnectionHandler} that will recieve data.
*/
virtual Status update(iServerConnectionHandler &handler) = 0;
/**
* @return true if the server is alive and valid
*/
virtual bool valid() const = 0;
/**
* Send data to a specific client
*
* @param connectionId active connection to send data to
* @param msg data to send. Caller owns blob.
*/
virtual Status send(
const tConnectionId connectionId, const core::memory::ConstBlob &msg) = 0;
/**
* @return statistics about the connection
*/
virtual NetStats stats() const = 0;
/**
* @return the mode of this server (eg. TCP vs UDP)
*/
virtual eConnectionMode::type getConnectionMode() const = 0;
};
/**
* Networking server
*/
class NetServer : public iNetServer {
public:
/**
* Create a server with {@code mode} type of network protocol.
*/
NetServer(eConnectionMode::type mode);
~NetServer();
virtual Status start(const core::net::ServerDef &def);
virtual void stop();
virtual Status update(iServerConnectionHandler &handler);
virtual bool valid() const;
virtual Status
send(const tConnectionId connectionId, const core::memory::ConstBlob &msg);
virtual eConnectionMode::type getConnectionMode() const;
virtual NetStats stats() const { return m_stats; }
private:
class Impl;
Impl *m_pImpl;
NetStats m_stats;
};
} // namespace net
} // namespace core
#endif
|
int peak(vector<int> &a,int l,int h)
{
int n=a.size();
int m=l+(h-l)/2;
if((m==0 or a[m-1]<a[m]) and (m==n-1 or a[m]>a[m+1]))
return m;
else if(m!=0 and a[m-1]>a[m])
return peak(a,l,h-1);
else if(m!=n-1 and a[m]<a[m+1])
return peak(a,m+1,h);
}
int incBinarysearch(vector<int> &a,int l,int h,int k)
{
while(l<=h)
{
int m=l+(h-l)/2;
if(a[m]==k)
return m;
if(a[m]>k)
return incBinarysearch(a,l,m-1,k);
else
return incBinarysearch(a,m+1,h,k);
}
return -1;
}
int decBinarysearch(vector<int> &a,int l,int h,int k)
{
while(l<=h)
{
int m=l+(h-l)/2;
if(a[m]==k)
return m;
if(a[m]>k)
return decBinarysearch(a,m+1,h,k);
else if(a[m]<k)
return decBinarysearch(a,l,m-1,k);
}
return -1;
}
int Solution::solve(vector<int> &a, int k) {
int n=a.size();
int p=peak(a,0,n-1);
int d=-1,i=-1;
i=incBinarysearch(a,0,p,k);
d=decBinarysearch(a,p+1,n-1,k);
if(i!=-1 or d!=-1)
return i!=-1?i:d;
return -1;
}
|
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int min_distance=10000;
int closet=0;
int ssize=nums.size();
for(int i=0;i<ssize;i++){
int two_target=target-nums[i];
int m=i+1,n=ssize-1;
while(m<n){
int dis=two_target-(nums[m]+nums[n]);
if(dis>0){
if(abs(dis)<min_distance){
min_distance=abs(dis);
closet=nums[m]+nums[n]+nums[i];
}
m++;
continue;
}
else if(dis<0){
if(abs(dis)<min_distance){
min_distance=abs(dis);
closet=nums[m]+nums[n]+nums[i];
}
n--;
continue;
}
else{
return nums[m]+nums[n]+nums[i];
}
}
}
return closet;
}
};
|
#pragma once
#include <map>
#include "Animation.h"
#include "AnimationMap.h"
using namespace std;
class AnimationMap
{
public:
AnimationMap(void);
~AnimationMap(void);
void addAnimation(string name, Animation animation);
void deleteAnimation(string name);
Animation * getAnimation(string name);
void rename(string from, string to);
map<string, Animation>* getAnimationMap();
protected:
map<string, Animation> animationMap;
};
|
/*
* SPDX-FileCopyrightText: 2008 Till Harbaum <till@harbaum.org>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#pragma once
#include "osm.h"
#include <osm2go_platform.h>
struct appdata_t;
struct project_t;
class settings_t;
bool osm_download(osm2go_platform::Widget *parent, project_t *project);
void osm_upload(appdata_t &appdata);
void osm_modified_info(const osm_t::dirty_t &context, osm2go_platform::Widget *parent);
|
#include "common/WorkloadSim.h"
#include <benchmark/benchmark.h>
#include <numeric>
#include <vector>
// Measure runtime and noise ratio of workload simulation
void BM_100xWorkloadBindConst(benchmark::State &state) {
while (state.KeepRunning()) {
int i = 100;
do {
workload(0);
} while (--i != 0);
}
}
void BM_100xWorkloadBindVariable(benchmark::State &state) {
while (state.KeepRunning()) {
int i = 100;
do {
workload(i);
} while (--i != 0);
}
}
static double calc_mean_single(const std::vector<double>& v) {
return (std::accumulate(std::begin(v), std::end(v), 0.0) / 100.0) / v.size();
}
BENCHMARK(BM_100xWorkloadBindConst)
->Repetitions(32)
->ReportAggregatesOnly(true)
->ComputeStatistics("mean_single", calc_mean_single);
BENCHMARK(BM_100xWorkloadBindVariable)
->Repetitions(32)
->ReportAggregatesOnly(true)
->ComputeStatistics("mean_single", calc_mean_single);
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int>& prices)
{
int minPrice = INT_MAX;
int maxprofitValue = 0;
for(auto price : prices)
{
minPrice = min(minPrice,price);
maxprofitValue = max(maxprofitValue, price-minPrice);
}
return maxprofitValue;
}
};
// int main()
// {
// Solution s;
// //vector<int> input {7,1,5,3,6,4};
// vector<int> input {7,6,4,3,1};
// int output = s.maxProfit(input);
// cout << "Output : " << output << "\n";
// return 0;
// }
|
#pragma once
class RShaderBase;
class BViewport;
class RRenderTarget;
class BRenderingBatch;
class RMaterial;
class BRenderPassResource
{
public:
BRenderPassResource();
~BRenderPassResource();
unsigned int RenderTargetWidth;
unsigned int RenderTargetHeight;
RRenderTarget* m_BaseSceneRT;
void Initialize(unsigned int Width, unsigned int Height);
};
class BRenderPass
{
public:
BRenderPass();
~BRenderPass();
virtual void BeginPass(BViewport* InViewport);
virtual void EndPass();
virtual void BeginRenderBatch(BRenderingBatch* Batch);
virtual void EndRenderBatch();
BRenderPassResource* RPR;
BViewport* Viewport;
RShaderBase* Shader;
};
extern BRenderPassResource GRenderPassResource;
|
#ifndef SUDOKUSOLVER_H
#define SUDOKUSOLVER_H
#include <QWidget>
class SudokuWidget;
class SudokuSolver : public QWidget
{
Q_OBJECT
public:
SudokuSolver(QWidget *parent = Q_NULLPTR);
private slots:
void onSolve();
void onClear();
void onOpen();
bool solutionFound(const std::vector<std::vector<short>>&) const;
private:
SudokuWidget* m_sudokuWidget;
};
#endif
|
class Solution {
public:
bool search(vector<int>& nums, int target) {
int end = nums.size()-1;
int begin = 0;
while(begin < end)
{
int mid = (begin + end)/2;
if(nums[mid] == target) return true;
if(nums[mid] == nums[begin])
{
begin++;
continue;
}
if(nums[begin] < nums[mid])
{
if(nums[begin] <= target&&nums[mid] >= target)
{
end = mid;
}
else
{
begin = mid + 1;
}
}
else{
if(nums[end] >= target&&nums[mid] <= target)
{
begin = mid+1;
}
else
{
end = mid;
}
}
}
return end>=0 &&(nums[begin] == target||nums[end] == target);
}
};
|
#include "Purchase.h"
|
#include<bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
using namespace std;
int main(){
fastio;
int N;
cin>>N;
int vet[N];
for(int i=0;i<N;i++) cin>>vet[i];
sort(vet,(vet+N));
for(int i=0;i<N;i++) cout<<vet[i]<<" ";
cout<<"\n";
return 0;
}
|
#include "UscxmlClibExtensions.h"
#include "uscxml/util/DOM.h"
#include <xercesc/dom/DOM.hpp>
#include "UscxmlClibBase.h"
namespace uscxml {
/* GlobalDataIOProcessor */
GlobalDataIOProcessor::GlobalDataIOProcessor(ScxmlBase *AScxmlBase) : _ScxmlBase(AScxmlBase) {
}
void GlobalDataIOProcessor::eventFromSCXML(const std::string& target, const Event& event) {
SCXMLIOProcessor::eventFromSCXML(target, event);
_ScxmlBase->setGlobal(event.name, "", event.data, SCXMLTASK_TO_GLOBAL_ONLY);
}
std::shared_ptr<IOProcessorImpl> GlobalDataIOProcessor::create(IOProcessorCallbacks* callbacks) {
std::shared_ptr<GlobalDataIOProcessor> ioProc(new GlobalDataIOProcessor(_ScxmlBase));
ioProc->_callbacks = callbacks;
return ioProc;
}
/* SetValueExecutableContent */
SetValueExecutableContent::SetValueExecutableContent(ScxmlBase *AScxmlBase) :_ScxmlBase(AScxmlBase) {
}
void SetValueExecutableContent::enterElement(XERCESC_NS::DOMElement* node) {
// std::cout << "Entering custom element" << std::endl;
}
void SetValueExecutableContent::exitElement(XERCESC_NS::DOMElement* node) {
// std::cout << "Exiting custom element" << std::endl;
std::string s_target = "";
if (HAS_ATTR(node, kXMLCharTarget)) {
s_target = ATTR(node, kXMLCharTarget);
}
else if (HAS_ATTR(node, kXMLCharTargetExpr)) {
s_target = _interpreter->evalAsData(ATTR(node, kXMLCharTargetExpr)).atom;
}
else {
ERROR_EXECUTION_THROW2("<setvalue> element has neither 'target' nor 'targetexpr' attribute", node);
}
std::string s_type = "0"; // by default SCXMLTASK_TO_GLOBAL_ONLY
if (HAS_ATTR(node, kXMLCharType)) {
s_type = ATTR(node, kXMLCharType);
}
else if (HAS_ATTR(node, kXMLCharTypeExpr)) {
s_type = _interpreter->evalAsData(ATTR(node, X("targetexpr"))).atom;
}
std::string s_path = "";
if (HAS_ATTR(node, X("path"))) {
s_path = ATTR(node, X("path"));
}
else if (HAS_ATTR(node, X("pathexpr"))) {
s_path = _interpreter->evalAsData(ATTR(node, X("pathexpr"))).atom;
}
if (HAS_ATTR(node, X("value"))) {
uscxml::Data data(ATTR(node, X("value")),uscxml::Data::INTERPRETED);
_ScxmlBase->setGlobal(s_target, s_path, data, std::stoi(s_type));
}
else if (HAS_ATTR(node, X("valueexpr"))) {
uscxml::Data data = _interpreter->evalAsData(ATTR(node, X("valueexpr")));
_ScxmlBase->setGlobal(s_target, s_path, data, std::stoi(s_type));
}
else {
ERROR_EXECUTION_THROW2("<setvalue> element has neither 'value' nor 'valueexpr' attribute", node);
}
}
}
|
#ifndef RPEMONI_h
#define RPEMONI_h
#include <Arduino.h>
#include "CircularBuffer.h"
#include "EmonLib.h"
#define RP_KWH_VAR V_VAR2
class RpEmonI : public RpSensor {
public:
RpEmonI(byte pin);
void setup();
void presentation();
void loop_1s_tick();
void receiveCReq(const MyMessage &message);
void receive(const MyMessage &message);
RpEmonI* setVoltage(int v);
RpEmonI* setCurrentCalibration(float iCal, float iOffset);
RpEmonI* setIOffset(float iOffset);
RpEmonI* setNumSamples(int numSamples);
void setTimer(int8_t delay);
private:
byte _pin;
EnergyMonitor _emon1;
int _numSamples;
float _iCal;
float _iOffset;
int _voltage;
int _prevP;
uint32_t _lastKwhTime;
uint32_t _kwhCount;
uint32_t _localKwhCount;
byte _idKwh;
bool _ready;
CircularBuffer* myBuffer;
int8_t _countdownTimer;
uint32_t _sum;
int8_t _sumCount;
};
#endif
|
//
// Maze.hpp
// teensyMicromouse
//
// Created by Yikealo Abraha on 4/23/17.
// Copyright © 2017 Yikealo Abraha . All rights reserved.
//
#ifndef Maze_hpp
#define Maze_hpp
#include <stdio.h>
#include <unordered_map>
#include <vector>
#include <queue>
#include <math.h>
//To be removed later here just for debuging purpose only
#include <iostream>
//My own classess
#include "Vector.h"
#include "Path.h"
#define mazeHeight 16
#define mazeWidth 16
/*This queue wraper struct code and the findPath function
which implment the A* algorithm is also adaptation from
Amit Patel @ https://twitter.com/redblobgames
*/
struct PriorityQueue {
typedef std::pair<float, Node> PQElement;
std::priority_queue<PQElement, std::vector<PQElement>,
std::greater<PQElement>> elements;
inline bool empty() const { return elements.empty(); }
inline void put(Node item, float priority) {
elements.emplace(priority, item);
}
inline Node get() {
Node best_item = elements.top().second;
elements.pop();
return best_item;
}
};
class Maze
{
public:
Maze();
~Maze();
std::unordered_map<Node,std::vector<Node>,NodeHasher> getMaze() const;
float movementCost(const Node& from, const Node& to) const;
bool mazeExplored();
Path findPath(const Node& from , const Node& to , bool diagnoalAllowed = true );
std::vector<Node> getNeighbour(const Node& location);
std::vector<Node> getStoredNeighbour(const Node& location);
bool isNeigbour(const Node& a, Direction dir);
Node getNeigbour(const Node& a, Direction dir);
void setExplored(const Node& location);
bool isExplored(const Node& location) const;
void removeNeighbour(const Node& current, const Node& toBeRemoved);
void removeNeighbour(const Node& current, Direction dir);
void addNeighbour(const Node& current, const Node& toBeAdded);
void removeNode(const Node& toBeRemoved);
void addNode(const Node& toBeAdded);
void addNode(const Node& toBeAdded, std::vector<Node> neighbour);
bool areNeighbours(const Node& a, const Node& b);
bool isvalidNode(const Node& node);
void resetMaze();
void print(const Node& temp);
private:
void _removeNeighbour(const Node& current, const Node& toBeRemoved);
std::unordered_map<Node,std::vector<Node>,NodeHasher> maze;
std::unordered_map<Node, bool,NodeHasher> explored;
};
#endif /* Maze_hpp */
|
// \file SliceTiming.cpp
#include <cstdio>
#include <ctime>
#include <vector>
#include <type_to_vector/SliceMatcher.hpp>
using namespace type_to_vector;
struct Test {
std::string name;
StringVector slices;
StringVector places;
int n; // amount of runs
int m; // amount of slicing run
double result[2];
template <typename S>
double test() {
clock_t start, end;
bool r;
StringVector::const_iterator sit, pit;
start = clock();
for ( int i = 0; i < n; i++ ) {
sit = slices.begin();
for ( ; sit != slices.end(); sit++ ) {
S slicer(*sit);
for (int j=0; j<m; j++ ) {
pit = places.begin();
for ( ; pit != places.end(); pit++ )
r = slicer.fitsASlice(*pit);
}
}
}
end = clock();
printf("Last result is %d (output only to use the var).\n", r);
return double(end-start)/CLOCKS_PER_SEC;
}
};
typedef std::vector<Test> Tests;
int main() {
Tests tests;
{
Test T;
T.name = "one construct";
T.n = 100000;
T.m = 1;
T.slices.push_back("first_place");
tests.push_back(T);
}
{
Test T;
T.name = "one m'n'c";
T.n = 100000;
T.m = 1;
T.slices.push_back("first_place");
T.places.push_back("first_place");
T.places.push_back("second_place");
tests.push_back(T);
}
{
{
Test T;
T.name = "one match";
T.n = 1;
T.m = 100000;
T.slices.push_back("first_place");
T.places.push_back("first_place");
T.places.push_back("second_place");
tests.push_back(T);
}
Test T;
T.name = "start constr.";
T.n = 10000;
T.m = 1;
T.slices.push_back("start.idx start.[1,4-6].a start.[1,4-6].b start.*.c zwei");
tests.push_back(T);
}
{
Test T;
T.name = "start mnc";
T.n = 10000;
T.m = 1;;
T.slices.push_back("start.idx start.[1,4-6].a start.[1,4-6].b start.*.c zwei");
T.places.push_back("start.idx");
T.places.push_back("start.5.a");
T.places.push_back("start.8.c");
T.places.push_back("start.idx.val");
T.places.push_back("zwei.idx");
T.places.push_back("drei");
T.places.push_back("start.2.a");
T.places.push_back("start.1.d");
T.places.push_back("start.1");
tests.push_back(T);
}
{
Test T;
T.name = "start match";
T.n = 1;
T.m = 10000;
T.slices.push_back("start.idx start.[1,4-6].a start.[1,4-6].b start.*.c zwei");
T.places.push_back("start.idx");
T.places.push_back("start.5.a");
T.places.push_back("start.8.c");
T.places.push_back("start.idx.val");
T.places.push_back("zwei.idx");
T.places.push_back("drei");
T.places.push_back("start.2.a");
T.places.push_back("start.1.d");
T.places.push_back("start.1");
tests.push_back(T);
}
{
Test T;
T.name = "long constr";
T.n = 10000;
T.m = 1;
T.slices.push_back("a.*.b.[1-7:3].*.c");
tests.push_back(T);
}
{
Test T;
T.name = "a longer";
T.n = 10000;
T.m = 1;
T.slices.push_back("a.*.b.[1-7:3].*.c");
T.places.push_back("a.12.b.1.3.c");
T.places.push_back("a.12.b.1.10.c");
T.places.push_back("a.30.b.1.10.d");
T.places.push_back("a.12.b.2.10.d");
T.places.push_back("a.12.b.2.10.d");
T.places.push_back("d.12.b.2.10.d");
tests.push_back(T);
}
{
Test T;
T.name = "a longer";
T.n = 1;
T.m = 10000;
T.slices.push_back("a.*.b.[1-7:3].*.c");
T.places.push_back("a.12.b.1.3.c");
T.places.push_back("a.12.b.1.10.c");
T.places.push_back("a.30.b.1.10.d");
T.places.push_back("a.12.b.2.10.d");
T.places.push_back("a.12.b.2.10.d");
T.places.push_back("d.12.b.2.10.d");
tests.push_back(T);
}
Tests::iterator tit = tests.begin();
for (int i=0; tit != tests.end(); tit++, i++ ) {
printf("%d/%d\n",i+1,tests.size());
tit->result[0] = tit->test<SliceMatcher>();
tit->result[1] = tit->test<SliceTree>();
}
printf("Timing results in seconds.\n");
printf("%15s | %8s | %8s | %10s\n","Name","Matcher","Tree","Runs");
printf("-----------------+----------+----------+-----------\n");
for (tit = tests.begin(); tit != tests.end(); tit++ ) {
printf ("%15s | %8.3f | %8.3f | %7d/%7d\n", tit->name.c_str(), tit->result[0], tit->result[1],
tit->n, tit->m);
}
}
|
#include <iostream>
using namespace std;
const int size = 3;
void printArr(int *arr, int arrSize)
{
for(int i = 0; i<= arrSize; ++i)
{
cout << arr[i]<< '\t';
}
cout << endl;
}
void printVariations(int *arr, int n, int start=0)
{
if (start==n)
{
printArr(arr, n);
return;
}
//
printVariations(arr, n-1);
//
printVariations(arr, n-1);
}
int main (){
cout << "Hello world" << endl;
int a[size];
printArr(a, size)
return 0;
}
|
#include "animations\Singularity.Animations.h"
namespace Singularity
{
namespace Animations
{
struct Keyframe
{
#pragma region Variables
int JointIndex;
int FrameNumber;
Vector3 Translation;
Quaternion Rotation;
Vector3 Scale;
Vector4 RotTanX; //Do we need these last bits anymore?
Vector4 RotTanY;
Vector4 RotTanZ;
Vector4 TransTanX;
Vector4 TransTanY;
Vector4 TransTanZ;
#pragma endregion
};
}
}
|
#include "animations\Singularity.Animations.h"
namespace Singularity
{
namespace Animations
{
struct AnimationState
{
public:
#pragma region Variables
float ElapsedTime;
float Speed;
#pragma endregion
#pragma region Constructors and Finalizers
AnimationState(float elapsedTime = 1.0f, float speed = 1.0f/100.0f) : ElapsedTime(elapsedTime), Speed(speed) { }
#pragma endregion
};
}
}
|
#ifndef EXAMPLE_WORLD_H
#define EXAMPLE_WORLD_H
#include "engine/input.h"
#include "engine/camera.h"
#include "opengl/renderer.h"
#include "prefab/ground.h"
#include "point_cloud.h"
namespace example {
class World final
{
public:
World();
void init(int window_width, int window_height);
void update(float time, float delta_time, const apeiron::engine::Input* input = nullptr);
void render();
private:
apeiron::opengl::Renderer renderer_;
apeiron::engine::Camera camera_;
apeiron::prefab::Ground ground_;
Point_cloud point_cloud_;
int frame_ = 0;
};
} // namespace example
#endif // EXAMPLE_WORLD_H
|
#define BOOST_TEST_MODULE "dsn::lambda_unique_ptr"
#include <dsnutil/lambda_unique_ptr.hpp>
#include <iostream>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(basic_lambda_unique_ptr)
{
using ptr_type = dsn::lambda_unique_ptr<void>;
bool free_executed{ false };
{
ptr_type ptr(malloc(10 * sizeof(char)), [&](void* ptr) {
std::cout << "Hello from lambda in lambda_unique_ptr. Got ptr=" << ptr << std::endl;
if (ptr != nullptr) {
free_executed = true;
free(ptr);
}
});
BOOST_CHECK(ptr.get() != nullptr);
}
BOOST_CHECK(free_executed);
}
|
/*
* File: main.cpp
* Author: dan
*
* Created on November 20, 2012, 4:53 PM
*/
#define HOMEADV 3
#define MAX 1000
#define GAMES 475
#define CHOP 100
#define START 0
#define FIL "predmar7-1.csv"
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <cmath>
#include "game.h"
#include "team.h"
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
/*
*
*
*
*/
//void getTeamName(char *, int);
void sortAndChop(double num[], double num2[]);
int main() {
int n, g, count=0, i;
double homeScores[MAX], visScores[MAX], winPerc, wins=0;
double homeChopped[MAX-(2*CHOP)], visChopped[MAX-(2*CHOP)];
char schedule[GAMES][2][4];
double score[2], homeTotal=0, visTotal=0;
double finalHome, finalVis;
ifstream schedfile;
schedfile.open("schedule.csv");
while(schedfile.good() && count < GAMES){
schedfile >> schedule[count][0];
schedfile >> schedule[count][1];
count++;
}
schedfile.close();
for(g=START;g<GAMES;g++){
Team home(schedule[g][0]), vis(schedule[g][1]);
Game game1(home, vis);
for(n=0;n<MAX;n++){
game1.setScore();
score[0] = game1.getScore(0);
score[1] = game1.getScore(1);
// game1.displayScore();
// homeTotal += score[0];
// visTotal += score[1];
homeScores[n]=score[0];
visScores[n]=score[1];
score[0] = 0;
if (homeScores[n] > visScores[n])
wins++;
}
sortAndChop(homeScores, homeChopped);
sortAndChop(visScores, visChopped);
for(i=0;i<(MAX-(2*CHOP));i++){
homeTotal += homeScores[i];
visTotal += visScores[i];
}
//calculating standard dev
winPerc = wins/MAX;
finalHome = homeTotal/(MAX-(CHOP*2));
finalVis = visTotal/(MAX-(CHOP*2));
// cout << homeTeam << "," << finalHome << "," << visTeam << "," << finalVis << endl;
ofstream myfile;
myfile.open (FIL, ios::app);
myfile << schedule[g][0] << "," << finalHome << "," << schedule[g][1] << "," << finalVis << "," << winPerc << "," << endl;
myfile.close();
finalHome = 0;
finalVis = 0;
visTotal = 0;
homeTotal = 0;
wins = 0;
}
return 0;
}
/*void getTeamName(char * p, int n){
teams[30][4] = {
}*/
void sortAndChop(double num[], double num2[]){
int i, j;
double temp; // holding variable
int numLength = MAX;
for (i=0; i< (numLength -1); i++) // element to be compared
{
for(j = (i+1); j < numLength; j++) // rest of the elements
{
if (num[i] < num[j]) // descending order
{
temp= num[i]; // swap
num[i] = num[j];
num[j] = temp;
}
}
}
for(i=CHOP;i<numLength-CHOP;i++){
for(j=0;j<(numLength-(2*CHOP));j++)
num2[j] = num[i];
}
return;
}
#endif
|
#include "souvpurchases.h"
#include <iomanip>
#include <fstream>
#include <sstream>
#include <limits>
#include <ios>
#include <qdebug.h>
//creates a souvenir class based on the text file souvenirInfoList.txt
souvPurchases::souvPurchases() {
std::ifstream inFile;
inFile.open("C:/Users/gdfgdf/Documents/findingnemo/souvenirpurchase.txt");
while(!inFile.eof()) {
std::vector<souvenirPurchase> newSouvenirs;
std::string teamName;
souvenirPurchase newSouvenir;
std::string souvenirName;
float souvenirPrice;
int souvenirQuantity;
//getting the stadium name that will hold the list of souvenirs
std::getline(inFile, teamName);
if (inFile.eof())
{
return;
}
//getting the stadium's souvenir name
std::getline(inFile, souvenirName);
//taking in all the souvenirs the stadium has to offer
while(souvenirName != "~") {
//getting the souvenir's price
inFile >> souvenirPrice;
inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
//setting the name and price to the struct
newSouvenir.item = souvenirName;
newSouvenir.price = souvenirPrice;
newSouvenir.quantity = souvenirQuantity;
//pushing the new souvenir info into the vector
newSouvenirs.push_back(newSouvenir);
//getting the stadium's souvenir name
std::getline(inFile, souvenirName);
}//end - while
listOfPurchases[teamName] = newSouvenirs;
}//end - while
inFile.close();
}//end - default constructor
souvPurchases::~souvPurchases() { }//end - default constructor
//this method will make the soucenir list presistant between runs depending on
//the changes that were made to it.
void souvPurchases::updateSouvenirPurchases() {
std::map< std::string, std::vector<souvenirPurchase> >::iterator
it = listOfPurchases.begin();
//opening file for update
std::ofstream outFile;
outFile.open("C:/Users/gdfgdf/Documents/findingnemo/souvenirpurchases.txt");
int sizeOfSouvs = listOfPurchases.size();
int i = 0;
for(; it != listOfPurchases.end(); it++) {
i++;
outFile << it->first << std::endl;
std::vector<souvenirPurchase>::iterator it2 = it->second.begin();
for(; it2 != it->second.end(); it2++) {
outFile << it2->item << std::endl;
outFile << it2->price << std::endl;
outFile << it2->quantity << std::endl;
}//end - for
outFile << "~";
if(sizeOfSouvs != i) outFile << std::endl;
}//end - for
outFile.close();
}//end - updateSouvenirList
//adding a souvenir to the passed in stadium. returns true if item was
//added successfully
bool souvPurchases::addSouvenirPurchase(std::string stadiumName,
std::string itemName,
float itemPrice,
int quantity) {
//the .count() method will return a bool if the key is in the map.
//if stadium is not in the map, return false.
if(!listOfPurchases.count(stadiumName)) return false;
souvenirPurchase newSouvenir;
newSouvenir.item = itemName;
newSouvenir.price = itemPrice;
newSouvenir.quantity = quantity;
listOfPurchases.at(stadiumName).push_back(newSouvenir);
return true;
}//end - addSouvenir
//returns a string all the souvenir's information at the passed in stadium
//returns an error message if the stadium is not found
std::map< std::string, std::vector<souvenirPurchase> > souvPurchases::getAllInfoAt(std::string stadiumName) {
//the .count() method will return a bool if the key is in the map.
//if stadium is not in the map, return false.
// if(!listOfSouvenirs.count(stadiumName)) return "::ERROR:: Stadium Not Found\n";
return listOfPurchases;
}//end - getAllInfoAt
|
/* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@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.
*/
#include "../inc/NetworkInitializer.h"
#include "../inc/CommandRfkill.h"
#include "../../common/inc/ChildProcess.h"
#include "../../common/inc/DebugLog.h"
#include "../../configs/BtConfig.h"
#include "../../configs/ExpConfig.h"
#include "../../configs/PathConfig.h"
#include "../../configs/WfdConfig.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
using namespace sc;
void NetworkInitializer::initialize(void) {
char cmdLine[500] = {
0,
};
// Step 1. Bluetooth OFF
LOG_VERB("Init (1/3): BT OFF");
CommandRfkill::block_device(DEFAULT_BT_DEVICE_RFKILL_NAME);
snprintf(cmdLine, 500, "%s %s down", HCICONFIG_PATH,
DEFAULT_BT_INTERFACE_NAME);
system(cmdLine);
// Step 2. Bluetooth ON
LOG_VERB("Init (2/3): BT ON");
CommandRfkill::unblock_device(DEFAULT_BT_DEVICE_RFKILL_NAME);
snprintf(cmdLine, 500, "%s %s up piscan", HCICONFIG_PATH,
DEFAULT_BT_INTERFACE_NAME);
system(cmdLine);
// Step 3. Wi-fi Direct OFF
LOG_VERB("Init (3/4). Wi-fi Direct OFF");
snprintf(cmdLine, 500, "killall udhcpd");
system(cmdLine);
// snprintf(cmdLine, 500, "%s %s down", IFCONFIG_PATH,
// DEFAULT_WFD_INTERFACE_NAME);
// system(cmdLine);
#if CONFIG_REALTEK_MODE == 1
#else
// snprintf(cmdLine, 500, "%s %s", IFDOWN_PATH, DEFAULT_WFD_INTERFACE_NAME);
// system(cmdLine);
#endif
// Step 4. Wi-fi ON
LOG_VERB("Init (4/4). Wi-fi Direct ON");
#if CONFIG_REALTEK_MODE == 1
#else
// snprintf(cmdLine, 500, "%s %s", IFUP_PATH,
// DEFAULT_WFD_INTERFACE_NAME);
// system(cmdLine);
#endif
// snprintf(cmdLine, 500, "%s %s up", IFCONFIG_PATH, DEFAULT_WFD_INTERFACE_NAME);
// system(cmdLine);
#if CONFIG_REALTEK_MODE == 1
// Restart wpa_supplicant
snprintf(cmdLine, 500, "%s wpa_supplicant", KILLALL_PATH);
system(cmdLine);
sleep(3);
FILE *p2p_conf_file = NULL;
p2p_conf_file = fopen("p2p.conf", "w");
if (p2p_conf_file == NULL) {
LOG_ERR("Cannot write p2p.conf file");
return;
}
fprintf(p2p_conf_file, "ctrl_interface=/var/run/wpa_supplicant \
\nap_scan=1 \
\ndevice_name=SelCon \
\ndevice_type=1-0050F204-1 \
\ndriver_param=p2p_device=1 \
\n\nnetwork={ \
\n\tmode=3 \
\n\tdisabled=2 \
\n\tssid=\"DIRECT-SelCon\" \
\n\tkey_mgmt=WPA-PSK \
\n\tproto=RSN \
\n\tpairwise=CCMP \
\n\tpsk=\"12345670\" \
\n}");
fclose(p2p_conf_file);
snprintf(cmdLine, 500, "%s -Dnl80211 -iwlan1 -cp2p.conf -Bd",
WPA_SUPPLICANT_PATH);
system(cmdLine);
#endif
}
int NetworkInitializer::ping_wpa_cli(char ret[], size_t len) {
char const *const params[] = {"wpa_cli", "-i", DEFAULT_WFD_INTERFACE_NAME,
"ping", NULL};
return ChildProcess::run(WPA_CLI_PATH, params, ret, len, true);
}
void NetworkInitializer::retrieve_wpa_interface_name(std::string &wpaIntfName) {
char wpaIntfNameCstr[100];
char buf[1024];
// In the case of Wi-fi USB Dongle, it uses 'wlanX'.
snprintf(wpaIntfNameCstr, sizeof(wpaIntfNameCstr), DEFAULT_WFD_INTERFACE_NAME,
strlen(DEFAULT_WFD_INTERFACE_NAME));
// In the case of Raspberry Pi 3 Internal Wi-fi Module, it uses 'p2p-wlanX-Y'.
int ret = this->ping_wpa_cli(buf, 1024);
if (ret < 0) {
LOG_ERR("P2P ping call failed");
return;
} else {
char *ptrptr;
char *ptr = strtok_r(buf, "\t \n\'", &ptrptr);
while (ptr != NULL) {
if (strstr(ptr, "p2p-wlan")) {
snprintf(wpaIntfNameCstr, sizeof(wpaIntfNameCstr), "%s", ptr);
} else if (strstr(ptr, "FAIL")) {
LOG_ERR("P2P ping failed");
return;
}
ptr = strtok_r(NULL, "\t \n\'", &ptrptr);
}
}
wpaIntfName.assign(wpaIntfNameCstr, strlen(wpaIntfNameCstr));
}
|
/*-----------------------------------------------------------------------
Matt Marchant 2015 - 2016
http://trederia.blogspot.com
Robomower - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#include <components/StackLogicComponent.hpp>
#include <components/InstructionBlockLogic.hpp>
#include <components/LoopHandle.hpp>
#include <RoundedRectangle.hpp>
#include <Messages.hpp>
#include <CommandCategories.hpp>
#include <xygine/Entity.hpp>
#include <xygine/Log.hpp>
#include <xygine/Reports.hpp>
#include <xygine/Scene.hpp>
#include <xygine/components/ParticleController.hpp>
#include <xygine/components/SfDrawableComponent.hpp>
#include <SFML/Graphics/Text.hpp>
namespace
{
const std::size_t maxInstructions = 32;
const float padding = 22.f;
const float margin = 8.f;
}
StackLogicComponent::StackLogicComponent(xy::MessageBus& mb, const sf::Vector2f& slotSize, const sf::Vector2f& bounds)
: xy::Component (mb, this),
m_slots (maxInstructions),
m_updateTransform (true),
m_localBounds ({}, bounds),
m_parentEntity (nullptr),
m_maxScrollDistance (bounds.y),
m_instructionCount (0)
{
for (auto i = 0u; i < m_slots.size(); ++i)
{
m_slots[i].slotLocalArea = { { margin, (i * (slotSize.y + padding)) + (margin * 2.f) }, slotSize };
}
m_localBounds.height = m_slots.back().slotLocalArea.top + slotSize.y + margin;
m_maxScrollDistance = m_localBounds.height - m_maxScrollDistance;
xy::Component::MessageHandler mh;
mh.id = MessageId::InstructionBlockMessage;
mh.action = std::bind(&StackLogicComponent::instructionBlockHandler, this, std::placeholders::_1, std::placeholders::_2);
addMessageHandler(mh);
mh.id = MessageId::ScrollbarMessage;
mh.action = std::bind(&StackLogicComponent::scrollHandler, this, std::placeholders::_1, std::placeholders::_2);
addMessageHandler(mh);
}
//public
void StackLogicComponent::entityUpdate(xy::Entity& entity, float)
{
if (m_updateTransform)
{
auto tr = entity.getWorldTransform();
for (auto& s : m_slots)
{
s.slotArea = tr.transformRect(s.slotLocalArea);
}
m_globalBounds = tr.transformRect(m_localBounds);
m_updateTransform = false;
}
#ifdef _DEBUG_
//std::string targeted;
//for (auto i = 0u; i < m_slots.size() / 2; ++i)
//{
// targeted = (m_slots[i].targeted) ? "true" : "false";
// REPORT("Slot " + std::to_string(i + 10), std::to_string(m_slots[i].occupierID) + ", " + targeted);
//}
#endif //_DEBUG_
}
void StackLogicComponent::onStart(xy::Entity& entity)
{
m_parentEntity = &entity;
}
//private
void StackLogicComponent::updateInstructionCount()
{
m_instructionCount = 0;
for (const auto& s : m_slots)
{
if (s.occupierID != 0) m_instructionCount++;
}
REPORT("Instruction Count", std::to_string(m_instructionCount));
}
void StackLogicComponent::instructionBlockHandler(xy::Component* c, const xy::Message& msg)
{
//if (msg.id == MessageId::InstructionBlockMessage)
//{
auto& msgData = msg.getData<InstructionBlockEvent>();
switch (msgData.action)
{
case InstructionBlockEvent::Moved:
{
auto size = std::min(m_instructionCount + 1, maxInstructions);
for (auto i = 0u; i < size; ++i)
{
const auto& area = m_slots[i].slotArea;
if (area.contains(msgData.position) && !m_slots[i].targeted)
{
auto targetIdx = msgData.component->getTargetIndex();
if (targetIdx != i)
{
if (targetIdx > -1) m_slots[targetIdx].targeted = false;
msgData.component->setTargetIndex(i);
m_slots[i].targeted = true;
msgData.component->setTarget({ area.left, area.top }, false);
}
//we need to move out occupier if it exists
if (m_slots[i].occupierID != 0)
{
//check previous slot is empty and move any icons up
if (i > 0 && m_slots[i - 1].occupierID == 0)
{
auto idx = i - 1;
{
sf::Vector2f targetPos(m_slots[idx].slotArea.left, m_slots[idx].slotArea.top);
xy::Command cmd;
cmd.entityID = m_slots[i].occupierID;
cmd.action = [targetPos](xy::Entity& entity, float)
{
auto ib = entity.getComponent<InstructionBlockLogic>();
XY_ASSERT(ib, "component doesn't exist");
ib->setTarget(targetPos, false);
ib->setCarried(false);
};
m_parentEntity->getScene()->sendCommand(cmd);
m_slots[i].occupierID = 0;
m_slots[i].instruction = Instruction::NOP; //wipe instruction else it may get counted for being something it isn't
m_slots[idx].targeted = true;
}
}
else
{
//move existing instruction tabs down
for (auto j = i; j < m_slots.size(); ++j)
{
if (m_slots[j].occupierID == 0) break; //got to end of occupied slots
xy::Command cmd;
cmd.entityID = m_slots[j].occupierID;
if (j < m_slots.size() - 1)
{
//safe to move down
auto idx = j + 1;
sf::Vector2f targetPos(m_slots[idx].slotArea.left, m_slots[idx].slotArea.top);
cmd.action = [targetPos](xy::Entity& entity, float)
{
auto ib = entity.getComponent<InstructionBlockLogic>();
XY_ASSERT(ib, "component doesn't exist");
ib->setTarget(targetPos, false);
ib->setCarried(false);
};
m_slots[j + 1].targeted = true;
}
else
{
//pop off end
cmd.action = [](xy::Entity& entity, float)
{
auto ib = entity.getComponent<InstructionBlockLogic>();
XY_ASSERT(ib, "component doesn't exist");
ib->setTarget(entity.getWorldPosition() + sf::Vector2f(0.f, 500.f)); //arbitary number here just to push icon off bottom
ib->setCarried(false);
ib->setStackIndex(-1);
};
}
m_parentEntity->getScene()->sendCommand(cmd);
m_slots[j].occupierID = 0;
m_slots[j].instruction = Instruction::NOP;
}
}
}
break;
}
//we got to the end so therefore test for deletion
auto idx = msgData.component->getPreviousStackIndex();
if (idx >= 0 &&
!m_globalBounds.contains(msgData.position))
{
msgData.component->setTarget({ 1920.f - m_slots[0].slotArea.width, 20.f }); //TODO somewhere with a bin icon, or set this on mouse up
msgData.component->setStackIndex(-1);
m_slots[idx].targeted = false;
if (idx >= 0)
{
//block was dragged off stack so realign remaining
for (auto i = idx + 1; i < maxInstructions; ++i)
{
sf::Vector2f targetPos(m_slots[i - 1].slotArea.left, m_slots[i - 1].slotArea.top);
xy::Command cmd;
cmd.entityID = m_slots[i].occupierID;
cmd.action = [targetPos](xy::Entity& entity, float)
{
auto ib = entity.getComponent<InstructionBlockLogic>();
XY_ASSERT(ib, "component doesn't exist");
ib->setTarget(targetPos, false);
ib->setCarried(false);
};
m_parentEntity->getScene()->sendCommand(cmd);
m_slots[i].occupierID = 0;
m_slots[i].targeted = false;
}
}
}
}
break;
}
case InstructionBlockEvent::Dropped:
{
//update the slot data with the block info and vice versa
auto lastLoop = m_slots.size(); //so we know the last loop before current
for (auto i = 0u; i < m_slots.size(); ++i)
{
if (m_slots[i].slotArea.contains(msgData.position))
{
m_slots[i].occupierID = msgData.component->getParentUID();
m_slots[i].instruction = msgData.component->getInstruction();
m_slots[i].targeted = false;
msgData.component->setStackIndex(i);
msgData.component->setPreviousLoop(lastLoop);
bool child = (m_slots[i].instruction == Instruction::Forward || m_slots[i].instruction == Instruction::Loop);
auto instruction = m_slots[i].instruction;
//send command to enable cropping shader
xy::Command cmd;
cmd.entityID = m_slots[i].occupierID;
cmd.action = [child, instruction](xy::Entity& entity, float)
{
entity.getComponent<xy::SfDrawableComponent<sf::Text>>()->setShaderActive();
entity.getComponent<xy::SfDrawableComponent<RoundedRectangle>>()->setShaderActive();
if (child) //also activate on input box
{
auto& chent = *entity.getChildren()[0];
chent.getComponent<xy::SfDrawableComponent<RoundedRectangle>>()->setShaderActive();
chent.getComponent<xy::SfDrawableComponent<sf::Text>>()->setShaderActive();
}
};
m_parentEntity->getScene()->sendCommand(cmd);
break;
}
//remember this for next iter
if (m_slots[i].instruction == Instruction::Loop)
{
lastLoop = i;
}
}
//recalc size
updateInstructionCount();
}
break;
case InstructionBlockEvent::PickedUp:
{
//empty the slot if this block previously occupied it
auto i = msgData.component->getStackIndex();
if (i >= 0)
{
bool child = (m_slots[i].instruction == Instruction::Forward || m_slots[i].instruction == Instruction::Loop);
auto instruction = m_slots[i].instruction;
m_slots[i].occupierID = 0;
m_slots[i].instruction = Instruction::NOP;
m_slots[i].targeted = false;
msgData.component->setStackIndex(-1);
updateInstructionCount();
//send command to disable cropping shader
xy::Command cmd;
cmd.entityID = msgData.component->getParentUID();
cmd.action = [child, instruction](xy::Entity& entity, float)
{
entity.getComponent<xy::SfDrawableComponent<sf::Text>>()->setShaderActive(false);
entity.getComponent<xy::SfDrawableComponent<RoundedRectangle>>()->setShaderActive(false);
if (child) //also deactivate on input box
{
auto& chent = *entity.getChildren()[0];
chent.getComponent<xy::SfDrawableComponent<RoundedRectangle>>()->setShaderActive(false);
chent.getComponent<xy::SfDrawableComponent<sf::Text>>()->setShaderActive(false);
}
};
m_parentEntity->getScene()->sendCommand(cmd);
}
}
break;
case InstructionBlockEvent::Destroyed:
{
auto position = msgData.position;
//send a message to particle controller
xy::Command cmd;
cmd.category = CommandCategory::ParticleController;
cmd.action = [position](xy::Entity& entity, float)
{
entity.getComponent<xy::ParticleController>()->fire(0, position);
};
m_parentEntity->getScene()->sendCommand(cmd);
}
break;
default: break;
}
//}
}
void StackLogicComponent::scrollHandler(xy::Component* c, const xy::Message& msg)
{
//else if (msg.id == MessageId::ScrollbarMessage)
//{
auto& msgData = msg.getData<ScrollbarEvent>();
const float distance = msgData.position * m_maxScrollDistance;
xy::Command cmd;
cmd.category = CommandCategory::InstructionList;
cmd.action = [distance](xy::Entity& entity, float)
{
auto position = entity.getPosition();
position.y = -distance;
entity.setPosition(position);
};
m_parentEntity->getScene()->sendCommand(cmd);
m_updateTransform = true;
//}
}
|
#include "Network.h"
namespace Network {
Network::Network(bool isServer) :m_IsServer(isServer) {
if (m_IsServer) {
if (WSAStartup(MAKEWORD(2, 2), &m_WSA) != 0) {
printf("Failed. Error Code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
if ((m_Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
DWORD dwBytesReturned = 0;
BOOL bNewBehavior = FALSE;
if (WSAIoctl(m_Socket, SIO_UDP_CONNRESET, &bNewBehavior, sizeof(bNewBehavior), NULL, 0, &dwBytesReturned, NULL, NULL) == SOCKET_ERROR) {
DWORD dwErr = WSAGetLastError();
if (WSAEWOULDBLOCK == dwErr) {
printf("Yea, your stuffed!");
} else {
printf("WSAIoctl(SIO_UDP_CONNRESET) Error: %d\n", dwErr);
}
}
m_ServerAddress.sin_family = AF_INET;
m_ServerAddress.sin_addr.S_un.S_addr = INADDR_ANY;
m_ServerAddress.sin_port = htons(SERVERPORT);
int i = bind(m_Socket, (sockaddr*)&m_ServerAddress, sizeof(m_ServerAddress));
printf("Code: %d", i);
if (i == SOCKET_ERROR) {
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
} else {
if (WSAStartup(MAKEWORD(2, 2), &m_WSA) != 0) {
printf("Failed. Error Code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
if ((m_Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR) {
printf("socket() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
DWORD dwBytesReturned = 0;
BOOL bNewBehavior = FALSE;
if (WSAIoctl(m_Socket, SIO_UDP_CONNRESET, &bNewBehavior, sizeof(bNewBehavior), NULL, 0, &dwBytesReturned, NULL, NULL) == SOCKET_ERROR) {
DWORD dwErr = WSAGetLastError();
if (WSAEWOULDBLOCK == dwErr) {
printf("Yea, your stuffed!");
}
else {
printf("WSAIoctl(SIO_UDP_CONNRESET) Error: %d\n", dwErr);
}
}
}
}
Network::~Network() {
closesocket(m_Socket);
WSACleanup();
}
sockaddr_in Network::Recieve(char buffer[BUFLEN]) {
sockaddr_in from = sockaddr_in();
int size = sizeof(from);
int ret = recvfrom(m_Socket, buffer, BUFLEN, 0, (SOCKADDR*)&from, &size);
if (ret < 0) {
buffer[ret] = 0;
int x = WSAGetLastError();
m_LastError = -1;
printf("recvfrom() failed with error code : %d", x);
return from;
} else {
buffer[ret] = 0;
m_LastError = 0;
return from;
}
}
void Network::Send(const std::string& address, unsigned short port, const char* buffer) {
sockaddr_in add;
add.sin_family = AF_INET;
add.sin_addr.s_addr = inet_addr(address.c_str());
add.sin_port = htons(port);
int ret = sendto(m_Socket, buffer, strlen(buffer), 0, (struct sockaddr*) &add, sizeof(add));
if (ret < 0) {
m_LastError = -1;
printf("sendto() failed with error code : %d", WSAGetLastError());
}
m_LastError = 0;
}
void Network::Send(sockaddr_in add, const char* buffer) {
add.sin_family = AF_INET;
int ret = sendto(m_Socket, buffer, strlen(buffer), 0, (struct sockaddr*) &add, sizeof(add));
if (ret < 0) {
m_LastError = -1;
printf("sendto() failed with error code : %d", WSAGetLastError());
}
m_LastError = 0;
}
bool Network::IsServer() {
return m_IsServer;
}
}
|
#include <irtkTransformation.h>
//#include <nr.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_sort_vector.h>
char **dofin_names = NULL, *dofout = NULL;
void usage() {
cerr
<< "\t Usage: ffdmedianaverage [dofout] [N] [dofin1...N] <-noaffine> \n"
<< endl;
cerr << "\t The input mffds are assumed to relate to the same target image"
<< endl;
cerr << "\t and have the same lattice dimensions and a single level. "
<< endl;
cerr << "\t The output mffd will also point to this target and it will "
<< endl;
cerr
<< "\t have a single level with the same control point structure as the "
<< endl;
cerr << "\t input transformations." << endl;
cerr
<< "\t The rigid parameters of the output mffd will be the identity and "
<< endl;
cerr
<< "\t the scale and skew parameters are those of the input mffds averaged."
<< endl;
cerr << "\t " << endl;
cerr
<< "\t The input transformation control points are averaged using the median4 "
<< endl;
cerr
<< "\t and assigned to each output control point. Affine correction is first "
<< endl;
cerr << "\t done on the input transformations' local control point values."
<< endl;
cerr << "\t An identity mffd from the target to itself is assumed present."
<< endl;
cerr
<< "\t -noaffine = Don't combine with affine average, i.e. resulting "
<< endl;
cerr
<< "\t transformation will have identity global component."
<< endl;
exit(1);
}
void checkLevelsAndDimensions(irtkMultiLevelFreeFormTransformation **mffds,
int inputCount) {
int i, x, y, z;
x = mffds[0]->GetLocalTransformation(0)->GetX();
y = mffds[0]->GetLocalTransformation(0)->GetY();
z = mffds[0]->GetLocalTransformation(0)->GetZ();
for (i = 0; i < inputCount; ++i) {
if (mffds[i]->NumberOfLevels() > 1) {
cerr
<< "All input transformations must have the same number of levels."
<< endl;
exit(1);
}
if (x != mffds[i]->GetLocalTransformation(0)->GetX() || y
!= mffds[i]->GetLocalTransformation(0)->GetY() || z
!= mffds[i]->GetLocalTransformation(0)->GetZ()) {
cerr
<< "All input transformations must have the same lattice dimensions."
<< endl;
exit(1);
}
}
}
void resetRigidComponents(irtkAffineTransformation *a) {
a->PutTranslationX(0);
a->PutTranslationY(0);
a->PutTranslationZ(0);
a->PutRotationX(0);
a->PutRotationY(0);
a->PutRotationZ(0);
}
int main(int argc, char **argv) {
int i, j, k, n, xdim, ydim, zdim, inputCount;
bool ok;
double x, y, z, xAffCorr, yAffCorr, zAffCorr;
double xAv, yAv, zAv, xFinal, yFinal, zFinal;
bool combineaffine = true;
irtkMatrix *globalMatrices;
irtkMatrix globalMatrixAv(4, 4);
irtkMatrix sumLogs(4, 4);
irtkMatrix jac(3, 3);
irtkMatrix globalAvJac(3, 3);
if (argc < 4) {
usage();
}
// Parse arguments.
dofout = argv[1];
argc--;
argv++;
inputCount = atoi(argv[1]);
argc--;
argv++;
if (inputCount < 1) {
cerr
<< "checkLevelsAndDimensions: Must have at least one input transformation."
<< endl;
exit(1);
}
// Read input transformation names.
dofin_names = new char *[inputCount];
for (i = 0; i < inputCount; ++i) {
dofin_names[i] = argv[1];
argc--;
argv++;
}
// Parse options.
while (argc > 1) {
ok = false;
if ((ok == false) && (strcmp(argv[1], "-noaffine") == 0)) {
argc--;
argv++;
combineaffine = false;
ok = true;
}
if (ok == false) {
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
// Read the mffds.
// The output mffd is a copy of the first input (for now).
irtkTransformation *transform;
irtkMultiLevelFreeFormTransformation *mffdOut;
irtkMultiLevelFreeFormTransformation **mffds;
transform = irtkTransformation::New(dofin_names[0]);
mffdOut = dynamic_cast<irtkMultiLevelFreeFormTransformation *> (transform);
mffds = new irtkMultiLevelFreeFormTransformation *[inputCount];
globalMatrices = new irtkMatrix[inputCount];
for (i = 0; i < inputCount; ++i) {
transform = irtkTransformation::New(dofin_names[i]);
mffds[i]
= dynamic_cast<irtkMultiLevelFreeFormTransformation *> (transform);
globalMatrices[i].Initialize(4, 4);
}
checkLevelsAndDimensions(mffds, inputCount);
////////////////////////////////////////////////////
// Affine part:
globalMatrixAv.Ident();
// Is affine portion to be averaged?
if (combineaffine == true) {
// Average the affine parts separately from the displacement fields.
// Only the scales and skew are actually averaged.
for (i = 0; i < inputCount; ++i) {
resetRigidComponents(mffds[i]);
globalMatrices[i] = mffds[i]->irtkAffineTransformation::GetMatrix();
sumLogs += logm(globalMatrices[i]);
}
// The affine portion of the target to itself is the identity. The log
// of the identity matrix is zero so its contribution does not appear
// in the sum. The sum, however, is divided by one more than the input
// count because this identity transform is taken into account. There
// is a similar situation with the displacement field averages below.
globalMatrixAv = expm(sumLogs / (double) (1.0 + inputCount));
}
mffdOut->irtkAffineTransformation::PutMatrix(globalMatrixAv);
////////////////////////////////////////////////////
// Now tackle the displacement fields.
// Re-read the original global matrices.
for (i = 0; i < inputCount; ++i) {
transform = irtkTransformation::New(dofin_names[i]);
mffds[i]
= dynamic_cast<irtkMultiLevelFreeFormTransformation *> (transform);
globalMatrices[i] = mffds[i]->irtkAffineTransformation::GetMatrix();
}
// Space for storing the output control points.
irtkFreeFormTransformation3D
*ffdOut =
dynamic_cast<irtkFreeFormTransformation3D *> (mffdOut->GetLocalTransformation(
0));
// Space for storing the control point displacements.
double* xdata = new double[ffdOut->NumberOfDOFs() / 3];
double* ydata = new double[ffdOut->NumberOfDOFs() / 3];
double* zdata = new double[ffdOut->NumberOfDOFs() / 3];
xdim = ffdOut->GetX();
ydim = ffdOut->GetY();
zdim = ffdOut->GetZ();
irtkFreeFormTransformation3D *ffdCurr;
// Correct the control point values in each of the input FFDs with
// respect to their corresponding affine components.
for (n = 0; n < inputCount; ++n) {
// Correcting the cp values requires the affine part to be S->T.
globalMatrices[n].Invert();
ffdCurr
= dynamic_cast<irtkFreeFormTransformation3D *> (mffds[n]->GetLocalTransformation(
0));
for (k = 0; k < zdim; ++k) {
for (j = 0; j < ydim; ++j) {
for (i = 0; i < xdim; ++i) {
ffdCurr->Get(i, j, k, x, y, z);
xAffCorr = globalMatrices[n](0, 0) * x + globalMatrices[n](
0, 1) * y + globalMatrices[n](0, 2) * z;
yAffCorr = globalMatrices[n](1, 0) * x + globalMatrices[n](
1, 1) * y + globalMatrices[n](1, 2) * z;
zAffCorr = globalMatrices[n](2, 0) * x + globalMatrices[n](
2, 1) * y + globalMatrices[n](2, 2) * z;
ffdCurr->Put(i, j, k, xAffCorr, yAffCorr, zAffCorr);
}
}
}
}
// Copy the average jacobian section for correcting the CP values in the
// output transformation.
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
globalAvJac(i, j) = globalMatrixAv(i, j);
}
}
// float *xs = new float[1 + inputCount];
// float *ys = new float[1 + inputCount];
// float *zs = new float[1 + inputCount];
gsl_vector *xs = gsl_vector_alloc(inputCount);
gsl_vector *ys = gsl_vector_alloc(inputCount);
gsl_vector *zs = gsl_vector_alloc(inputCount);
bool even = (inputCount % 2 == 0);
// int index1 = 1 + inputCount / 2;
int index1 = inputCount / 2;
int index2 = index1 - 1;
// Now can average the displacement fields.
for (k = 0; k < zdim; ++k) {
for (j = 0; j < ydim; ++j) {
for (i = 0; i < xdim; ++i) {
xAv = yAv = zAv = 0.0;
for (n = 0; n < inputCount; ++n) {
ffdCurr =
dynamic_cast<irtkFreeFormTransformation3D *> (mffds[n]->GetLocalTransformation(0));
ffdCurr->Get(i, j, k, x, y, z);
// xs[n + 1] = x;
// ys[n + 1] = y;
// zs[n + 1] = z;
gsl_vector_set(xs, n, x);
gsl_vector_set(ys, n, y);
gsl_vector_set(zs, n, z);
}
// sort(inputCount, xs);
// sort(inputCount, ys);
// sort(inputCount, zs);
gsl_sort_vector(xs);
gsl_sort_vector(ys);
gsl_sort_vector(zs);
// if (even) {
// xAv = 0.5 * (xs[index1] + xs[index2]);
// yAv = 0.5 * (ys[index1] + ys[index2]);
// zAv = 0.5 * (zs[index1] + zs[index2]);
// } else {
// xAv = xs[index1];
// yAv = ys[index1];
// zAv = zs[index1];
// }
if (even) {
xAv = 0.5 * (gsl_vector_get(xs, index1) + gsl_vector_get(xs, index2));
yAv = 0.5 * (gsl_vector_get(ys, index1) + gsl_vector_get(ys, index2));
zAv = 0.5 * (gsl_vector_get(zs, index1) + gsl_vector_get(zs, index2));
} else {
xAv = gsl_vector_get(xs, index1);
yAv = gsl_vector_get(ys, index1);
zAv = gsl_vector_get(zs, index1);
}
if (combineaffine == true) {
// Now introduce the affine component.
xFinal = globalAvJac(0, 0) * xAv + globalAvJac(0, 1) * yAv
+ globalAvJac(0, 2) * zAv;
yFinal = globalAvJac(1, 0) * xAv + globalAvJac(1, 1) * yAv
+ globalAvJac(1, 2) * zAv;
zFinal = globalAvJac(2, 0) * xAv + globalAvJac(2, 1) * yAv
+ globalAvJac(2, 2) * zAv;
} else {
xFinal = xAv;
yFinal = yAv;
zFinal = zAv;
}
ffdOut->Put(i, j, k, xFinal, yFinal, zFinal);
}
}
}
// Some reporting.
if (combineaffine == true) {
cout << "Affine component combined with ffd." << endl;
} else {
cout << "ffd has identity affine component." << endl;
}
mffdOut->irtkTransformation::Write(dofout);
delete[] xdata;
delete[] ydata;
delete[] zdata;
}
|
#include <stdio.h>
#include <stdlib.h>
#include "diag/Trace.h"
#include "qp_port.h"
#include "BoardSupportPackage.h"
#include "BatteryController.h"
#include "DebugTracer.h"
#include "initQP.h"
#include "myEvents.h"
/* the start point */
int main (int argc, char* argv[]);
int main (int argc, char* argv[]) {
(void)argc;
(void)argv;
uint_fast8_t prio = 1;
BSP::system.systemInit();
BSP::system.setLedState(BSP::RED_LED, true);
QP::initializeFramework();
/* the whole queue for events */
static QP::QEvt const *queueSto[200];
DT::item.start(prio++, queueSto, Q_DIM(queueSto), (void *)0, 0);
BC::item.start(prio++, queueSto, Q_DIM(queueSto), (void *)0, 0);
return QP::QF::run();
}
|
#include <cstdint>
#include <iostream>
#include <sys/timerfd.h>
#include <unistd.h>
int main() {
const auto timer = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
itimerspec value{};
value.it_value.tv_sec = 1;
value.it_interval.tv_sec = 3;
timerfd_settime(timer, 0, &value, nullptr);
int count = 0;
while (true) {
uint64_t val;
auto ret = read(timer, &val, sizeof val);
std::cout << "alarm: " << count++ << std::endl;
}
}
|
class functions
{
public:
void leseZeile(char* line, int y);
void schreibeZeile(char* line);
};
|
#include<bits/stdc++.h>
#include<stdio.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
using namespace std;
#define ll long long
#define scl(n) scanf("%lld",&n)
#define scc(c) scanf("%c",&c)
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define pfl(x) printf("%lld\n",x)
#define pb push_back
#define debug cout<<"I am here"<<endl;
#define pno cout<<"NO"<<endl
#define pys cout<<"YES"<<endl
#define tcas(i,t) for(ll i=1;i<=t;i++)
#define l(s) s.size()
#define N 100006
int main()
{
ll m,n,b,c,d,i,j,k,x,y,z,l,q,r;
string s,s1, s2, s3, s4;
ll cnt=0,cn=0,ans=0,sum=0 ;
cin>>s>>s1>>k;
set<ll>st;
n=l(s);
fr(i, n)
{
x=0, cnt=0;
for(j=i; j<n; j++)
{
if(s1[s[j]-'a']=='0' )
cnt++;
if(cnt>k)
break;
x*=117ll, x+=s[j];
st.insert(x);
}
}
cout<<st.size()<<endl;
return 0;
}
|
#include "targetwidget.h"
#include "playerwidget.h"
#include "network/connection.h"
#include "json11/json11.hpp"
#include <QWidget>
using namespace json11;
TargetWidget::TargetWidget(QWidget *parent) : PlayerWidget(parent) {
QSizePolicy sp_retain = this->sizePolicy();
sp_retain.setRetainSizeWhenHidden(true);
this->setSizePolicy(sp_retain);
QObject::connect(
this, SIGNAL(activate(bool)),
this, SLOT(setVisible(bool))
);
}
std::string TargetWidget::target() const {
if (_target) {
return _target->name();
} else {
return "";
}
}
void TargetWidget::select_target(Actor * a) {
update_target(a);
emit activate(true);
const Json data = Json::object {
{"Type", "Attack"},
{"Condition", "Start"},
{"Victim", a->name()}
};
connection::write(data);
}
void TargetWidget::unselect_target() {
emit activate(false);
stop_attack();
_target = 0;
}
void TargetWidget::update_target(Actor * a) {
_target = a;
this->update();
}
void TargetWidget::stop_attack() {
const Json data = Json::object {
{"Type", "Attack"},
{"Condition", "Stop"}
};
connection::write(data);
}
void TargetWidget::paintEvent(QPaintEvent * event) {
paint(event, _target);
}
|
//! Bismillahi-Rahamanirahim.
/** ========================================**
** @Author: Md. Abu Farhad ( RUET, CSE'15)
** @Category:
/** ========================================**/
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define fr(i,n) for(int i=0;i<n;i++)
int main()
{
ll m,n,l,k;
string s;
while(cin>>k>>s)
{
ll ans=0;
n=s.size();
sort(s.begin(), s.end());
// cout<<s<<endl;
fr(i,n){ k-=s[i]-'0';}
fr(i,n){if(k>0){ k-=9-(s[i]-'0'); ans++; } }
cout<<ans<<endl;
}
return 0;
}
|
#include "engine.h"
#include "ctfi.h"
#include "origctf.h"
#include <iostream>
#include <fstream>
#include <opencv2/highgui/highgui.hpp>
#include <string>
using namespace cv;
using namespace std;
int main(int argc, const char * argv[]) {
Mat image = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);
string filename = string(argv[1]);
Engine e = Engine(image, filename, atoi(argv[2]));
// if (string(argv[3]) == "orig") {
// CTFIAlgorithm algo(e);
// e.setup(&algo);
// }
// else {
OrigCTFAlgorithm algo2(e);
e.setup(&algo2);
// }
Mat m;
Mat m2;
e.draw_boundaries(m);
e.draw_means(m2);
imwrite(string("/me/d/iCtF superpixels/101087 intermediates/Orig/") + argv[2] + "/out-init.png", m);
imwrite(string("/me/d/iCtF superpixels/101087 intermediates/Orig/") + argv[2] + "/out-init-mean.png", m2);
ofstream out;
out.open(e.get_input_basename() + ".log", ios::out);
out << e.algorithm->total_energy.col_part << "\t" << e.algorithm->total_energy.reg_part << "\t" << 0 << "\t" << e.level << endl;
Mat out_mat;
e.labels.convertTo(out_mat, CV_16U);
out_mat += 1;
imwrite(e.get_input_basename() + "-init.png", out_mat);
while (e.level > 0) {
e.run_level();
e.draw_boundaries(m);
e.draw_means(m2);
// for(auto b: e.blocks) {
// cout << "(" << b->index << "): " << e.algorithm.label_change_violates_connectivity(b);
// }
imwrite(string("/me/d/iCtF superpixels/101087 intermediates/Orig/") + argv[2] + "/out-" + to_string(e.level) + ".png", m);
imwrite(string("/me/d/iCtF superpixels/101087 intermediates/Orig/") + argv[2] + "/out-" + to_string(e.level) + "-mean.png", m2);
}
e.labels.convertTo(out_mat, CV_16U);
out_mat += 1;
imwrite(e.get_input_basename() + ".png", out_mat);
auto &move = e.algorithm->moves_log.back();
out << move.energy.col_part << "\t" << e.algorithm->moves_log.size() - 1 << "\t" << move.num_iterations << "\t" << move.level << endl;
out.close();
}
// interesting image in Vitaliy's initial grid algorithm: 101087
|
#ifndef __CLineFeature
#define __CLineFeature
#include "MultiSegLine.h"
#include "Feature.h"
// 特征类型
#define GENERIC_LINE_FEATURE 0 // 一般直线特征
#define SINGLE_SIDED_LINE_FEATURE 1 // 单侧直线特征
///////////////////////////////////////////////////////////////////////////////
// 定义“特征”基类。
class CLineFeature : public CFeature, public CMultiSegLine
{
public:
long m_lStart;
long m_lEnd; // point numbers in scan
float m_fSigma2; // 匹配误差
int m_nWhichSideToUse; // 使用直线的哪一侧(1-前面;2-后面;3-两面)
bool m_bSelected; // 标明此线段是否被选中(用于屏幕编辑处理)
bool m_bCreateRef; // 是否已生成参考点
CPnt m_ptRef; // 参考点的位置
CPnt m_ptProjectFoot; // 投影点的位置
public:
CLineFeature(CPnt& ptStart, CPnt& ptEnd);
CLineFeature();
// 生成一个复本
virtual CLineFeature* Duplicate() const;
CLineFeature& GetLineFeatureObject() {return *this; }
// 从文本文件读入数据
virtual int LoadText(FILE* file);
// 将数据写入到文本文件
virtual int SaveText(FILE* file);
// 从二进制文件读入数据
virtual int LoadBinary(FILE* file);
// 将数据写入到二进制文件
virtual int SaveBinary(FILE* file);
// 生成线段
void Create(CPnt& ptStart, CPnt& ptEnd);
// 生成线段
void Create(CLine& ln);
// 根据多段线生成特征
void Create(CMultiSegLine& MultiSegLine);
// 设置扫检测到该直线特征时的激光头姿态,以便计算有效的观测朝向
void SetDetectPosture(const CPosture& pstDetect);
// 判断本线段是否与另一线段有重叠区
bool IsOverlapWith(CLineFeature& Feature2);
// 将此多段线与另外一条多段线(如果共线的话)进行合并
bool ColinearMerge(CLineFeature& Feature2, float fMaxAngDiff, float fMaxDistDiff, float fMaxGapBetweenLines);
bool ColinearMerge1(CLineFeature& Feature2, float fMaxAngDiff, float fMaxDistDiff, float fMaxGapBetweenLines);
// 将特征进行平移
virtual void Move(float fX, float fY);
// 将特征进行旋转
virtual void Rotate(CAngle ang, CPnt ptCenter);
// 选中/取消选中此线段
void Select(bool bOn) {m_bSelected = bOn;}
// 以pstScanner为观测姿态,判断本直线特征是否可与给定的另一直线特征进行配准
bool RegisterWith(CLineFeature& another, CPosture& pstScanner, float fDistGate, float fAngGate);
// 计算本直线特征到另一直线特征的变换代价
float TransformCostTo(const CLineFeature& another) const;
// 判断该直线特征能否与另外一个直线特征构成一个“角点”
bool MakeCorner(const CLineFeature& another, float fMinAngle, float fMaxAngle, float fMaxGap, CPnt& ptCorner);
// 进行坐标正变换
virtual void Transform(const CFrame& frame);
// 进行坐标逆变换
virtual void InvTransform(const CFrame& frame);
#ifdef _MSC_VER
// (在屏幕窗口上)测试指定的点是否在线段上
bool HitTest(CScreenReference& ScrnRef, CPoint point);
// 在屏幕上显示此直线特征
virtual void Plot(CScreenReference& ScrnRef, CDC* pDC, COLORREF crColor, COLORREF crSelected,
int nSize, int nShowDisabled = DISABLED_FEATURE_UNDERTONE, bool bShowSuggested = true);
#endif
};
#endif
|
#ifndef __TYPEDEF_H__
#define __TYPEDEF_H__
#include "serialization.h"
#include <iostream>
#include <string>
#include <vector>
namespace fgtcc {
struct SvcConfig {
int port;
};
struct ImageSizeInfo {
int width;
int height;
};
struct GetOpencvVersionResp {
std::string version;
};
struct GetImageSizeInfoReq {
std::string imgBase64;
};
struct GetImageSizeInfoResp {
int width;
int height;
};
} // namespace fgtcc
DEFINE_STRUCT_SCHEMA(fgtcc::SvcConfig,
DEFINE_STRUCT_FIELD(port, "port"));
DEFINE_STRUCT_SCHEMA(fgtcc::GetOpencvVersionResp,
DEFINE_STRUCT_FIELD(version, "version"));
DEFINE_STRUCT_SCHEMA(fgtcc::GetImageSizeInfoReq,
DEFINE_STRUCT_FIELD(imgBase64, "img_base64"));
DEFINE_STRUCT_SCHEMA(fgtcc::GetImageSizeInfoResp,
DEFINE_STRUCT_FIELD(width, "width"),
DEFINE_STRUCT_FIELD(height, "height"));
#endif /* __TYPEDEF_H__ */
|
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <ros/ros.h>
#include "camina/v_repConst.h"
//#include "../msg_gen/cpp/include/camina/motor.h"
#include "../msg_gen/cpp/include/camina/AngulosMotor.h"
// Used data structures:
#include <std_msgs/Float64.h>
#include <sensor_msgs/JointState.h>
#include "vrep_common/JointSetStateData.h"
#include "vrep_common/VrepInfo.h"
// Used API services:
#include "vrep_common/simRosSetJointState.h"
#include "vrep_common/simRosGetJointState.h"
#include "vrep_common/simRosEnableSubscriber.h"
#define pi 3.14159
// Global variables (modified by topic subscribers):
bool simulationRunning=true;
bool sensorTrigger=false;
float simulationTime=0.0f;
int arg_global=0;
sensor_msgs::JointState patasMotores;
float q[3] = {0.0,0.0,0.0}; //Angulos de motores q1, q2, q3
ros::ServiceClient client_SetJointStatesPublisher;
vrep_common::simRosSetJointState srv_SetJointStatesPublisher; //Servicio para setear los joints de vrep
ros::ServiceClient client_GetJointStatesPublisher;
vrep_common::simRosGetJointState srv_GetJointStatesPublisher; //Servicio para obtener los joints de vrep
//float b=0;
// Topic subscriber callbacks:
void infoCallback(const vrep_common::VrepInfo::ConstPtr& info)
{
simulationTime=info->simulationTime.data;
simulationRunning=(info->simulatorState.data&1)!=0;
}
void motoresCallback(const camina::AngulosMotor qMotor)
{
// srv_SetJointStatesPublisher.request.values[qMotor.Npata*3-3+0] = qMotor.q1;
// srv_SetJointStatesPublisher.request.values[qMotor.Npata*3-3+1] = qMotor.q2-pi/2;
// srv_SetJointStatesPublisher.request.values[qMotor.Npata*3-3+2] = -qMotor.q3;
q[0]=qMotor.q1;
q[1]=qMotor.q2;
q[2]=qMotor.q3;
srv_SetJointStatesPublisher.request.values[qMotor.Npata*3-3+0] = q[0];
srv_SetJointStatesPublisher.request.values[qMotor.Npata*3-3+1] = q[1];
srv_SetJointStatesPublisher.request.values[qMotor.Npata*3-3+2] = q[2];
ROS_INFO("4-Angulos q1q2q3:[Npata=%.1f, ite=%.1f, q1= %.3f, q2= %.3f, q3= %.3f]", qMotor.Npata, qMotor.iteracion, q[0]*180.0/pi,q[1]*180.0/pi,q[2]*180.0/pi);
if(qMotor.Npata==1)
//Al recibir pata # manda todos los mensajes
{
if (client_GetJointStatesPublisher.call(srv_GetJointStatesPublisher)&&(srv_GetJointStatesPublisher.response.result!=-1))
{
patasMotores = srv_GetJointStatesPublisher.response.state;
//simRosGetJointState(arg_global);
//Manda motores 2 - 3 - 1 ... -.-'
//1-->[2]
//2-->[0]
//3-->[1]
//std::cout << "Motor1n: " << patasMotores.position[0] << ", Motor2n: " << patasMotores.position[1] << ", Motor3n: " << patasMotores.position[2] << "\n";
ROS_INFO("Motor11: %.3f, Motor2: %.3f, Motor3: %.3f", patasMotores.position[0]*180.0/pi,patasMotores.position[1]*180.0/pi,patasMotores.position[2]*180.0/pi);
}
if (client_SetJointStatesPublisher.call(srv_SetJointStatesPublisher)&&(srv_SetJointStatesPublisher.response.result!=-1))
{
//printf("motoresCallback funciona\n");
} else{
printf("motoresCallback NOOO funciona\n");
}
if (client_GetJointStatesPublisher.call(srv_GetJointStatesPublisher)&&(srv_GetJointStatesPublisher.response.result!=-1))
{
patasMotores = srv_GetJointStatesPublisher.response.state;
//simRosGetJointState(arg_global);
//Manda motores 2 - 3 - 1 ... -.-'
//1-->[2]
//2-->[0]
//3-->[1]
//std::cout << "Motor1n: " << patasMotores.position[0] << ", Motor2n: " << patasMotores.position[1] << ", Motor3n: " << patasMotores.position[2] << "\n";
ROS_INFO("Motor12: %.3f, Motor2: %.3f, Motor3: %.3f", patasMotores.position[0]*180.0/pi,patasMotores.position[1]*180.0/pi,patasMotores.position[2]*180.0/pi);
}
}
}
// Main code:
int main(int argc,char* argv[])
{
int Narg=0; //numero de argumentos que mande (se excluye el fantasma que el manda solo)
Narg=3;
if (argc>Narg)
{
printf("argumento 1: %d\n",atoi(argv[1]));
printf("argumento 2: %d\n",atoi(argv[2]));
printf("argumento 3: %d\n",atoi(argv[3]));
arg_global=atoi(argv[1]);
}
else
{
printf("Indique argumentos!\n");
return (0);
}
// Create a ROS node:
int _argc = 0;
char** _argv = NULL;
ros::init(_argc,_argv,"Nodo3_Arana_RosVrep");
if(!ros::master::check())
return(0);
ros::NodeHandle node;
printf("Arana_RosVrep just started\n");
//Subscripcion a nodo que publica posicion deseada de motores
ros::Subscriber subMq=node.subscribe("DatosDeMotores", 100, motoresCallback);
ros::Subscriber subInfo=node.subscribe("/vrep/info",1,infoCallback);
client_SetJointStatesPublisher=node.serviceClient<vrep_common::simRosSetJointState>("/vrep/simRosSetJointState");
client_GetJointStatesPublisher=node.serviceClient<vrep_common::simRosGetJointState>("/vrep/simRosGetJointState");
srv_GetJointStatesPublisher.request.handle=sim_handle_all;
srv_SetJointStatesPublisher.request.handles.resize(Narg,0);
srv_SetJointStatesPublisher.request.setModes.resize(Narg,0);
srv_SetJointStatesPublisher.request.values.resize(Narg,0);
for (int i=0; i < Narg; i++)
{
srv_SetJointStatesPublisher.request.handles[i]=atoi(argv[i+1]);
srv_SetJointStatesPublisher.request.setModes[i]=1;
}
while (ros::ok() && simulationRunning)
{
ros::spinOnce();
//printf("Hola de Arana_RosVrep\n");
}
ROS_INFO("Adios3!");
ros::shutdown();
return(0);
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* 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.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
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 HOLDER 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.
*/
#ifndef _PSEUDOECGALCALCULATOR_HPP_
#define _PSEUDOECGALCALCULATOR_HPP_
#include "AbstractFunctionalCalculator.hpp"
#include "AbstractTetrahedralMesh.hpp"
#include "ChastePoint.hpp"
#include "UblasCustomFunctions.hpp"
#include "Hdf5DataReader.hpp"
/**
* This class implements a pseudo-ECG calculator. It is a concrete class of AbstractFunctionalCalculator.
* The pseudo-ECG is defined as the integral over the mesh of the following integrand:
*
* - D * grad (solution) dot grad (1/r)
*
* where D is a diffusion coefficient and r is the distance between a recording electrode
* and a given point in the mesh.
*
* References for the formula that defines the pseudo-ECG:
*
* Gima K, Rudy Y Circ Res (2002) 90:889-896 (equation 1)
* Baher et al. Am J Physiol (2007) 292:H180-H189 (equation 5)
*/
/*
* NB I don't think that this class needs to be templated over PROBLEM_DIM,
* since even when working with Bidomain we only integrate one thing at once,
* and hence still need to call AbstractFunctionalCalculator<ELEMENT_DIM, SPACE_DIM, 1>.
* See PostProcessingWriter.cpp line ~141. The fact that it is only explicitly
* instantiated (at the bottom of the cpp) for cases with 1, would agree with this.
*
* But at the same time it probably isn't worth breaking users' code by changing it.
* Might also make it easier to copy and paste for any new class that does a
* fancier integral with more quantities.
*/
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
class PseudoEcgCalculator : public AbstractFunctionalCalculator<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>
{
private:
friend class TestPseudoEcgCalculator;//for testing
Hdf5DataReader* mpDataReader; /**< An HDF5 reader from which to get the solution*/
unsigned mNumberOfNodes; /**< Number of nodes in the mesh (got from the data reader)*/
unsigned mNumTimeSteps;/**< Number of time steps in the simulation (got from the data reader)*/
AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>& mrMesh;/**< A mesh used by the calculator*/
ChastePoint<SPACE_DIM> mProbeElectrode; /**<The point from where we want to calculate the pseudoECG*/
double mDiffusionCoefficient;/**<The diffusion coefficient D*/
std::string mVariableName;/**< the variable for which we want to calculate the pseudo ecg, defaults to "V"*/
unsigned mTimestepStride; /**< The number of timesteps in a stride (so that we don't have to compute all the ECGs). This defaults to 1.*/
/**
* @return the integrand.
* The pseudo-ECG is defined as the integral over the mesh of the following integrand:
*
* - D * grad (solution) dot grad (1/r)
*
* @param rX The point in space
* @param rU The unknown as a vector, u(i) = u_i
* @param rGradU The gradient of the unknown as a matrix, rGradU(i,j) = d(u_i)/d(X_j)
*/
double GetIntegrand(ChastePoint<SPACE_DIM>& rX,
c_vector<double,PROBLEM_DIM>& rU,
c_matrix<double,PROBLEM_DIM,SPACE_DIM>& rGradU);
/**
* Calculates the pseudo-ECG and returns its value at the given time step.
*
* @param timeStep the time step where we want to calculate the pseudo-ecg
* @return the pseudo ECG at the given time step.
*
*/
double ComputePseudoEcgAtOneTimeStep(unsigned timeStep);
/**
* Whether we should not calculate the Pseudo ECG on this element.
*
* This method returns true if we are integrating voltage and the
* tissue element is in the bath.
*
* @param rElement the element of interest
* @return whether we should skip this element.
*/
bool ShouldSkipThisElement(Element<ELEMENT_DIM,SPACE_DIM>& rElement);
public:
/**
* Constructor
*
* @param rMesh A reference to the mesh
* @param rProbeElectrode The location of the recording electrode
* @param rDirectory The directory where the simulation results are stored
* @param rHdf5FileName The file name where the simulation results are stored
* @param rVariableName The name of the voltage variable (is V by default)
* @param timestepStride The number of timesteps in a stride (so that we don't
* have to compute all the ECGs). This defaults to 1.
*
*/
PseudoEcgCalculator(AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>& rMesh,
const ChastePoint<SPACE_DIM>& rProbeElectrode,
const FileFinder& rDirectory,
const std::string& rHdf5FileName,
const std::string& rVariableName = "V",
unsigned timestepStride = 1);
/**
* Destructor.
*/
~PseudoEcgCalculator();
/**
* Sets the value of the diffusion coefficient (D)
*
* @param diffusionCoefficient The desired value of the diffusion coefficient
*
*/
void SetDiffusionCoefficient(double diffusionCoefficient);
/**
*
* Calculates and writes the pseudo-ECG to file. the file will be named PseudoEcgFromElectrodeAt_x_y_z.dat,
* where x,y,z are replaced by the location of the electrode.
* It will contain one column of numbers, each being the pseudoECG at each time step.
* It will be created by the master processor into /output relaitive to where the output
* directory is set (by the HeartConfig or by default)
*
*/
void WritePseudoEcg();
};
#endif //_PSEUDOECGALCALCULATOR_HPP_
|
//
// Created by jf on 11/21/17.
//
#ifndef SAKJDHASDKJ_ALGORITHM_H
#define SAKJDHASDKJ_ALGORITHM_H
#include "graph.h"
using namespace std;
class algorithm {
private:
CGraph graph;
public:
bool deep_search(std::vector<CGraph::Graph> &tree, int source, int dest,std::vector<int> &pth);
bool wide_search(CGraph *tree, int source, int dest,std::vector<int> &pth);
bool deep_search_weight(std::vector<CGraph::Graph> &tree, int source, int dest,std::vector<int> &pth);
bool dijkstra_search(CGraph *tree, int source, int destination,std::vector<int> &pth);
bool floyd_warshal_search(CGraph *tree, int source, int destination,std::vector<int> &pth);
};
#endif //SAKJDHASDKJ_ALGORITHM_H
|
#include <iostream>
#include "State_Space_Generator.h"
int main (int argc, char * argv[])
{
SCHED_ALGO algo;
if (!strcmp (argv[1], "OTH"))
algo = OTH;
else if (!strcmp (argv[1], "RM"))
algo = RM;
else if (!strcmp (argv[1], "EDF"))
algo = EDF;
else if (!strcmp (argv[1], "LLF"))
algo = LLF;
else if (!strcmp (argv[1], "SJF"))
algo = SJF;
else if (!strcmp (argv[1], "DLJ"))
algo = DLJ;
else if (!strcmp (argv[1], "PVAL"))
algo = PVAL;
else if (!strcmp (argv[1], "CON"))
algo = CON;
else if (!strcmp (argv[1], "MLF"))
algo = MLF;
else if (!strcmp (argv[1], "PVALM"))
algo = PVALM;
else if (!strcmp (argv[1], "OPT"))
algo = OPT;
long long num = atoi (argv[2]);
if (argc != 4)
State_Space_Gen::start_simulation ();
for (long long i = 0; i < num;i++)
{
State_Space_Gen* gen = new State_Space_Gen (algo);
if (argc == 4)
gen->not_matlab ();
if (algo == PVALM)
{
gen->pval_modify ();
delete gen;
exit (0);
}
gen->init_states ();
gen->generate_states (2);
// gen->print_states ();
if (algo == CON)
{
gen->generate_con_opt_eqn ();
}
else
gen->generate_simulatanoeus_eqn ();
gen->gen_ddln_miss_eqn ();
gen->gen_ddln_met_eqn ();
gen->gen_cpu_util_eqn ();
if (algo !=CON)
{
gen->solve_simul_eqn ();
if (argc != 4)
{
gen->compute_cpu_util ();
gen->compute_ddln_miss ();
gen->compute_ddln_met ();
}
}
if (argc != 4)
gen->print_result ();
gen->pval_modify ();
delete gen;
}
if (argc != 4)
State_Space_Gen::stop_simulation ();
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* 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.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
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 HOLDER 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.
*/
#include "PopulationTestingForce.hpp"
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
PopulationTestingForce<ELEMENT_DIM, SPACE_DIM>::PopulationTestingForce(bool hasPositionDependence)
:AbstractForce<ELEMENT_DIM, SPACE_DIM>(),
mWithPositionDependence(hasPositionDependence)
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void PopulationTestingForce<ELEMENT_DIM, SPACE_DIM>::AddForceContribution(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation)
{
for (unsigned i=0; i<rCellPopulation.GetNumNodes(); i++)
{
c_vector<double, SPACE_DIM> force;
for (unsigned j=0; j<SPACE_DIM; j++)
{
if (mWithPositionDependence)
{
force[j] = (j+1)*i*0.01*rCellPopulation.GetNode(i)->rGetLocation()[j];
}
else
{
force[j] = (j+1)*i*0.01;
}
}
rCellPopulation.GetNode(i)->ClearAppliedForce();
rCellPopulation.GetNode(i)->AddAppliedForceContribution(force);
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
c_vector<double, SPACE_DIM> PopulationTestingForce<ELEMENT_DIM, SPACE_DIM>::GetExpectedOneStepLocationFE(unsigned nodeIndex,
double damping,
c_vector<double, SPACE_DIM>& oldLocation,
double dt)
{
c_vector<double, SPACE_DIM> result;
for (unsigned j = 0; j < SPACE_DIM; j++)
{
if (mWithPositionDependence)
{
result[j] = oldLocation[j] + dt * (j+1)*0.01*nodeIndex * oldLocation[j] / damping;
}
else
{
result[j] = oldLocation[j] + dt * (j+1)*0.01*nodeIndex/damping;
}
}
return result;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
c_vector<double, SPACE_DIM> PopulationTestingForce<ELEMENT_DIM, SPACE_DIM>::GetExpectedOneStepLocationRK4(unsigned nodeIndex,
double damping,
c_vector<double, SPACE_DIM>& oldLocation,
double dt)
{
c_vector<double, SPACE_DIM> result;
for (unsigned j = 0; j < SPACE_DIM; j++)
{
double k1 = (j+1)*0.01*nodeIndex * oldLocation[j] / damping;
double k2 = (j+1)*0.01*nodeIndex * (oldLocation[j] + (dt/2.0)*k1) / damping;
double k3 = (j+1)*0.01*nodeIndex * (oldLocation[j] + (dt/2.0)*k2) / damping;
double k4 = (j+1)*0.01*nodeIndex * (oldLocation[j] + dt*k3) / damping;
result[j] = oldLocation[j] + (1.0/6.0)*dt*(k1 + 2*k2 + 2*k3 + k4);
}
return result;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
c_vector<double, SPACE_DIM> PopulationTestingForce<ELEMENT_DIM, SPACE_DIM>::GetExpectedOneStepLocationAM2(unsigned nodeIndex,
double damping,
c_vector<double, SPACE_DIM>& oldLocation,
double dt)
{
c_vector<double, SPACE_DIM> result;
for (unsigned j = 0; j < SPACE_DIM; j++)
{
result[j] = oldLocation[j] * (1 + 0.5*dt*0.01*(j+1)*nodeIndex / damping) / (1 - 0.5*dt*0.01*(j+1)*nodeIndex / damping);
}
return result;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
c_vector<double, SPACE_DIM> PopulationTestingForce<ELEMENT_DIM, SPACE_DIM>::GetExpectedOneStepLocationBE(unsigned nodeIndex,
double damping,
c_vector<double, SPACE_DIM>& oldLocation,
double dt)
{
c_vector<double, SPACE_DIM> result;
for (unsigned j = 0; j < SPACE_DIM; j++)
{
result[j] = oldLocation[j] / (1 - dt*0.01*(j+1)*nodeIndex/damping);
}
return result;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void PopulationTestingForce<ELEMENT_DIM, SPACE_DIM>::OutputForceParameters(out_stream& rParamsFile)
{
// This force is not used in a simulation so this method is never called
NEVER_REACHED;
}
// Explicit instantiation
template class PopulationTestingForce<1,1>;
template class PopulationTestingForce<1,2>;
template class PopulationTestingForce<2,2>;
template class PopulationTestingForce<1,3>;
template class PopulationTestingForce<2,3>;
template class PopulationTestingForce<3,3>;
// Serialization for Boost >= 1.36
#include "SerializationExportWrapperForCpp.hpp"
EXPORT_TEMPLATE_CLASS_ALL_DIMS(PopulationTestingForce)
|
#include <GL/freeglut.h>
#include<time.h>
#include<math.h>
#define PI 3.141592
GLvoid DrawScene();
GLvoid Reshape(int, int);
GLvoid Keyboard(unsigned char, int, int);
GLvoid Timerfunction(int);
time_t now;
struct tm curr_time;
int nums[6];
int rotate_degree = 0;
void main(int argc, char** argv) // 윈도우 출력하고 출력함수 설정
{
// 초기화 함수들
glutInit(&argc, argv); // glut 초기화
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); // 디스플레이 모드 설정
glutInitWindowPosition(100, 100); // 윈도우의 위치 지정
glutInitWindowSize(800, 600); // 윈도우의 크기 지정
glutCreateWindow("Tiles"); // 윈도우 생성 (윈도우 이름)
glutDisplayFunc(DrawScene); // 출력 함수의 지정
glutReshapeFunc(Reshape); // 다시 그리기 함수 지정
glutTimerFunc(1000 / 60, Timerfunction, 1); // 타이머 셋팅
glutKeyboardFunc(Keyboard); // 키보드 입력 받기
glutMainLoop(); // 이벤트 처리 시작
}
GLvoid DrawScene() // 출력 함수
{
glClearColor(0, 0, 0, 1); // 바탕색을 지정
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 설정된 색으로 전체를 칠하기
glEnable(GL_DEPTH_TEST); //깊이테스트
glDepthFunc(GL_LESS); //Passes if the fragment's depth value is less than the stored depth value.
glMatrixMode(GL_MODELVIEW);
glLineWidth(2);
glPushMatrix();
glRotated(rotate_degree, 0, 1.0, 0);
glRotated(30, 1.0, 1.0, 0);
//glRotated(90, 0, 1.0, 0);
glScaled(0.6, 0.6, 1.0);
glTranslated(-460, 0, 0);
for (int j = 0; j < 6; ++j) {
if (j != 0) {
glTranslated(170, 0, 0);
if (j % 2 == 0) {
glTranslated(40, 0, 0);
}
}
glPushMatrix();
glTranslated(0, 125, 0);
for (int i = 0; i < 3; ++i) {
if (i)
glTranslated(0, -125, 0);
glPushMatrix();
glScaled(1.0, 0.25, 1.0);
switch (i) {
case 0:
if (nums[j] == 2 || nums[j] == 3 || nums[j] == 5 || nums[j] == 6 || nums[j] == 7 || nums[j] == 8 || nums[j] == 9 || nums[j] == 0) {
glColor3f(0, 1.0, 0);
glutSolidCube(100);
}
break;
case 1:
if (nums[j] == 2 || nums[j] == 3 || nums[j] == 4 || nums[j] == 5 || nums[j] == 6 || nums[j] == 8 || nums[j] == 9) {
glColor3f(0, 1.0, 0);
glutSolidCube(100);
}
break;
case 2:
if (nums[j] == 2 || nums[j] == 3 || nums[j] == 5 || nums[j] == 6 || nums[j] == 8 || nums[j] == 0) {
glColor3f(0, 1.0, 0);
glutSolidCube(100);
}
break;
}
glColor3f(0, 0, 0);
glutWireCube(100);
glPopMatrix();
}
glTranslated(-63, 187, 0);
for (int i = 0; i < 2; ++i) {
if (i)
glTranslated(125, 0, 0);
glPushMatrix();
glScaled(0.25, 1.0, 1.0);
switch (i) {
case 0:
if (nums[j] == 4 || nums[j] == 5 || nums[j] == 6 || nums[j] == 8 || nums[j] == 9 || nums[j] == 0) {
glColor3f(0, 1.0, 0);
glutSolidCube(100);
}
break;
case 1:
if (nums[j] == 1 || nums[j] == 2 || nums[j] == 3 || nums[j] == 4 || nums[j] == 7 || nums[j] == 8 || nums[j] == 9 || nums[j] == 0) {
glColor3f(0, 1.0, 0);
glutSolidCube(100);
}
}
glColor3f(0, 0, 0);
glutWireCube(100);
glTranslated(0, -125, 0);
switch (i) {
case 0:
if (nums[j] == 2 || nums[j] == 6 || nums[j] == 8 || nums[j] == 0) {
glColor3f(0, 1.0, 0);
glutSolidCube(100);
}
break;
case 1:
if (nums[j] == 1 || nums[j] == 3 || nums[j] == 4 || nums[j] == 5 || nums[j] == 6 || nums[j] == 7 || nums[j] == 8 || nums[j] == 9 || nums[j] == 0) {
glColor3f(0, 1.0, 0);
glutSolidCube(100);
}
}
glColor3f(0, 0, 0);
glutWireCube(100);
glPopMatrix();
}
glPopMatrix();
}
glPopMatrix();
glutSwapBuffers(); // 화면에 출력하기
}
GLvoid Reshape(int w, int h) // 다시 그리기 함수
{
glViewport(0, 0, w, h);
glOrtho(-400.0, 400.0, -300.0, 300.0, -400.0, 400.0);
}
GLvoid Keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 'q':
case 'Q':
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
glutLeaveMainLoop();
break;
case 'r':
rotate_degree += 5;
//if (rotate_degree >= 360)
//rotate_degree = 0;
break;
case 'R':
rotate_degree -= 5;
if (rotate_degree <= 0)
rotate_degree = 360;
break;
}
}
GLvoid Timerfunction(int value) {
switch (value) {
case 1:
now = time(0);
localtime_s(&curr_time, &now);
nums[0] = curr_time.tm_hour / 10;
nums[1] = curr_time.tm_hour % 10;
nums[2] = curr_time.tm_min / 10;
nums[3] = curr_time.tm_min % 10;
nums[4] = curr_time.tm_sec / 10;
nums[5] = curr_time.tm_sec % 10;
glutPostRedisplay();
glutTimerFunc(1000 / 60, Timerfunction, 1);
break;
}
}
|
#ifndef _VIEW_MOUSE_PAINT_H_
#define _VIEW_MOUSE_PAINT_H_
#include "trinity/trinity_widget_view.h"
class ViewMousePaint : public NextAI::WidgetView, NextAI::AppEventListener
{
public:
ViewMousePaint();
virtual ~ViewMousePaint();
virtual void drawImpl();
virtual NextAI::ListenerResult touch(NextAI::TouchType touch, int32 touchCount, const int32 touchId[], const NextAI::ScreenPoint touchPos[]);
private:
std::vector<NextAI::Point> m_mouseTrace;
};
#endif // !_VIEW_MOUSE_PAINT_H_
|
///connector_co.h
//
//
#ifndef CONNECTOR_CO_H
#define CONNECTOR_CO_H
#include "connector.h"
#include "tcppeer_co.h"
#ifndef NAMESPDEF_H
#include "namespdef.h"
#endif
NAMESP_BEGIN
namespace net
{
//@param EventQueueT
//@param NetPeer
template<class Connector, class EventQueueT
,class TcpPeer
>
class Connector_co
{
public:
using peer_t = TcpPeer;
public:
Connector_co(EventQueueT* q, uint16_t local_port)
:Connector_co(q, AddrPair{"", local_port})
{
}
Connector_co(EventQueueT* q, const AddrPair& local_addr)
:_conn(q, local_addr)
{
}
peer_t connect(const AddrPair& remote_addr){
auto peer = _conn.connect(remote_addr);
if(peer != nullptr ){
return TcpPeer(peer);
}
return TcpPeer(nullptr);
}
protected:
Connector _conn;
};
using Connector_co4 =Connector_co<Connector4, EventQueueEpoll, TcpPeer_co4>;
using Connector_co6 =Connector_co<Connector6, EventQueueEpoll, TcpPeer_co6>;
}//net
NAMESP_END
#endif /*CONNECTOR_CO_H*/
|
/* primitive_long.cpp -*- C++ -*-
Rémi Attab (remi.attab@gmail.com), 12 Apr 2014
FreeBSD-style copyright and disclaimer apply
Long reflection
*/
#include "primitives.h"
#include "primitives.tcc"
/******************************************************************************/
/* REFLECT LONG */
/******************************************************************************/
reflectNumber(long int)
reflectNumber(unsigned long int)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.