blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3568fb2a780b11f991d3227566154c4809c9ca8b
|
133c3a252d150d3527e4f9df654210866af6615c
|
/source/RsEncodeTop.cpp
|
fda752bd4a5df1bb175e80c405f91183a03f1d27
|
[] |
no_license
|
freecores/reed_solomon_codec_generator
|
7399f9a37f73ff11b1125a47034568a4cb1da1a1
|
7a21b43705ec8f7cce3c540f77ad36089ddfc1a6
|
refs/heads/master
| 2021-01-22T04:53:52.431901 | 2011-07-28T01:32:14 | 2011-07-28T01:32:14 | 21,917,909 | 8 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 26,499 |
cpp
|
//===================================================================
// Module Name : RsEncodeTop
// File Name : RsEncodeTop.cpp
// Function : RTL Encoder Top Module generation
//
// Revision History:
// Date By Version Change Description
//===================================================================
// 2009/02/03 Gael Sapience 1.0 Original
//
//===================================================================
// (C) COPYRIGHT 2009 SYSTEM LSI CO., Ltd.
//
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include<windows.h>
#include<fstream>
#include <string.h>
using namespace std;
FILE *OutFileEncodeTop;
void RsGfMultiplier( int*, int*,int*, int, int);
void RsEncodeTop(int DataSize, int TotalSize, int PrimPoly, int bitSymbol, int *coeffTab, int *MrefTab, int *PrefTab, int pathFlag, int lengthPath, char *rootFolderPath) {
//---------------------------------------------------------------
// C parameters
//---------------------------------------------------------------
int syndromeLength;
syndromeLength = TotalSize - DataSize;
int ii,jj,zz;
int countSize;
int flag;
int flagIndex;
int Pidx;
int init;
int idx1;
int idx2;
int idx;
int tempNum;
int LoopSize;
int Temp;
int mmTabSize = (bitSymbol*2) -1;
int *ttTab;
int *bbTab;
int *ppTab;
int *bidon;
char *strRsEncodeTop;
ttTab = new int[bitSymbol];
bbTab = new int[bitSymbol];
ppTab = new int[bitSymbol];
bidon = new int[bitSymbol];
//---------------------------------------------------------------
// open file
//---------------------------------------------------------------
strRsEncodeTop = (char *)calloc(lengthPath + 20, sizeof(char));
if (pathFlag == 0) {
strRsEncodeTop[0] = '.';
}else{
for(ii=0; ii<lengthPath; ii++){
strRsEncodeTop[ii] = rootFolderPath[ii];
}
}
strcat(strRsEncodeTop, "/rtl/RsEncodeTop.v");
OutFileEncodeTop = fopen(strRsEncodeTop,"w");
//---------------------------------------------------------------
// Ports Declaration
//---------------------------------------------------------------
fprintf(OutFileEncodeTop, "//===================================================================\n");
fprintf(OutFileEncodeTop, "// Module Name : RsEncodeTop\n");
fprintf(OutFileEncodeTop, "// File Name : RsEncodeTop.v\n");
fprintf(OutFileEncodeTop, "// Function : Rs Encoder Top Module\n");
fprintf(OutFileEncodeTop, "// \n");
fprintf(OutFileEncodeTop, "// Revision History:\n");
fprintf(OutFileEncodeTop, "// Date By Version Change Description\n");
fprintf(OutFileEncodeTop, "//===================================================================\n");
fprintf(OutFileEncodeTop, "// 2009/02/03 Gael Sapience 1.0 Original\n");
fprintf(OutFileEncodeTop, "//\n");
fprintf(OutFileEncodeTop, "//===================================================================\n");
fprintf(OutFileEncodeTop, "// (C) COPYRIGHT 2009 SYSTEM LSI CO., Ltd.\n");
fprintf(OutFileEncodeTop, "//\n\n\n");
fprintf(OutFileEncodeTop, "module RsEncodeTop(\n");
fprintf(OutFileEncodeTop, " CLK, // system clock\n");
fprintf(OutFileEncodeTop, " RESET, // system reset\n");
fprintf(OutFileEncodeTop, " enable, // rs encoder enable signal\n");
fprintf(OutFileEncodeTop, " startPls, // rs encoder sync signal\n");
fprintf(OutFileEncodeTop, " dataIn, // rs encoder data in\n");
fprintf(OutFileEncodeTop, " dataOut // rs encoder data out\n");
fprintf(OutFileEncodeTop, ");\n\n\n");
fprintf(OutFileEncodeTop, " input CLK; // system clock\n");
fprintf(OutFileEncodeTop, " input RESET; // system reset\n");
fprintf(OutFileEncodeTop, " input enable; // rs encoder enable signal\n");
fprintf(OutFileEncodeTop, " input startPls; // rs encoder sync signal\n");
fprintf(OutFileEncodeTop, " input [%d:0] dataIn; // rs encoder data in\n", (bitSymbol-1));
fprintf(OutFileEncodeTop, " output [%d:0] dataOut; // rs encoder data out\n", (bitSymbol-1));
fprintf(OutFileEncodeTop, "\n\n\n");
//---------------------------------------------------------------
//- registers
//---------------------------------------------------------------
countSize = 0;
if (TotalSize > 2047) {
countSize = 12;
} else{
if (TotalSize > 1023) {
countSize = 11;
} else{
if (TotalSize > 511) {
countSize = 10;
}else{
if (TotalSize > 255) {
countSize = 9;
}else{
if (TotalSize > 127) {
countSize = 8;
}else{
if (TotalSize > 63) {
countSize = 7;
}else{
if (TotalSize > 31) {
countSize = 6;
}else{
if (TotalSize > 15) {
countSize = 5;
}else{
if (TotalSize > 7) {
countSize = 4;
}else{
if (TotalSize > 3) {
countSize = 3;
}else{
countSize = 2;
}
}
}
}
}
}
}
}
}
}
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- registers\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
// fprintf(OutFileEncodeTop, " reg [%d:0] count;\n", bitSymbol);
fprintf(OutFileEncodeTop, " reg [%d:0] count;\n", countSize-1);
fprintf(OutFileEncodeTop, " reg dataValid;\n");
fprintf(OutFileEncodeTop, " reg [%d:0] feedbackReg;\n", (bitSymbol-1));
for(ii=0; ii<syndromeLength; ii++){
fprintf(OutFileEncodeTop, " wire [%d:0] mult_%d;\n", (bitSymbol-1), ii);
}
for(ii=0; ii<syndromeLength; ii++){
fprintf(OutFileEncodeTop, " reg [%d:0] syndromeReg_%d;\n", (bitSymbol-1), ii);
}
fprintf(OutFileEncodeTop, " reg [%d:0] dataReg;\n", (bitSymbol-1));
fprintf(OutFileEncodeTop, " reg [%d:0] syndromeRegFF;\n", (bitSymbol-1));
fprintf(OutFileEncodeTop, " reg [%d:0] wireOut;\n", (bitSymbol-1));
//-----------------------------------------------------------------------
// + genPolynomCoeff_
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, "\n\n\n");
//-----------------------------------------------------------------------
// count
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- count\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " always @(posedge CLK or negedge RESET) begin\n");
fprintf(OutFileEncodeTop, " if (~RESET) begin\n");
// fprintf(OutFileEncodeTop, " count [%d:0] <= %d'd0;\n", bitSymbol, (bitSymbol+1));
fprintf(OutFileEncodeTop, " count [%d:0] <= %d'd0;\n", (countSize-1), countSize);
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else if (enable == 1'b1) begin\n");
fprintf(OutFileEncodeTop, " if (startPls == 1'b1) begin\n");
// fprintf(OutFileEncodeTop, " count[%d:0] <= %d'd1;\n", bitSymbol, (bitSymbol+1));
fprintf(OutFileEncodeTop, " count[%d:0] <= %d'd1;\n", (countSize-1), countSize);
fprintf(OutFileEncodeTop, " end\n");
// fprintf(OutFileEncodeTop, " else if ((count[%d:0] ==%d'd0) || (count[%d:0] ==%d'd%d)) begin\n", bitSymbol, (bitSymbol+1), bitSymbol, (bitSymbol+1), TotalSize);
fprintf(OutFileEncodeTop, " else if ((count[%d:0] ==%d'd0) || (count[%d:0] ==%d'd%d)) begin\n", (countSize-1), countSize, (countSize-1), countSize, TotalSize);
// fprintf(OutFileEncodeTop, " count[%d:0] <= %d'd0;\n", bitSymbol, (bitSymbol+1));
fprintf(OutFileEncodeTop, " count[%d:0] <= %d'd0;\n", (countSize-1), countSize);
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else begin\n");
// fprintf(OutFileEncodeTop, " count[%d:0] <= count[%d:0] + %d'd1;\n", bitSymbol, bitSymbol, (bitSymbol+1));
fprintf(OutFileEncodeTop, " count[%d:0] <= count[%d:0] + %d'd1;\n", (countSize-1), (countSize-1), countSize);
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, "\n\n\n");
//-----------------------------------------------------------------------
// dataValid
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- dataValid\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " always @(count or startPls) begin\n");
// fprintf(OutFileEncodeTop, " if (startPls == 1'b1 || (count[%d:0] < %d'd%d)) begin\n", bitSymbol, (bitSymbol+1), DataSize);
fprintf(OutFileEncodeTop, " if (startPls == 1'b1 || (count[%d:0] < %d'd%d)) begin\n", (countSize-1), countSize, DataSize);
// fprintf(OutFileEncodeTop, " dataValid <= 1'b1;\n");
fprintf(OutFileEncodeTop, " dataValid = 1'b1;\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else begin\n");
// fprintf(OutFileEncodeTop, " dataValid <= 1'b0;\n");
fprintf(OutFileEncodeTop, " dataValid = 1'b0;\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, "\n\n\n\n");
//-----------------------------------------------------------------------
// Multipliers
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- Multipliers\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// Multplication Process
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//------------------------------------------------------------------------
// initialize ttTab
//------------------------------------------------------------------------
ttTab[0] = 1;
for (ii=1;ii<bitSymbol;ii++){
ttTab[ii] = 0;
}
//------------------------------------------------------------------------
// initialize bbTab
//------------------------------------------------------------------------
bbTab[0] = 0;
bbTab[1] = 1;
for (ii=2;ii<bitSymbol;ii++){
bbTab[ii] = 0;
}
//------------------------------------------------------------------------
// initialize LoopSize
//------------------------------------------------------------------------
LoopSize = 2;
for(ii=0; ii<(bitSymbol-1); ii++){
LoopSize = LoopSize*2;
}
//------------------------------------------------------------------------
// if coeefTab is null
//------------------------------------------------------------------------
for(jj=0; jj<syndromeLength; jj++){
if (coeffTab[jj] == 0) {
for (idx2=0; idx2<bitSymbol;idx2++){
fprintf(OutFileEncodeTop, " assign mult_%d[%d] = feedbackReg[%d];\n", jj, idx2, idx2);
}
}
}
for(ii=1; ii<LoopSize; ii++){
//------------------------------------------------------------------------
// ppTab = ttTab * bbTab
//------------------------------------------------------------------------
RsGfMultiplier(ppTab, ttTab, bbTab, PrimPoly, bitSymbol);
//------------------------------------------------------------------------
// reassign ttTab
//------------------------------------------------------------------------
for (jj=0;jj<bitSymbol;jj++){
ttTab[jj] = ppTab[jj];
}
flag = 0;
flagIndex = 0;
for(jj=0; jj<syndromeLength; jj++){
flag = 0;
flagIndex = 0;
if (coeffTab[jj] == ii) {
flag = 1;
flagIndex = jj;
//------------------------------------------------------------------------
// printf P_OUT[]
//------------------------------------------------------------------------
for (Pidx=0; Pidx<bitSymbol; Pidx++){
if (flag == 1) {
fprintf(OutFileEncodeTop, " assign mult_%d[%d] = ", flagIndex, Pidx);
}
init = 0;
for (idx2=0; idx2<bitSymbol;idx2++){
bidon [idx2] = 0;
}
for (idx1=0; idx1<mmTabSize;idx1++){
tempNum = PrefTab [Pidx*mmTabSize+idx1];
if (tempNum == 1) {
//------------------------------------------------------------------------
// search
//------------------------------------------------------------------------
for (idx2=0; idx2<bitSymbol;idx2++){
tempNum = MrefTab[idx1*bitSymbol+idx2];
if ((tempNum > 0) && (ttTab[tempNum-1] == 1)) {
if (bidon [idx2] == 0) {
bidon [idx2] = 1;
}
else {
bidon [idx2] = 0;
}
}
}
}
}
//------------------------------------------------------------------------
// printf
//------------------------------------------------------------------------
for (idx2=0; idx2<bitSymbol; idx2++){
if (bidon[idx2] == 1) {
if (init == 0) {
if (flag == 1) {
fprintf(OutFileEncodeTop, " feedbackReg[%d]", idx2);
}
init = 1;
}
else {
if (flag == 1) {
fprintf(OutFileEncodeTop, " ^ feedbackReg[%d]", idx2);
}
}
}
}
if (flag == 1) {
fprintf(OutFileEncodeTop,";\n");
}
}
}
}
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// Multplication Process
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
fprintf(OutFileEncodeTop, "\n\n\n");
//-----------------------------------------------------------------------
// syndromeReg
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- syndromeReg\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " always @(posedge CLK or negedge RESET) begin\n");
fprintf(OutFileEncodeTop, " if (~RESET) begin\n");
for (ii=0; ii < syndromeLength; ii++) {
if (ii < 10) {
fprintf(OutFileEncodeTop, " syndromeReg_%d [%d:0] <= %d'd0;\n", ii, (bitSymbol-1), bitSymbol);
}else{
fprintf(OutFileEncodeTop, " syndromeReg_%d [%d:0] <= %d'd0;\n", ii, (bitSymbol-1), bitSymbol);
}
}
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else if (enable == 1'b1) begin\n");
fprintf(OutFileEncodeTop, " if (startPls == 1'b1) begin\n");
for (ii=0; ii < syndromeLength; ii++) {
if (ii < 10) {
fprintf(OutFileEncodeTop, " syndromeReg_%d [%d:0] <= mult_%d [%d:0];\n", ii, (bitSymbol-1), ii, (bitSymbol-1));
}else{
fprintf(OutFileEncodeTop, " syndromeReg_%d [%d:0] <= mult_%d [%d:0];\n", ii, (bitSymbol-1), ii, (bitSymbol-1));
}
}
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else begin\n");
fprintf(OutFileEncodeTop, " syndromeReg_0 [%d:0] <= mult_0 [%d:0];\n", (bitSymbol-1), (bitSymbol-1));
for (ii=1; ii < syndromeLength; ii++){
if (ii < 10) {
fprintf(OutFileEncodeTop, " syndromeReg_%d [%d:0] <= (syndromeReg_%d [%d:0] ^ mult_%d [%d:0]);\n", ii,(bitSymbol-1), (ii-1),(bitSymbol-1), ii, (bitSymbol-1));
}else{
fprintf(OutFileEncodeTop, " syndromeReg_%d [%d:0] <= (syndromeReg_%d [%d:0] ^ mult_%d [%d:0]);\n", ii,(bitSymbol-1), (ii-1),(bitSymbol-1), ii, (bitSymbol-1));
}
}
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, "\n\n\n");
//-----------------------------------------------------------------------
// feedbackReg
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- feedbackReg\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " always @( startPls, dataValid, dataIn");
fprintf(OutFileEncodeTop, ", syndromeReg_%d",(syndromeLength-1));
fprintf(OutFileEncodeTop, " ) begin\n");
fprintf(OutFileEncodeTop, " if (startPls == 1'b1) begin\n");
// fprintf(OutFileEncodeTop, " feedbackReg[%d:0] <= dataIn[%d:0];\n", (bitSymbol-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " feedbackReg[%d:0] = dataIn[%d:0];\n", (bitSymbol-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else if (dataValid == 1'b1) begin\n");
// fprintf(OutFileEncodeTop, " feedbackReg [%d:0] <= dataIn[%d:0] ^ syndromeReg_%d [%d:0];\n", (bitSymbol-1), (bitSymbol-1), (syndromeLength-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " feedbackReg [%d:0] = dataIn[%d:0] ^ syndromeReg_%d [%d:0];\n", (bitSymbol-1), (bitSymbol-1), (syndromeLength-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else begin\n");
// fprintf(OutFileEncodeTop, " feedbackReg [%d:0] <= %d'd0;\n", (bitSymbol-1), bitSymbol);
fprintf(OutFileEncodeTop, " feedbackReg [%d:0] = %d'd0;\n", (bitSymbol-1), bitSymbol);
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, "\n\n\n");
//-----------------------------------------------------------------------
// dataReg syndromeRegFF
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- dataReg syndromeRegFF\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " always @(posedge CLK, negedge RESET) begin\n");
fprintf(OutFileEncodeTop, " if (~RESET) begin\n");
fprintf(OutFileEncodeTop, " dataReg [%d:0] <= %d'd0;\n", (bitSymbol-1), bitSymbol);
fprintf(OutFileEncodeTop, " syndromeRegFF [%d:0] <= %d'd0;\n", (bitSymbol-1), bitSymbol);
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else if (enable == 1'b1) begin\n");
fprintf(OutFileEncodeTop, " dataReg [%d:0] <= dataIn [%d:0];\n", (bitSymbol-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " syndromeRegFF [%d:0] <= syndromeReg_%d [%d:0];\n", (bitSymbol-1), (syndromeLength-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, "\n\n\n");
//-----------------------------------------------------------------------
// wireOut
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- wireOut\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " always @( count, dataReg, syndromeRegFF) begin\n");
// fprintf(OutFileEncodeTop, " if (count [%d:0]<= %d'd%d) begin\n", (bitSymbol-1), bitSymbol, DataSize);
fprintf(OutFileEncodeTop, " if (count [%d:0]<= %d'd%d) begin\n", (countSize-1), countSize, DataSize);
// fprintf(OutFileEncodeTop, " wireOut[%d:0] <= dataReg[%d:0];\n", (bitSymbol-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " wireOut[%d:0] = dataReg[%d:0];\n", (bitSymbol-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else begin\n");
// fprintf(OutFileEncodeTop, " wireOut[%d:0] <= syndromeRegFF[%d:0];\n", (bitSymbol-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " wireOut[%d:0] = syndromeRegFF[%d:0];\n", (bitSymbol-1), (bitSymbol-1));
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, "\n\n\n");
//-----------------------------------------------------------------------
// dataOutInner
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- dataOutInner\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " reg [%d:0] dataOutInner;\n", (bitSymbol-1));
fprintf(OutFileEncodeTop, " always @(posedge CLK, negedge RESET) begin\n");
fprintf(OutFileEncodeTop, " if (~RESET) begin\n");
fprintf(OutFileEncodeTop, " dataOutInner <= %d'd0;\n", bitSymbol);
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " else begin\n");
fprintf(OutFileEncodeTop, " dataOutInner <= wireOut;\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, " end\n");
fprintf(OutFileEncodeTop, "\n\n\n");
//-----------------------------------------------------------------------
// Output ports
//------------------------------------------------------------------------
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " //- Output ports\n");
fprintf(OutFileEncodeTop, " //---------------------------------------------------------------\n");
fprintf(OutFileEncodeTop, " assign dataOut = dataOutInner;\n");
fprintf(OutFileEncodeTop, "\n\n\n");
fprintf(OutFileEncodeTop, "endmodule\n");
//---------------------------------------------------------------
// close file
//---------------------------------------------------------------
fclose(OutFileEncodeTop);
//---------------------------------------------------------------
// Free memory
//---------------------------------------------------------------
delete[] ttTab;
delete[] bbTab;
delete[] ppTab;
delete[] bidon;
//---------------------------------------------------------------
// automatically convert Dos mode To Unix mode
//---------------------------------------------------------------
char ch;
char temp[MAX_PATH]="\0";
//Open the file for reading in binarymode.
ifstream fp_read(strRsEncodeTop, ios_base::in | ios_base::binary);
sprintf(temp, "%s.temp", strRsEncodeTop);
//Create a temporary file for writing in the binary mode. This
//file will be created in the same directory as the input file.
ofstream fp_write(temp, ios_base::out | ios_base::trunc | ios_base::binary);
while(fp_read.eof() != true)
{
fp_read.get(ch);
//Check for CR (carriage return)
if((int)ch == 0x0D)
continue;
if (!fp_read.eof())fp_write.put(ch);
}
fp_read.close();
fp_write.close();
//Delete the existing input file.
remove(strRsEncodeTop);
//Rename the temporary file to the input file.
rename(temp, strRsEncodeTop);
//Delete the temporary file.
remove(temp);
//---------------------------------------------------------------
// clean string
//---------------------------------------------------------------
free(strRsEncodeTop);
}
|
[
"issei@63dfa89e-be0c-41ba-a503-15c1e88f16c2"
] |
[
[
[
1,
588
]
]
] |
0a4cb45a65cd1d312310acd228e1299b3fa7b349
|
847cccd728e768dc801d541a2d1169ef562311cd
|
/src/ScriptSystem/AddOn/scriptstring.cpp
|
fcd9b74625862039153639ac04ef05f3620f9f11
|
[] |
no_license
|
aadarshasubedi/Ocerus
|
1bea105de9c78b741f3de445601f7dee07987b96
|
4920b99a89f52f991125c9ecfa7353925ea9603c
|
refs/heads/master
| 2021-01-17T17:50:00.472657 | 2011-03-25T13:26:12 | 2011-03-25T13:26:12 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 19,666 |
cpp
|
#include "Common.h"
#include "scriptstring.h"
#include <sstream>
#include <cstring>
#undef assert
#define assert(A) OC_ASSERT(A)
BEGIN_AS_NAMESPACE
static void StringFactoryGeneric(asIScriptGeneric *gen) {
asUINT length = gen->GetArgDWord(0);
const char *s = (const char*)gen->GetArgAddress(1);
string str(s, length);
gen->SetReturnObject(&str);
}
static void ConstructStringGeneric(asIScriptGeneric * gen) {
new (gen->GetObject()) string();
}
static void DestructStringGeneric(asIScriptGeneric * gen) {
string * ptr = static_cast<string *>(gen->GetObject());
ptr->~string();
}
static void AssignStringGeneric(asIScriptGeneric *gen) {
string * a = static_cast<string *>(gen->GetArgObject(0));
string * self = static_cast<string *>(gen->GetObject());
*self = *a;
gen->SetReturnAddress(self);
}
static void AddAssignStringGeneric(asIScriptGeneric *gen) {
string * a = static_cast<string *>(gen->GetArgObject(0));
string * self = static_cast<string *>(gen->GetObject());
*self += *a;
gen->SetReturnAddress(self);
}
/*static void StringEqualGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetArgAddress(0));
string * b = static_cast<string *>(gen->GetArgAddress(1));
*(bool*)gen->GetAddressOfReturnLocation() = (*a == *b);
}*/
static void StringEqualsGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetObject());
string * b = static_cast<string *>(gen->GetArgAddress(0));
*(bool*)gen->GetAddressOfReturnLocation() = (*a == *b);
}
static void StringCmpGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetObject());
string * b = static_cast<string *>(gen->GetArgAddress(0));
int cmp = 0;
if( *a < *b ) cmp = -1;
else if( *a > *b ) cmp = 1;
*(int*)gen->GetAddressOfReturnLocation() = cmp;
}
/*static void StringNotEqualGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetArgAddress(0));
string * b = static_cast<string *>(gen->GetArgAddress(1));
*(bool*)gen->GetAddressOfReturnLocation() = (*a != *b);
}
static void StringLEqualGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetArgAddress(0));
string * b = static_cast<string *>(gen->GetArgAddress(1));
*(bool*)gen->GetAddressOfReturnLocation() = (*a <= *b);
}
static void StringGEqualGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetArgAddress(0));
string * b = static_cast<string *>(gen->GetArgAddress(1));
*(bool*)gen->GetAddressOfReturnLocation() = (*a >= *b);
}
static void StringLessThanGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetArgAddress(0));
string * b = static_cast<string *>(gen->GetArgAddress(1));
*(bool*)gen->GetAddressOfReturnLocation() = (*a < *b);
}
static void StringGreaterThanGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetArgAddress(0));
string * b = static_cast<string *>(gen->GetArgAddress(1));
*(bool*)gen->GetAddressOfReturnLocation() = (*a > *b);
}*/
static void StringAddGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetObject());
string * b = static_cast<string *>(gen->GetArgAddress(0));
string ret_val = *a + *b;
gen->SetReturnObject(&ret_val);
}
static void StringLengthGeneric(asIScriptGeneric * gen) {
string * self = static_cast<string *>(gen->GetObject());
*static_cast<size_t *>(gen->GetAddressOfReturnLocation()) = self->length();
}
static void StringResizeGeneric(asIScriptGeneric * gen) {
string * self = static_cast<string *>(gen->GetObject());
self->resize(*static_cast<size_t *>(gen->GetAddressOfArg(0)));
}
static void StringCharAtGeneric(asIScriptGeneric * gen) {
unsigned int index = gen->GetArgDWord(0);
string * self = static_cast<string *>(gen->GetObject());
if (index >= self->size()) {
// Set a script exception
asIScriptContext *ctx = asGetActiveContext();
ctx->SetException("Out of range");
gen->SetReturnAddress(0);
} else {
gen->SetReturnAddress(&(self->operator [](index)));
}
}
/*void AssignInt2StringGeneric(asIScriptGeneric *gen)
{
int *a = static_cast<int*>(gen->GetAddressOfArg(0));
string *self = static_cast<string*>(gen->GetObject());
std::stringstream sstr;
sstr << *a;
*self = sstr.str();
gen->SetReturnAddress(self);
}
void AssignUInt2StringGeneric(asIScriptGeneric *gen)
{
unsigned int *a = static_cast<unsigned int*>(gen->GetAddressOfArg(0));
string *self = static_cast<string*>(gen->GetObject());
std::stringstream sstr;
sstr << *a;
*self = sstr.str();
gen->SetReturnAddress(self);
}
void AssignDouble2StringGeneric(asIScriptGeneric *gen)
{
double *a = static_cast<double*>(gen->GetAddressOfArg(0));
string *self = static_cast<string*>(gen->GetObject());
std::stringstream sstr;
sstr << *a;
*self = sstr.str();
gen->SetReturnAddress(self);
}
void AddAssignDouble2StringGeneric(asIScriptGeneric * gen) {
double * a = static_cast<double *>(gen->GetAddressOfArg(0));
string * self = static_cast<string *>(gen->GetObject());
std::stringstream sstr;
sstr << *a;
*self += sstr.str();
gen->SetReturnAddress(self);
}
void AddAssignInt2StringGeneric(asIScriptGeneric * gen) {
int * a = static_cast<int *>(gen->GetAddressOfArg(0));
string * self = static_cast<string *>(gen->GetObject());
std::stringstream sstr;
sstr << *a;
*self += sstr.str();
gen->SetReturnAddress(self);
}
void AddAssignUInt2StringGeneric(asIScriptGeneric * gen) {
unsigned int * a = static_cast<unsigned int *>(gen->GetAddressOfArg(0));
string * self = static_cast<string *>(gen->GetObject());
std::stringstream sstr;
sstr << *a;
*self += sstr.str();
gen->SetReturnAddress(self);
}
void AddString2DoubleGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetObject());
double * b = static_cast<double *>(gen->GetAddressOfArg(0));
std::stringstream sstr;
sstr << *a << *b;
std::string ret_val = sstr.str();
gen->SetReturnObject(&ret_val);
}
void AddString2IntGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetObject());
int * b = static_cast<int *>(gen->GetAddressOfArg(0));
std::stringstream sstr;
sstr << *a << *b;
std::string ret_val = sstr.str();
gen->SetReturnObject(&ret_val);
}
void AddString2UIntGeneric(asIScriptGeneric * gen) {
string * a = static_cast<string *>(gen->GetObject());
unsigned int * b = static_cast<unsigned int *>(gen->GetAddressOfArg(0));
std::stringstream sstr;
sstr << *a << *b;
std::string ret_val = sstr.str();
gen->SetReturnObject(&ret_val);
}
void AddDouble2StringGeneric(asIScriptGeneric * gen) {
double* a = static_cast<double *>(gen->GetAddressOfArg(0));
string * b = static_cast<string *>(gen->GetObject());
std::stringstream sstr;
sstr << *a << *b;
std::string ret_val = sstr.str();
gen->SetReturnObject(&ret_val);
}
void AddInt2StringGeneric(asIScriptGeneric * gen) {
int* a = static_cast<int *>(gen->GetAddressOfArg(0));
string * b = static_cast<string *>(gen->GetObject());
std::stringstream sstr;
sstr << *a << *b;
std::string ret_val = sstr.str();
gen->SetReturnObject(&ret_val);
}
void AddUInt2StringGeneric(asIScriptGeneric * gen) {
unsigned int* a = static_cast<unsigned int *>(gen->GetAddressOfArg(0));
string * b = static_cast<string *>(gen->GetObject());
std::stringstream sstr;
sstr << *a << *b;
std::string ret_val = sstr.str();
gen->SetReturnObject(&ret_val);
}*/
void RegisterStdString_Generic(asIScriptEngine *engine) {
int r;
// Register the string type
r = engine->RegisterObjectType("string", sizeof(string), asOBJ_VALUE | asOBJ_APP_CLASS_CDA); assert( r >= 0 );
// Register the string factory
r = engine->RegisterStringFactory("string", asFUNCTION(StringFactoryGeneric), asCALL_GENERIC); assert( r >= 0 );
// Register the object operator overloads
r = engine->RegisterObjectBehaviour("string", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ConstructStringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectBehaviour("string", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(DestructStringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAssign(const string &in)", asFUNCTION(AssignStringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAddAssign(const string &in)", asFUNCTION(AddAssignStringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "bool opEquals(const string &in) const", asFUNCTION(StringEqualsGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "int opCmp(const string &in) const", asFUNCTION(StringCmpGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd(const string &in) const", asFUNCTION(StringAddGeneric), asCALL_GENERIC); assert( r >= 0 );
// Register the object methods
if (sizeof(size_t) == 4) {
r = engine->RegisterObjectMethod("string", "uint length() const", asFUNCTION(StringLengthGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "void resize(uint)", asFUNCTION(StringResizeGeneric), asCALL_GENERIC); assert( r >= 0 );
} else {
r = engine->RegisterObjectMethod("string", "uint64 length() const", asFUNCTION(StringLengthGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "void resize(uint64)", asFUNCTION(StringResizeGeneric), asCALL_GENERIC); assert( r >= 0 );
}
// Register the index operator, both as a mutator and as an inspector
r = engine->RegisterObjectBehaviour("string", asBEHAVE_INDEX, "uint8 &f(uint)", asFUNCTION(StringCharAtGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectBehaviour("string", asBEHAVE_INDEX, "const uint8 &f(uint) const", asFUNCTION(StringCharAtGeneric), asCALL_GENERIC); assert( r >= 0 );
// Automatic conversion from values
/*r = engine->RegisterObjectMethod("string", "string &opAssign(double)", asFUNCTION(AssignDouble2StringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAddAssign(double)", asFUNCTION(AddAssignDouble2StringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd(double) const", asFUNCTION(AddString2DoubleGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd_r(double) const", asFUNCTION(AddDouble2StringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAssign(int)", asFUNCTION(AssignInt2StringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAddAssign(int)", asFUNCTION(AddAssignInt2StringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd(int) const", asFUNCTION(AddString2IntGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd_r(int) const", asFUNCTION(AddInt2StringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAssign(uint)", asFUNCTION(AssignUInt2StringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAddAssign(uint)", asFUNCTION(AddAssignUInt2StringGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd(uint) const", asFUNCTION(AddString2UIntGeneric), asCALL_GENERIC); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd_r(uint) const", asFUNCTION(AddUInt2StringGeneric), asCALL_GENERIC); assert( r >= 0 );*/
}
static string StringFactory(asUINT length, const char *s)
{
return string(s, length);
}
static void ConstructString(string *thisPointer)
{
new(thisPointer) string();
}
static void CopyString(const string& s, string *thisPointer)
{
new(thisPointer) string(s);
}
static void DestructString(string *thisPointer)
{
thisPointer->~string();
}
static bool StringEquals(const string& s1, const string& s2)
{
return s1==s2;
}
static string StringAdd(const string& s1, const string& s2)
{
return s1+s2;
}
/*static string &AssignUIntToString(unsigned int i, string &dest)
{
ostringstream stream;
stream << i;
dest = stream.str();
return dest;
}
static string &AddAssignUIntToString(unsigned int i, string &dest)
{
ostringstream stream;
stream << i;
dest += stream.str();
return dest;
}
static string AddStringUInt(string &str, unsigned int i)
{
ostringstream stream;
stream << i;
str += stream.str();
return str;
}
static string AddIntString(int i, string &str)
{
ostringstream stream;
stream << i;
return stream.str() + str;
}
static string &AssignIntToString(int i, string &dest)
{
ostringstream stream;
stream << i;
dest = stream.str();
return dest;
}
static string &AddAssignIntToString(int i, string &dest)
{
ostringstream stream;
stream << i;
dest += stream.str();
return dest;
}
static string AddStringInt(string &str, int i)
{
ostringstream stream;
stream << i;
str += stream.str();
return str;
}
static string AddUIntString(unsigned int i, string &str)
{
ostringstream stream;
stream << i;
return stream.str() + str;
}
static string &AssignDoubleToString(double f, string &dest)
{
ostringstream stream;
stream << f;
dest = stream.str();
return dest;
}
static string &AddAssignDoubleToString(double f, string &dest)
{
ostringstream stream;
stream << f;
dest += stream.str();
return dest;
}
static string AddStringDouble(string &str, double f)
{
ostringstream stream;
stream << f;
str += stream.str();
return str;
}
static string AddDoubleString(double f, string &str)
{
ostringstream stream;
stream << f;
return stream.str() + str;
}*/
static char *StringCharAt(unsigned int i, string &str)
{
if( i >= str.size() )
{
// Set a script exception
asIScriptContext *ctx = asGetActiveContext();
ctx->SetException("Out of range");
// Return a null pointer
return 0;
}
return &str[i];
}
static int StringCmp(const string &a, const string &b)
{
int cmp = 0;
if( a < b ) cmp = -1;
else if( a > b ) cmp = 1;
return cmp;
}
void RegisterStdString_Native(asIScriptEngine *engine)
{
int r;
// Register the string type
r = engine->RegisterObjectType("string", sizeof(string), asOBJ_VALUE | asOBJ_APP_CLASS_CDA); assert( r >= 0 );
// Register the string factory
r = engine->RegisterStringFactory("string", asFUNCTION(StringFactory), asCALL_CDECL); assert( r >= 0 );
// Register the object operator overloads
r = engine->RegisterObjectBehaviour("string", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ConstructString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectBehaviour("string", asBEHAVE_CONSTRUCT, "void f(const string &in)", asFUNCTION(CopyString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectBehaviour("string", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(DestructString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAssign(const string &in)", asMETHODPR(string, operator =, (const string&), string&), asCALL_THISCALL); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAddAssign(const string &in)", asMETHODPR(string, operator+=, (const string&), string&), asCALL_THISCALL); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "bool opEquals(const string &in) const", asFUNCTIONPR(StringEquals, (const string &, const string &), bool), asCALL_CDECL_OBJFIRST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "int opCmp(const string &in) const", asFUNCTION(StringCmp), asCALL_CDECL_OBJFIRST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd(const string &in) const", asFUNCTIONPR(StringAdd, (const string &, const string &), string), asCALL_CDECL_OBJFIRST); assert( r >= 0 );
// Register the object methods
if( sizeof(size_t) == 4 )
{
r = engine->RegisterObjectMethod("string", "uint length() const", asMETHOD(string,size), asCALL_THISCALL); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "void resize(uint)", asMETHODPR(string,resize,(size_t),void), asCALL_THISCALL); assert( r >= 0 );
}
else
{
r = engine->RegisterObjectMethod("string", "uint64 length() const", asMETHOD(string,size), asCALL_THISCALL); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "void resize(uint64)", asMETHODPR(string,resize,(size_t),void), asCALL_THISCALL); assert( r >= 0 );
}
// Register the index operator, both as a mutator and as an inspector
// Note that we don't register the operator[] directory, as it doesn't do bounds checking
r = engine->RegisterObjectBehaviour("string", asBEHAVE_INDEX, "uint8 &f(uint)", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectBehaviour("string", asBEHAVE_INDEX, "const uint8 &f(uint) const", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST); assert( r >= 0 );
// Automatic conversion from values
/*r = engine->RegisterObjectMethod("string", "string &opAssign(double)", asFUNCTION(AssignDoubleToString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAddAssign(double)", asFUNCTION(AddAssignDoubleToString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd(double) const", asFUNCTION(AddStringDouble), asCALL_CDECL_OBJFIRST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd_r(double) const", asFUNCTION(AddDoubleString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAssign(int)", asFUNCTION(AssignIntToString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAddAssign(int)", asFUNCTION(AddAssignIntToString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd(int) const", asFUNCTION(AddStringInt), asCALL_CDECL_OBJFIRST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd_r(int) const", asFUNCTION(AddIntString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAssign(uint)", asFUNCTION(AssignUIntToString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string &opAddAssign(uint)", asFUNCTION(AddAssignUIntToString), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd(uint) const", asFUNCTION(AddStringUInt), asCALL_CDECL_OBJFIRST); assert( r >= 0 );
r = engine->RegisterObjectMethod("string", "string opAdd_r(uint) const", asFUNCTION(AddUIntString), asCALL_CDECL_OBJLAST); assert( r >= 0 );*/
}
void RegisterStdString(asIScriptEngine * engine)
{
if (strstr(asGetLibraryOptions(), "AS_MAX_PORTABILITY"))
RegisterStdString_Generic(engine);
else
RegisterStdString_Native(engine);
}
END_AS_NAMESPACE
|
[
"[email protected]",
"[email protected]",
"[email protected]"
] |
[
[
[
1,
3
],
[
5,
5
],
[
7,
135
],
[
137,
145
],
[
147,
496
]
],
[
[
4,
4
],
[
136,
136
],
[
146,
146
]
],
[
[
6,
6
]
]
] |
367aae56e5d168121f42f3fee7fde1bd218c4901
|
21868e763ab7ee92486a16164ccf907328123c00
|
/codeeditor.cpp
|
d569d861d034ce9d21910345b5c5f7d6000cf9ec
|
[] |
no_license
|
nodesman/flare
|
73aacd54b5b59480901164f83905cf6cc77fe2bb
|
ba95fbfdeec1d557056054cbf007bf485c8144a6
|
refs/heads/master
| 2020-05-09T11:17:15.929029 | 2011-11-26T16:54:07 | 2011-11-26T16:54:07 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,675 |
cpp
|
#include "codeeditor.h"
#include <QtGui>
#include "completer.h"
#include <QFocusEvent>
CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent), completer(0)
{
lineNumberArea = new LineNumberArea(this);
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(const QRect &, int)), this, SLOT(updateLineNumberArea(const QRect &, int)));
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
updateLineNumberAreaWidth(0);
highlightCurrentLine();
this->initializeCompleter();
this->completer->complete();
this->setToolTip("The tool tip goes here");
}
void CodeEditor::keyPressEvent(QKeyEvent *e)
{
Completer *c = this->completer;
if (c && c->popup()->isVisible()) {
// The following keys are forwarded by the completer to the widget
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Escape:
case Qt::Key_Tab:
case Qt::Key_Backtab:
e->ignore();
return; // let the completer do default behavior
default:
break;
}
}
bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E
if (!c || !isShortcut) // dont process the shortcut when we have a completer
QPlainTextEdit::keyPressEvent(e);
//if pressed key is ctrl or shift just return.
const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
if (!c || (ctrlOrShift && e->text().isEmpty()))
return;
static QString eow("~!@#$%^&*()_+{}|\">?,./;'[]\\-="); // end of word
bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
QString completionPrefix = textUnderCursor();
if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3
|| eow.contains(e->text().right(1)))) {
c->popup()->hide();
return;
}
if (completionPrefix != c->completionPrefix()) {
c->setCompletionPrefix(completionPrefix);
c->popup()->setCurrentIndex(c->completionModel()->index(0, 0));
}
QRect cr = cursorRect();
cr.setWidth(c->popup()->sizeHintForColumn(0)
+ c->popup()->verticalScrollBar()->sizeHint().width());
c->complete(cr);
}
void CodeEditor::focusInEvent(QFocusEvent *e)
{
Completer *c = this->completer;
if (c)
c->setWidget(this);
QPlainTextEdit::focusInEvent(e);
}
void CodeEditor::initializeCompleter()
{
this->completer = new Completer(this);
this->completer->setCompletionMode(QCompleter::PopupCompletion);
this->completer->setCompletionRole(Qt::EditRole);
this->completer->setCaseSensitivity(Qt::CaseInsensitive);
this->completer->setWidget(this);
connect(this->completer,SIGNAL(activated(QString)),this,SLOT(insertCompletion(QString)));
}
void CodeEditor::setCompleterModel(QStringList *wordlist)
{
QStringListModel *wordModel = new QStringListModel(*wordlist,0);
this->completer->setModel(wordModel);
}
void CodeEditor::insertCompletion(QString completion)
{
if (completer->widget() != this)
return;
QTextCursor tc = textCursor();
int extra = completion.length() - completer->completionPrefix().length();
tc.movePosition(QTextCursor::Left);
tc.movePosition(QTextCursor::EndOfWord);
tc.insertText(completion.right(extra));
setTextCursor(tc);
}
QString CodeEditor::textUnderCursor() const
{
QTextCursor tc = textCursor();
tc.select(QTextCursor::WordUnderCursor);
return tc.selectedText();
}
Completer *CodeEditor::getCompleter()
{
return this->completer;
}
int CodeEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
return space;
}
void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void CodeEditor::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void CodeEditor::highlightCurrentLine()
{
QList<QTextEdit::ExtraSelection> extraSelections;
if (!isReadOnly()) {
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor(Qt::yellow).lighter(160);
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();
extraSelections.append(selection);
}
setExtraSelections(extraSelections);
}
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
QPoint origin(0,0);
QPoint globalStart = this->mapToGlobal(origin);
QPoint globalEnd(globalStart.x()+this->width(),globalStart.y()+this->height());
QRect theRect(origin,globalEnd);
painter.fillRect(theRect, Qt::lightGray);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
painter.setPen(Qt::black);
painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
Qt::AlignRight, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
|
[
"[email protected]"
] |
[
[
[
1,
211
]
]
] |
0b4bfd3b6be68196f8f7b4bdca7fa460fdc77477
|
d87a855d1ae81cd3a27cf6ceb1b56f1c481f9a70
|
/jkllib.cpp
|
ea94d1b29cf57ce15e72dfdf2cfe042fd90baf6f
|
[] |
no_license
|
code-google-com/jktools
|
779b1e5476d95c8cb0d45beaca79402996863c76
|
47dbfef6db90ca36e661940ec0341dc6f893440d
|
refs/heads/master
| 2020-06-04T09:43:07.532188 | 2006-07-28T03:16:19 | 2006-07-28T03:16:19 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 12,451 |
cpp
|
#include "jkllib.h"
#include "jkllib_local.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <ctype.h>
jkl_library* jkl_init( jkl_malloc a, jkl_free f )
{
jkl_library* lib = (jkl_library*)a( sizeof( jkl_library ) );
lib->_malloc = a;
lib->_free = f;
return lib;
}
void jkl_quit( jkl_library* lib )
{
lib->_free( lib );
}
#ifndef HAVE_STRNCASECMP
static int strncasecmp(const char *s1, const char *s2, size_t n)
{
if (n == 0)
return 0;
while ((n-- != 0)
&& (tolower(*(unsigned char *) s1) ==
tolower(*(unsigned char *) s2))) {
if (n == 0 || *s1 == '\0' || *s2 == '\0')
return 0;
s1++;
s2++;
}
return tolower(*(unsigned char *) s1) - tolower(*(unsigned char *) s2);
}
#endif // HAVE_STRNCASECMP
jkl_section_name jkl_sections[] =
{
{ SECTION_JK, "JK" },
{ SECTION_COPYRIGHT, "COPYRIGHT" },
{ SECTION_HEADER, "HEADER" },
{ SECTION_SOUNDS, "SOUNDS" },
{ SECTION_MATERIALS, "MATERIALS" },
{ SECTION_GEORESOURCE, "GEORESOURCE" },
{ SECTION_SECTORS, "SECTORS" },
{ SECTION_AICLASS, "AICLASS" },
{ SECTION_MODELS, "MODELS" },
{ SECTION_SPRITES, "SPRITES" },
{ SECTION_KEYFRAMES, "KEYFRAMES" },
{ SECTION_ANIMCLASS, "ANIMCLASS" },
{ SECTION_SOUNDCLASS, "SOUNDCLASS" },
{ SECTION_COGSCRIPTS, "COGSCRIPTS" },
{ SECTION_COGS, "COGS" },
{ SECTION_TEMPLATES, "TEMPLATES" },
{ SECTION_THINGS, "THINGS" },
{ SECTION_ARCHLIGHTING, "ARCHLIGHTING" },
{ SECTION_LIGHTS, "LIGHTS" },
};
static e_jkl_section get_section( const char* line )
{
e_jkl_section sect = SECTION_INVALID;
char sectionTitle[64] = {0};
sscanf( line, "SECTION: %s\n", §ionTitle );
if( 0 == sectionTitle[0] )
sscanf( line, "Section: %s\n", §ionTitle );
assert( strlen( sectionTitle ) );
for( int i = 0; i < SECTION_MAX; i++ )
{
const char* st = jkl_sections[i]._sectionTitle;
if( 0 == strncasecmp( sectionTitle, st, strlen( st ) ) )
{
fprintf( stderr, "found section %s\n", st );
sect = jkl_sections[i]._section;
break;
}
}
return sect;
}
static bool is_comment( const char* line )
{
if( '#' == line[0] )
return true;
return false;
}
const char* skip_words( const char* line, int num_words )
{
int skipped = 0;
while( *line && skipped < num_words )
{
while( !isspace( *line++ ) )
;
while( isspace( *line ) )
line++;
skipped++;
}
return line;
}
static void read_section( FILE* jkl_file, jkl_data* jkl, jkl_section_line_parser parser, void* parser_data )
{
char buffer[MAX_LINE_LENGTH];
while( !feof( jkl_file ) )
{
fpos_t pos;
fgetpos( jkl_file, &pos );
const char* line = fgets( buffer, MAX_LINE_LENGTH, jkl_file );
if( !line )
return;
if( is_comment( line ) )
continue;
if( 1 == strlen( line ) )
continue;
if( 0 == strncasecmp( line, "SECTION:", strlen("SECTION:") ) )
{
fsetpos( jkl_file, &pos );
return;
}
parser( line, jkl, parser_data );
}
}
static void header_line_parser( const char* line, jkl_data* data, void* parser_data )
{
if( 0 == strncmp( line, "Version", strlen("Version") ) )
{
sscanf( line, "Version %d", &data->_version );
}
}
static void georesource_line_parser( const char* line, jkl_data* data, void* parser_data )
{
jkl_georesource_parser_data* gr_data = (jkl_georesource_parser_data*)parser_data;
// find a section if we don't have one
if( !isdigit(line[0]) )
{
if( 0 == strncmp( line, "World Colormaps", strlen( "World Colormaps" ) ) )
{
gr_data->_mode = jkl_georesource_parser_data::GR_COLORMAPS;
//sscanf( line, "World Colormaps %d\n", &data->_numColormaps );
}
else if( 0 == strncmp( line, "World vertices", strlen( "World vertices" ) ) )
{
gr_data->_mode = jkl_georesource_parser_data::GR_VERTICES;
sscanf( line, "World vertices %d\n", &data->_numVerts );
}
else if( 0 == strncmp( line, "World texture vertices", strlen( "World texture vertices" ) ) )
{
gr_data->_mode = jkl_georesource_parser_data::GR_TEXTURE_VERTICES;
sscanf( line, "World texture vertices %d\n", &data->_numTextureVerts );
}
else if( 0 == strncmp( line, "World adjoins", strlen( "World adjoins" ) ) )
{
gr_data->_mode = jkl_georesource_parser_data::GR_ADJOINS;
//sscanf( line, "World adjoins %d\n", &data->_numAdjoins );
}
else if( 0 == strncmp( line, "World surfaces", strlen( "World surfaces" ) ) )
{
gr_data->_mode = jkl_georesource_parser_data::GR_SURFACES;
sscanf( line, "World surfaces %d\n", &data->_numSurfaces );
}
else
{
assert( false );
}
return;
}
assert( gr_data->_mode != jkl_georesource_parser_data::GR_INVALID );
switch( gr_data->_mode )
{
case jkl_georesource_parser_data::GR_COLORMAPS:
break;
case jkl_georesource_parser_data::GR_VERTICES:
{
struct _gr_vertex
{
int _index;
float _xyz[3];
};
_gr_vertex gv;
sscanf( line, "%d: %f %f %f\n",
&gv._index, &gv._xyz[0], &gv._xyz[1], &gv._xyz[2] );
assert( gv._index >= 0 && gv._index < data->_numVerts );
data->_verts[ gv._index ]._xyz[0] = gv._xyz[0];
data->_verts[ gv._index ]._xyz[1] = gv._xyz[1];
data->_verts[ gv._index ]._xyz[2] = gv._xyz[2];
}
break;
case jkl_georesource_parser_data::GR_TEXTURE_VERTICES:
{
struct _gr_texture_vertex
{
int _index;
float _uv[2];
};
_gr_texture_vertex gtv;
sscanf( line, "%d: %f %f\n",
>v._index, >v._uv[0], >v._uv[1] );
assert( gtv._index >= 0 && gtv._index < data->_numTextureVerts );
data->_textureVerts[ gtv._index ]._uv[0] = gtv._uv[0];
data->_textureVerts[ gtv._index ]._uv[1] = gtv._uv[1];
}
break;
case jkl_georesource_parser_data::GR_ADJOINS:
break;
case jkl_georesource_parser_data::GR_SURFACES:
{
struct _gr_surface_static
{
int _index;
int _material;
int _surfflags;
int _faceflags;
int _geo;
int _light;
int _tex;
int _adjoin;
float _extralight;
int _numVerts;
};
_gr_surface_static gss;
sscanf( line, "%d: %d 0x%x 0x%x %d %d %d %d %f %d\n",
&gss._index, &gss._material, &gss._surfflags, &gss._faceflags,
&gss._geo, &gss._light, &gss._tex, &gss._adjoin,
&gss._extralight, &gss._numVerts
);
data->_surfaces[ gss._index ]._material = gss._material;
data->_surfaces[ gss._index ]._surfflags = gss._surfflags;
data->_surfaces[ gss._index ]._faceflags = gss._faceflags;
data->_surfaces[ gss._index ]._geo = gss._geo;
data->_surfaces[ gss._index ]._light = gss._light;
data->_surfaces[ gss._index ]._tex = gss._tex;
data->_surfaces[ gss._index ]._adjoin = gss._adjoin;
data->_surfaces[ gss._index ]._extralight = gss._extralight;
data->_surfaces[ gss._index ]._numVerts = gss._numVerts;
data->_surfaces[ gss._index ]._firstVert = data->_numSurfaceVerts;
const char* vertex_data = skip_words( line, 10 );
for( int v = 0; v < gss._numVerts; v++ )
{
jkl_surface_vertex& jsv = data->_surfaceVerts[data->_numSurfaceVerts + v];
sscanf( vertex_data, "%d,%d", &jsv._vert, &jsv._texVert );
vertex_data = skip_words( vertex_data, 1 );
}
data->_numSurfaceVerts += gss._numVerts;
// surface normals aren't explicitly delimited,
// they just come after the surfaces (1-1 mapping)
gr_data->_numReadSurfaces++;
if( gr_data->_numReadSurfaces == data->_numSurfaces )
gr_data->_mode = jkl_georesource_parser_data::GR_SURFACE_NORMALS;
}
break;
case jkl_georesource_parser_data::GR_SURFACE_NORMALS:
{
struct _gr_normal
{
int _index;
float _nrm[3];
};
_gr_normal gn;
sscanf( line, "%d: %f %f %f\n",
&gn._index, &gn._nrm[0], &gn._nrm[1], &gn._nrm[2] );
assert( gn._index >= 0 && gn._index < data->_numSurfaces );
data->_surfaces[ gn._index ]._nrm[0] = gn._nrm[0];
data->_surfaces[ gn._index ]._nrm[1] = gn._nrm[1];
data->_surfaces[ gn._index ]._nrm[2] = gn._nrm[2];
}
break;
default:
assert( false );
break;
}
}
static void sector_line_parser( const char* line, jkl_data* data, void* parser_data )
{
jkl_sector_parser_data* sc_data = (jkl_sector_parser_data*)parser_data;
jkl_sector& sec = data->_sectors[ sc_data->_numReadSectors ];
if( 0 == data->_numSectors )
{
// read the sector chunk data
sscanf( line, "World sectors %d\n", &data->_numSectors );
}
else if( !isdigit( line[0] ) )
{
// read this sector
if( 0 == strncmp( line, "FLAGS", strlen( "FLAGS" ) ) )
{
sscanf( line, "FLAGS 0x%x\n", &sec._flags );
}
else if( 0 == strncmp( line, "AMBIENT LIGHT", strlen( "AMBIENT LIGHT" ) ) )
{
sscanf( line, "AMBIENT LIGHT %f\n", &sec._ambientLight );
}
else if( 0 == strncmp( line, "EXTRA LIGHT", strlen( "EXTRA LIGHT" ) ) )
{
sscanf( line, "EXTRA LIGHT %f\n", &sec._extraLight );
}
else if( 0 == strncmp( line, "COLORMAP", strlen( "COLORMAP" ) ) )
{
sscanf( line, "COLORMAP %d\n", &sec._colorMap );
}
else if( 0 == strncmp( line, "TINT", strlen( "TINT" ) ) )
{
sscanf( line, "TINT %f %f %f\n", &sec._tint[0], &sec._tint[1], &sec._tint[2] );
}
else if( 0 == strncmp( line, "BOUNDBOX", strlen( "BOUNDBOX" ) ) )
{
sscanf( line, "BOUNDBOX %f %f %f %f %f %f\n",
&sec._boundBox._min[0], &sec._boundBox._min[1], &sec._boundBox._min[2],
&sec._boundBox._max[0], &sec._boundBox._max[1], &sec._boundBox._max[2] );
}
else if( 0 == strncmp( line, "COLLIDEBOX", strlen( "COLLIDEBOX" ) ) )
{
sscanf( line, "COLLIDEBOX %f %f %f %f %f %f\n",
&sec._collideBox._min[0], &sec._collideBox._min[1], &sec._collideBox._min[2],
&sec._collideBox._max[0], &sec._collideBox._max[1], &sec._collideBox._max[2] );
}
else if( 0 == strncmp( line, "CENTER", strlen( "CENTER" ) ) )
{
sscanf( line, "CENTER %f %f %f\n", &sec._center[0], &sec._center[1], &sec._center[2] );
}
else if( 0 == strncmp( line, "RADIUS", strlen( "RADIUS" ) ) )
{
sscanf( line, "RADIUS %f\n", &sec._radius );
}
else if( 0 == strncmp( line, "VERTICES", strlen( "VERTICES" ) ) )
{
sscanf( line, "VERTICES %d\n", &sec._numVerts );
sec._firstVert = data->_numSectorVerts;
}
else if( 0 == strncmp( line, "SURFACES", strlen( "SURFACES" ) ) )
{
sscanf( line, "SURFACES %d %d\n", &sec._firstSurface, &sec._numSurfaces );
sc_data->_numReadSectors++;
}
}
else
{
// we must be reading vertices at this point
assert( sec._numVerts > 0 );
struct _sc_vertex
{
int _index;
int _vert;
};
_sc_vertex sv;
sscanf( line, "%d: %d\n", &sv._index, &sv._vert );
assert( sv._index >= 0 && sv._index < data->_numVerts );
data->_sectorVerts[ data->_numSectorVerts ] = sv._vert;
data->_numSectorVerts++;
}
}
static void skip_line_parser( const char* line, jkl_data* data, void* parser_data )
{
}
static void read_data( FILE* jkl_file, jkl_data* jkl )
{
char buffer[MAX_LINE_LENGTH];
while( !feof( jkl_file ) )
{
const char* line = fgets( buffer, MAX_LINE_LENGTH, jkl_file );
if( !line )
break;
if( is_comment( line ) )
continue;
if( 1 == strlen( line ) )
continue;
assert( 0 == strncasecmp( line, "SECTION:", strlen("SECTION:") ) );
e_jkl_section sect = get_section( line );
assert( SECTION_INVALID != sect );
switch( sect )
{
case SECTION_HEADER:
{
read_section( jkl_file, jkl, header_line_parser, NULL );
assert( -1 != jkl->_version );
break;
}
case SECTION_GEORESOURCE:
{
jkl_georesource_parser_data data;
read_section( jkl_file, jkl, georesource_line_parser, &data );
break;
}
case SECTION_SECTORS:
{
jkl_sector_parser_data data;
read_section( jkl_file, jkl, sector_line_parser, &data );
break;
}
default:
read_section( jkl_file, jkl, skip_line_parser, NULL );
break;
};
}
}
jkl_data* jkl_open( jkl_library* lib, const char* fname )
{
jkl_data* jkl = 0;
FILE* jkl_file = fopen( fname, "rt" );
if( jkl_file )
{
jkl = (jkl_data*)lib->_malloc( sizeof(jkl_data) );
memset( jkl, 0, sizeof(jkl_data) );
jkl->_version = -1;
read_data( jkl_file, jkl );
}
return jkl;
}
void jkl_close( jkl_library* lib, jkl_data* jkl )
{
lib->_free( jkl );
}
|
[
"barrettcolin@c12101a6-9b19-0410-a86e-396b6ccb6ab3"
] |
[
[
[
1,
444
]
]
] |
852aa5cbdac5c4fab38b21ed38da8b04fd49f091
|
6a0972b3ead93648a9142fcc9ff2be97580cf60a
|
/trunk/win/winvideo.cpp
|
b2fe747e551e51d6f9572c6e843bb42c0a33c9e4
|
[
"LicenseRef-scancode-philippe-de-muyter"
] |
permissive
|
BackupTheBerlios/tkvideo-svn
|
e5573ad1b0e1acdb67c327324e0572e2efdf4080
|
86fe21d6c09be8f202fcabe7e7cfa8887871ab3b
|
refs/heads/master
| 2021-01-20T15:37:31.126045 | 2007-10-07T23:48:07 | 2007-10-07T23:48:07 | 40,820,666 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 63,615 |
cpp
|
/* winvidep.cpp - Copyright (C) 2003-2007 Pat Thoyts <[email protected]>
*
* --- THIS IS C++ ---
*
* This provides the Windows platform specific code for the tkvideo
* widget. This uses the DirectX DirectShow API and objects to hook
* up either a video input device or a file source and render this
* to the widget window.
*
* --------------------------------------------------------------------------
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
* --------------------------------------------------------------------------
* $Id$
*/
#define WIN32_LEAN_AND_MEAN
#define OEMRESOURCE
#include <windows.h>
#include <shlwapi.h>
#include "tkvideo.h"
#include <tkPlatDecls.h>
#include "graph.h"
/** Application specific window message for filter graph notifications */
#define WM_GRAPHNOTIFY WM_APP + 82
/**
* Windows platform specific data to be added to the tkvide widget structure
*/
typedef struct {
IGraphBuilder *pFilterGraph;
IMediaEventEx *pMediaEvent;
IMediaSeeking *pMediaSeeking;
IMediaControl *pMediaControl;
IVideoWindow *pVideoWindow;
IAMVideoControl *pAMVideoControl;
IPin *pStillPin;
HBITMAP hbmOverlay;
DWORD dwRegistrationId;
WNDPROC wndproc;
GraphSpecification spec;
} VideoPlatformData;
static HRESULT ShowCaptureFilterProperties(GraphSpecification *pSpec, IGraphBuilder *pFilterGraph, HWND hwnd);
static HRESULT ShowCapturePinProperties(GraphSpecification *pSpec, IGraphBuilder *pFilterGraph, HWND hwnd);
static HRESULT ConnectVideo(Video *videoPtr, HWND hwnd, IVideoWindow **ppVideoWindow);
static HRESULT GetVideoSize(Video *videoPtr, long *pWidth, long *pHeight);
static void ReleasePlatformData(VideoPlatformData *pPlatformData);
static int GrabSample(Video *videoPtr, LPCSTR imageName);
static int GetDeviceList(Tcl_Interp *interp, CLSID clsidCategory);
LRESULT APIENTRY VideopWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static Tcl_Obj *Win32Error(const char * szPrefix, HRESULT hr);
static void ComputeAnchor(Tk_Anchor anchor, Tk_Window tkwin,
int padX, int padY, int innerWidth, int innerHeight, int *xPtr, int *yPtr);
static int PhotoToHBITMAP(Tcl_Interp *interp, const char *imageName, HBITMAP *phBitmap);
static HRESULT AddOverlay(Video *videoPtr);
static HRESULT WriteBitmapFile(HDC hdc, HBITMAP hbmp, LPCTSTR szFilename);
static HRESULT VideoStart(Video *videoPtr);
static HRESULT VideoPause(Video *videoPtr);
static HRESULT VideoStop(Video *videoPtr);
static int FormatCmd(Video *videoPtr, IAMStreamConfig *pStreamConfig, AM_MEDIA_TYPE *pmt, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int FramerateCmd(Video *videoPtr, IAMStreamConfig *pStreamConfig, AM_MEDIA_TYPE *pmt, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetPropPageCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetDevicesCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetControlCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetSeekCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetTellCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetPictureCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetInvalidCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetOverlayCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetStreamConfigCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
static int VideopWidgetFormatsCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
struct Ensemble {
const char *name; /* subcommand name */
Tcl_ObjCmdProc *command; /* subcommand implementation OR */
struct Ensemble *ensemble; /* subcommand ensemble */
};
struct Ensemble VideoWidgetEnsemble[] = {
{ "configure", VideopWidgetInvalidCmd, NULL }, /* we need to list the platform independent */
{ "cget", VideopWidgetInvalidCmd, NULL }, /* widget commands so that they appear in */
{ "xview", VideopWidgetInvalidCmd, NULL }, /* the list when an error is returned */
{ "yview", VideopWidgetInvalidCmd, NULL }, /* */
{ "propertypage", VideopWidgetPropPageCmd, NULL },
{ "devices", VideopWidgetDevicesCmd, NULL },
{ "start", VideopWidgetControlCmd, NULL },
{ "stop", VideopWidgetControlCmd, NULL },
{ "pause", VideopWidgetControlCmd, NULL },
{ "seek", VideopWidgetSeekCmd, NULL },
{ "tell", VideopWidgetTellCmd, NULL },
{ "picture", VideopWidgetPictureCmd, NULL },
{ "overlay", VideopWidgetOverlayCmd, NULL }, /* this should probably be a configure option */
{ "format", VideopWidgetStreamConfigCmd, NULL }, /* this should probably be a configure option */
{ "framerate", VideopWidgetStreamConfigCmd, NULL }, /* this should probably be a configure option */
{ "formats", VideopWidgetFormatsCmd, NULL }, /* this should probably be a configure option */
{ "framerates", VideopWidgetFormatsCmd, NULL }, /* this should probably be a configure option */
{ NULL, NULL, NULL }
};
/**
* Windows platform specific package initialization. We only need to setup for COM
* This call joins our interpreter thread to a single threaded apartment.
* @return A tcl result code.
*/
int
VideopInit(Tcl_Interp *interp)
{
HRESULT hr = CoInitialize(0);
return SUCCEEDED(hr) ? TCL_OK : TCL_ERROR;
}
/**
* Windows platform specific widget initialization. This function
* is called just after the Tk widget has been created and the core
* data structure initialized. This is our oportunity to initialize
* any platform specific extension data. See VideoPlatformData
*
* @param videoPtr pointer to the widget instance data
*/
int
VideopCreateWidget(Video *videoPtr)
{
VideoPlatformData *platformPtr = (VideoPlatformData *)ckalloc(sizeof(VideoPlatformData));
videoPtr->platformData = (ClientData)platformPtr;
if (videoPtr->platformData != NULL) {
memset(videoPtr->platformData, 0, sizeof(VideoPlatformData));
} else {
Tcl_Panic("out of memory");
}
return TCL_OK;
}
/**
* Windows platform specific cleanup. This function is called to permit us
* to release any platform specific resources associated with this widget.
* It is called after the Tk windows has been destroyed and all the core
* memory has been released.
* We need to free the memory allocated during VideopCreateWidget here.
* We also have to tidy up the filter graph and de-register it from the
* running object table.
*
* @param memPtr pointer tothe widget instance data
*/
void
VideopCleanup(char *memPtr)
{
Video *videoPtr = (Video *)memPtr;
if (videoPtr->platformData != NULL) {
ReleasePlatformData((VideoPlatformData *)videoPtr->platformData);
ckfree((char *)videoPtr->platformData);
videoPtr->platformData = NULL;
}
}
/**
* Windows platform specific window destruction. This function is
* called just before the Tk window is destroyed. For the windows
* implementation we must unsubclass the Tk window.
*/
void
VideopDestroy(Video *videoPtr)
{
VideoPlatformData *platformPtr = (VideoPlatformData *)videoPtr->platformData;
ReleasePlatformData(platformPtr);
if (platformPtr->wndproc != NULL)
{
HWND hwnd = Tk_GetHWND(Tk_WindowId(videoPtr->tkwin));
SetWindowLong(hwnd, GWL_WNDPROC, (LONG)platformPtr->wndproc);
platformPtr->wndproc = NULL;
RemoveProp(hwnd, TEXT("Tkvideo"));
}
}
/**
* Called when the video or audio source has been changed or when the output
* file has been changed. We construct the DirectShow graph appropriate to
* the specified options and get it ready to run.
*/
int
VideopInitializeSource(Video *videoPtr)
{
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
HRESULT hr = S_OK;
// Release the current graph and any pointers into it.
ReleasePlatformData(pPlatformData);
pPlatformData->spec.nDeviceIndex = -1;
pPlatformData->spec.nAudioIndex = -1;
wcsncpy(pPlatformData->spec.wszOutputPath, Tcl_GetUnicode(videoPtr->outputPtr), MAX_PATH);
if (Tcl_GetIntFromObj(NULL, videoPtr->sourcePtr, &pPlatformData->spec.nDeviceIndex) != TCL_OK)
wcsncpy(pPlatformData->spec.wszSourcePath, Tcl_GetUnicode(videoPtr->sourcePtr), MAX_PATH);
if (Tcl_GetIntFromObj(NULL, videoPtr->audioPtr, &pPlatformData->spec.nAudioIndex) != TCL_OK)
pPlatformData->spec.nAudioIndex = -1;
hr = ConstructCaptureGraph(&pPlatformData->spec, &pPlatformData->pFilterGraph);
if (SUCCEEDED(hr))
hr = pPlatformData->pFilterGraph->QueryInterface(&pPlatformData->pMediaControl);
if (SUCCEEDED(hr)) {
RegisterFilterGraph(pPlatformData->pFilterGraph, &pPlatformData->dwRegistrationId);
HWND hwnd = Tk_GetHWND(Tk_WindowId(videoPtr->tkwin));
hr = ConnectVideo(videoPtr, hwnd, &pPlatformData->pVideoWindow);
if (SUCCEEDED(hr)) {
// Subclass the tk window so we can recieve graph messages
if (pPlatformData->wndproc == NULL) {
SetProp(hwnd, TEXT("Tkvideo"), (HANDLE)videoPtr);
pPlatformData->wndproc = (WNDPROC)SetWindowLong(hwnd, GWL_WNDPROC, (LONG)VideopWndProc);
}
long w = 0, h = 0;
hr = GetVideoSize(videoPtr, &w, &h);
videoPtr->videoHeight = h;
videoPtr->videoWidth = w;
if (pPlatformData->pVideoWindow)
pPlatformData->pVideoWindow->put_BorderColor(0xffffff);
}
}
if (FAILED(hr))
{
Tcl_SetObjResult(videoPtr->interp, Win32Error("failed to initialize video source", hr));
return TCL_ERROR;
}
return TCL_OK;
}
void
ReleasePlatformData(VideoPlatformData *pPlatformData)
{
if (pPlatformData->pFilterGraph) {
pPlatformData->pFilterGraph->Abort();
}
const int nLimit = sizeof(pPlatformData->spec.aFilters)/sizeof(pPlatformData->spec.aFilters[0]);
for (int n = 0; n < nLimit; ++n) {
if (pPlatformData->spec.aFilters[n])
pPlatformData->spec.aFilters[n]->Release();
pPlatformData->spec.aFilters[n] = NULL;
}
if (pPlatformData->pMediaEvent) {
pPlatformData->pMediaEvent->SetNotifyWindow((OAHWND)NULL, 0, 0);
pPlatformData->pMediaEvent->Release();
pPlatformData->pMediaEvent = NULL;
}
if (pPlatformData->pAMVideoControl) {
pPlatformData->pAMVideoControl->Release();
pPlatformData->pAMVideoControl = NULL;
}
if (pPlatformData->pStillPin) {
pPlatformData->pStillPin->Release();
pPlatformData->pStillPin = NULL;
}
if (pPlatformData->pMediaSeeking) {
pPlatformData->pMediaSeeking->Release();
pPlatformData->pMediaSeeking = NULL;
}
if (pPlatformData->pMediaControl) {
pPlatformData->pMediaControl->Release();
pPlatformData->pMediaControl = NULL;
}
if (pPlatformData->pVideoWindow) {
pPlatformData->pVideoWindow->Release();
pPlatformData->pVideoWindow = NULL;
}
if (pPlatformData->pFilterGraph != NULL) {
UnregisterFilterGraph(pPlatformData->dwRegistrationId);
pPlatformData->pFilterGraph->Release();
pPlatformData->pFilterGraph = NULL;
}
}
void
VideopCalculateGeometry(Video *videoPtr)
{
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
int width, height, x = 0, y = 0;
if (videoPtr->stretch) {
width = Tk_ReqWidth(videoPtr->tkwin);
height = Tk_ReqHeight(videoPtr->tkwin);
} else {
width = videoPtr->videoWidth;
height = videoPtr->videoHeight;
ComputeAnchor(videoPtr->anchor, videoPtr->tkwin, 0, 0, width, height, &x, &y);
}
if (pPlatformData && pPlatformData->pVideoWindow) {
x = (videoPtr->offset.x > 0) ? -videoPtr->offset.x : x;
y = (videoPtr->offset.y > 0) ? -videoPtr->offset.y : y;
pPlatformData->pVideoWindow->SetWindowPosition(x, y, width, height);
}
}
int
VideopWidgetObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
Video *videoPtr = (Video *)clientData;
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
struct Ensemble *ensemble = VideoWidgetEnsemble;
int optPtr = 1;
int index;
if (pPlatformData == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("platform data not initialized yet", -1));
return TCL_ERROR;
}
while (optPtr < objc) {
if (Tcl_GetIndexFromObjStruct(interp, objv[optPtr], ensemble, sizeof(ensemble[0]), "command", 0, &index) != TCL_OK)
{
return TCL_ERROR;
}
if (ensemble[index].command) {
return ensemble[index].command(clientData, interp, objc, objv);
}
ensemble = ensemble[index].ensemble;
++optPtr;
}
Tcl_WrongNumArgs(interp, optPtr, objv, "option ?arg arg...?");
return TCL_ERROR;
}
int
VideopWidgetInvalidCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
ATLASSERT(FALSE && "We should never get here");
Tcl_SetResult(interp, "invalid command: you should never see this", TCL_STATIC);
return TCL_ERROR;
}
int
VideopWidgetPropPageCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
Video *videoPtr = (Video *)clientData;
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
IGraphBuilder *pFilterGraph = NULL;
int r = TCL_OK;
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "\"filter\" or \"pin\"");
r = TCL_ERROR;
} else {
char * page = Tcl_GetString(objv[2]);
pFilterGraph = pPlatformData->pFilterGraph;
if (strncmp("filter", page, 6) == 0) {
ShowCaptureFilterProperties(&pPlatformData->spec, pFilterGraph, Tk_GetHWND(Tk_WindowId(videoPtr->tkwin)));
} else if (strncmp("pin", page, 3) == 0) {
VideoStop(videoPtr);
ShowCapturePinProperties(&pPlatformData->spec, pFilterGraph, Tk_GetHWND(Tk_WindowId(videoPtr->tkwin)));
long w = 0, h = 0;
if (SUCCEEDED(GetVideoSize(videoPtr, &w, &h))) {
videoPtr->videoHeight = h;
videoPtr->videoWidth = w;
}
} else {
Tcl_WrongNumArgs(interp, 2, objv, "\"filter\" or \"pin\"");
r = TCL_ERROR;
}
}
return r;
}
int
VideopWidgetDevicesCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
int r = TCL_OK;
if (objc < 2 || objc > 3) {
Tcl_WrongNumArgs(interp, 2, objv, "?video | audio?");
r = TCL_ERROR;
} else {
CLSID clsid = CLSID_VideoInputDeviceCategory;
if (objc == 3) {
const char *type = Tcl_GetString(objv[2]);
if (strcmp("audio", type) == 0)
clsid = CLSID_AudioInputDeviceCategory;
else if (strcmp("video", type) != 0) {
Tcl_WrongNumArgs(interp, 2, objv, "?video | audio?");
r = TCL_ERROR;
}
}
if (r == TCL_OK) {
r = GetDeviceList(interp, clsid);
}
}
return r;
}
int
VideopWidgetControlCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
Video *videoPtr = (Video *)clientData;
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
IGraphBuilder *pFilterGraph = NULL;
int r = TCL_OK, index = 0;
static const char *options[] = { "start", "stop", "pause", NULL };
enum {Video_Start, Video_Stop, Video_Pause};
if (Tcl_GetIndexFromObj(interp, objv[1], options, "command", 0, &index) != TCL_OK) {
return TCL_ERROR;
}
pFilterGraph = pPlatformData->pFilterGraph;
if (! pFilterGraph) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("error: no video source initialized", -1));
return TCL_ERROR;
}
HRESULT hr = S_OK;
switch (index) {
case Video_Start:
hr = VideoStart(videoPtr);
break;
case Video_Pause:
hr = VideoPause(videoPtr);
break;
case Video_Stop:
hr = VideoStop(videoPtr);
break;
}
if (FAILED(hr)) {
Tcl_SetObjResult(interp, Win32Error("video command failed", hr));
r = TCL_ERROR;
}
return r;
}
int
VideopWidgetTellCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
Video *videoPtr = (Video *)clientData;
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
int r = TCL_OK;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, "");
r = TCL_ERROR;
} else {
if (pPlatformData->pFilterGraph == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("error: no video source initialized", -1));
return TCL_ERROR;
}
if (pPlatformData->pMediaSeeking == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("seeking not supported for this type of source", -1));
r = TCL_ERROR;
} else {
REFERENCE_TIME tDuration, tCurrent, tStop;
pPlatformData->pMediaSeeking->SetTimeFormat(&TIME_FORMAT_MEDIA_TIME);
pPlatformData->pMediaSeeking->GetDuration(&tDuration);
pPlatformData->pMediaSeeking->GetPositions(&tCurrent, &tStop);
tDuration /= 10000; tStop /= 10000; tCurrent /= 10000; // convert units from 100ns to ms.
Tcl_Obj *resObj = Tcl_NewListObj(0, NULL);
r = Tcl_ListObjAppendElement(interp, resObj, Tcl_NewWideIntObj(tCurrent));
if (r == TCL_OK)
r = Tcl_ListObjAppendElement(interp, resObj, Tcl_NewWideIntObj(tStop));
if (r == TCL_OK)
r = Tcl_ListObjAppendElement(interp, resObj, Tcl_NewWideIntObj(tDuration));
Tcl_SetObjResult(interp, resObj);
}
}
return r;
}
int
VideopWidgetSeekCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
Video *videoPtr = (Video *)clientData;
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
int r = TCL_OK;
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "position");
r = TCL_ERROR;
} else {
if (pPlatformData->pFilterGraph == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("error: no video source initialized", -1));
return TCL_ERROR;
}
if (pPlatformData->pMediaSeeking == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("seeking not supported on this source", -1));
r = TCL_ERROR;
} else {
REFERENCE_TIME t = 0;
r = Tcl_GetWideIntFromObj(interp, objv[2], &t);
if (r == TCL_OK) {
t *= 10000; // convert from ms to 100ns
pPlatformData->pMediaSeeking->SetPositions(&t, AM_SEEKING_AbsolutePositioning, NULL, AM_SEEKING_NoPositioning);
}
}
}
return r;
}
int
VideopWidgetPictureCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
Video *videoPtr = (Video *)clientData;
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
int r = TCL_OK;
if (objc < 2 || objc > 3) {
Tcl_WrongNumArgs(interp, 2, objv, "?imagename?");
r = TCL_ERROR;
} else {
if (pPlatformData->pFilterGraph == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("error: no video source initialized", -1));
return TCL_ERROR;
}
const char *imageName = NULL;
if (objc == 3) {
imageName = Tcl_GetString(objv[2]);
}
r = GrabSample(videoPtr, imageName);
}
return r;
}
// Any command that uses the current capture pin media structure...
// framerate, framerates, format, formats
int
VideopWidgetStreamConfigCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
Video *videoPtr = (Video *)clientData;
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
int r = TCL_OK;
HRESULT hr = S_OK;
CComPtr<IBaseFilter> pCaptureFilter;
if (pPlatformData->pFilterGraph == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("error: no video source initialized", -1));
return TCL_ERROR;
}
hr = pPlatformData->pFilterGraph->FindFilterByName(CAPTURE_FILTER_NAME, &pCaptureFilter);
if (SUCCEEDED(hr))
{
CComPtr<IPin> pCapturePin;
hr = FindPinByCategory(pCaptureFilter, PIN_CATEGORY_CAPTURE, &pCapturePin);
if (SUCCEEDED(hr) && pCapturePin)
{
CComPtr<IAMStreamConfig> pStreamConfig;
hr = pCapturePin.QueryInterface(&pStreamConfig);
if (SUCCEEDED(hr))
{
AM_MEDIA_TYPE *pmt = 0;
hr = pStreamConfig->GetFormat(&pmt);
if (FAILED(hr))
//hr = pCapturePin->ConnectionMediaType(pmt);
ATLASSERT(SUCCEEDED(hr) && _T("You need to use pPin->ConnectionMediaType"));
if (SUCCEEDED(hr))
{
if (pmt->formattype == FORMAT_VideoInfo)
{
const char *cmd = Tcl_GetString(objv[1]);
if (strncmp("framerate", cmd, 9) == 0) {
r = FramerateCmd(videoPtr, pStreamConfig, pmt, interp, objc, objv);
} else if (strncmp("format", cmd, 6) == 0) {
r = FormatCmd(videoPtr, pStreamConfig, pmt, interp, objc, objv);
} else {
Tcl_SetResult(interp, "invalid command", TCL_STATIC);
r = TCL_ERROR;
}
}
FreeMediaType(pmt);
}
}
}
}
if (FAILED(hr)) {
Tcl_SetObjResult(interp, Win32Error("failed to get stream config", hr));
r = TCL_ERROR;
}
return r;
}
int
FramerateCmd(Video *videoPtr, IAMStreamConfig *pStreamConfig, AM_MEDIA_TYPE *pmt, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
int r = TCL_OK;
if (objc < 2 || objc > 3) {
Tcl_WrongNumArgs(interp, 2, objv, "?rate?");
r = TCL_ERROR;
} else {
VIDEOINFOHEADER *pvih = reinterpret_cast<VIDEOINFOHEADER *>(pmt->pbFormat);
double dRate = 10000000.0 / pvih->AvgTimePerFrame;
if (objc == 2)
{
Tcl_SetObjResult(interp, Tcl_NewDoubleObj(dRate));
}
else
{
r = Tcl_GetDoubleFromObj(interp, objv[2], &dRate);
if (r == TCL_OK)
{
REFERENCE_TIME tNew = static_cast<REFERENCE_TIME>(10000000 / dRate);
pvih->AvgTimePerFrame = tNew;
HRESULT hr = pStreamConfig->SetFormat(pmt);
if (hr == VFW_E_NOT_STOPPED || hr == VFW_E_WRONG_STATE)
{
VideoStop(videoPtr);
hr = pStreamConfig->SetFormat(pmt);
VideoStart(videoPtr);
}
if (SUCCEEDED(hr)) {
r = VideopWidgetStreamConfigCmd((ClientData)videoPtr, interp, 2, objv);
} else {
Tcl_SetObjResult(interp, Win32Error("failed to set rate", hr));
r = ERROR;
}
}
}
}
return r;
}
int
FormatCmd(Video *videoPtr, IAMStreamConfig *pStreamConfig, AM_MEDIA_TYPE *pmt, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
int r = TCL_OK;
if (objc < 2 || objc > 3) {
Tcl_WrongNumArgs(interp, 2, objv, "?format?");
r = TCL_ERROR;
} else {
VIDEOINFOHEADER *pvih = reinterpret_cast<VIDEOINFOHEADER *>(pmt->pbFormat);
int width = (int)abs(pvih->bmiHeader.biWidth);
int height = (int)abs(pvih->bmiHeader.biHeight);
if (objc == 2)
{
char szFormat[(TCL_INTEGER_SPACE * 2) + 2];
sprintf(szFormat, "%ux%u", width, height);
Tcl_SetObjResult(interp, Tcl_NewStringObj(szFormat, -1));
}
else
{
if (sscanf(Tcl_GetString(objv[2]), "%dx%d", &width, &height) == 2)
{
pvih->bmiHeader.biWidth = width;
pvih->bmiHeader.biHeight = height;
HRESULT hr = pStreamConfig->SetFormat(pmt);
if (hr == VFW_E_NOT_STOPPED || hr == VFW_E_WRONG_STATE)
{
VideoStop(videoPtr);
DisconnectFilterGraph(pPlatformData->pFilterGraph);
hr = pStreamConfig->SetFormat(pmt);
ConnectFilterGraph(&pPlatformData->spec, pPlatformData->pFilterGraph);
VideoStart(videoPtr);
videoPtr->videoHeight = height;
videoPtr->videoWidth = width;
long w = 0, h = 0;
if (SUCCEEDED(GetVideoSize(videoPtr, &w, &h))) {
videoPtr->videoHeight = h;
videoPtr->videoWidth = w;
}
VideopCalculateGeometry(videoPtr);
SendConfigureEvent(videoPtr->tkwin, 0, 0, videoPtr->videoWidth, videoPtr->videoHeight);
}
if (SUCCEEDED(hr)) {
r = VideopWidgetStreamConfigCmd((ClientData)videoPtr, interp, 2, objv);
} else {
Tcl_SetObjResult(interp, Win32Error("failed to set format", hr));
r = ERROR;
}
}
else
{
Tcl_SetResult(interp, "invalid format: must be WxH", TCL_STATIC);
r = TCL_ERROR;
}
}
}
return r;
}
int
VideopWidgetFormatsCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
Video *videoPtr = (Video *)clientData;
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
int r = TCL_OK;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "");
return TCL_ERROR;
}
if (pPlatformData->pFilterGraph == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("error: no video source initialized", -1));
return TCL_ERROR;
}
Tcl_Obj *resultObj = NULL;
HRESULT hr = S_OK;
CComPtr<IBaseFilter> pCaptureFilter;
hr = pPlatformData->pFilterGraph->FindFilterByName(CAPTURE_FILTER_NAME, &pCaptureFilter);
if (SUCCEEDED(hr))
{
CComPtr<IPin> pCapturePin;
hr = FindPinByCategory(pCaptureFilter, PIN_CATEGORY_CAPTURE, &pCapturePin);
if (SUCCEEDED(hr) && pCapturePin)
{
CComPtr<IAMStreamConfig> pStreamConfig;
hr = pCapturePin.QueryInterface(&pStreamConfig);
if (SUCCEEDED(hr))
{
resultObj = Tcl_NewListObj(0, NULL);
int nCaps = 0, cbSize = 0;
hr = pStreamConfig->GetNumberOfCapabilities(&nCaps, &cbSize);
LPBYTE pData = new BYTE[cbSize];
AM_MEDIA_TYPE *pmtCurrent = 0;
if (SUCCEEDED(hr))
hr = pStreamConfig->GetFormat(&pmtCurrent);
for (int n = 0; SUCCEEDED(hr) && n < nCaps; ++n)
{
AM_MEDIA_TYPE *pmt = 0;
hr = pStreamConfig->GetStreamCaps(n, &pmt, pData);
if (SUCCEEDED(hr))
{
if (pmt->formattype == FORMAT_VideoInfo)
{
if (IsEqualGUID(pmtCurrent->subtype, pmt->subtype))
{
VIDEOINFOHEADER *pvih = reinterpret_cast<VIDEOINFOHEADER *>(pmt->pbFormat);
VIDEO_STREAM_CONFIG_CAPS *pcaps = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS *>(pData);
if (strncmp("formats", Tcl_GetString(objv[1]), 7) == 0)
{
char szFormat[(TCL_INTEGER_SPACE * 2) + 2];
sprintf(szFormat, "%ux%u", abs(pvih->bmiHeader.biWidth), abs(pvih->bmiHeader.biHeight));
Tcl_ListObjAppendElement(interp, resultObj, Tcl_NewStringObj(szFormat, -1));
}
else if (strncmp("framerates", Tcl_GetString(objv[1]), 10) == 0)
{
long nMin = static_cast<long>(10000000.0 / pcaps->MinFrameInterval);
long nMax = static_cast<long>(10000000.0 / pcaps->MaxFrameInterval);
Tcl_ListObjAppendElement(interp, resultObj, Tcl_NewLongObj(nMin));
Tcl_ListObjAppendElement(interp, resultObj, Tcl_NewLongObj(nMax));
FreeMediaType(pmt);
break;
}
else
{
Tcl_SetStringObj(resultObj, "invalid command", -1);
r = TCL_ERROR;
FreeMediaType(pmt);
break;
}
}
}
FreeMediaType(pmt);
}
}
delete [] pData;
FreeMediaType(pmtCurrent);
Tcl_SetObjResult(interp, resultObj);
}
}
}
if (FAILED(hr)) {
Tcl_SetObjResult(interp, Win32Error("failed to get stream config", hr));
r = TCL_ERROR;
}
return r;
}
int
VideopWidgetOverlayCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
Video *videoPtr = (Video *)clientData;
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
int r = TCL_OK;
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "imagename");
r = TCL_ERROR;
} else {
if (pPlatformData->pFilterGraph == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("error: no video source initialized", -1));
return TCL_ERROR;
}
const char *imageName = NULL;
if (objc == 3) {
imageName = Tcl_GetString(objv[2]);
}
HBITMAP hbm = NULL;
r = PhotoToHBITMAP(interp, imageName, &hbm);
if (hbm) {
if (pPlatformData->hbmOverlay)
DeleteObject(pPlatformData->hbmOverlay);
pPlatformData->hbmOverlay = hbm;
}
if (r == TCL_OK) {
HRESULT hr = AddOverlay(videoPtr);
if (FAILED(hr))
Tcl_SetObjResult(interp, Win32Error("failed to set overlay", hr));
r = SUCCEEDED(hr) ? TCL_OK : TCL_ERROR;
}
}
return r;
}
//HBITMAP hbmTest = (HBITMAP)LoadImage(0, _T("logo.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
//if (hbmTest) {
// WriteBitmapFile(hdc, hbmTest, _T("C:\\temp\\ztkvideo_test.bmp"));
// DeleteObject(hbmTest);
//}
//WriteBitmapFile(hdc, platformData->hbmOverlay, _T("C:\\temp\\ztkvideo_overlay.bmp"));
int
PhotoToHBITMAP(Tcl_Interp *interp, const char *imageName, HBITMAP *phBitmap)
{
BITMAP bm;
int x, y;
unsigned char *srcPtr, *dstPtr, *bits;
Tk_PhotoImageBlock block;
Tk_PhotoHandle img = Tk_FindPhoto(interp, imageName);
Tk_PhotoGetImage(img, &block);
bits = (unsigned char *)ckalloc(block.width * block.height * sizeof(unsigned char));
srcPtr = block.pixelPtr;
for (y = block.height - 1; y >= 0; y--)
{
dstPtr = bits + (y * block.width);
for (x = 0; x < block.width; x++)
{
*dstPtr++ = *(srcPtr + block.offset[2]); /* B */
*dstPtr++ = *(srcPtr + block.offset[1]); /* G */
*dstPtr++ = *(srcPtr + block.offset[0]); /* R */
*dstPtr++ = *(srcPtr + block.offset[3]); /* A */
srcPtr += block.pixelSize;
}
}
bm.bmType = 0;
bm.bmWidth = block.width;
bm.bmHeight = block.height;
bm.bmWidthBytes = block.width * block.pixelSize;
bm.bmPlanes = 1;
bm.bmBitsPixel = 32;
bm.bmBits = bits;
*phBitmap = CreateBitmapIndirect(&bm);
if (*phBitmap)
return TCL_OK;
return TCL_ERROR;
}
HRESULT
ShowCaptureFilterProperties(GraphSpecification *pSpec, IGraphBuilder *pFilterGraph, HWND hwnd)
{
HRESULT hr = E_UNEXPECTED;
if (pFilterGraph)
{
CComPtr<IBaseFilter> pFilter;
hr = pFilterGraph->FindFilterByName(CAPTURE_FILTER_NAME, &pFilter);
if (SUCCEEDED(hr))
{
int oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL);
hr = ::ShowPropertyPages(pFilter, L"Capture Filter", hwnd);
Tcl_SetServiceMode(oldMode);
//FIX ME: check for changed format.
}
}
return hr;
}
HRESULT
ShowCapturePinProperties(GraphSpecification *pSpec, IGraphBuilder *pGraphBuilder, HWND hwnd)
{
HRESULT hr = E_UNEXPECTED;
if (pGraphBuilder)
{
CComPtr<IBaseFilter> pFilter;
CComPtr<IPin> pPin;
hr = pGraphBuilder->FindFilterByName(CAPTURE_FILTER_NAME, &pFilter);
if (SUCCEEDED(hr))
hr = FindPinByCategory(pFilter, PIN_CATEGORY_CAPTURE, &pPin);
if (SUCCEEDED(hr))
{
hr = DisconnectFilterGraph(pGraphBuilder);
const int nLimit = sizeof(pSpec->aFilters)/sizeof(pSpec->aFilters[0]);
for (int n = 0; n < nLimit; ++n) {
if (pSpec->aFilters[n])
DisconnectPins(pSpec->aFilters[n]);
}
if (SUCCEEDED(hr))
{
int oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL);
hr = ::ShowPropertyPages(pPin, L"Capture Pin", hwnd);
Tcl_SetServiceMode(oldMode);
ConnectFilterGraph(pSpec, pGraphBuilder);
}
}
}
return hr;
}
HRESULT
VideoStart(Video *videoPtr)
{
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
HRESULT hr = E_UNEXPECTED;
if (pPlatformData->pFilterGraph)
{
hr = S_OK;
CComPtr<IBaseFilter> pGrabberFilter;
CComPtr<ISampleGrabber> pSampleGrabber;
if (SUCCEEDED( pPlatformData->pFilterGraph->FindFilterByName(SAMPLE_GRABBER_NAME, &pGrabberFilter) ))
pGrabberFilter.QueryInterface(&pSampleGrabber);
if (SUCCEEDED(hr) && pPlatformData->pVideoWindow)
hr = pPlatformData->pVideoWindow->put_Visible(OATRUE);
if (SUCCEEDED(hr) && pSampleGrabber)
hr = pSampleGrabber->SetBufferSamples(TRUE);
if (SUCCEEDED(hr) && pPlatformData->pMediaControl)
hr = pPlatformData->pMediaControl->Run();
}
return hr;
}
HRESULT
VideoPause(Video *videoPtr)
{
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
HRESULT hr = E_UNEXPECTED;
if (pPlatformData->pFilterGraph)
{
hr = S_OK;
CComPtr<IBaseFilter> pGrabberFilter;
CComPtr<ISampleGrabber> pSampleGrabber;
if (SUCCEEDED( pPlatformData->pFilterGraph->FindFilterByName(SAMPLE_GRABBER_NAME, &pGrabberFilter) ))
pGrabberFilter.QueryInterface(&pSampleGrabber);
if (SUCCEEDED(hr) && pPlatformData->pVideoWindow)
hr = pPlatformData->pVideoWindow->put_Visible(OATRUE);
if (SUCCEEDED(hr) && pSampleGrabber)
hr = pSampleGrabber->SetBufferSamples(TRUE);
if (SUCCEEDED(hr) && pPlatformData->pMediaControl)
hr = pPlatformData->pMediaControl->Pause();
}
return hr;
}
HRESULT
VideoStop(Video *videoPtr)
{
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
HRESULT hr = E_UNEXPECTED;
if (pPlatformData->pFilterGraph)
{
hr = S_OK;
CComPtr<IBaseFilter> pGrabberFilter;
CComPtr<ISampleGrabber> pSampleGrabber;
if (SUCCEEDED( pPlatformData->pFilterGraph->FindFilterByName(SAMPLE_GRABBER_NAME, &pGrabberFilter) ))
pGrabberFilter.QueryInterface(&pSampleGrabber);
if (SUCCEEDED(hr) && pSampleGrabber)
hr = pSampleGrabber->SetBufferSamples(FALSE);
if (SUCCEEDED(hr) && pPlatformData->pMediaControl)
hr = pPlatformData->pMediaControl->Stop();
}
return hr;
}
/**
* Obtains a list of Direct Show registered devices in a specified category.
* For instance CLSID_VideoInputDeviceCategory lists video sources and
* or CLSID_AudioInputDeviceCategory will list audio sources.
*
* @param interp [in] pointer to the tcl interpreter
* @param clsidCategory [in] identifier of the device category to list
*
* @return A tcl result code. The interpreter result is set to a Tcl list
* containing the devices names.
*/
int
GetDeviceList(Tcl_Interp *interp, CLSID clsidCategory)
{
CComPtr<ICreateDevEnum> pCreateDevEnum;
CComPtr<IBindCtx> pctx;
Tcl_Obj *listPtr = NULL;
HRESULT hr = pCreateDevEnum.CoCreateInstance(CLSID_SystemDeviceEnum);
if (SUCCEEDED(hr))
hr = CreateBindCtx(0, &pctx);
if (SUCCEEDED(hr))
{
CComPtr<IEnumMoniker> pEnumMoniker;
IMoniker *pmks[12];
ULONG nmks = 0;
HRESULT hrLoop = S_OK;
listPtr = Tcl_NewListObj(0, NULL);
// bug #4992: returns S_FALSE in the event of failure and sets the pointer NULL.
hr = pCreateDevEnum->CreateClassEnumerator(clsidCategory, &pEnumMoniker, 0);
while (SUCCEEDED(hr) && pEnumMoniker && hrLoop == S_OK)
{
hr = hrLoop = pEnumMoniker->Next(12, pmks, &nmks);
for (ULONG n = 0; SUCCEEDED(hr) && n < nmks; n++)
{
CComPtr<IPropertyBag> pbag;
CComVariant vName;
hr = pmks[n]->BindToStorage(pctx, NULL, IID_IPropertyBag, reinterpret_cast<void**>(&pbag));
if (SUCCEEDED(hr))
hr = pbag->Read(L"FriendlyName", &vName, NULL);
if (SUCCEEDED(hr))
Tcl_ListObjAppendElement(interp, listPtr, Tcl_NewUnicodeObj(vName.bstrVal, -1));
pmks[n]->Release(), pmks[n] = 0;
}
if (hrLoop == S_OK)
hr = pEnumMoniker->Reset();
}
if (SUCCEEDED(hr)) {
Tcl_SetObjResult(interp, listPtr);
}
}
return SUCCEEDED(hr) ? TCL_OK : TCL_ERROR;
}
// -----------------------------------------------------------------
/**
* Connect the capture graph to a window. This window needs
* to adjust itself for the correct size. Note that some types of
* graph may not have a video window object. For instance a graph
* based on an audio-only sample.
*
* @param pGraph [in] interface to the current filter graph
* @param hwnd [in] handle to the window we will display in.
* @param ppVideoWindow [out] pointer to the IVideoWindow interface of this
* filter graph if available.
* @return S_OK on success. E_INVALIDARG if the hwnd parameter is invalid.
*/
HRESULT
ConnectVideo(Video *videoPtr, HWND hwnd, IVideoWindow **ppVideoWindow)
{
VideoPlatformData *platformPtr = (VideoPlatformData *)videoPtr->platformData;
CComPtr<IVideoWindow> pVideoWindow;
RECT rc;
HRESULT hr = E_INVALIDARG;
if (::IsWindow(hwnd))
{
::GetClientRect(hwnd, &rc);
// Connect our window for graph events
if (SUCCEEDED( platformPtr->pFilterGraph->QueryInterface(&platformPtr->pMediaEvent) ))
{
hr = platformPtr->pMediaEvent->SetNotifyWindow((OAHWND)hwnd, WM_GRAPHNOTIFY, 0);
}
// Get a seeking pointer only if seeking is supported.
if (SUCCEEDED( platformPtr->pFilterGraph->QueryInterface(&platformPtr->pMediaSeeking) ))
{
DWORD grfCaps = AM_SEEKING_CanSeekAbsolute | AM_SEEKING_CanGetDuration;
if (platformPtr->pMediaSeeking->CheckCapabilities(&grfCaps) != S_OK)
{
platformPtr->pMediaSeeking->Release();
platformPtr->pMediaSeeking = NULL;
}
}
// Configure the overlay window.
if (SUCCEEDED(hr))
hr = platformPtr->pFilterGraph->QueryInterface(&pVideoWindow);
if (SUCCEEDED(hr))
hr = pVideoWindow->put_Owner((OAHWND)hwnd);
if (SUCCEEDED(hr))
hr = pVideoWindow->put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
if (SUCCEEDED(hr))
hr = pVideoWindow->SetWindowPosition(rc.left, rc.top, rc.right, rc.bottom);
if (SUCCEEDED(hr))
hr = pVideoWindow->put_Visible(OATRUE);
if (SUCCEEDED(hr))
hr = pVideoWindow.CopyTo(ppVideoWindow);
}
return hr;
}
/**
* Obtains the width and height in pixels of the video renderer filter
*
* @param pGraph [in] pointer to the current filter graph
* @param pWidth [out] set to the width in pixels of the video image
* @param pHeight [out] set to the height in pixels of the video image
*
* @return S_OK on success or S_FALSE if the graph does not support video.
*/
HRESULT
GetVideoSize(Video *videoPtr, long *pWidth, long *pHeight)
{
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
HRESULT hr = S_FALSE;
if (pPlatformData->pFilterGraph)
{
CComPtr<IBaseFilter> pFilter;
CComPtr<IPin> pPin;
AM_MEDIA_TYPE mt;
hr = pPlatformData->pFilterGraph->FindFilterByName(RENDERER_FILTER_NAME, &pFilter);
if (SUCCEEDED(hr))
hr = FindPinByDirection(pFilter, PINDIR_INPUT, &pPin);
if (SUCCEEDED(hr))
hr = pPin->ConnectionMediaType(&mt);
if (SUCCEEDED(hr))
{
if (mt.formattype == FORMAT_VideoInfo)
{
VIDEOINFOHEADER *pvih = reinterpret_cast<VIDEOINFOHEADER *>(mt.pbFormat);
*pWidth = abs(pvih->bmiHeader.biWidth);
*pHeight = abs(pvih->bmiHeader.biHeight);
}
// We have to clean up the media format properly.
if (mt.cbFormat > 0)
CoTaskMemFree(mt.pbFormat);
}
}
return hr;
}
/**
* This function takes an image from the sample grabber and creates a
* Tk photo using the returned data.
*
* @param interp [in] pointer to the tcl interpreter
* @param pGraph [in] pointer to the filter graph
* @param imageName [in] optional name to use for the new Tk image
*
* @return TCL_OK on success. On failure TCL_ERROR and the interpreter
* result is set to describe the error.
*/
int
GrabSample(Video *videoPtr, LPCSTR imageName)
{
VideoPlatformData *pPlatformData = (VideoPlatformData *)videoPtr->platformData;
CComPtr<IBaseFilter> pGrabberFilter;
CComPtr<ISampleGrabber> pSampleGrabber;
Tcl_Obj *errObj = NULL;
int r = TCL_OK;
#ifdef USE_STILL_PIN
// If we have a still pin hooked up, trigger it now.
HRESULT hr = pPlatformData->pFilterGraph->FindFilterByName(STILL_GRABBER_NAME, &pGrabberFilter);
if (SUCCEEDED(hr))
{
CComPtr<IBaseFilter> pCaptureFilter;
hr = pPlatformData->pFilterGraph->FindFilterByName(CAPTURE_FILTER_NAME, &pCaptureFilter);
if (SUCCEEDED(hr))
{
CComPtr<IPin> pStillPin;
hr = FindPinByCategory(pCaptureFilter, PIN_CATEGORY_STILL, &pStillPin);
if (SUCCEEDED(hr) && pStillPin)
{
CComPtr<IAMVideoControl> pAMVideoControl;
hr = pCaptureFilter->QueryInterface(IID_IAMVideoControl, reinterpret_cast<void **>(&pAMVideoControl));
if (SUCCEEDED(hr))
hr = pAMVideoControl->SetMode(pStillPin, VideoControlFlag_Trigger);
}
}
}
else
{
hr = pPlatformData->pFilterGraph->FindFilterByName(SAMPLE_GRABBER_NAME, &pGrabberFilter);
}
#else /* USE_STILL_PIN */
HRESULT hr = pPlatformData->pFilterGraph->FindFilterByName(SAMPLE_GRABBER_NAME, &pGrabberFilter);
#endif /* USE_STILL_PIN */
if (SUCCEEDED(hr))
hr = pGrabberFilter.QueryInterface(&pSampleGrabber);
AM_MEDIA_TYPE mt;
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
if (SUCCEEDED(hr))
hr = pSampleGrabber->GetConnectedMediaType(&mt);
// Copy the bitmap info from the media type structure
VIDEOINFOHEADER *pvih = reinterpret_cast<VIDEOINFOHEADER *>(mt.pbFormat);
BITMAPINFOHEADER bih;
if (SUCCEEDED(hr))
{
ZeroMemory(&bih, sizeof(BITMAPINFOHEADER));
CopyMemory(&bih, &pvih->bmiHeader, sizeof(BITMAPINFOHEADER));
if (mt.cbFormat > 0)
CoTaskMemFree(mt.pbFormat);
}
// Get the image data - first finding out how much space to allocate.
// Copy the image into the buffer.
long cbData = 0;
LPBYTE pData = NULL;
if (SUCCEEDED(hr))
hr = pSampleGrabber->GetCurrentBuffer(&cbData, NULL);
if (hr == E_INVALIDARG || hr == VFW_E_WRONG_STATE)
errObj = Tcl_NewStringObj("image capture failed: no samples are being buffered", -1);
if (SUCCEEDED(hr))
{
pData = new BYTE[cbData];
if (pData == NULL)
hr = E_OUTOFMEMORY;
if (SUCCEEDED(hr))
hr = pSampleGrabber->GetCurrentBuffer(&cbData, reinterpret_cast<long*>(pData));
if (SUCCEEDED(hr))
{
// Create a photo image.
//image create photo -height n -width
Tcl_Obj *objv[8];
int ndx = 0;
objv[ndx++] = Tcl_NewStringObj("image", -1);
objv[ndx++] = Tcl_NewStringObj("create", -1);
objv[ndx++] = Tcl_NewStringObj("photo", -1);
if (imageName != NULL)
objv[ndx++] = Tcl_NewStringObj(imageName, -1);
objv[ndx++] = Tcl_NewStringObj("-height", -1);
objv[ndx++] = Tcl_NewLongObj(bih.biHeight);
objv[ndx++] = Tcl_NewStringObj("-width", -1);
objv[ndx++] = Tcl_NewLongObj(bih.biWidth);
r = Tcl_EvalObjv(videoPtr->interp, ndx, objv, 0);
if (r == TCL_OK) {
imageName = Tcl_GetStringResult(videoPtr->interp);
Tk_PhotoHandle img = Tk_FindPhoto(videoPtr->interp, imageName);
Tk_PhotoImageBlock block;
Tk_PhotoBlank(img);
block.width = bih.biWidth;
block.height = bih.biHeight;
// hard coding for 24/32 bit bitmaps.
block.pixelSize = bih.biBitCount / 8;
block.pitch = block.pixelSize * block.width;
block.offset[0] = 2; /* R */
block.offset[1] = 1; /* G */
block.offset[2] = 0; /* B */
#if TK_MINOR_VERSION >= 3
block.offset[3] = 3;
#endif
block.pixelPtr = pData;
#if TK_MINOR_VERSION >= 3
// We have to fix the alpha channel. By default it is
// undefined and tends to produce a transparent image.
for (LPBYTE p = block.pixelPtr; p < block.pixelPtr+cbData; p += block.pixelSize)
*(p + block.offset[3]) = 0xff;
#endif
// If biHeight is positive the bitmap is a bottom-up DIB.
if (bih.biHeight > 0)
{
DWORD cbRow = block.pitch;
LPBYTE pTmp = new BYTE[cbRow];
for (int i = 0; i < block.height/2; i++)
{
LPBYTE pTop = block.pixelPtr + (i * cbRow);
LPBYTE pBot = block.pixelPtr + ((block.height - i - 1) * cbRow);
CopyMemory(pTmp, pBot, cbRow);
CopyMemory(pBot, pTop, cbRow);
CopyMemory(pTop, pTmp, cbRow);
}
delete [] pTmp;
}
Tk_PhotoPutBlock(
#if TK_MAJOR_VERSION >= 8 && TK_MINOR_VERSION >= 5
videoPtr->interp,
#endif
img, &block,
0, 0, bih.biWidth, bih.biHeight, TK_PHOTO_COMPOSITE_SET);
}
}
delete [] pData;
}
if (FAILED(hr)) {
if (errObj == NULL)
errObj = Win32Error("failed to capture image", hr);
Tcl_SetObjResult(videoPtr->interp, errObj);
r = TCL_ERROR;
}
return r;
}
LRESULT APIENTRY
VideopWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
Video *videoPtr = (Video *)GetProp(hwnd, TEXT("Tkvideo"));
VideoPlatformData *platformPtr = (VideoPlatformData *)videoPtr->platformData;
Tcl_Obj *userObj = NULL;
if (uMsg == WM_GRAPHNOTIFY && platformPtr->pMediaEvent != NULL)
{
long evCode = 0, lParam1 = 0, lParam2 = 0;
while (SUCCEEDED( platformPtr->pMediaEvent->GetEvent(&evCode, &lParam1, &lParam2, 0) ))
{
switch (evCode)
{
case EC_PAUSED:
SendVirtualEvent(videoPtr->tkwin, "VideoPaused", 0);
break;
case EC_COMPLETE:
SendVirtualEvent(videoPtr->tkwin, "VideoComplete", 0);
break;
case EC_USERABORT:
SendVirtualEvent(videoPtr->tkwin, "VideoUserAbort", 0);
break;
case EC_VIDEO_SIZE_CHANGED:
{
int width = LOWORD(lParam1);
int height = HIWORD(lParam1);
SendConfigureEvent(videoPtr->tkwin, 0, 0, width, height);
}
break;
case EC_ERRORABORT:
if (lParam1 == VFW_E_CANNOT_CONNECT) {
/* occurs when the window is moved onto a display with a
* different colour depth
*/
/* ??? VideopInitializeSource(videoPtr); */
}
SendVirtualEvent(videoPtr->tkwin, "VideoErrorAbort", lParam1);
break;
case EC_REPAINT:
/* FIX ME: SendExposeEvent ?? */
SendVirtualEvent(videoPtr->tkwin, "VideoRepaint", 0);
break;
case EC_DEVICE_LOST:
SendVirtualEvent(videoPtr->tkwin, "VideoDeviceLost", 0);
break;
case EC_BUFFERING_DATA:
case EC_STEP_COMPLETE:
case EC_DVD_TITLE_CHANGE:
case EC_DVD_DOMAIN_CHANGE:
case EC_DVD_CURRENT_HMSF_TIME:
case EC_DVD_ERROR:
case EC_DVD_WARNING:
case EC_LENGTH_CHANGED:
default:
break;
}
platformPtr->pMediaEvent->FreeEventParams(evCode, lParam1, lParam2);
}
}
return CallWindowProc(platformPtr->wndproc, hwnd, uMsg, wParam, lParam);
}
/**
* Convert windows errors into a Tcl string object including a specified
* prefix.
*/
static Tcl_Obj *
Win32Error(const char * szPrefix, HRESULT hr)
{
Tcl_Obj *msgObj = NULL;
char * lpBuffer = NULL;
DWORD dwLen = 0;
dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM,
NULL, (DWORD)hr, LANG_NEUTRAL,
(LPTSTR)&lpBuffer, 0, NULL);
if (dwLen < 1) {
dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_STRING
| FORMAT_MESSAGE_ARGUMENT_ARRAY,
"code 0x%1!08X!%n", 0, LANG_NEUTRAL,
(LPTSTR)&lpBuffer, 0, (va_list *)&hr);
}
msgObj = Tcl_NewStringObj(szPrefix, -1);
if (dwLen > 0) {
char *p = lpBuffer + dwLen - 1; /* remove cr-lf at end */
for ( ; p && *p && isspace(*p); p--)
;
*++p = 0;
Tcl_AppendToObj(msgObj, ": ", 2);
Tcl_AppendToObj(msgObj, lpBuffer, -1);
}
LocalFree((HLOCAL)lpBuffer);
return msgObj;
}
/*
*---------------------------------------------------------------------------
*
* TkComputeAnchor --
*
* Determine where to place a rectangle so that it will be properly
* anchored with respect to the given window. Used by widgets
* to align a box of text inside a window. When anchoring with
* respect to one of the sides, the rectangle be placed inside of
* the internal border of the window.
*
* Results:
* *xPtr and *yPtr set to the upper-left corner of the rectangle
* anchored in the window.
*
* Side effects:
* None.
*
*---------------------------------------------------------------------------
*/
void
ComputeAnchor(Tk_Anchor anchor, Tk_Window tkwin,
int padX, int padY, int innerWidth, int innerHeight, int *xPtr, int *yPtr)
{
switch (anchor) {
case TK_ANCHOR_NW:
case TK_ANCHOR_W:
case TK_ANCHOR_SW:
*xPtr = Tk_InternalBorderLeft(tkwin) + padX;
break;
case TK_ANCHOR_N:
case TK_ANCHOR_CENTER:
case TK_ANCHOR_S:
*xPtr = (Tk_Width(tkwin) - innerWidth) / 2;
break;
default:
*xPtr = Tk_Width(tkwin) - (Tk_InternalBorderRight(tkwin) + padX)
- innerWidth;
break;
}
switch (anchor) {
case TK_ANCHOR_NW:
case TK_ANCHOR_N:
case TK_ANCHOR_NE:
*yPtr = Tk_InternalBorderTop(tkwin) + padY;
break;
case TK_ANCHOR_W:
case TK_ANCHOR_CENTER:
case TK_ANCHOR_E:
*yPtr = (Tk_Height(tkwin) - innerHeight) / 2;
break;
default:
*yPtr = Tk_Height(tkwin) - Tk_InternalBorderBottom(tkwin) - padY
- innerHeight;
break;
}
}
HRESULT
AddOverlay(Video *videoPtr)
{
VideoPlatformData *platformData = (VideoPlatformData *)videoPtr->platformData;
LONG cx, cy;
HRESULT hr;
HWND hwnd = Tk_GetHWND(Tk_WindowId(videoPtr->tkwin));
hr = GetVideoSize(videoPtr, &cx, &cy);
if (SUCCEEDED(hr))
{
HDC hdcBitmap;
HDC hdc = GetDC(hwnd);
if (hdc == NULL)
hr = E_FAIL;
if (SUCCEEDED(hr))
{
hdcBitmap = CreateCompatibleDC(hdc);
if (hdcBitmap == NULL)
hr = E_FAIL;
ReleaseDC(hwnd, hdc);
}
BITMAP bitmap = {0};
if (SUCCEEDED(hr))
{
if (GetObject(platformData->hbmOverlay, sizeof(BITMAP), &bitmap) == NULL)
//if (GetObject(hbmTest, sizeof(BITMAP), &bitmap) == NULL)
{
DeleteDC(hdcBitmap);
hr = E_FAIL;
}
}
HBITMAP hbmOld;
if (SUCCEEDED(hr))
{
hbmOld = (HBITMAP)SelectObject(hdcBitmap, platformData->hbmOverlay);
//hbmOld = (HBITMAP)SelectObject(hdcBitmap, hbmTest);
if (hbmOld == NULL)
{
DeleteDC(hdcBitmap);
hr = E_FAIL;
}
}
VMRALPHABITMAP bmpInfo;
if (SUCCEEDED(hr))
{
ZeroMemory(&bmpInfo, sizeof(bmpInfo) );
bmpInfo.dwFlags = VMRBITMAP_HDC;
bmpInfo.hdc = hdcBitmap;
// Show the entire bitmap in the top-left corner of the video image.
SetRect(&bmpInfo.rSrc, 0, 0, bitmap.bmWidth, bitmap.bmHeight);
bmpInfo.rDest.left = 0;
bmpInfo.rDest.top = 0;
bmpInfo.rDest.right = (float)bitmap.bmWidth / (float)cx;
bmpInfo.rDest.bottom = (float)bitmap.bmHeight / (float)cy;
// Set the transparency value (1.0 is opaque, 0.0 is transparent).
bmpInfo.fAlpha = 1.0;
CComPtr<IBaseFilter> pFilter;
CComPtr<IVMRMixerBitmap> pMixer;
hr = platformData->pFilterGraph->FindFilterByName(RENDERER_FILTER_NAME, &pFilter);
if (SUCCEEDED(hr))
hr = pFilter->QueryInterface(&pMixer);
if (SUCCEEDED(hr))
hr = pMixer->SetAlphaBitmap(&bmpInfo);
DeleteObject(SelectObject(hdcBitmap, hbmOld));
DeleteDC(hdcBitmap);
}
}
return hr;
}
// -------------------------------------------------------------------------
static HRESULT
CreateBitmapInfoStruct(HBITMAP hBmp, PBITMAPINFO *ppbmi)
{
PBITMAPINFO pbmi = NULL;
BITMAP bmp;
WORD cClrBits;
HRESULT hr = E_POINTER;
if (ppbmi)
{
hr = S_OK;
// Retrieve the bitmap's color format, width, and height.
if (GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp) == NULL)
hr = E_INVALIDARG;
// Convert the color format to a count of bits.
if (SUCCEEDED(hr))
{
cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel);
if (cClrBits == 1)
cClrBits = 1;
else if (cClrBits <= 4)
cClrBits = 4;
else if (cClrBits <= 8)
cClrBits = 8;
else if (cClrBits <= 16)
cClrBits = 16;
else if (cClrBits <= 24)
cClrBits = 24;
else cClrBits = 32;
// Allocate memory for the BITMAPINFO structure. (This structure
// contains a BITMAPINFOHEADER structure and an array of RGBQUAD
// data structures.)
if (cClrBits != 24)
{
pbmi = (PBITMAPINFO) LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * (1<< cClrBits));
}
else
{
// There is no RGBQUAD array for the 24-bit-per-pixel format.
pbmi = (PBITMAPINFO) LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER));
}
// Initialize the fields in the BITMAPINFO structure.
pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pbmi->bmiHeader.biWidth = bmp.bmWidth;
pbmi->bmiHeader.biHeight = bmp.bmHeight;
pbmi->bmiHeader.biPlanes = bmp.bmPlanes;
pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel;
if (cClrBits < 24)
pbmi->bmiHeader.biClrUsed = (1<<cClrBits);
// If the bitmap is not compressed, set the BI_RGB flag.
pbmi->bmiHeader.biCompression = BI_RGB;
// Compute the number of bytes in the array of color
// indices and store the result in biSizeImage.
// For Windows NT/2000, the width must be DWORD aligned unless
// the bitmap is RLE compressed. This example shows this.
// For Windows 95/98, the width must be WORD aligned unless the
// bitmap is RLE compressed.
pbmi->bmiHeader.biSizeImage = ((pbmi->bmiHeader.biWidth * cClrBits +31) & ~31) /8 * pbmi->bmiHeader.biHeight;
// Set biClrImportant to 0, indicating that all of the
// device colors are important.
pbmi->bmiHeader.biClrImportant = 0;
*ppbmi = pbmi;
}
}
return hr;
}
HRESULT
WriteBitmapFile(HDC hdc, HBITMAP hbmp, LPCTSTR szFilename)
{
BITMAPFILEHEADER hdr = {0};
PBITMAPINFO pbi = NULL;
PBITMAPINFOHEADER pbih = NULL;
DWORD cbWrote = 0;
LPBYTE bits = NULL;
HRESULT hr = CreateBitmapInfoStruct(hbmp, &pbi);
if (SUCCEEDED(hr))
{
pbih = (PBITMAPINFOHEADER)pbi;
bits = (LPBYTE) GlobalAlloc(GMEM_FIXED, pbih->biSizeImage);
if (bits == NULL)
hr = E_OUTOFMEMORY;
if (SUCCEEDED(hr))
{
if (GetDIBits(hdc, hbmp, 0, (WORD)pbih->biHeight, bits, pbi, DIB_RGB_COLORS) == 0)
hr = E_INVALIDARG;
hdr.bfType = 0x4d42; // 0x42 = "B" 0x4d = "M"
hdr.bfReserved1 = 0;
hdr.bfReserved2 = 0;
// Compute the size of the entire file.
hdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) + pbih->biSize + pbih->biClrUsed * sizeof(RGBQUAD) + pbih->biSizeImage);
// Compute the offset to the array of color indices.
hdr.bfOffBits = (DWORD) sizeof(BITMAPFILEHEADER) + pbih->biSize + pbih->biClrUsed * sizeof (RGBQUAD);
if (SUCCEEDED(hr))
{
HANDLE hFile = CreateFile(szFilename, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(hFile, (LPVOID)&hdr, sizeof(BITMAPFILEHEADER), &cbWrote, NULL);
WriteFile(hFile, (LPVOID)pbih, sizeof(BITMAPINFOHEADER) + pbih->biClrUsed * sizeof(RGBQUAD), &cbWrote, NULL);
WriteFile(hFile, (LPBYTE)bits, pbih->biSize, &cbWrote, NULL);
CloseHandle(hFile);
}
GlobalFree(bits);
}
LocalFree(pbi);
}
return hr;
}
// -------------------------------------------------------------------------
// Local variables:
// mode: c++
// indent-tabs-mode: nil
// End:
|
[
"patthoyts@b88840ed-c3d9-0310-943c-dd7c4c0605d0"
] |
[
[
[
1,
1686
]
]
] |
3f9d1236812d32beccf6384518b7f106e9963551
|
df070aa6eb5225412ebf0c3916b41449edfa16ac
|
/AVS_Transcoder_SDK/kernel/video/tavs/avs_enc/src/vlc.cpp
|
8591d941fa0b261427bb6bea2a1787cd8440aa2a
|
[] |
no_license
|
numericalBoy/avs-transcoder
|
659b584cc5bbc4598a3ec9beb6e28801d3d33f8d
|
56a3238b34ec4e0bf3a810cedc31284ac65361c5
|
refs/heads/master
| 2020-04-28T21:08:55.048442 | 2010-03-10T13:28:18 | 2010-03-10T13:28:18 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 16,696 |
cpp
|
/*
*****************************************************************************
* COPYRIGHT AND WARRANTY INFORMATION
*
* Copyright 2003, Advanced Audio Video Coding Standard, Part II
*
* DISCLAIMER OF WARRANTY
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE AVS PATENT POLICY.
* The AVS Working Group doesn't represent or warrant that the programs
* furnished here under are free of infringement of any third-party patents.
* Commercial implementations of AVS, including shareware, may be
* subject to royalty fees to patent holders. Information regarding
* the AVS patent policy for standardization procedure is available at
* AVS Web site http://www.avs.org.cn. Patent Licensing is outside
* of AVS Working Group.
*
* THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE AVS PATENT POLICY.
************************************************************************
*/
/*
*************************************************************************************
* File name:
* Function:
*
*************************************************************************************
*/
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "global.h"
#include "const_data.h"
#if TRACE
#define SYMTRACESTRING(s) strncpy(sym.tracestring,s,TRACESTRING_SIZE)
#else
#define SYMTRACESTRING(s) // to nothing
#endif
/*
*************************************************************************
* Function:ue_v, writes an ue(v) syntax element, returns the length in bits
* Input:
tracestring
the string for the trace file
value
the value to be coded
bitstream
the Bitstream the value should be coded into
* Output:
* Return: Number of bits used by the coded syntax element
* Attention: This function writes always the bit buffer for the progressive scan flag, and
should not be used (or should be modified appropriately) for the interlace crap
When used in the context of the Parameter Sets, this is obviously not a
problem.
*************************************************************************
*/
int_32_t c_avs_enc::ue_v (char *tracestring, int_32_t value, Bitstream *bitstream)
{
SyntaxElement symbol, *sym=&symbol;
sym->type = SE_HEADER;
sym->mapping = &c_avs_enc::ue_linfo; // Mapping rule: unsigned integer
sym->value1 = value;
#if TRACE
strncpy(sym->tracestring,tracestring,TRACESTRING_SIZE);
#endif
return writeSyntaxElement_UVLC (sym, bitstream);
}
/*
*************************************************************************
* Function:ue_v, writes an ue(v) syntax element, returns the length in bits
* Input:
tracestring
the string for the trace file
value
the value to be coded
bitstream
the Bitstream the value should be coded into
* Output:
* Return: Number of bits used by the coded syntax element
* Attention:
This function writes always the bit buffer for the progressive scan flag, and
should not be used (or should be modified appropriately) for the interlace crap
When used in the context of the Parameter Sets, this is obviously not a
problem.
*************************************************************************
*/
int_32_t c_avs_enc::se_v (char *tracestring, int_32_t value, Bitstream *bitstream)
{
SyntaxElement symbol, *sym=&symbol;
sym->type = SE_HEADER;
sym->mapping = &c_avs_enc::se_linfo; // Mapping rule: signed integer
sym->value1 = value;
#if TRACE
strncpy(sym->tracestring,tracestring,TRACESTRING_SIZE);
#endif
return writeSyntaxElement_UVLC (sym, bitstream);
}
/*
*************************************************************************
* Function: u_1, writes a flag (u(1) syntax element, returns the length in bits,
always 1
* Input:
tracestring
the string for the trace file
value
the value to be coded
bitstream
the Bitstream the value should be coded into
* Output:
* Return: Number of bits used by the coded syntax element (always 1)
* Attention:This function writes always the bit buffer for the progressive scan flag, and
should not be used (or should be modified appropriately) for the interlace crap
When used in the context of the Parameter Sets, this is obviously not a
problem.
*************************************************************************
*/
int_32_t c_avs_enc::u_1 (char *tracestring, int_32_t value, Bitstream *bitstream)
{
SyntaxElement symbol, *sym=&symbol;
sym->bitpattern = value;
sym->len = 1;
sym->type = SE_HEADER;
sym->value1 = value;
#if TRACE
strncpy(sym->tracestring,tracestring, TRACESTRING_SIZE);
#endif
return writeSyntaxElement_fixed(sym, bitstream);
}
/*
*************************************************************************
* Function:u_v, writes a a n bit fixed length syntax element, returns the length in bits,
* Input:
tracestring
the string for the trace file
value
the value to be coded
bitstream
the Bitstream the value should be coded into
* Output:
* Return: Number of bits used by the coded syntax element
* Attention:This function writes always the bit buffer for the progressive scan flag, and
should not be used (or should be modified appropriately) for the interlace crap
When used in the context of the Parameter Sets, this is obviously not a
problem.
*************************************************************************
*/
int_32_t c_avs_enc::u_v (int_32_t n, char *tracestring, int_32_t value, Bitstream *bitstream)
{
SyntaxElement symbol, *sym=&symbol;
sym->bitpattern = value;
sym->len = n;
sym->type = SE_HEADER;
sym->value1 = value;
#if TRACE
strncpy(sym->tracestring,tracestring,TRACESTRING_SIZE);
#endif
return writeSyntaxElement_fixed(sym, bitstream);
}
/*
*************************************************************************
* Function:mapping for ue(v) syntax elements
* Input:
ue
value to be mapped
info
returns mapped value
len
returns mapped value length
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::ue_linfo(int_32_t ue, int_32_t dummy, int_32_t *len,int_32_t *info)
{
int_32_t i,nn;
nn=(ue+1)/2;
for (i=0; i < 16 && nn != 0; i++)
{
nn /= 2;
}
*len= 2*i + 1;
*info=ue+1-(int_32_t)pow((float)2, (float)i);
}
/*
*************************************************************************
* Function:mapping for ue(v) syntax elements
* Input:
ue
value to be mapped
info
returns mapped value
len
returns mapped value length
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::se_linfo(int_32_t se, int_32_t dummy, int_32_t *len,int_32_t *info)
{
int_32_t i,n,sign,nn;
sign=0;
if (se <= 0)
{
sign=1;
}
n=abs(se) << 1;
//n+1 is the number in the code table. Based on this we find length and info
nn=n/2;
for (i=0; i < 16 && nn != 0; i++)
{
nn /= 2;
}
*len=i*2 + 1;
*info=n - (int_32_t)pow((float)2, (float)i) + sign;
}
/*
*************************************************************************
* Function:
* Input:Number in the code table
* Output:lenght and info
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::cbp_linfo_intra(int_32_t cbp, int_32_t dummy, int_32_t *len,int_32_t *info)
{
ue_linfo(NCBP[cbp][0], dummy, len, info);
}
/*
*************************************************************************
* Function:
* Input:Number in the code table
* Output:lenght and info
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::cbp_linfo_inter(int_32_t cbp, int_32_t dummy, int_32_t *len,int_32_t *info)
{
ue_linfo(NCBP[cbp][1], dummy, len, info);
}
/*
*************************************************************************
* Function:Makes code word and passes it back
A code word has the following format: 0 0 0 ... 1 Xn ...X2 X1 X0.
* Input: Info : Xn..X2 X1 X0 \n
Length : Total number of bits in the codeword
* Output:
* Return:
* Attention:this function is called with sym->inf > (1<<(sym->len/2)).
The upper bits of inf are junk
*************************************************************************
*/
int_32_t c_avs_enc::symbol2uvlc(SyntaxElement *sym)
{
int_32_t suffix_len=sym->len/2;
sym->bitpattern = (1<<suffix_len)|(sym->inf&((1<<suffix_len)-1));
return 0;
}
/*
*************************************************************************
* Function:generates UVLC code and passes the codeword to the buffer
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
int_32_t c_avs_enc::writeSyntaxElement_UVLC(SyntaxElement *se, Bitstream *bitstream)
{
if( se->golomb_maxlevels && (se->type==SE_LUM_DC_INTRA||se->type==SE_LUM_AC_INTRA||se->type==SE_LUM_DC_INTER||se->type==SE_LUM_AC_INTER) )
return writeSyntaxElement_GOLOMB(se,bitstream);
if(se->type == SE_REFFRAME)
{
se->bitpattern = se->value1;
se->len = 1;
}
else
{
(this->*(se->mapping))(se->value1,se->value2,&(se->len),&(se->inf));
symbol2uvlc(se);
}
writeUVLC2buffer(se, bitstream);
#if TRACE
if(se->type <= 1)
trace2out (se);
#endif
return (se->len);
}
/*
*************************************************************************
* Function:passes the fixed codeword to the buffer
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
int_32_t c_avs_enc::writeSyntaxElement_fixed(SyntaxElement *se, Bitstream *bitstream)
{
writeUVLC2buffer(se, bitstream);
#if TRACE
if(se->type <= 1)
trace2out (se);
#endif
return (se->len);
}
/*
*************************************************************************
* Function:generates code and passes the codeword to the buffer
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
int_32_t c_avs_enc::writeSyntaxElement_Intra4x4PredictionMode(SyntaxElement *se, Bitstream *bitstream)
{
if (se->value1 == -1)
{
se->len = 1;
se->inf = 1;
}
else
{
se->len = 3;
se->inf = se->value1;
}
se->bitpattern = se->inf;
writeUVLC2buffer(se, bitstream);
#if TRACE
if(se->type <= 1)
trace2out (se);
#endif
return (se->len);
}
/*
*************************************************************************
* Function:writes UVLC code to the appropriate buffer
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::writeUVLC2buffer(SyntaxElement *se, Bitstream *currStream)
{
int_32_t i;
uint_32_t mask = 1 << (se->len-1);
// Add the new bits to the bitstream.
// Write out a byte if it is full
for (i=0; i<se->len; i++)
{
currStream->byte_buf <<= 1;
if (se->bitpattern & mask)
currStream->byte_buf |= 1;
currStream->bits_to_go--;
mask >>= 1;
if (currStream->bits_to_go==0)
{
currStream->bits_to_go = 8;
currStream->streamBuffer[currStream->byte_pos++] = currStream->byte_buf;
currStream->byte_buf = 0;
}
}
}
/*
*************************************************************************
* Function:generates UVLC code and passes the codeword to the buffer
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
int_32_t c_avs_enc::writeSyntaxElement2Buf_Fixed(SyntaxElement *se, Bitstream* this_streamBuffer )
{
writeUVLC2buffer(se, this_streamBuffer );
#if TRACE
if(se->type <= 1)
trace2out (se);
#endif
return (se->len);
}
/*
*************************************************************************
* Function:Makes code word and passes it back
* Input:
Info : Xn..X2 X1 X0 \n
Length : Total number of bits in the codeword
* Output:
* Return:
* Attention:
*************************************************************************
*/
int_32_t c_avs_enc::symbol2vlc(SyntaxElement *sym)
{
int_32_t info_len = sym->len;
// Convert info into a bitpattern int_32_t
sym->bitpattern = 0;
// vlc coding
while(--info_len >= 0)
{
sym->bitpattern <<= 1;
sym->bitpattern |= (0x01 & (sym->inf >> info_len));
}
return 0;
}
/*
*************************************************************************
* Function:write VLC for Run Before Next Coefficient, VLC0
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
int_32_t c_avs_enc::writeSyntaxElement_Run(SyntaxElement *se, Bitstream *bitstream)
{
int_32_t lentab[TOTRUN_NUM][16] =
{
{1,1},
{1,2,2},
{2,2,2,2},
{2,2,2,3,3},
{2,2,3,3,3,3},
{2,3,3,3,3,3,3},
{3,3,3,3,3,3,3,4,5,6,7,8,9,10,11},
};
int_32_t codtab[TOTRUN_NUM][16] =
{
{1,0},
{1,1,0},
{3,2,1,0},
{3,2,1,1,0},
{3,2,3,2,1,0},
{3,0,1,3,2,5,4},
{7,6,5,4,3,2,1,1,1,1,1,1,1,1,1},
};
int_32_t vlcnum;
vlcnum = se->len;
// se->value1 : run
se->len = lentab[vlcnum][se->value1];
se->inf = codtab[vlcnum][se->value1];
if (se->len == 0)
{
printf("ERROR: (run) not valid: (%d)\n",se->value1);
exit(-1);
}
symbol2vlc(se);
writeUVLC2buffer(se, bitstream);
#if TRACE
if (se->type <= 1)
trace2out (se);
#endif
return (se->len);
}
/*
*************************************************************************
* Function:Write out a trace string on the trace file
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
#if TRACE
void c_avs_enc::trace2out(SyntaxElement *sym)
{
TLS static int_32_t bitcounter = 0;
int_32_t i, chars;
bitcounter = 0;
if (p_trace != NULL)
{
putc('@', p_trace);
chars = fprintf(p_trace, "%i", bitcounter);
while(chars++ < 6)
putc(' ',p_trace);
chars += fprintf(p_trace, "%s", sym->tracestring);
while(chars++ < 55)
putc(' ',p_trace);
// Align bitpattern
if(sym->len<15)
{
for(i=0 ; i<15-sym->len ; i++)
fputc(' ', p_trace);
}
// Print bitpattern
bitcounter += sym->len;
for(i=1 ; i<=sym->len ; i++)
{
if((sym->bitpattern >> (sym->len-i)) & 0x1)
fputc('1', p_trace);
else
fputc('0', p_trace);
}
fprintf(p_trace, " (%3d) \n",sym->value1);
}
fflush (p_trace);
}
#endif
/*
*************************************************************************
* Function:puts the less than 8 bits in the byte buffer of the Bitstream into
the streamBuffer.
* Input:
currStream: the Bitstream the alignment should be established
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::writeVlcByteAlign(Bitstream* currStream)
{
if (currStream->bits_to_go < 8)
{ // trailing bits to process
currStream->byte_buf = (currStream->byte_buf <<currStream->bits_to_go) | (0xff >> (8 - currStream->bits_to_go));
stat->bit_use_stuffingBits[img->type]+=currStream->bits_to_go;
currStream->streamBuffer[currStream->byte_pos++]=currStream->byte_buf;
currStream->bits_to_go = 8;
}
}
|
[
"zhihang.wang@6c8d3a4c-d4d5-11dd-b6b4-918b84bbd919"
] |
[
[
[
1,
617
]
]
] |
558d41cee13679a7d64bb8ec81dd3c566a8b4779
|
00c36cc82b03bbf1af30606706891373d01b8dca
|
/Amethyst/Amethyst.cpp
|
656c43ee09f63a98ce68e557f49261a447ff2bae
|
[
"BSD-3-Clause"
] |
permissive
|
VB6Hobbyst7/opengui
|
8fb84206b419399153e03223e59625757180702f
|
640be732a25129a1709873bd528866787476fa1a
|
refs/heads/master
| 2021-12-24T01:29:10.296596 | 2007-01-22T08:00:22 | 2007-01-22T08:00:22 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,600 |
cpp
|
// OpenGUI (http://opengui.sourceforge.net)
// This source code is released under the BSD License
// See LICENSE.TXT for details
#include "Amethyst.h"
//! This is the OpenGUI namespace, which contains the Amethyst namespace
namespace OpenGUI {
//! All Amethyst classes are placed within this namespace
namespace Amethyst {
//############################################################################
void Initialize() {
LogManager::SlogMsg( "Amethyst", OGLL_MSG )
<< "Initializing Amethyst" << Log::endlog;
// register all widgets
WidgetManager& wm = WidgetManager::getSingleton();
wm.RegisterWidgetFactory( "Label", "Amethyst", &Label::createLabelFactory );
wm.RegisterWidgetFactory( "Button", "Amethyst", &Button::createButtonFactory );
wm.RegisterWidgetFactory( "CheckBox", "Amethyst", &CheckBox::createCheckBoxFactory );
wm.RegisterWidgetFactory( "RadioButton", "Amethyst", &RadioButton::createRadioButtonFactory );
wm.RegisterWidgetFactory( "StaticImage", "Amethyst", &StaticImage::createStaticImageFactory );
wm.RegisterWidgetFactory( "ProgressBar", "Amethyst", &ProgressBar::createProgressBarFactory );
wm.RegisterWidgetFactory( "Panel", "Amethyst", &Panel::createPanelFactory );
wm.RegisterWidgetFactory( "ScrollBar", "Amethyst", &ScrollBar::createScrollBarFactory );
wm.RegisterWidgetFactory( "Window", "Amethyst", &Window::createWindowFactory );
}
//############################################################################
void Shutdown() {
LogManager::SlogMsg( "Amethyst", OGLL_MSG )
<< "Shutting down Amethyst" << Log::endlog;
// remove widget registrations
WidgetManager& wm = WidgetManager::getSingleton();
wm.UnregisterWidgetFactory( "Label", "Amethyst" );
wm.UnregisterWidgetFactory( "Button", "Amethyst" );
wm.UnregisterWidgetFactory( "CheckBox", "Amethyst" );
wm.UnregisterWidgetFactory( "RadioButton", "Amethyst" );
wm.UnregisterWidgetFactory( "StaticImage", "Amethyst" );
wm.UnregisterWidgetFactory( "ProgressBar", "Amethyst" );
wm.UnregisterWidgetFactory( "Panel", "Amethyst" );
wm.UnregisterWidgetFactory( "ScrollBar", "Amethyst" );
wm.UnregisterWidgetFactory( "Window", "Amethyst" );
}
//############################################################################
}
}
extern "C" {
void __declspec( dllexport ) pluginStart() {
using namespace OpenGUI::Amethyst;
Initialize();
}
void __declspec( dllexport ) pluginStop() {
using namespace OpenGUI::Amethyst;
Shutdown();
}
} // extern "C" {
|
[
"zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59"
] |
[
[
[
1,
64
]
]
] |
5258ea1f3d625620577bbd7d0fb5db0bc07797be
|
4497c10f3b01b7ff259f3eb45d0c094c81337db6
|
/shift_map/mg_shift_map/mg_shift_map.cpp
|
24ccb55058c1cbe50bf0b775e0319d452146a3b7
|
[] |
no_license
|
liuguoyou/retarget-toolkit
|
ebda70ad13ab03a003b52bddce0313f0feb4b0d6
|
d2d94653b66ea3d4fa4861e1bd8313b93cf4877a
|
refs/heads/master
| 2020-12-28T21:39:38.350998 | 2010-12-23T16:16:59 | 2010-12-23T16:16:59 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 16,869 |
cpp
|
//////////////////////////////////////////////////////////////////////////////
// Motion Guided Shift-Map for Video Retargeting
//////////////////////////////////////////////////////////////////////////////
//
// Its graph labeling formulation:
// For every frame, we design a 2d grid graph to represent it. Every node in
// the graph corresponds to a pixel in the frame and is connected to 4 nieg-
// boring nodes. The labels are the shift-offset of the spatial coordinates
// of the pixel from source to target.
// Similar to original shift-map, the objective energy function of graph-cut
// consists of 2 terms:
// 1. Data terms: sum_p D(p,l_p)
// 2. Smoothness terms: sum_{p,q} V_{pq}(l_p,l_q)
// Instead of directly applying shift-map on individual frames, whose output
// is not motion consistent, we introduce the motion-consistent shift-map for
// video retargeting. The idea of motion-consistency is to ensure that the
// temporal changes are as similar as possible to the source. We encode the
// data term to ensure such mostion-consistency.
// Given the shift-map of previous frame, we use it to constrain the graph-cut
// of current frame. For every spatial location $p$ in target, we have their
// shifts (l_{t-1}(p),l_{t}(p)) in both previous and current frame. The temporal
// change in the target is |I_{t-1}(p+l_{t-1}(p))-I_{t}(p+l_{t}(p))|. By fixing
// the mapping in the previous frame, the temporal change of this location in
// the source is |I_{t-1}(p+l_{t-1}(p))-I_{t}(p+l_{t-1}(p))|. So the similarity
// of the temporal change at this location between target and source can be
// decided by |I_{t}(p+l_{t-1}(p))-I_{t}(p+l_{t}(p))|.
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include "../Common/picture.h"
#include "../Common/utils.h"
#include "../GCoptimization/GCoptimization.h"
using namespace std;
/*
* data structure for saliency data term
*/
struct ForDataFn
{
Picture *src;
gradient2D *gradient;
Matrix *saliency;
int *assignments;
imageSize previous_size;
imageSize target_size;
};
/*
* data structure for motion-guided data term
*/
struct ForMGDataFn
{
Picture *src;
gradient2D *gradient;
Matrix *saliency;
int *pre_assignments;
imageSize previous_size;
imageSize target_size;
Picture *pre;
};
/*
* data structure for smoothness term
*/
struct ForSmoothFn
{
Picture *src;
gradient2D *gradient;
imageSize target_size;
imageSize previous_size;
float alpha;
float beta;
};
double PairwiseDiff(intensityType p1, intensityType p2, double threshold)
{
double result = 0.0;
double r_diff = pow(p1.r-p2.r,2.0);
r_diff = (r_diff<threshold) ? 0 : r_diff;
double g_diff = pow(p1.g-p2.g,2.0);
g_diff = (g_diff<threshold) ? 0 : g_diff;
double b_diff = pow(p1.b-p2.b,2.0);
b_diff = (b_diff<threshold) ? 0 : b_diff;
result += r_diff+g_diff+b_diff;
return result;
}
/*
* Saliency-based data term calculation
* (used for first frame and shot boundaries)
*/
double dataFn(int p, int l, void *data)
{
ForDataFn *myData = (ForDataFn *) data;
int x = p % myData->target_size.width;
int y = p / myData->target_size.width;
double cost = 0.0;
// pixel rearrangement:
// keep the leftmost/rightmost columns
if (x==0 && l!=0)
cost = 100000*MAX_COST_VALUE;
if (x==myData->target_size.width-1 &&
l!=myData->src->GetWidth()-myData->target_size.width)
cost = 100000*MAX_COST_VALUE;
// motion saliency
// TODO: improve motion saliency calculation
//cost = 1/(0.01+myData->saliency->Get(y+1,x+l+1));
//cost += 0.01/(0.01+1000*myData->gradient->dx->Get(y+1,x+l+1));
//cost += 0.01/(0.01+1000*myData->gradient->dy->Get(y+1,x+l+1));
//printf("data cost for (%d,%d) is %f\n",x+l,y,myData->saliency->Get(y+1,x+l+1));
return 0.01*cost;
}
/*
* Motion-guided data term calculation
*/
double MGDataFn(int p, int l, void *data)
{
ForMGDataFn *myData = (ForMGDataFn *) data;
int x = p % myData->target_size.width;
int y = p / myData->target_size.width;
double cost = 0.0;
if (x==0 && l!=0)
cost = 100000*MAX_COST_VALUE;
if (x==myData->target_size.width-1 &&
l!=myData->src->GetWidth()-myData->target_size.width)
cost = 100000*MAX_COST_VALUE;
// Assign motion guided data energy
// preserve temporal consistency
int cur_match = x+l;
int pre_match = x+myData->pre_assignments[p];
int offset = 10;
double min_diff;
min_diff = PairwiseDiff(myData->src->GetPixelIntensity(cur_match,y),
myData->src->GetPixelIntensity(pre_match,y),30.0);
/*
for (int x_off = -offset; x_off <= offset; x_off++)
{
if (pre_match+x_off>0 && pre_match+x_off<myData->src->GetWidth())
{
double min_off_diff;
min_off_diff = PairwiseDiff(myData->src->GetPixelIntensity(cur_match,y),
myData->src->GetPixelIntensity(pre_match+x_off,y),30.0);
min_diff = min(min_diff,min_off_diff);
}
}
*/
cost += min_diff;
// maximizing the mutual information between current frame
// and previou frame in the target
/*
double min_dist = 1000;
int min_match = 1000;
for (int y_off = -offset; y_off <= offset; y_off++)
{
for (int x_off = -offset; x_off <= offset; x_off++)
{
if (x+x_off>=0 && x+x_off<myData->target_size.width &&
y+y_off>=0 && y+y_off<myData->target_size.height)
{
int nn_p = (y+y_off)*myData->target_size.width+x+x_off;
int nn_match = x+x_off+myData->pre_assignments[nn_p];
double nn_diff = PairwiseDiff(myData->src->GetPixelIntensity(cur_match,y),
myData->pre->GetPixelIntensity(nn_match,y),0.0);
if (nn_diff<=min_dist && abs(x_off)+abs(y_off)<min_match)
{
min_dist = nn_diff;
min_match = abs(x_off)+abs(y_off);
}
//min_match = min(min_match,nn_diff);
}
}
}
cost += min_match;
*/
// TODO: whether integrated with saliency?
//cost += 1/(0.01+myData->saliency->Get(y+1,x+l+1));
//cost += 0.01/(0.01+10000*(myData->gradient->dx->Get(y+1,x+l+1)));
//cost += 0.01/(0.01+10000*(myData->gradient->dy->Get(y+1,x+l+1)));
return 0.01*cost;
}
/*
* Compute color difference between two mapped points
*/
double ColorDiff(Picture *src, int x1, int y1,
int x2, int y2, int l1, int l2)
{
double diff = 0.0;
int width = src->GetWidth();
int height = src->GetHeight();
int x_offset = x2-x1;
int y_offset = y2-y1;
//printf("ColorDiff: pixels: (%d,%d) and (%d,%d) labels: %d and %d\n",x2,y2+l2,x1+x_offset,y1+l1+y_offset,l2,l1);
if (x2+l2>=0 && x2+l2<width && x1+l1+x_offset>=0 && x1+l1+x_offset<width)
{
//printf("(%d,%d) color components: %d,%d,%d\n",src->GetPixel(y2+l2,x2).r,src->GetPixel(y2+l2,x2).g,src->GetPixel(y2+l2,x2).b);
diff += pow((double)src->GetPixel(x2+l2,y2).r-src->GetPixel(x1+l1+x_offset,y1+y_offset).r,2);
diff += pow((double)src->GetPixel(x2+l2,y2).g-src->GetPixel(x1+l1+x_offset,y1+y_offset).g,2);
diff += pow((double)src->GetPixel(x2+l2,y2).b-src->GetPixel(x1+l1+x_offset,y1+y_offset).b,2);
} else
{
diff += MAX_COST_VALUE;
}
//printf("ColorDiff: finished\n");
//printf("ColorDiff: cost between (%d,%d) and (%d,%d) with labels %d and %d is %d\n",x1,y1,x2,y2,l1,l2,diff);
return diff;
}
/*
* Compute gradient difference between two mapped points
*/
double GradientDiff(gradient2D *gradient, int x1, int y1,
int x2, int y2, int l1, int l2)
{
double diff = 0.0;
int width = gradient->dx->NumOfCols();
int height = gradient->dx->NumOfRows();
int x_offset = x2-x1;
int y_offset = y2-y1;
if (x2+l2>0 && x2+l2<=width && x1+l1+x_offset>0 && x1+l1+x_offset<=width)
{
diff += pow((gradient->dx->Get(y2,x2+l2)-gradient->dx->Get(y1+y_offset,x1+l1+x_offset)),2)+
pow((gradient->dy->Get(y2,x2+l2)-gradient->dy->Get(y1+y_offset,x1+l1+x_offset)),2);
} else
{
diff += MAX_COST_VALUE;
}
return diff;
}
/*
* Smoothness term calculation
*/
double smoothFn(int p1, int p2, int l1, int l2, void *data)
{
ForSmoothFn *myData = (ForSmoothFn *) data;
double cost = 0.0;
//printf("smoothFn: calculating image gradient...\n");
int width = myData->target_size.width;
int height = myData->target_size.height;
//printf("smoothFn: image width=%d and height=%d\n",width,height);
int x1 = p1 % width;
int y1 = p1 / width;
int x2 = p2 % width;
int y2 = p2 / width;
//printf("smoothFn: (%d,%d) and (%d,%d)\n",x1,y1,x2,y2);
if (abs(x1-x2)<=1 && abs(y1-y2)<=1)
{
cost += myData->alpha*ColorDiff(myData->src, x1, y1, x2, y2, l1, l2);
cost += myData->beta*GradientDiff(myData->gradient, x1+1, y1+1, x2+1, y2+1, l1, l2);
}
else
{
cost = 0.1*MAX_COST_VALUE;
}
//printf("smoothFn: computing cost between (%d,%d) and (%d,%d) with labels %d and %d : %d\n",y1,x1,y2,x2,l1,l2,cost);
return cost;
}
/*
* Function to generate and save retargeted image
* using shift-map labels
*/
void SaveRetargetPicture(int *labels, Picture *src,int width, int height, char *name)
{
Picture *result = new Picture(width,height);
result->SetName(name);
int x, y;
pixelType pixel;
for ( int i = 0; i < width*height; i++ )
{
x = i % width;
y = i / width;
//printf("SaveRetargetPicture: GetPixel(%d,%d)\n",x+gc->whatLabel(i),y);
pixel.r = src->GetPixel(x+labels[i],y).r;
pixel.g = src->GetPixel(x+labels[i],y).g;
pixel.b = src->GetPixel(x+labels[i],y).b;
result->SetPixel(x,y,pixel);
}
result->Save(result->GetName());
delete result;
}
/*
* Function to generate and save shift image
* using shift-map labels
*/
void SaveShiftMap(int *labels, int width, int height, char *name)
{
Picture *result = new Picture(width,height);
result->SetName(name);
int x, y;
intensityType pixel;
for ( int i = 0; i < width*height; i++ )
{
x = i % width;
y = i / width;
//printf("SaveRetargetPicture: GetPixel(%d,%d)\n",x+gc->whatLabel(i),y);
pixel.r = labels[i];
pixel.g = labels[i];
pixel.b = labels[i];
result->SetPixelIntensity(x,y,pixel);
}
result->Save(result->GetName());
delete result;
}
/*
* Function to find the optimal shift-map
*/
int *GridGraph_GraphCut(listPyramidType *src, int level, int t, int *pre_assignments,
imageSize &target_size, imageSize &previous_size, int num_labels,
float alpha, float beta, char *target_path, Matrix *saliency_map)
{
Picture *cur_frame, *pre_frame;
if (t==0)
{
cur_frame = src->Lists[level].GetPicture(0);
pre_frame = src->Lists[level].GetPicture(0);
}
else
{
pre_frame = src->Lists[level].GetPicture(0);
cur_frame = src->Lists[level].GetPicture(1);
}
// set up the needed data to pass to function for the data costs
double tdt;
gradient2D *gradient = Gradient(cur_frame);
int num_pixels = target_size.width*target_size.height;
int *result = new int[num_pixels]; // stores result of optimization
try{
GCoptimizationGridGraph *gc = new GCoptimizationGridGraph(target_size.width,
target_size.height,
num_labels);
// TODO: replace the hardcode of gradient threoshold
// for shot boundary
// data terms comes from function pointer
if (t>=0)
{
ForDataFn toDataFn;
toDataFn.src = cur_frame;
toDataFn.gradient = gradient;
toDataFn.saliency = saliency_map;
toDataFn.target_size = target_size;
toDataFn.previous_size = previous_size;
gc->setDataCost(&dataFn,&toDataFn);
}
else
{
ForMGDataFn toDataFn;
toDataFn.src = cur_frame;
toDataFn.pre = pre_frame;
toDataFn.gradient = gradient;
toDataFn.saliency = saliency_map;
toDataFn.pre_assignments = pre_assignments;
toDataFn.target_size = target_size;
toDataFn.previous_size = previous_size;
gc->setDataCost(&MGDataFn,&toDataFn);
}
// smoothness comes from function pointer
ForSmoothFn toSmoothFn;
toSmoothFn.src = cur_frame;
toSmoothFn.gradient = gradient;
toSmoothFn.previous_size = previous_size;
toSmoothFn.target_size = target_size;
toSmoothFn.alpha = alpha;
toSmoothFn.beta = beta;
gc->setSmoothCost(&smoothFn, &toSmoothFn);
printf("Before optimization energy is %f\n",gc->compute_energy());
gc->expansion();// run expansion for 2 iterations. For swap use gc->swap(num_iterations);
printf("After optimization energy is %f\n",gc->compute_energy());
// obtain the labels
int assign_idx, assignment;
for ( int i = 0; i < num_pixels; i++ )
{
//printf("The optimal label for pixel %d is %d\n",i,gc->whatLabel(i));
result[i] = gc->whatLabel(i);
}
// upsampling shift-map from low-resolution
// to high-resolution
double ratio = pow(2.0,level);
int *up_result = SimpleUpsamplingMap(result,target_size,ratio);
//delete [] result;
// generate and save retargeted images
// from source and shift-map
char target_name[512] = {'\0'};
strcat(target_name,target_path);
strcat(target_name,cur_frame->GetName());
char map_name[512] = {'\0'};
strcat(map_name,target_path);
strcat(map_name,"shift_");
strcat(map_name,cur_frame->GetName());
Picture *up_frame;
if (t==0)
up_frame = src->Lists[0].GetPicture(0);
else
up_frame = src->Lists[0].GetPicture(1);
SaveRetargetPicture(up_result,up_frame,target_size.width*ratio,
target_size.height*ratio,target_name);
SaveShiftMap(up_result,target_size.width*ratio,
target_size.height*ratio,map_name);
if (t>0)
delete [] pre_assignments;
delete gradient->dx;
delete gradient->dy;
delete gradient;
delete [] up_result;
delete gc;
}
catch (GCException e){
e.Report();
}
return result;
}
/*
*
*/
Matrix *Simple_SaliencyMap(PictureList *frames, int time, int level)
{
double tdt = 0.0;
Matrix *smap = new Matrix(frames->GetPicture(0)->GetHeight(),frames->GetPicture(0)->GetWidth());
smap->LoadZero();
for (int t = 0; t < time-1; t++)
{
Matrix *gradient = FrameDifference(frames->GetPicture(t),frames->GetPicture(t+1),tdt,30.0);
for (int i = 1; i <= gradient->NumOfRows(); i++)
for (int j = 1; j <= gradient->NumOfCols(); j++)
smap->Set(i,j,smap->Get(i,j)+gradient->Get(i,j));
delete gradient;
}
Matrix *result = NULL;
for (int i = 1; i <= level; i++)
{
result = ReduceMatrix(smap);
delete smap;
smap = result;
}
return result;
}
/*
* main entry of the grogram
*/
int main(int argc, char **argv)
{
PictureList *input = NULL;
PictureList *shot = NULL;
listPyramidType *vpyramid = NULL;
listPyramidType *spyramid = NULL;
int width, height, time;
Matrix *saliency_map = NULL;
int num_pixels, num_labels;
int *assignments = NULL; // store shift labels of every pixel
imageSize target_size, previous_size;
if (argc<6)
{
cout << "Usage: mg_shift_map <input_folder> <alpha> <beta> <ratio> <output_folder>" << endl;
return 0;
//default parameters
}
// load input video
vector<string> filenames = Get_FrameNames(argv[1],
PICTURE_FRAME_EXT);
int level = 1; // gpyramid->Levels-1
shot = new PictureList(argv[1]);
spyramid = ListPyramid(shot,level+1);
saliency_map = Simple_SaliencyMap(&(spyramid->Lists[0]),filenames.size(),level);
delete shot;
delete [] spyramid->Lists;
delete spyramid;
for (int t = 0; t < filenames.size(); t++)
{
cout << "Processing " << t << "th frames ..." << endl;
if (t>0)
input = new PictureList(argv[1],t-1,t);
else
input = new PictureList(argv[1],t,t+1);
vpyramid = ListPyramid(input,level+1);
/*
int end_t = (t+4<filenames.size()) ? t+4 : filenames.size()-1;
shot = new PictureList(argv[1],t,end_t);
spyramid = ListPyramid(shot,level+1);
saliency_map = Simple_SaliencyMap(&(spyramid->Lists[0]),end_t-t+1,level);
delete shot;
delete [] spyramid->Lists;
delete spyramid;
*/
width = vpyramid->Lists[level].GetPicture(1)->GetWidth();
height = vpyramid->Lists[level].GetPicture(1)->GetHeight();
num_pixels = ceil(width*atof(argv[4]))*height;
num_labels = width-ceil(width*atof(argv[4]))+1;
width = ceil(width*atof(argv[4]));
target_size.width = width;
target_size.height = height;
previous_size.width = 0;
previous_size.height = 0;
assignments = GridGraph_GraphCut(vpyramid,level,t,assignments,target_size,previous_size,
num_labels,atof(argv[2]),atof(argv[3]),argv[5],saliency_map);
//delete framename;
//delete buf;
delete input;
delete [] vpyramid->Lists;
delete vpyramid;
//delete saliency_map;
}
delete [] assignments;
delete saliency_map;
return 1;
}
/////////////////////////////////////////////////////////////////////////////////
|
[
"yiqun.hu@aeedd7dc-6096-11de-8dc1-e798e446b60a"
] |
[
[
[
1,
584
]
]
] |
85a2f3159236c9222826c9ac001c1711a78a1406
|
b4d726a0321649f907923cc57323942a1e45915b
|
/CODE/BMPMAN/BMPMAN.CPP
|
8c228073834fed372d33ae4258c517cc9936ff48
|
[] |
no_license
|
chief1983/Imperial-Alliance
|
f1aa664d91f32c9e244867aaac43fffdf42199dc
|
6db0102a8897deac845a8bd2a7aa2e1b25086448
|
refs/heads/master
| 2016-09-06T02:40:39.069630 | 2010-10-06T22:06:24 | 2010-10-06T22:06:24 | 967,775 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 88,242 |
cpp
|
/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/Bmpman/BmpMan.cpp $
*
* $Revision: 1.1.1.1 $
* $Date: 2004/08/13 22:47:40 $
* $Author: Spearhawk $
*
* Code to load and manage all bitmaps for the game
*
* $Log: BMPMAN.CPP,v $
* Revision 1.1.1.1 2004/08/13 22:47:40 Spearhawk
* no message
*
* Revision 1.1.1.1 2004/08/13 20:07:43 Darkhill
* no message
*
* Revision 2.30 2004/05/11 23:08:55 taylor
* do page in unlock but not for gr_preload() stuff
*
* Revision 2.29 2004/05/06 22:35:25 taylor
* DDS mipmap reading, remove unneeded bm_unlock() during page in
*
* Revision 2.28 2004/04/26 15:51:26 taylor
* forgot to remove some safety checks that aren't needed anymore
*
* Revision 2.27 2004/04/26 12:44:54 taylor
* 32-bit targa and jpeg loaders, bug fixes, some preload stuff
*
* Revision 2.26 2004/04/09 20:32:31 phreak
* moved an assignment statement inside an #ifdef block so dds works in release mode
*
* Revision 2.25 2004/04/09 20:07:56 phreak
* fixed DDS not working in OpenGL. there was a misplaced Assert()
*
* Revision 2.24 2004/04/01 15:31:20 taylor
* don't use interface anis as ship textures
*
* Revision 2.23 2004/03/05 09:01:54 Goober5000
* Uber pass at reducing #includes
* --Goober5000
*
* Revision 2.22 2004/02/28 14:14:56 randomtiger
* Removed a few uneeded if DIRECT3D's.
* Set laser function to only render the effect one sided.
* Added some stuff to the credits.
* Set D3D fogging to fall back to vertex fog if table fog not supported.
*
* Revision 2.21 2004/02/20 21:45:40 randomtiger
* Removed some uneeded code between NO_DIRECT3D and added gr_zbias call, ogl is set to a stub func.
* Changed -htl param to -nohtl. Fixed some badly named functions to match convention.
* Fixed setup of center_alpha in OGL which was causing crash.
*
* Revision 2.20 2004/02/14 00:18:29 randomtiger
* Please note that from now on OGL will only run with a registry set by Launcher v4. See forum for details.
* OK, these changes effect a lot of file, I suggest everyone updates ASAP:
* Removal of many files from project.
* Removal of meanless Gr_bitmap_poly variable.
* Removal of glide, directdraw, software modules all links to them, and all code specific to those paths.
* Removal of redundant Fred paths that arent needed for Fred OGL.
* Have seriously tidied the graphics initialisation code and added generic non standard mode functionality.
* Fixed many D3D non standard mode bugs and brought OGL up to the same level.
* Removed texture section support for D3D8, voodoo 2 and 3 cards will no longer run under fs2_open in D3D, same goes for any card with a maximum texture size less than 1024.
*
* Revision 2.19 2004/01/18 14:03:22 randomtiger
* A couple of FRED_OGL changes.
*
* Revision 2.18 2004/01/17 21:59:52 randomtiger
* Some small changes to the main codebase that allow Fred_open OGL to compile.
*
* Revision 2.17 2003/11/16 09:42:38 Goober5000
* clarified and pruned debug spew messages
* --Goober5000
*
* Revision 2.16 2003/10/24 17:35:04 randomtiger
* Implemented support for 32bit TGA and JPG for D3D
* Also 32 bit PCX, but it still has some bugs to be worked out
* Moved convert_24_to_16 out of the bitmap pfunction structures and into packunpack.cpp because thats the only place that uses it.
*
* Revision 2.15 2003/08/16 03:52:22 bobboau
* update for the specmapping code includeing
* suport for seperate specular levels on lights and
* optional strings for the stars table
* code has been made more organised,
* though there seems to be a bug in the state selecting code
* resulting in the HUD being rendered incorectly
* and specmapping failing ocasionaly
*
* Revision 2.14 2003/08/12 03:18:32 bobboau
* Specular 'shine' mapping;
* useing a phong lighting model I have made specular highlights
* that are mapped to the model,
* rendering them is still slow, but they look real purdy
*
* also 4 new (untested) comand lines, the XX is a floating point value
* -spec_exp XX
* the n value, you can set this from 0 to 200 (actualy more than that, but this is the recomended range), it will make the highlights bigger or smaller, defalt is 16.0 so start playing around there
* -spec_point XX
* -spec_static XX
* -spec_tube XX
* these are factors for the three diferent types of lights that FS uses, defalt is 1.0,
* static is the local stars,
* point is weapons/explosions/warp in/outs,
* tube is beam weapons,
* for thouse of you who think any of these lights are too bright you can configure them you're self for personal satisfaction
*
* Revision 2.13 2003/06/07 21:08:09 phreak
* bmp_gfx_get_components now works with 32 bit opengl
*
* Revision 2.12 2003/03/18 10:07:00 unknownplayer
* The big DX/main line merge. This has been uploaded to the main CVS since I can't manage to get it to upload to the DX branch. Apologies to all who may be affected adversely, but I'll work to debug it as fast as I can.
*
*
* Revision 2.11 2003/01/19 01:07:41 bobboau
* redid the way glowmaps are handeled, you now must set the global int GLOWMAP (no longer an array) before you render a poly that uses a glow map then set GLOWMAP to -1 when you're done with, fixed a few other misc bugs it
*
* Revision 2.10 2003/01/18 19:55:16 phreak
* fixed around the bmpman system to now accept compressed textures
*
* Revision 2.9 2003/01/09 22:23:38 inquisitor
* Rollback to 2.7 to fix glow code issue that phreak noticed.
* -Quiz
*
* Revision 2.7 2003/01/05 23:41:50 bobboau
* disabled decals (for now), removed the warp ray thingys,
* made some better error mesages while parseing weapons and ships tbls,
* and... oh ya, added glow mapping
*
* Revision 2.6 2002/12/02 23:26:08 Goober5000
* fixed misspelling
*
* Revision 2.5 2002/12/02 20:46:41 Goober5000
* fixed misspelling of "category" as "catagory"
*
* Revision 2.4 2002/11/22 20:55:27 phreak
* changed around some page-in functions to work with opengl
* changed bm_set_components_opengl
* -phreak
*
* Revision 2.3 2002/11/18 21:27:13 phreak
* added bm_select_components functions for OpenGL -phreak
*
*
* Revision 2.2.2.12 2002/11/04 16:04:20 randomtiger
*
* Tided up some bumpman stuff and added a few function points to gr_screen. - RT
*
* Revision 2.2.2.11 2002/11/04 03:02:28 randomtiger
*
* I have made some fairly drastic changes to the bumpman system. Now functionality can be engine dependant.
* This is so D3D8 can call its own loading code that will allow good efficient loading and use of textures that it desparately needs without
* turning bumpman.cpp into a total hook infested nightmare. Note the new bumpman code is still relying on a few of the of the old functions and all of the old bumpman arrays.
*
* I have done this by adding to the gr_screen list of function pointers that are set up by the engines init functions.
* I have named the define calls the same name as the original 'bm_' functions so that I havent had to change names all through the code.
*
* Rolled back to an old version of bumpman and made a few changes.
* Added new files: grd3dbumpman.cpp and .h
* Moved the bitmap init function to after the 3D engine is initialised
* Added includes where needed
* Disabled (for now) the D3D8 TGA loading - RT
*
*
* Revision 2.2 2002/08/01 01:41:04 penguin
* The big include file move
*
* Revision 2.1 2002/07/07 19:55:58 penguin
* Back-port to MSVC
*
* Revision 2.0 2002/06/03 04:02:21 penguin
* Warpcore CVS sync
*
* Revision 1.4 2002/05/21 15:36:25 mharris
* Added ifdef WIN32
*
* Revision 1.3 2002/05/09 13:49:30 mharris
* Added ifndef NO_DIRECT3D
*
* Revision 1.2 2002/05/03 22:07:08 mharris
* got some stuff to compile
*
* Revision 1.1 2002/05/02 18:03:04 mharris
* Initial checkin - converted filenames and includes to lower case
*
*
* 37 9/13/99 11:26p Andsager
* Add debug code to check for poorly sized anis
*
* 36 9/05/99 11:19p Dave
* Made d3d texture cache much more safe. Fixed training scoring bug where
* it would backout scores without ever having applied them in the first
* place.
*
* 35 8/20/99 2:09p Dave
* PXO banner cycling.
*
* 34 8/10/99 6:54p Dave
* Mad optimizations. Added paging to the nebula effect.
*
* 33 8/06/99 1:52p Dave
* Bumped up MAX_BITMAPS for the demo.
*
* 32 8/02/99 1:49p Dave
* Fixed low-mem animation problem. Whee!
*
* 31 7/16/99 1:49p Dave
* 8 bit aabitmaps. yay.
*
* 30 7/13/99 1:15p Dave
* 32 bit support. Whee!
*
* 29 6/29/99 10:35a Dave
* Interface polygon bitmaps! Whee!
*
* 28 6/16/99 4:06p Dave
* New pilot info popup. Added new draw-bitmap-as-poly function.
*
* 27 5/05/99 9:02p Dave
* Fixed D3D aabitmap rendering. Spiffed up nebula effect a bit (added
* rotations, tweaked values, made bitmap selection more random). Fixed
* D3D beam weapon clipping problem. Added D3d frame dumping.
*
* 26 4/27/99 12:16a Dave
* Fixed beam weapon muzzle glow problem. Fixed premature timeout on the
* pxo server list screen. Fixed secondary firing for hosts on a
* standalone. Fixed wacky multiplayer weapon "shuddering" problem.
*
* 25 4/09/99 2:21p Dave
* Multiplayer beta stuff. CD checking.
*
* 24 4/08/99 10:42a Johnson
* Don't try to swizzle a texture to transparent in Fred.
*
* 23 3/31/99 8:24p Dave
* Beefed up all kinds of stuff, incluging beam weapons, nebula effects
* and background nebulae. Added per-ship non-dimming pixel colors.
*
* 22 3/20/99 3:46p Dave
* Added support for model-based background nebulae. Added 3 new
* sexpressions.
*
* 21 2/11/99 3:08p Dave
* PXO refresh button. Very preliminary squad war support.
*
* 20 2/08/99 5:07p Dave
* FS2 chat server support. FS2 specific validated missions.
*
* 19 2/05/99 12:52p Dave
* Fixed Glide nondarkening textures.
*
* 18 2/04/99 6:29p Dave
* First full working rev of FS2 PXO support. Fixed Glide lighting
* problems.
*
* 17 2/03/99 11:44a Dave
* Fixed d3d transparent textures.
*
* 16 1/15/99 11:29a Neilk
* Fixed D3D screen/texture pixel formatting problem.
*
* 15 1/14/99 12:48a Dave
* Todo list bug fixes. Made a pass at putting briefing icons back into
* FRED. Sort of works :(
*
* 14 1/12/99 12:53a Dave
* More work on beam weapons - made collision detection very efficient -
* collide against all object types properly - made 3 movement types
* smooth. Put in test code to check for possible non-darkening pixels on
* object textures.
*
* 13 1/08/99 2:08p Dave
* Fixed software rendering for pofview. Super early support for AWACS and
* beam weapons.
*
* 12 1/06/99 2:24p Dave
* Stubs and release build fixes.
*
* 11 12/14/98 4:01p Dave
* Got multi_data stuff working well with new xfer stuff.
*
* 10 12/06/98 2:36p Dave
* Drastically improved nebula fogging.
*
* 9 12/01/98 5:53p Dave
* Simplified the way pixel data is swizzled. Fixed tga bitmaps to work
* properly in D3D and Glide.
*
* 8 12/01/98 4:46p Dave
* Put in targa bitmap support (16 bit).
*
* 7 12/01/98 10:32a Johnson
* Fixed direct3d font problems. Fixed sun bitmap problem. Fixed direct3d
* starfield problem.
*
* 6 12/01/98 8:06a Dave
* Temporary checkin to fix some texture transparency problems in d3d.
*
* 5 11/30/98 5:31p Dave
* Fixed up Fred support for software mode.
*
* 4 11/30/98 1:07p Dave
* 16 bit conversion, first run.
*
* 3 10/22/98 6:14p Dave
* Optimized some #includes in Anim folder. Put in the beginnings of
* parse/localization support for externalized strings and tstrings.tbl
*
* 2 10/07/98 10:52a Dave
* Initial checkin.
*
* 1 10/07/98 10:48a Dave
*
* 106 5/23/98 4:43p John
* Took out debugging sleep
*
* 105 5/23/98 4:14p John
* Added code to preload textures to video card for AGP. Added in code
* to page in some bitmaps that weren't getting paged in at level start.
*
* 104 5/20/98 12:59p John
* Turned optimizations on for debug builds. Also turning on automatic
* function inlining. Turned off the unreachable code warning.
*
* 103 5/20/98 10:20a Hoffoss
* Fixed warning in the code.
*
* 102 5/19/98 3:45p John
* fixed bug causing lowmem to drop half of the frames. Also halved fps
* during lowmem.
*
* 101 5/14/98 3:38p John
* Added in more non-darkening colors for Adam. Had to fix some bugs in
* BmpMan and Ani stuff to get this to work.
*
* 100 4/22/98 9:13p John
* Added code to replace frames of animations in vram if so desired.
*
* 99 4/17/98 6:56a John
* Fixed bug where RLE'd user bitmaps caused data to not get freed.
* (Turned off RLE for use bitmaps). Made lossy animations reduce
* resolution by a factor of 2 in low memory conditions.
*
* 98 4/16/98 6:31p Hoffoss
* Added function to get filename of a bitmap handle, which we don't have
* yet and I need.
*
* 97 4/01/98 9:27p John
* Fixed debug info in bmpman.
*
* 96 4/01/98 5:34p John
* Made only the used POFs page in for a level. Reduced some interp
* arrays. Made custom detail level work differently.
*
* 95 3/31/98 9:55a Lawrance
* JOHN: get xparency working for user bitmaps
*
* 94 3/30/98 4:02p John
* Made machines with < 32 MB of RAM use every other frame of certain
* bitmaps. Put in code to keep track of how much RAM we've malloc'd.
*
* 93 3/29/98 4:05p John
* New paging code that loads everything necessary at level startup.
*
* 92 3/27/98 11:20a John
* commented back in some debug code.
*
* 91 3/26/98 5:21p John
* Added new code to preload all bitmaps at the start of a level.
* Commented it out, though.
*
* 90 3/26/98 4:56p Jasen
* AL: Allow find_block_of() to allocate a series of bitmaps from index 0
*
* 89 3/26/98 10:21a John
* Made no palette-mapped bitmaps use 0,255,0 as transparent.
*
* 88 3/24/98 5:39p John
* Added debug code to show bitmap fragmentation. Made user bitmaps
* allocate from top of array.
*
* 87 3/22/98 3:28p John
* Added in stippled alpha for lower details. Made medium detail use
* engine glow.
*
* 86 3/11/98 1:55p John
* Fixed warnings
*
* 85 3/06/98 4:09p John
* Changed the way we do bitmap RLE'ing... this speds up HUD bitmaps by
* about 2x
*
* 84 3/02/98 6:00p John
* Moved MAX_BITMAPS into BmpMan.h so the stuff in the graphics code that
* is dependent on it won't break if it changes. Made ModelCache slots
* be equal to MAX_OBJECTS which is what it is.
*
* 83 3/02/98 9:51a John
* Added code to print the number of bitmap slots in use between levels.
*
* 82 2/16/98 3:54p John
* Changed a bunch of mprintfs to categorize to BmpInfo
*
* 81 2/13/98 5:00p John
* Made user bitmaps not get wrote to level cache file.
*
* 80 2/06/98 8:25p John
* Added code for new bitmaps since last frame
*
* 79 2/06/98 8:10p John
* Added code to show amout of texture usage each frame.
*
* 78 2/05/98 9:21p John
* Some new Direct3D code. Added code to monitor a ton of stuff in the
* game.
*
* 77 1/29/98 11:48a John
* Added new counter measure rendering as model code. Made weapons be
* able to have impact explosion.
*
* 76 1/28/98 6:19p Dave
* Reduced standalone memory usage ~8 megs. Put in support for handling
* multiplayer submenu handling for endgame, etc.
*
* 75 1/17/98 12:55p John
* Fixed bug that I just created that loaded all ani frames.
*
* 74 1/17/98 12:33p John
* Made the game_busy function be called a constant amount of times per
* level load, making the bar prediction easier.
*
* 73 1/17/98 12:14p John
* Added loading... bar to freespace.
*
* 72 1/11/98 3:20p John
* Made so that if no .clt exists, it will load all the bitmaps
*
* 71 1/11/98 3:06p John
* Made bitmap loading stop when cache gets full.
*
* 70 1/11/98 2:45p John
* Changed .lst to .clt
*
* 69 1/11/98 2:14p John
* Changed a lot of stuff that had to do with bitmap loading. Made cfile
* not do callbacks, I put that in global code. Made only bitmaps that
* need to load for a level load.
*
* 67 1/09/98 4:07p John
* Made all bitmap functions return a bitmap "Handle" not number. This
* helps to find bm_release errors.
*
* 66 1/09/98 1:38p John
* Fixed some bugs from previous comment
*
* 65 1/09/98 1:32p John
* Added some debugging code to track down a weird error. Namely I fill
* in the be structure with bogus values when someone frees it.
*
* 64 12/28/97 2:00p John
* put in another assert checking for invalid lock/unlock sequencing
*
* 63 12/24/97 2:02p John
* Changed palette translation to be a little faster for unoptimized
* builds
*
* 62 12/18/97 8:59p Dave
* Finished putting in basic support for weapon select and ship select in
* multiplayer.
*
* 61 12/15/97 10:27p John
* fixed bug where 2 bm_loads of same file both open the header.
*
* 60 12/08/97 2:17p John
* fixed bug with bmpman and cf_callback.
* made cf_callback in Freespace set small font back when done.
*
* 59 12/03/97 5:01p Lawrance
* bump up MAX_BITMAPS to 1500. People have reached 1000 bitmaps while
* playing multiple missions.
*
* 58 12/02/97 3:59p John
* Added first rev of thruster glow, along with variable levels of
* translucency, which retquired some restructing of palman.
*
* 57 11/30/97 3:57p John
* Made fixed 32-bpp translucency. Made BmpMan always map translucent
* color into 255 even if you aren't supposed to remap and make it's
* palette black.
*
* 56 10/05/97 10:39a John
* fixed bug with palette on unmapped bitmaps. Made unmapped bitmaps get
* marked with xparent.
*
* 55 9/23/97 11:46a Lawrance
* fixed bug with rle'ing with spans get big
*
* 54 9/23/97 10:45a John
* made so you can tell bitblt code to rle a bitmap by passing flag to
* gr_set_bitmap
*
* 53 9/19/97 10:18a John
* fixed bug with aa animations being re-rle'd every
* frame.
*
*
* 52 9/09/97 10:08a Sandeep
* Fixed Compiler Level 4 warnings
*
* 51 9/08/97 2:02p John
* fixed typo in nprintf
*
* 50 9/08/97 1:56p John
* fixed some memory housekeeping bugs
*
* 49 9/03/97 4:19p John
* changed bmpman to only accept ani and pcx's. made passing .pcx or .ani
* to bm_load functions not needed. Made bmpman keep track of palettes
* for bitmaps not mapped into game palettes.
*
* 48 8/29/97 7:35p Lawrance
* check if .ani animation is already loaded in bm_load_animation()
*
* 47 8/25/97 11:14p Lawrance
* added support for .ani files in bm_load_animation()
*
* 46 8/17/97 2:42p Lawrance
* only flag PCX files as xparent if they have xparent pixels in them
*
* 45 8/15/97 9:57a Lawrance
* support multiple xparent entries for PCX files
*
* 44 8/05/97 10:18a Lawrance
* my_rand() being used temporarily instead of rand()
*
* 43 8/01/97 4:30p John
*
* 42 7/29/97 8:34a John
* took out png stuff
*
* 41 7/18/97 3:27p Lawrance
* have pcx files use (0,255,0) for transparency
*
* 40 7/16/97 3:07p John
*
* 39 7/10/97 8:34a John
* Added code to read TGA files.
*
* 38 6/20/97 1:50p John
* added rle code to bmpman. made gr8_aabitmap use it.
*
* 37 6/18/97 12:07p John
* fixed some color bugs
*
* 36 6/17/97 8:58p Lawrance
* fixed bug with not nulling bm.data with USER bitmaps
*
* 35 6/12/97 2:44a Lawrance
* changed bm_unlock() to take an index into bm_bitmaps(). Added
* ref_count to bitmap_entry struct
*
* 34 5/20/97 10:36a John
* Fixed problem with user bitmaps and direct3d caching.
*
* 33 5/14/97 1:59p John
* fixed a palette bug with vclips.
*
* 32 3/24/97 4:43p John
* speed up chunked collision detection by only checking cubes the vector
* goes through.
*
* 31 3/24/97 3:25p John
* Cleaned up and restructured model_collide code and fvi code. In fvi
* made code that finds uvs work.. Added bm_get_pixel to BmpMan.
*
* 30 3/11/97 2:49p Allender
*
* 29 2/18/97 9:43a Lawrance
* added Assert() in bm_release
*
* 28 1/22/97 4:29p John
* maybe fixed bug with code that counts total bytes of texture ram used.
*
* 27 1/22/97 4:19p Lawrance
* added flags to bm_create to allow transparency
*
* 26 1/21/97 5:24p John
* fixed another bug with bm_release.
*
* 25 1/21/97 5:12p John
* fixed bug with case
*
* 24 1/21/97 5:02p John
* Added code for 8bpp user bitmaps.
*
* 23 1/09/97 11:35a John
* Added some 2d functions to get/put screen images.
*
* 22 11/26/96 6:50p John
* Added some more hicolor primitives. Made windowed mode run as current
* bpp, if bpp is 8,16,or 32.
*
* 21 11/26/96 9:44a Allender
* Allow for use of different bitmap palettes
*
* 20 11/25/96 10:36a Allender
* started working on 32 bpp support. Added 15 bpp.
*
* 19 11/18/96 1:51p Allender
* fix up manager code to reread bitmaps if needed in newer bit depth
*
* 18 11/15/96 4:24p Allender
* more bmpman stuff -- only free bitmap slots when releasing copied
* texture -- otherwise, only release the data for the bitmap
*
* 17 11/15/96 3:33p Allender
* added support for converting to 16 bit textures when requested with
* bm_load. Added some other management functions
*
* 16 11/13/96 4:51p Allender
* started overhaul of bitmap manager. bm_load no longer actually load
* the data, only the info for the bitmap. Locking the bitmap now forces
* load when no data present (or will if bpp changes)
*
* $NoKeywords: $
*/
#include "bmpman/bmpman.h"
#include "pcxutils/pcxutils.h"
#include "palman/palman.h"
#include "graphics/2d.h"
#include "anim/animplay.h"
#include "io/timer.h"
#include "globalincs/systemvars.h"
#include "io/key.h"
#include "anim/packunpack.h"
#include "graphics/grinternal.h"
#include "tgautils/tgautils.h"
#include "ship/ship.h"
#include "ddsutils/ddsutils.h"
#include "cfile/cfile.h"
#include "cmdline/cmdline.h"
#include "jpgutils/jpgutils.h"
#include "openil/il_func.h" // needed for the #define's
#ifndef NDEBUG
#define BMPMAN_NDEBUG
#endif
extern int Cmdline_jpgtga;
extern int Texture_compression_enabled;
int GLOWMAP = -1;
int SPECMAP = -1;
int ENVMAP = -1;
int NORMMAP = -1; //Angelus
#define MAX_BMAP_SECTION_SIZE 256
// keep this defined to use per-ship nondarkening pixels
#define BMPMAN_SPECIAL_NONDARK
int bm_inited = 0;
#define BM_TYPE_NONE 0
#define BM_TYPE_PCX 1
#define BM_TYPE_USER 2
#define BM_TYPE_ANI 3 // in-house ANI format
#define BM_TYPE_TGA 4 // 16 or 32 bit targa
#define BM_TYPE_DXT1 5 // 24 bit with switchable alpha (compressed)
#define BM_TYPE_DXT3 6 // 32 bit with 4 bit alpha (compressed)
#define BM_TYPE_DXT5 7 // 32 bit with 8 bit alpha (compressed)
#define BM_TYPE_JPG 8 // 32 bit jpeg
uint Bm_next_signature = 0x1234;
bitmap_entry bm_bitmaps[MAX_BITMAPS];
int bm_texture_ram = 0;
// Bm_max_ram - How much RAM bmpman can use for textures.
// Set to <1 to make it use all it wants.
int Bm_max_ram = 0; //16*1024*1024; // Only use 16 MB for textures
int bm_next_handle = 1;
int Bm_paging = 0;
static int Bm_low_mem = 0;
// 16 bit pixel formats
int Bm_pixel_format = BM_PIXEL_FORMAT_ARGB;
// get and put functions for 16 bit pixels - neat bit slinging, huh?
#define BM_SET_R_ARGB(p, r) { p[1] &= ~(0x7c); p[1] |= ((r & 0x1f) << 2); }
#define BM_SET_G_ARGB(p, g) { p[0] &= ~(0xe0); p[1] &= ~(0x03); p[0] |= ((g & 0x07) << 5); p[1] |= ((g & 0x18) >> 3); }
#define BM_SET_B_ARGB(p, b) { p[0] &= ~(0x1f); p[0] |= b & 0x1f; }
#define BM_SET_A_ARGB(p, a) { p[1] &= ~(0x80); p[1] |= ((a & 0x01) << 7); }
#define BM_SET_R_D3D(p, r) { *p |= (ushort)(( (int)r / Gr_current_red->scale ) << Gr_current_red->shift); }
#define BM_SET_G_D3D(p, g) { *p |= (ushort)(( (int)g / Gr_current_green->scale ) << Gr_current_green->shift); }
#define BM_SET_B_D3D(p, b) { *p |= (ushort)(( (int)b / Gr_current_blue->scale ) << Gr_current_blue->shift); }
#define BM_SET_A_D3D(p, a) { if(a == 0){ *p = (ushort)Gr_current_green->mask; } }
#define BM_SET_R(p, r) { switch(Bm_pixel_format){ case BM_PIXEL_FORMAT_ARGB: BM_SET_R_ARGB(((char*)p), r); break; case BM_PIXEL_FORMAT_D3D: BM_SET_R_D3D(p, r); break; default: Int3(); } }
#define BM_SET_G(p, g) { switch(Bm_pixel_format){ case BM_PIXEL_FORMAT_ARGB: BM_SET_G_ARGB(((char*)p), g); break; case BM_PIXEL_FORMAT_D3D: BM_SET_G_D3D(p, g); break; default: Int3(); } }
#define BM_SET_B(p, b) { switch(Bm_pixel_format){ case BM_PIXEL_FORMAT_ARGB: BM_SET_B_ARGB(((char*)p), b); break; case BM_PIXEL_FORMAT_D3D: BM_SET_B_D3D(p, b); break; default: Int3(); } }
#define BM_SET_A(p, a) { switch(Bm_pixel_format){ case BM_PIXEL_FORMAT_ARGB: BM_SET_A_ARGB(((char*)p), a); break; case BM_PIXEL_FORMAT_D3D: BM_SET_A_D3D(p, a); break; default: Int3(); } }
// ===========================================
// Mode: 0 = High memory
// 1 = Low memory ( every other frame of ani's)
// 2 = Debug low memory ( only use first frame of each ani )
void bm_set_low_mem( int mode )
{
Assert( (mode >= 0) && (mode<=2 ));
Bm_low_mem = mode;
}
int bm_gfx_get_next_handle()
{
int n = bm_next_handle;
bm_next_handle++;
if ( bm_next_handle > 30000 ) {
bm_next_handle = 1;
}
return n;
}
// Frees a bitmaps data if it should, and
// Returns true if bitmap n can free it's data.
static void bm_free_data(int n)
{
bitmap_entry *be;
bitmap *bmp;
Assert( n >= 0 && n < MAX_BITMAPS );
be = &bm_bitmaps[n];
bmp = &be->bm;
// If there isn't a bitmap in this structure, don't
// do anything but clear out the bitmap info
if ( be->type==BM_TYPE_NONE)
goto SkipFree;
// If this bitmap doesn't have any data to free, skip
// the freeing it part of this.
if ( bmp->data == 0 )
goto SkipFree;
// Don't free up memory for user defined bitmaps, since
// BmpMan isn't the one in charge of allocating/deallocing them.
if ( ( be->type==BM_TYPE_USER ) )
goto SkipFree;
// Free up the data now!
// mprintf(( "Bitmap %d freed %d bytes\n", n, bm_bitmaps[n].data_size ));
#ifdef BMPMAN_NDEBUG
bm_texture_ram -= be->data_size;
#endif
free((void *)bmp->data);
SkipFree:
// Clear out & reset the bitmap data structure
bmp->flags = 0;
bmp->bpp = 0;
bmp->data = 0;
bmp->palette = NULL;
#ifdef BMPMAN_NDEBUG
be->data_size = 0;
#endif
be->signature = Bm_next_signature++;
}
#ifdef BMPMAN_NDEBUG
int Bm_ram_freed = 0;
static void bm_free_some_ram( int n, int size )
{
/*
if ( Bm_max_ram < 1 ) return;
if ( bm_texture_ram + size < Bm_max_ram ) return;
int current_time = timer_get_milliseconds();
while( bm_texture_ram + size > Bm_max_ram ) {
Bm_ram_freed++;
// Need to free some RAM up!
int i, oldest=-1, best_val=0;
for (i = 0; i < MAX_BITMAPS; i++) {
if ( (bm_bitmaps[i].type != BM_TYPE_NONE) && (bm_bitmaps[i].first_frame!=bm_bitmaps[n].first_frame) && (bm_bitmaps[i].ref_count==0) && (bm_bitmaps[i].data_size>0) ) {
int page_func = ( current_time-bm_bitmaps[i].last_used)*bm_bitmaps[i].data_size;
if ( (oldest==-1) || (page_func>best_val) ) {
oldest=i;
best_val = page_func;
}
}
}
if ( oldest > -1 ) {
//mprintf(( "Freeing bitmap '%s'\n", bm_bitmaps[oldest].filename ));
for (i=0; i<bm_bitmaps[oldest].num_frames; i++ ) {
bm_free_data(bm_bitmaps[oldest].first_frame+i);
}
} else {
//mprintf(( "Couldn't free enough! %d\n", bm_texture_ram ));
break;
}
}
*/
}
#endif
static void *bm_malloc( int n, int size )
{
Assert( n >= 0 && n < MAX_BITMAPS );
// mprintf(( "Bitmap %d allocated %d bytes\n", n, size ));
#ifdef BMPMAN_NDEBUG
bm_free_some_ram( n, size );
Assert( bm_bitmaps[n].data_size == 0 );
bm_bitmaps[n].data_size += size;
bm_texture_ram += size;
#endif
return malloc(size);
}
void bm_gfx_close()
{
int i;
if ( bm_inited ) {
for (i=0; i<MAX_BITMAPS; i++ ) {
bm_free_data(i); // clears flags, bbp, data, etc
}
bm_inited = 0;
}
}
void bm_gfx_init()
{
int i;
mprintf(( "Size of bitmap info = %d KB\n", sizeof( bm_bitmaps )/1024 ));
mprintf(( "Size of bitmap extra info = %d bytes\n", sizeof( bm_extra_info ) ));
if (!bm_inited) {
bm_inited = 1;
atexit(bm_close);
}
for (i=0; i<MAX_BITMAPS; i++ ) {
bm_bitmaps[i].filename[0] = '\0';
bm_bitmaps[i].type = BM_TYPE_NONE;
bm_bitmaps[i].info.user.data = NULL;
bm_bitmaps[i].bm.data = 0;
bm_bitmaps[i].bm.palette = NULL;
#ifdef BMPMAN_NDEBUG
bm_bitmaps[i].data_size = 0;
bm_bitmaps[i].used_count = 0;
bm_bitmaps[i].used_last_frame = 0;
bm_bitmaps[i].used_this_frame = 0;
#endif
bm_free_data(i); // clears flags, bbp, data, etc
}
}
#ifdef BMPMAN_NDEBUG
// Returns number of bytes of bitmaps locked this frame
// ntotal = number of bytes of bitmaps locked this frame
// nnew = number of bytes of bitmaps locked this frame that weren't locked last frame
void bm_gfx_get_frame_usage(int *ntotal, int *nnew)
{
int i;
*ntotal = 0;
*nnew = 0;
for (i=0; i<MAX_BITMAPS; i++ ) {
if ( (bm_bitmaps[i].type != BM_TYPE_NONE) && (bm_bitmaps[i].used_this_frame)) {
if ( !bm_bitmaps[i].used_last_frame ) {
*nnew += bm_bitmaps[i].bm.w*bm_bitmaps[i].bm.h;
}
*ntotal += bm_bitmaps[i].bm.w*bm_bitmaps[i].bm.h;
}
bm_bitmaps[i].used_last_frame = bm_bitmaps[i].used_this_frame;
bm_bitmaps[i].used_this_frame = 0;
}
}
#else
void bm_gfx_get_frame_usage(int *ntotal, int *nnew)
{
}
#endif
// given a loaded bitmap with valid info, calculate sections
void bm_calc_sections(bitmap *be)
{
int idx;
// number of x and y sections
be->sections.num_x = (ubyte)(be->w / MAX_BMAP_SECTION_SIZE);
if((be->sections.num_x * MAX_BMAP_SECTION_SIZE) < be->w){
be->sections.num_x++;
}
be->sections.num_y = (ubyte)(be->h / MAX_BMAP_SECTION_SIZE);
if((be->sections.num_y * MAX_BMAP_SECTION_SIZE) < be->h){
be->sections.num_y++;
}
// calculate the offsets for each section
for(idx=0; idx<be->sections.num_x; idx++){
be->sections.sx[idx] = (ushort)(MAX_BMAP_SECTION_SIZE * idx);
}
for(idx=0; idx<be->sections.num_y; idx++){
be->sections.sy[idx] = (ushort)(MAX_BMAP_SECTION_SIZE * idx);
}
}
// Creates a bitmap that exists in RAM somewhere, instead
// of coming from a disk file. You pass in a pointer to a
// block of 32 (or 8)-bit-per-pixel data. Right now, the only
// bpp you can pass in is 32 or 8. On success, it returns the
// bitmap number. You cannot free that RAM until bm_release
// is called on that bitmap.
int bm_gfx_create( int bpp, int w, int h, void * data, int flags )
{
int i, n, first_slot = MAX_BITMAPS;
// Assert((bpp==32)||(bpp==8));
if(bpp == 8){
Assert(flags & BMP_AABITMAP);
} else {
Assert( (bpp == 16) || (bpp == 32) );
}
if ( !bm_inited ) bm_init();
for (i = MAX_BITMAPS-1; i >= 0; i-- ) {
if ( bm_bitmaps[i].type == BM_TYPE_NONE ) {
first_slot = i;
break;
}
}
n = first_slot;
Assert( n > -1 );
// Out of bitmap slots
if ( n == -1 ) return -1;
memset( &bm_bitmaps[n], 0, sizeof(bitmap_entry) );
sprintf( bm_bitmaps[n].filename, "TMP%dx%d", w, h );
bm_bitmaps[n].type = BM_TYPE_USER;
bm_bitmaps[n].palette_checksum = 0;
bm_bitmaps[n].bm.w = (short) w;
bm_bitmaps[n].bm.h = (short) h;
bm_bitmaps[n].bm.rowsize = (short) w;
bm_bitmaps[n].bm.bpp = (unsigned char) bpp;
bm_bitmaps[n].bm.flags = 0;
bm_bitmaps[n].bm.flags |= flags;
bm_bitmaps[n].bm.data = 0;
bm_bitmaps[n].bm.palette = NULL;
bm_bitmaps[n].info.user.bpp = ubyte(bpp);
bm_bitmaps[n].info.user.data = data;
bm_bitmaps[n].info.user.flags = ubyte(flags);
bm_bitmaps[n].signature = Bm_next_signature++;
bm_bitmaps[n].handle = bm_get_next_handle()*MAX_BITMAPS + n;
bm_bitmaps[n].last_used = -1;
// fill in section info
bm_calc_sections(&bm_bitmaps[n].bm);
return bm_bitmaps[n].handle;
}
// sub helper function. Given a raw filename and an extension, try and find the bitmap
// returns -1 if it could not be found
// 0 if it was found as a file
// 1 if it already exists, fills in handle
int Bm_ignore_duplicates = 0;
int bm_load_sub(char *real_filename, char *ext, int *handle)
{
int i;
char filename[MAX_FILENAME_LEN] = "";
strcpy( filename, real_filename );
strcat( filename, ext );
for (i=0; i<(int)strlen(filename); i++ ){
filename[i] = char(tolower(filename[i]));
}
// try to find given filename to see if it has been loaded before
if(!Bm_ignore_duplicates){
for (i = 0; i < MAX_BITMAPS; i++) {
if ( (bm_bitmaps[i].type != BM_TYPE_NONE) && !stricmp(filename, bm_bitmaps[i].filename) ) {
nprintf (("BmpMan", "Found bitmap %s -- number %d\n", filename, i));
*handle = bm_bitmaps[i].handle;
return 1;
}
}
}
// try and find the file
CFILE *test = cfopen(filename, "rb");
if(test != NULL){
cfclose(test);
return 0;
}
// could not be found
return -1;
}
// This loads a bitmap so we can draw with it later.
// It returns a negative number if it couldn't load
// the bitmap. On success, it returns the bitmap
// number. Function doesn't acutally load the data, only
// width, height, and possibly flags.
int bm_gfx_load( char * real_filename )
{
int i, n, first_slot = MAX_BITMAPS;
int w, h, bpp, lvls = 0;
char filename[MAX_FILENAME_LEN];
int tga = 0;
int dds = 0;
int jpg = 0;
int handle;
int found = 0;
unsigned char type;
if ( !bm_inited ) bm_init();
// nice little trick for keeping standalone memory usage way low - always return a bogus bitmap
if(Game_mode & GM_STANDALONE_SERVER){
return -1;
}
// if no file was passed then get out now
if (strlen(real_filename) <= 0) {
return -1;
}
// make sure no one passed an extension
strcpy( filename, real_filename );
char *p = strchr( filename, '.' );
if ( p ) {
mprintf(( "Someone passed an extension to bm_load for file '%s'\n", real_filename ));
//Int3();
*p = 0;
}
if (Cmdline_jpgtga)
{
FILE *fp = fopen("imped.txt", "w");
fclose(fp);
if(!found)
{
// try and find the tga file
switch(bm_load_sub(filename, ".tga", &handle)){
// error
case -1:
break;
// found as a file
case 0:
found = 1;
strcat(filename, ".tga");
tga = 1;
break;
// found as pre-existing
case 1:
found = 1;
return handle;
}
}
if (!found)
{
// try and fine the jpg file
switch(bm_load_sub(filename, ".jpg", &handle)){
// error
case -1:
break;
// found as a file
case 0:
found = 1;
strcat(filename, ".jpg");
jpg = 1;
break;
// found as pre-existing
case 1:
found = 1;
return handle;
}
}
}
// try and use a compressed texture before a pcx
if (Texture_compression_enabled)
{
if (!found)
{
switch(bm_load_sub(filename, ".dds", &handle)){
// error
case -1:
break;
// found as a file
case 0:
found = 1;
dds=1;
strcat(filename, ".dds");
break;
// found as pre-existing
case 1:
found = 1;
return handle;
}
}
}
if (!found)
{
// try and find the pcx file
switch(bm_load_sub(filename, ".pcx", &handle)){
// error
case -1:
break;
// found as a file
case 0:
found = 1;
strcat(filename, ".pcx");
break;
// found as pre-existing
case 1:
found = 1;
return handle;
}
}
if(!found){
// try and find the tga file
switch(bm_load_sub(filename, ".tga", &handle)){
// error
case -1:
return -1;
break;
// found as a file
case 0:
strcat(filename, ".tga");
tga = 1;
break;
// found as pre-existing
case 1:
return handle;
}
}
if (dds)
{
int ct;
int dds_error=dds_read_header ( filename, &w, &h, &bpp, &ct, &lvls);
if (dds_error != DDS_ERROR_NONE)
{
mprintf(("dds: Couldn't open '%s -- error description %s\n", filename, dds_error_string(dds_error)));
return -1;
}
mprintf(("Found a .dds file! %s\n", filename));
switch (ct)
{
case DDS_DXT1:
type=BM_TYPE_DXT1;
break;
case DDS_DXT3:
type=BM_TYPE_DXT3;
break;
case DDS_DXT5:
type=BM_TYPE_DXT5;
break;
default:
Error(LOCATION, "bad DDS file compression. Not using DXT1,3,5 %s", filename);
return -1;
}
}
// if its a tga file
else if(tga){
int tga_error=targa_read_header( filename, &w, &h, &bpp, NULL );
if ( tga_error != TARGA_ERROR_NONE ) {
mprintf(( "tga: Couldn't open '%s'\n", filename ));
return -1;
}
type = BM_TYPE_TGA;
}
// if its a jpg file
else if(jpg){
int jpg_error=jpeg_read_header( filename, &w, &h, &bpp, NULL );
if ( jpg_error != JPEG_ERROR_NONE ) {
mprintf(( "jpg: Couldn't open '%s'\n", filename ));
return -1;
}
type = BM_TYPE_JPG;
}
// if its a pcx file
else {
int pcx_error=pcx_read_header( filename, &w, &h, NULL );
if ( pcx_error != PCX_ERROR_NONE ) {
mprintf(( "pcx: Couldn't open '%s'\n", filename ));
return -1;
}
type=BM_TYPE_PCX;
}
// Error( LOCATION, "Unknown bitmap type %s\n", filename );
// Find an open slot
for (i = 0; i < MAX_BITMAPS; i++) {
if ( (bm_bitmaps[i].type == BM_TYPE_NONE) && (first_slot == MAX_BITMAPS) ){
first_slot = i;
}
}
n = first_slot;
Assert( n < MAX_BITMAPS );
if ( n == MAX_BITMAPS ) return -1;
// ensure fields are cleared out from previous bitmap
// Assert(bm_bitmaps[n].bm.data == 0);
// Assert(bm_bitmaps[n].bm.palette == NULL);
// Assert(bm_bitmaps[n].ref_count == 0 );
// Assert(bm_bitmaps[n].user_data == NULL);
memset( &bm_bitmaps[n], 0, sizeof(bitmap_entry) );
// Mark the slot as filled, because cf_read might load a new bitmap
// into this slot.
bm_bitmaps[n].type = type;
bm_bitmaps[n].signature = Bm_next_signature++;
Assert ( strlen(filename) < MAX_FILENAME_LEN );
strncpy(bm_bitmaps[n].filename, filename, MAX_FILENAME_LEN-1 );
bm_bitmaps[n].bm.w = short(w);
bm_bitmaps[n].bm.rowsize = short(w);
bm_bitmaps[n].bm.h = short(h);
bm_bitmaps[n].bm.bpp = 0;
bm_bitmaps[n].bm.flags = 0;
bm_bitmaps[n].bm.data = 0;
bm_bitmaps[n].bm.palette = NULL;
bm_bitmaps[n].num_mipmaps = lvls;
bm_bitmaps[n].palette_checksum = 0;
bm_bitmaps[n].handle = bm_get_next_handle()*MAX_BITMAPS + n;
bm_bitmaps[n].last_used = -1;
// fill in section info
bm_calc_sections(&bm_bitmaps[n].bm);
return bm_bitmaps[n].handle;
}
// special load function. basically allows you to load a bitmap which already exists (by filename).
// this is useful because in some cases we need to have a bitmap which is locked in screen format
// _and_ texture format, such as pilot pics and squad logos
int bm_gfx_load_duplicate(char *filename)
{
int ret;
// ignore duplicates
Bm_ignore_duplicates = 1;
// load
ret = bm_load(filename);
// back to normal
Bm_ignore_duplicates = 0;
return ret;
}
DCF(bm_frag,"Shows BmpMan fragmentation")
{
if ( Dc_command ) {
gr_clear();
int x=0, y=0;
int xs=2, ys=2;
int w=4, h=4;
for (int i=0; i<MAX_BITMAPS; i++ ) {
switch( bm_bitmaps[i].type ) {
case BM_TYPE_NONE:
gr_set_color(128,128,128);
break;
case BM_TYPE_PCX:
gr_set_color(255,0,0);
break;
case BM_TYPE_USER:
gr_set_color(0,255,0);
break;
case BM_TYPE_ANI:
gr_set_color(0,0,255);
break;
}
gr_rect( x+xs, y+ys, w, h );
x += w+xs+xs;
if ( x > 639 ) {
x = 0;
y += h + ys + ys;
}
}
gr_flip();
key_getch();
}
}
static int find_block_of(int n)
{
int i, cnt, nstart;
cnt=0;
nstart = 0;
for (i=0; i<MAX_BITMAPS; i++ ) {
if ( bm_bitmaps[i].type == BM_TYPE_NONE ) {
if (cnt==0) nstart = i;
cnt++;
} else
cnt=0;
if ( cnt == n ) return nstart;
}
// Error( LOCATION, "Couldn't find block of %d frames\n", n );
return -1;
}
// ------------------------------------------------------------------
// bm_load_animation()
//
// input: filename => filename of animation
// nframes => OUTPUT parameter: number of frames in the animation
// fps => OUTPUT/OPTIONAL parameter: intended fps for the animation
//
// returns: bitmap number of first frame in the animation
//
int bm_gfx_load_animation( char *real_filename, int *nframes, int *fps, int can_drop_frames, int dir_type)
{
int i, n;
anim the_anim;
CFILE *fp;
char filename[MAX_FILENAME_LEN];
if ( !bm_inited ) bm_init();
strcpy( filename, real_filename );
char *p = strchr( filename, '.' );
if ( p ) {
mprintf(( "Someone passed an extension to bm_load_animation for file '%s'\n", real_filename ));
//Int3();
*p = 0;
}
strcat( filename, ".ani" );
if ( (fp = cfopen(filename, "rb", CFILE_NORMAL, dir_type)) == NULL ) {
// Error(LOCATION,"Could not open filename %s in bm_load_ani()\n", filename);
return -1;
}
int reduced = 0;
#ifndef NDEBUG
// for debug of ANI sizes
strcpy(the_anim.name, real_filename);
#endif
anim_read_header(&the_anim, fp);
if ( can_drop_frames ) {
if ( Bm_low_mem == 1 ) {
reduced = 1;
the_anim.total_frames = ( the_anim.total_frames+1)/2;
} else if ( Bm_low_mem == 2 ) {
the_anim.total_frames = 1;
}
}
cfclose(fp);
*nframes = the_anim.total_frames;
if ( fps != NULL ) {
if ( reduced ) {
*fps = the_anim.fps / 2;
} else {
*fps = the_anim.fps;
}
}
// first check to see if this ani already has it's frames loaded
for (i = 0; i < MAX_BITMAPS; i++) {
if ( (bm_bitmaps[i].type == BM_TYPE_ANI) && !stricmp(filename, bm_bitmaps[i].filename) ) {
break;
}
}
if ( i < MAX_BITMAPS ) {
// in low memory modes this can happen
if(!Bm_low_mem){
Assert(bm_bitmaps[i].info.ani.num_frames == *nframes);
}
return bm_bitmaps[i].handle;
}
n = find_block_of(*nframes);
if(n < 0){
return -1;
}
// Assert( n >= 0 );
int first_handle = bm_get_next_handle();
Assert ( strlen(filename) < MAX_FILENAME_LEN );
for ( i = 0; i < *nframes; i++ ) {
memset( &bm_bitmaps[n+i], 0, sizeof(bitmap_entry) );
bm_bitmaps[n+i].info.ani.first_frame = n;
bm_bitmaps[n+i].info.ani.num_frames = ubyte(the_anim.total_frames);
bm_bitmaps[n+i].info.ani.fps = ubyte(the_anim.fps);
bm_bitmaps[n+i].bm.w = short(the_anim.width);
bm_bitmaps[n+i].bm.rowsize = short(the_anim.width);
bm_bitmaps[n+i].bm.h = short(the_anim.height);
if ( reduced ) {
bm_bitmaps[n+i].bm.w /= 2;
bm_bitmaps[n+i].bm.rowsize /= 2;
bm_bitmaps[n+i].bm.h /= 2;
}
bm_bitmaps[n+i].bm.flags = 0;
bm_bitmaps[n+i].bm.bpp = 0;
bm_bitmaps[n+i].bm.data = 0;
bm_bitmaps[n+i].bm.palette = NULL;
bm_bitmaps[n+i].type = BM_TYPE_ANI;
bm_bitmaps[n+i].palette_checksum = 0;
bm_bitmaps[n+i].signature = Bm_next_signature++;
bm_bitmaps[n+i].handle = first_handle*MAX_BITMAPS + n+i;
bm_bitmaps[n+i].last_used = -1;
// fill in section info
bm_calc_sections(&bm_bitmaps[n+i].bm);
if ( i == 0 ) {
sprintf( bm_bitmaps[n+i].filename, "%s", filename );
} else {
sprintf( bm_bitmaps[n+i].filename, "%s[%d]", filename, i );
}
}
return bm_bitmaps[n].handle;
}
// Gets info. w,h,or flags,nframes or fps can be NULL if you don't care.
void bm_gfx_get_info( int handle, int *w, int * h, ubyte * flags, int *nframes, int *fps, bitmap_section_info **sections )
{
bitmap * bmp;
if ( !bm_inited ) return;
int bitmapnum = handle % MAX_BITMAPS;
Assert( bm_bitmaps[bitmapnum].handle == handle ); // INVALID BITMAP HANDLE!
if ( (bm_bitmaps[bitmapnum].type == BM_TYPE_NONE) || (bm_bitmaps[bitmapnum].handle != handle) ) {
if (w) *w = 0;
if (h) *h = 0;
if (flags) *flags = 0;
if (nframes) *nframes=0;
if (fps) *fps=0;
if (sections != NULL) *sections = NULL;
return;
}
bmp = &(bm_bitmaps[bitmapnum].bm);
if (w) *w = bmp->w;
if (h) *h = bmp->h;
if (flags) *flags = bmp->flags;
if ( bm_bitmaps[bitmapnum].type == BM_TYPE_ANI ) {
if (nframes) {
*nframes = bm_bitmaps[bitmapnum].info.ani.num_frames;
}
if (fps) {
*fps= bm_bitmaps[bitmapnum].info.ani.fps;
}
} else {
if (nframes) {
*nframes = 1;
}
if (fps) {
*fps= 0;
}
}
if(sections != NULL){
*sections = &bm_bitmaps[bitmapnum].bm.sections;
}
}
uint bm_get_signature( int handle )
{
if ( !bm_inited ) bm_init();
int bitmapnum = handle % MAX_BITMAPS;
Assert( bm_bitmaps[bitmapnum].handle == handle ); // INVALID BITMAP HANDLE
return bm_bitmaps[bitmapnum].signature;
}
extern int palman_is_nondarkening(int r,int g, int b);
static void bm_convert_format( int bitmapnum, bitmap *bmp, ubyte bpp, ubyte flags )
{
int idx;
int r, g, b, a;
if(Pofview_running || Is_standalone){
Assert(bmp->bpp == 8);
return;
}
else
{
if(flags & BMP_AABITMAP){
Assert(bmp->bpp == 8);
} else {
Assert( (bmp->bpp == 16) || (bmp->bpp == 32) );
}
}
// maybe swizzle to be an xparent texture
if(!(bmp->flags & BMP_TEX_XPARENT) && (flags & BMP_TEX_XPARENT)){
for(idx=0; idx<bmp->w*bmp->h; idx++){
// if the pixel is transparent
if ( ((ushort*)bmp->data)[idx] == Gr_t_green.mask) {
switch(Bm_pixel_format){
// 1555, all we need to do is zero the whole thing
case BM_PIXEL_FORMAT_ARGB:
case BM_PIXEL_FORMAT_ARGB_D3D:
((ushort*)bmp->data)[idx] = 0;
break;
// d3d format
case BM_PIXEL_FORMAT_D3D:
r = g = b = a = 0;
r /= Gr_t_red.scale;
g /= Gr_t_green.scale;
b /= Gr_t_blue.scale;
a /= Gr_t_alpha.scale;
((ushort*)bmp->data)[idx] = (unsigned short)((a<<Gr_t_alpha.shift) | (r << Gr_t_red.shift) | (g << Gr_t_green.shift) | (b << Gr_t_blue.shift));
break;
default:
Int3();
}
}
}
bmp->flags |= BMP_TEX_XPARENT;
}
}
// basically, map the bitmap into the current palette. used to be done for all pcx's, now just for
// Fred, since its the only thing that uses the software tmapper
void bm_swizzle_8bit_for_fred(bitmap_entry *be, bitmap *bmp, ubyte *data, ubyte *palette)
{
int pcx_xparent_index = -1;
int i;
int r, g, b;
ubyte palxlat[256];
for (i=0; i<256; i++ ) {
r = palette[i*3];
g = palette[i*3+1];
b = palette[i*3+2];
if ( g == 255 && r == 0 && b == 0 ) {
palxlat[i] = 255;
pcx_xparent_index = i;
} else {
palxlat[i] = (ubyte)(palette_find( r, g, b ));
}
}
for (i=0; i<bmp->w * bmp->h; i++ ) {
ubyte c = palxlat[data[i]];
data[i] = c;
}
be->palette_checksum = gr_palette_checksum;
}
void bm_lock_pcx( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
{
ubyte *data, *palette;
ubyte pal[768];
palette = NULL;
int pcx_error;
// Unload any existing data
bm_free_data( bitmapnum );
if ( (bpp == 16) && Cmdline_pcx32) {
bpp = 32;
}
// allocate bitmap data
if(bpp == 8){
// Assert(Fred_running || Pofview_running || Is_standalone);
data = (ubyte *)bm_malloc(bitmapnum, bmp->w * bmp->h );
#ifdef BMPMAN_NDEBUG
Assert( be->data_size == bmp->w * bmp->h );
#endif
palette = pal;
bmp->data = (uint)data;
bmp->bpp = 8;
bmp->palette = gr_palette;
memset( data, 0, bmp->w * bmp->h);
} else if (bpp == 32) {
data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h * 4);
bmp->bpp = 32;
bmp->data = (uint)data;
bmp->palette = NULL;
memset( data, 0, bmp->w * bmp->h * 4 );
} else {
data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h * 2);
bmp->bpp = 16;
bmp->data = (uint)data;
bmp->palette = NULL;
memset( data, 0, bmp->w * bmp->h * 2);
}
Assert( &be->bm == bmp );
#ifdef BMPMAN_NDEBUG
Assert( be->data_size > 0 );
#endif
// some sanity checks on flags
Assert(!((flags & BMP_AABITMAP) && (flags & BMP_TEX_ANY))); // no aabitmap textures
Assert(!((flags & BMP_TEX_XPARENT) && (flags & BMP_TEX_NONDARK))); // can't be a transparent texture and a nondarkening texture
if(bpp == 8){
pcx_error = pcx_read_bitmap_8bpp( be->filename, data, palette );
if ( pcx_error != PCX_ERROR_NONE ) {
// Error( LOCATION, "Couldn't open '%s'\n", be->filename );
//Error( LOCATION, "Couldn't open '%s'\n", filename );
//return -1;
}
// now swizzle the thing into the proper format
if(Pofview_running){
bm_swizzle_8bit_for_fred(be, bmp, data, palette);
}
} else if (bpp == 32) {
pcx_error = pcx_read_bitmap_32( be->filename, data );
if ( pcx_error != PCX_ERROR_NONE ) {
// Error( LOCATION, "Couldn't open '%s'\n", be->filename );
//Error( LOCATION, "Couldn't open '%s'\n", filename );
//return -1;
}
} else {
// load types
if(flags & BMP_AABITMAP){
pcx_error = pcx_read_bitmap_16bpp_aabitmap( be->filename, data );
} else if(flags & BMP_TEX_NONDARK){
pcx_error = pcx_read_bitmap_16bpp_nondark( be->filename, data );
} else {
pcx_error = pcx_read_bitmap_16bpp( be->filename, data );
}
if ( pcx_error != PCX_ERROR_NONE ) {
// Error( LOCATION, "Couldn't open '%s'\n", be->filename );
//Error( LOCATION, "Couldn't open '%s'\n", filename );
//return -1;
}
}
#ifdef BMPMAN_NDEBUG
Assert( be->data_size > 0 );
#endif
bmp->flags = 0;
bm_convert_format( bitmapnum, bmp, bpp, flags );
}
void bm_lock_ani( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
{
anim *the_anim;
anim_instance *the_anim_instance;
bitmap *bm;
ubyte *frame_data;
int size, i;
int first_frame, nframes;
first_frame = be->info.ani.first_frame;
nframes = bm_bitmaps[first_frame].info.ani.num_frames;
if ( (the_anim = anim_load(bm_bitmaps[first_frame].filename)) == NULL ) {
// Error(LOCATION, "Error opening %s in bm_lock\n", be->filename);
}
if ( (the_anim_instance = init_anim_instance(the_anim, bpp)) == NULL ) {
// Error(LOCATION, "Error opening %s in bm_lock\n", be->filename);
anim_free(the_anim);
}
int can_drop_frames = 0;
if ( the_anim->total_frames != bm_bitmaps[first_frame].info.ani.num_frames ) {
can_drop_frames = 1;
}
bm = &bm_bitmaps[first_frame].bm;
if(bpp == 16){
size = bm->w * bm->h * 2;
} else {
size = bm->w * bm->h;
}
for ( i=0; i<nframes; i++ ) {
be = &bm_bitmaps[first_frame+i];
bm = &bm_bitmaps[first_frame+i].bm;
// Unload any existing data
bm_free_data( first_frame+i );
bm->flags = 0;
// briefing editor in Fred2 uses aabitmaps (ani's) - force to 8 bit
if(Is_standalone){
bm->bpp = 8;
} else
{
bm->bpp = bpp;
}
bm->data = (uint)bm_malloc(first_frame + i, size);
frame_data = anim_get_next_raw_buffer(the_anim_instance, 0 ,flags & BMP_AABITMAP ? 1 : 0, bm->bpp);
if ( frame_data == NULL ) {
// Error(LOCATION,"Fatal error locking .ani file: %s\n", be->filename);
}
ubyte *dptr, *sptr;
sptr = frame_data;
dptr = (ubyte *)bm->data;
if ( (bm->w!=the_anim->width) || (bm->h!=the_anim->height) ) {
// Scale it down
// Int3(); // not ready yet - should only be ingame
// 8 bit
if(bpp == 8){
int w,h;
fix u, utmp, v, du, dv;
u = v = 0;
du = ( the_anim->width*F1_0 ) / bm->w;
dv = ( the_anim->height*F1_0 ) / bm->h;
for (h = 0; h < bm->h; h++) {
ubyte *drow = &dptr[bm->w * h];
ubyte *srow = &sptr[f2i(v)*the_anim->width];
utmp = u;
for (w = 0; w < bm->w; w++) {
*drow++ = srow[f2i(utmp)];
utmp += du;
}
v += dv;
}
}
// 16 bpp
else {
int w,h;
fix u, utmp, v, du, dv;
u = v = 0;
du = ( the_anim->width*F1_0 ) / bm->w;
dv = ( the_anim->height*F1_0 ) / bm->h;
for (h = 0; h < bm->h; h++) {
ushort *drow = &((ushort*)dptr)[bm->w * h];
ushort *srow = &((ushort*)sptr)[f2i(v)*the_anim->width];
utmp = u;
for (w = 0; w < bm->w; w++) {
*drow++ = srow[f2i(utmp)];
utmp += du;
}
v += dv;
}
}
} else {
// 1-to-1 mapping
memcpy(dptr, sptr, size);
}
bm_convert_format( first_frame+i, bm, bpp, flags );
// Skip a frame
if ( (i < nframes-1) && can_drop_frames ) {
frame_data = anim_get_next_raw_buffer(the_anim_instance, 0, flags & BMP_AABITMAP ? 1 : 0, bm->bpp);
}
//mprintf(( "Checksum = %d\n", be->palette_checksum ));
}
free_anim_instance(the_anim_instance);
anim_free(the_anim);
}
void bm_lock_user( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
{
// int idx;
// ushort bit_16;
// Unload any existing data
bm_free_data( bitmapnum );
if ((bpp != be->info.user.bpp) && !(flags & BMP_AABITMAP))
bpp = be->info.user.bpp;
switch( bpp ) {
case 32: // user 32-bit bitmap
case 24:
bmp->bpp = bpp;
bmp->flags = be->info.user.flags;
bmp->data = (uint)be->info.user.data;
break;
case 16: // user 16 bit bitmap
bmp->bpp = bpp;
bmp->flags = be->info.user.flags;
bmp->data = (uint)be->info.user.data;
break;
case 8: // Going from 8 bpp to something (probably only for aabitmaps)
/*
Assert(flags & BMP_AABITMAP);
bmp->bpp = 16;
bmp->data = (uint)malloc(bmp->w * bmp->h * 2);
bmp->flags = be->info.user.flags;
bmp->palette = NULL;
// go through and map the pixels
for(idx=0; idx<bmp->w * bmp->h; idx++){
bit_16 = (ushort)((ubyte*)be->info.user.data)[idx];
Assert(bit_16 <= 255);
// stuff the final result
memcpy((char*)bmp->data + (idx * 2), &bit_16, sizeof(ushort));
}
*/
Assert(flags & BMP_AABITMAP);
bmp->bpp = bpp;
bmp->flags = be->info.user.flags;
bmp->data = (uint)be->info.user.data;
break;
// default:
// Error( LOCATION, "Unhandled user bitmap conversion from %d to %d bpp", be->info.user.bpp, bmp->bpp );
}
bm_convert_format( bitmapnum, bmp, bpp, flags );
}
void bm_lock_tga( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
{
ubyte *data = NULL;
int d_size, byte_size;
// Unload any existing data
bm_free_data( bitmapnum );
// support true color targas when requested
// then your 16bit tgas never get loaded
//if (Cmdline_jpgtga) {
// bpp = 32;
//}
int test_bpp;
targa_read_header(be->filename, NULL, NULL, &test_bpp, NULL);
if (test_bpp == 24 || test_bpp == 32)
bpp = 32;
if(Is_standalone){
Assert(bpp == 8);
}
else
{
Assert( (bpp == 16) || (bpp == 32) );
}
// should never try to make an aabitmap out of a targa
Assert(!(flags & BMP_AABITMAP));
// allocate bitmap data
byte_size = (bpp >> 3);
Assert(byte_size);
data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h * byte_size);
if (data) {
memset( data, 0, bmp->w * bmp->h * byte_size);
d_size = byte_size;
} else {
return;
}
bmp->bpp = bpp;
bmp->data = (uint)data;
bmp->palette = NULL;
Assert( &be->bm == bmp );
#ifdef BMPMAN_NDEBUG
Assert( be->data_size > 0 );
#endif
int tga_error;
if (bpp == 32) {
tga_error = targa_read_bitmap_32( be->filename, data, NULL, d_size);
} else {
tga_error = targa_read_bitmap( be->filename, data, NULL, d_size);
}
if ( tga_error != TARGA_ERROR_NONE ) {
// Error( LOCATION, "Couldn't open '%s'\n", be->filename );
//Error( LOCATION, "Couldn't open '%s'\n", filename );
//return -1;
data = NULL;
return;
}
#ifdef BMPMAN_NDEBUG
Assert( be->data_size > 0 );
#endif
bmp->flags = 0;
bm_convert_format( bitmapnum, bmp, bpp, flags );
}
//lock a dds file
void bm_lock_dds( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
{
uint data;
int size;
int error;
Assert(Texture_compression_enabled);
Assert(&be->bm == bmp);
//data is malloc'ed in the function
error=dds_read_bitmap( be->filename, &size, &data );
if (error != DDS_ERROR_NONE)
{
Error(LOCATION, "error loading %s -- %s", be->filename, dds_error_string(error));
}
bmp->bpp=bpp;
bmp->data=data;
bmp->flags =0;
be->mem_taken=size;
#ifdef BMPMAN_NDEBUG
be->data_size=size;
Assert( be->data_size > 0 );
#endif
}
// lock a JPEG file
void bm_lock_jpg( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
{
ubyte *data = NULL;
int d_size = 0;
int jpg_error = JPEG_ERROR_INVALID;
// Unload any existing data
bm_free_data( bitmapnum );
// support true color jpegs when requested
if (Cmdline_jpgtga) {
bpp = 32;
} else {
// not supported yet
return;
}
// should never try to make an aabitmap out of a jpeg
Assert(!(flags & BMP_AABITMAP));
// allocate bitmap data
if (bpp == 32) {
data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h * 4);
Assert(data);
if (data) {
memset( data, 0, bmp->w * bmp->h * 4);
d_size = 4;
} else {
return;
}
}
bmp->bpp = bpp;
bmp->data = (uint)data;
bmp->palette = NULL;
Assert( &be->bm == bmp );
if (bpp == 32) {
jpg_error = jpeg_read_bitmap_32( be->filename, data, NULL, d_size);
}
if ( jpg_error != JPEG_ERROR_NONE ) {
data = NULL;
return;
}
#ifdef BMPMAN_NDEBUG
Assert( be->data_size > 0 );
#endif
}
MONITOR( NumBitmapPage );
MONITOR( SizeBitmapPage );
// This locks down a bitmap and returns a pointer to a bitmap
// that can be accessed until you call bm_unlock. Only lock
// a bitmap when you need it! This will convert it into the
// appropriate format also.
bitmap * bm_gfx_lock( int handle, ubyte bpp, ubyte flags )
{
bitmap *bmp;
bitmap_entry *be;
if ( !bm_inited ) bm_init();
int bitmapnum = handle % MAX_BITMAPS;
Assert( bm_bitmaps[bitmapnum].handle == handle ); // INVALID BITMAP HANDLE
// flags &= (~BMP_RLE);
// to fix a couple of OGL bpp passes, force 8bit on AABITMAP - taylor
if (flags & BMP_AABITMAP)
bpp = 8;
// if we're on a standalone server, aways for it to lock to 8 bits
if(Is_standalone){
bpp = 8;
flags = 0;
}
// otherwise do it as normal
else {
if(Pofview_running){
Assert( bpp == 8 );
Assert( (bm_bitmaps[bitmapnum].type == BM_TYPE_PCX) || (bm_bitmaps[bitmapnum].type == BM_TYPE_ANI) || (bm_bitmaps[bitmapnum].type == BM_TYPE_TGA));
}
else
{
if(flags & BMP_AABITMAP){
Assert( bpp == 8 );
} else if ((flags & BMP_TEX_NONCOMP) && (!(flags & BMP_TEX_COMP))) {
Assert( (bpp == 16) || (bpp == 32) );
}
else if (flags & BMP_TEX_DXT1){
Assert(bpp==24);
}
else if (flags & (BMP_TEX_DXT3 | BMP_TEX_DXT5)){
Assert(bpp==32);
}
else
{
Assert(0); //?
}
}
}
be = &bm_bitmaps[bitmapnum];
bmp = &be->bm;
// If you hit this assert, chances are that someone freed the
// wrong bitmap and now someone is trying to use that bitmap.
// See John.
Assert( be->type != BM_TYPE_NONE );
// Increment ref count for bitmap since lock was made on it.
Assert(be->ref_count >= 0);
be->ref_count++; // Lock it before we page in data; this prevents a callback from freeing this
// as it gets read in
// Mark this bitmap as used this frame
#ifdef BMPMAN_NDEBUG
if ( be->used_this_frame < 255 ) {
be->used_this_frame++;
}
#endif
// if bitmap hasn't been loaded yet, then load it from disk
// reread the bitmap from disk under certain conditions
int pal_changed = 0;
int rle_changed = 0;
int fake_xparent_changed = 0;
// don't do a bpp check here since it could be different in OGL - taylor
if ( (bmp->data == 0) || pal_changed || rle_changed || fake_xparent_changed ) {
Assert(be->ref_count == 1);
if ( be->type != BM_TYPE_USER ) {
if ( bmp->data == 0 ) {
nprintf (("BmpMan","Loading %s for the first time.\n", be->filename));
} else if ( pal_changed ) {
nprintf (("BmpMan","Reloading %s to remap palette\n", be->filename));
} else if ( rle_changed ) {
nprintf (("BmpMan","Reloading %s to change RLE.\n", be->filename));
} else if ( fake_xparent_changed ) {
nprintf (("BmpMan","Reloading %s to change fake xparency.\n", be->filename));
}
}
MONITOR_INC( NumBitmapPage, 1 );
MONITOR_INC( SizeBitmapPage, bmp->w*bmp->h );
if ( !Bm_paging ) {
if ( be->type != BM_TYPE_USER ) {
char flag_text[64];
strcpy( flag_text, "--" );
nprintf(( "Paging", "Loading %s (%dx%dx%dx%s)\n", be->filename, bmp->w, bmp->h, bpp, flag_text ));
}
}
// select proper format
if(flags & BMP_AABITMAP){
BM_SELECT_ALPHA_TEX_FORMAT();
} else if(flags & BMP_TEX_ANY){
BM_SELECT_TEX_FORMAT();
} else {
BM_SELECT_SCREEN_FORMAT();
}
switch ( be->type ) {
case BM_TYPE_PCX:
bm_lock_pcx( handle, bitmapnum, be, bmp, bpp, flags );
break;
case BM_TYPE_ANI:
bm_lock_ani( handle, bitmapnum, be, bmp, bpp, flags );
break;
case BM_TYPE_USER:
bm_lock_user( handle, bitmapnum, be, bmp, bpp, flags );
break;
case BM_TYPE_TGA:
bm_lock_tga( handle, bitmapnum, be, bmp, bpp, flags );
break;
case BM_TYPE_JPG:
bm_lock_jpg( handle, bitmapnum, be, bmp, bpp, flags );
break;
case BM_TYPE_DXT1:
case BM_TYPE_DXT3:
case BM_TYPE_DXT5:
bm_lock_dds( handle, bitmapnum, be, bmp, bpp, flags );
break;
default:
Warning(LOCATION, "Unsupported type in bm_lock -- %d\n", be->type );
return NULL;
}
// always go back to screen format
BM_SELECT_SCREEN_FORMAT();
}
// oops, this isn't good
if ( !(bmp->data) ) {
// no data was loaded, reset everything and return NULL
bm_free_data( bitmapnum );
return NULL;
}
if ( be->type == BM_TYPE_ANI ) {
int i,first = bm_bitmaps[bitmapnum].info.ani.first_frame;
for ( i=0; i< bm_bitmaps[first].info.ani.num_frames; i++ ) {
// Mark all the bitmaps in this bitmap or animation as recently used
bm_bitmaps[first+i].last_used = timer_get_milliseconds();
// Mark all the bitmaps in this bitmap or animation as used for the usage tracker.
#ifdef BMPMAN_NDEBUG
bm_bitmaps[first+i].used_count++;
#endif
bm_bitmaps[first+i].used_flags = flags;
}
} else {
// Mark all the bitmaps in this bitmap or animation as recently used
be->last_used = timer_get_milliseconds();
// Mark all the bitmaps in this bitmap or animation as used for the usage tracker.
#ifdef BMPMAN_NDEBUG
be->used_count++;
#endif
be->used_flags = flags;
}
return bmp;
}
// Unlocks a bitmap
//
// Decrements the ref_count member of the bitmap_entry struct. A bitmap can only be unloaded
// when the ref_count is 0.
//
void bm_gfx_unlock( int handle )
{
bitmap_entry *be;
bitmap *bmp;
int bitmapnum = handle % MAX_BITMAPS;
Assert( bm_bitmaps[bitmapnum].handle == handle ); // INVALID BITMAP HANDLE
Assert(bitmapnum >= 0 && bitmapnum < MAX_BITMAPS);
if ( !bm_inited ) bm_init();
be = &bm_bitmaps[bitmapnum];
bmp = &be->bm;
be->ref_count--;
Assert(be->ref_count >= 0); // Trying to unlock data more times than lock was called!!!
}
void bm_update()
{
}
char *bm_get_filename(int handle)
{
int n;
n = handle % MAX_BITMAPS;
Assert(bm_bitmaps[n].handle == handle); // INVALID BITMAP HANDLE
return bm_bitmaps[n].filename;
}
void bm_gfx_get_palette(int handle, ubyte *pal, char *name)
{
char *filename;
int w,h;
int n= handle % MAX_BITMAPS;
Assert( bm_bitmaps[n].handle == handle ); // INVALID BITMAP HANDLE
filename = bm_bitmaps[n].filename;
if (name) {
strcpy( name, filename );
}
int pcx_error=pcx_read_header( filename, &w, &h, pal );
if ( pcx_error != PCX_ERROR_NONE ){
// Error(LOCATION, "Couldn't open '%s'\n", filename );
}
}
// --------------------------------------------------------------------------------------
// bm_release() - unloads the bitmap's data and entire slot, so bitmap 'n' won't be valid anymore
//
// parameters: n => index into bm_bitmaps ( index returned from bm_load() or bm_create() )
//
// returns: nothing
void bm_gfx_release(int handle)
{
bitmap_entry *be;
int n = handle % MAX_BITMAPS;
Assert(n >= 0 && n < MAX_BITMAPS);
be = &bm_bitmaps[n];
if ( bm_bitmaps[n].type == BM_TYPE_NONE ) {
return; // Already been released?
}
if ( bm_bitmaps[n].type != BM_TYPE_USER ) {
return;
}
Assert( be->handle == handle ); // INVALID BITMAP HANDLE
// If it is locked, cannot free it.
if (be->ref_count != 0) {
nprintf(("BmpMan", "tried to unload %s that has a lock count of %d.. not unloading\n", be->filename, be->ref_count));
return;
}
bm_free_data(n);
if ( bm_bitmaps[n].type == BM_TYPE_USER ) {
bm_bitmaps[n].info.user.data = NULL;
bm_bitmaps[n].info.user.bpp = 0;
}
bm_bitmaps[n].type = BM_TYPE_NONE;
// Fill in bogus structures!
// For debugging:
strcpy( bm_bitmaps[n].filename, "IVE_BEEN_RELEASED!" );
bm_bitmaps[n].signature = 0xDEADBEEF; // a unique signature identifying the data
bm_bitmaps[n].palette_checksum = 0xDEADBEEF; // checksum used to be sure bitmap is in current palette
// bookeeping
#ifdef BMPMAN_NDEBUG
bm_bitmaps[n].data_size = -1; // How much data this bitmap uses
#endif
bm_bitmaps[n].ref_count = -1; // Number of locks on bitmap. Can't unload unless ref_count is 0.
// Bitmap info
bm_bitmaps[n].bm.w = bm_bitmaps[n].bm.h = -1;
// Stuff needed for animations
// Stuff needed for user bitmaps
memset( &bm_bitmaps[n].info, 0, sizeof(bm_extra_info) );
bm_bitmaps[n].handle = -1;
}
// --------------------------------------------------------------------------------------
// bm_unload() - unloads the data, but not the bitmap info.
//
// parameters: n => index into bm_bitmaps ( index returned from bm_load() or bm_create() )
//
// returns: 0 => unload failed
// 1 => unload successful
//
int bm_gfx_unload( int handle )
{
bitmap_entry *be;
bitmap *bmp;
int n = handle % MAX_BITMAPS;
Assert(n >= 0 && n < MAX_BITMAPS);
be = &bm_bitmaps[n];
bmp = &be->bm;
if ( be->type == BM_TYPE_NONE ) {
return 0; // Already been released
}
//Assert( be->handle == handle ); // INVALID BITMAP HANDLE!
// If it is locked, cannot free it.
if (be->ref_count != 0) {
nprintf(("BmpMan", "tried to unload %s that has a lock count of %d.. not unloading\n", be->filename, be->ref_count));
return 0;
}
nprintf(("BmpMan", "unloading %s. %dx%dx%d\n", be->filename, bmp->w, bmp->h, bmp->bpp));
bm_free_data(n); // clears flags, bbp, data, etc
return 1;
}
// unload all used bitmaps
void bm_gfx_unload_all()
{
int i;
for (i = 0; i < MAX_BITMAPS; i++) {
if ( bm_bitmaps[i].type != BM_TYPE_NONE ) {
bm_unload(bm_bitmaps[i].handle);
}
}
}
DCF(bmpman,"Shows/changes bitmap caching parameters and usage")
{
if ( Dc_command ) {
dc_get_arg(ARG_STRING);
if ( !strcmp( Dc_arg, "flush" )) {
dc_printf( "Total RAM usage before flush: %d bytes\n", bm_texture_ram );
int i;
for (i = 0; i < MAX_BITMAPS; i++) {
if ( bm_bitmaps[i].type != BM_TYPE_NONE ) {
bm_free_data(i);
}
}
dc_printf( "Total RAM after flush: %d bytes\n", bm_texture_ram );
} else if ( !strcmp( Dc_arg, "ram" )) {
dc_get_arg(ARG_INT);
Bm_max_ram = Dc_arg_int*1024*1024;
} else {
// print usage, not stats
Dc_help = 1;
}
}
if ( Dc_help ) {
dc_printf( "Usage: BmpMan keyword\nWhere keyword can be in the following forms:\n" );
dc_printf( "BmpMan flush Unloads all bitmaps.\n" );
dc_printf( "BmpMan ram x Sets max mem usage to x MB. (Set to 0 to have no limit.)\n" );
dc_printf( "\nUse '? BmpMan' to see status of Bitmap manager.\n" );
Dc_status = 0; // don't print status if help is printed. Too messy.
}
if ( Dc_status ) {
dc_printf( "Total RAM usage: %d bytes\n", bm_texture_ram );
if ( Bm_max_ram > 1024*1024 )
dc_printf( "Max RAM allowed: %.1f MB\n", i2fl(Bm_max_ram)/(1024.0f*1024.0f) );
else if ( Bm_max_ram > 1024 )
dc_printf( "Max RAM allowed: %.1f KB\n", i2fl(Bm_max_ram)/(1024.0f) );
else if ( Bm_max_ram > 0 )
dc_printf( "Max RAM allowed: %d bytes\n", Bm_max_ram );
else
dc_printf( "No RAM limit\n" );
}
}
extern int OGL_inited;
// Marks a texture as being used for this level
void bm_gfx_page_in_texture( int bitmapnum, int nframes )
{
int i;
for (i=0; i<nframes;i++ ) {
int n = bitmapnum % MAX_BITMAPS;
bm_bitmaps[n+i].preloaded = 1;
//check if its compressed
if (OGL_inited)
{
switch (bm_bitmaps[n+i].type)
{
case BM_TYPE_DXT1:
bm_bitmaps[n+i].used_flags = BMP_TEX_DXT1;
continue;
case BM_TYPE_DXT3:
bm_bitmaps[n+i].used_flags = BMP_TEX_DXT3;
continue;
case BM_TYPE_DXT5:
bm_bitmaps[n+i].used_flags = BMP_TEX_DXT5;
continue;
}
}
bm_bitmaps[n+i].used_flags = BMP_TEX_OTHER;
}
}
// Marks a texture as being used for this level
// If num_frames is passed, assume this is an animation
void bm_gfx_page_in_nondarkening_texture( int bitmapnum, int nframes )
{
int i;
for (i=0; i<nframes;i++ ) {
int n = bitmapnum % MAX_BITMAPS;
bm_bitmaps[n+i].preloaded = 4;
bm_bitmaps[n+i].used_flags = BMP_TEX_NONDARK;
}
}
// marks a texture as being a transparent textyre used for this level
// Marks a texture as being used for this level
// If num_frames is passed, assume this is an animation
void bm_gfx_page_in_xparent_texture( int bitmapnum, int nframes)
{
int i;
for (i=0; i<nframes;i++ ) {
int n = bitmapnum % MAX_BITMAPS;
bm_bitmaps[n+i].preloaded = 3;
//check if its compressed
if (OGL_inited)
{
switch (bm_bitmaps[n+i].type)
{
case BM_TYPE_DXT1:
bm_bitmaps[n+i].used_flags = BMP_TEX_DXT1;
continue;
case BM_TYPE_DXT3:
bm_bitmaps[n+i].used_flags = BMP_TEX_DXT3;
continue;
case BM_TYPE_DXT5:
bm_bitmaps[n+i].used_flags = BMP_TEX_DXT5;
continue;
}
}
bm_bitmaps[n+i].used_flags = BMP_TEX_XPARENT;
}
}
// Marks an aabitmap as being used for this level
void bm_gfx_page_in_aabitmap( int bitmapnum, int nframes )
{
int i;
for (i=0; i<nframes;i++ ) {
int n = bitmapnum % MAX_BITMAPS;
bm_bitmaps[n+i].preloaded = 2;
bm_bitmaps[n+i].used_flags = BMP_AABITMAP;
}
}
// Tell the bitmap manager to start keeping track of what bitmaps are used where.
void bm_gfx_page_in_start()
{
int i;
Bm_paging = 1;
// Mark all as inited
for (i = 0; i < MAX_BITMAPS; i++) {
if ( bm_bitmaps[i].type != BM_TYPE_NONE ) {
bm_unload(bm_bitmaps[i].handle);
}
bm_bitmaps[i].preloaded = 0;
#ifdef BMPMAN_NDEBUG
bm_bitmaps[i].used_count = 0;
#endif
bm_bitmaps[i].used_flags = 0;
}
}
void bm_gfx_page_in_stop()
{
int i;
int ship_info_index;
int unlock = 0;
nprintf(( "BmpInfo","BMPMAN: Loading all used bitmaps.\n" ));
// Load all the ones that are supposed to be loaded for this level.
int n = 0;
#ifdef BMPMAN_NDEBUG
Bm_ram_freed = 0;
#endif
for (i = 0; i < MAX_BITMAPS; i++) {
if ( bm_bitmaps[i].type != BM_TYPE_NONE ) {
if ( bm_bitmaps[i].preloaded ) {
#ifdef BMPMAN_SPECIAL_NONDARK
// if this is a texture, check to see if a ship uses it
ship_info_index = ship_get_texture(bm_bitmaps[i].handle);
// use the colors from this ship
if((ship_info_index >= 0) && (Ship_info[ship_info_index].num_nondark_colors > 0)){
// mprintf(("Using custom pixels for %s\n", Ship_info[ship_info_index].name));
palman_set_nondarkening(Ship_info[ship_info_index].nondark_colors, Ship_info[ship_info_index].num_nondark_colors);
}
// use the colors from the default table
else {
// mprintf(("Using default pixels\n"));
palman_set_nondarkening(Palman_non_darkening_default, Palman_num_nondarkening_default);
}
#endif
// if preloaded == 3, load it as an xparent texture
if(bm_bitmaps[i].used_flags == BMP_AABITMAP){
bm_lock( bm_bitmaps[i].handle, 8, bm_bitmaps[i].used_flags );
unlock = 1;
} else if (bm_bitmaps[i].used_flags == BMP_TEX_XPARENT) {
if (!gr_preload(bm_bitmaps[i].handle, 0)) {
bm_lock( bm_bitmaps[i].handle, 16, bm_bitmaps[i].used_flags );
unlock = 1;
}
} else {
bm_lock( bm_bitmaps[i].handle, 16, bm_bitmaps[i].used_flags );
unlock = 1;
}
if (unlock)
bm_unlock( bm_bitmaps[i].handle ); // don't do this with gr_preload()
n++;
#ifdef BMPMAN_NDEBUG
if ( Bm_ram_freed ) {
nprintf(( "BmpInfo","BMPMAN: Not enough cache memory to load all level bitmaps\n" ));
break;
}
#endif
}
}
game_busy();
}
nprintf(( "BmpInfo","BMPMAN: Loaded %d bitmaps that are marked as used for this level.\n", n ));
int total_bitmaps = 0;
for (i = 0; i < MAX_BITMAPS; i++) {
if ( bm_bitmaps[i].type != BM_TYPE_NONE ) {
total_bitmaps++;
}
if ( bm_bitmaps[i].type == BM_TYPE_USER ) {
mprintf(( "User bitmap '%s'\n", bm_bitmaps[i].filename ));
}
}
mprintf(( "Bmpman: %d/%d bitmap slots in use.\n", total_bitmaps, MAX_BITMAPS ));
//mprintf(( "Bmpman: Usage went from %d KB to %d KB.\n", usage_before/1024, usage_after/1024 ));
Bm_paging = 0;
}
int bm_gfx_get_cache_slot( int bitmap_id, int separate_ani_frames )
{
int n = bitmap_id % MAX_BITMAPS;
if( bm_bitmaps[n].handle != bitmap_id ){//this should rightfully squash the invalid bitmap handel bug for the glow mapping
mprintf(("bitmap handel %d is not equil to bitmap id %d",bm_bitmaps[n].handle,bitmap_id));
return -1; // INVALID BITMAP HANDLE
}
bitmap_entry *be = &bm_bitmaps[n];
if ( (!separate_ani_frames) && (be->type == BM_TYPE_ANI) ) {
return be->info.ani.first_frame;
}
return n;
}
#ifndef NO_DIRECT3D
extern int D3D_32bit;
#endif
void (*bm_set_components)(ubyte *pixel, ubyte *r, ubyte *g, ubyte *b, ubyte *a) = NULL;
void bm_set_components_argb(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
{
// rgba
*((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
*((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
*((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
*((ushort*)pixel) &= ~(0x8000);
if(*av){
*((ushort*)pixel) |= 0x8000;
}
}
void bm_set_components_d3d(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
{
// rgba
*((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
*((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
*((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
if(*av == 0){
*((ushort*)pixel) = (ushort)Gr_current_green->mask;
}
}
void bm_set_components_argb_d3d_16_screen(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
{
*((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
*((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
*((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
if(*av == 0){
*((ushort*)pixel) = (ushort)Gr_current_green->mask;
}
}
void bm_set_components_argb_d3d_32_screen(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
{
*((uint*)pixel) |= (uint)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
*((uint*)pixel) |= (uint)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
*((uint*)pixel) |= (uint)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
if(*av == 0){
*((uint*)pixel) = (uint)Gr_current_green->mask;
}
}
void bm_set_components_argb_d3d_16_tex(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
{
*((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
*((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
*((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
*((ushort*)pixel) &= ~(Gr_current_alpha->mask);
if(*av){
*((ushort*)pixel) |= (ushort)(Gr_current_alpha->mask);
} else {
*((ushort*)pixel) = 0;
}
}
void bm_set_components_argb_d3d_32_tex(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
{
*((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
*((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
*((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
*((ushort*)pixel) &= ~(Gr_current_alpha->mask);
if(*av){
*((ushort*)pixel) |= (ushort)(Gr_current_alpha->mask);
} else {
*((ushort*)pixel) = 0;
}
}
void bm_set_components_opengl(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
{
// rgba
*((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
*((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
*((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
*((ushort*)pixel) &= ~(0x8000);
if (*((ushort*)pixel) == (ushort)Gr_current_green->mask) {
*((ushort*)pixel) = 0;
} else {
if(*av){
*((ushort*)pixel) |= 0x8000;
}
}
}
// for selecting pixel formats
void BM_SELECT_SCREEN_FORMAT()
{
Gr_current_red = &Gr_red;
Gr_current_green = &Gr_green;
Gr_current_blue = &Gr_blue;
Gr_current_alpha = &Gr_alpha;
// setup pointers
#ifdef _WIN32
if(gr_screen.mode == GR_DIRECT3D){
if(Bm_pixel_format == BM_PIXEL_FORMAT_D3D){
bm_set_components = bm_set_components_d3d;
} else {
#ifndef NO_DIRECT3D
if(D3D_32bit){
bm_set_components = bm_set_components_argb_d3d_32_screen;
} else {
bm_set_components = bm_set_components_argb_d3d_16_screen;
}
#else
bm_set_components = bm_set_components_argb_d3d_16_screen;
#endif // ifndef NO_DIRECT3D
}
}
else if (gr_screen.mode == GR_OPENGL)
{
if (gr_screen.bits_per_pixel == 32) {
bm_set_components = bm_set_components_argb_d3d_32_screen;
} else {
bm_set_components = bm_set_components_argb_d3d_16_screen;
}
}
#else
bm_set_components = bm_set_components_argb_d3d_16_screen;
#endif // ifdef WIN32
}
void BM_SELECT_TEX_FORMAT()
{
Gr_current_red = &Gr_t_red;
Gr_current_green = &Gr_t_green;
Gr_current_blue = &Gr_t_blue;
Gr_current_alpha = &Gr_t_alpha;
// setup pointers
#ifdef _WIN32
if(gr_screen.mode == GR_DIRECT3D){
if(Bm_pixel_format == BM_PIXEL_FORMAT_D3D){
bm_set_components = bm_set_components_d3d;
} else {
#ifndef NO_DIRECT3D
if(D3D_32bit){
bm_set_components = bm_set_components_argb_d3d_32_tex;
} else {
bm_set_components = bm_set_components_argb_d3d_16_tex;
}
#else
bm_set_components = bm_set_components_argb_d3d_16_tex;
#endif
}
}
else if (gr_screen.mode == GR_OPENGL)
{
if (gr_screen.bits_per_pixel == 32) {
bm_set_components = bm_set_components_argb_d3d_32_tex;
} else {
bm_set_components = bm_set_components_argb_d3d_16_tex;
}
}
#else
bm_set_components = bm_set_components_argb_d3d_16_tex;
#endif // ifdef WIN32
}
void BM_SELECT_ALPHA_TEX_FORMAT()
{
Gr_current_red = &Gr_ta_red;
Gr_current_green = &Gr_ta_green;
Gr_current_blue = &Gr_ta_blue;
Gr_current_alpha = &Gr_ta_alpha;
// setup pointers
#ifdef _WIN32
if(gr_screen.mode == GR_DIRECT3D){
if(Bm_pixel_format == BM_PIXEL_FORMAT_D3D){
bm_set_components = bm_set_components_d3d;
} else {
#ifndef NO_DIRECT3D
if(D3D_32bit){
bm_set_components = bm_set_components_argb_d3d_32_tex;
} else {
bm_set_components = bm_set_components_argb_d3d_16_tex;
}
#else
bm_set_components = bm_set_components_argb_d3d_16_tex;
#endif
}
}
else if (gr_screen.mode == GR_OPENGL)
{
if (gr_screen.bits_per_pixel == 32) {
bm_set_components = bm_set_components_argb_d3d_32_tex;
} else {
bm_set_components = bm_set_components_argb_d3d_16_tex;
}
}
#else
bm_set_components = bm_set_components_argb_d3d_16_tex;
#endif // ifdef WIN32
}
// set the rgba components of a pixel, any of the parameters can be -1
/*
void bm_set_components(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
{
int bit_32 = 0;
// pick a byte size - 32 bits only if 32 bit mode d3d and screen format
if(D3D_32bit && (Gr_current_red == &Gr_red)){
bit_32 = 1;
}
if(bit_32){
*((uint*)pixel) |= (uint)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
} else {
*((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
}
if(bit_32){
*((uint*)pixel) |= (uint)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
} else {
*((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
}
if(bit_32){
*((uint*)pixel) |= (uint)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
} else {
*((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
}
// NOTE - this is a semi-hack. For direct3d we don't use an alpha bit, so if *av == 0, we just set the whole pixel to be Gr_green.mask
// ergo, we need to do this _last_
switch(Bm_pixel_format){
// glide has an alpha channel so we have to unset ir or set it each time
case BM_PIXEL_FORMAT_ARGB:
Assert(!bit_32);
*((ushort*)pixel) &= ~(0x8000);
if(*av){
*((ushort*)pixel) |= 0x8000;
}
break;
// this d3d format has no alpha channel, so only make it "transparent", never make it "non-transparent"
case BM_PIXEL_FORMAT_D3D:
Assert(!bit_32);
if(*av == 0){
*((ushort*)pixel) = (ushort)Gr_current_green->mask;
}
break;
// nice 1555 texture format
case BM_PIXEL_FORMAT_ARGB_D3D:
// if we're writing to normal texture format
if(Gr_current_red == &Gr_t_red){
Assert(!bit_32);
*((ushort*)pixel) &= ~(Gr_current_alpha->mask);
if(*av){
*((ushort*)pixel) |= (ushort)(Gr_current_alpha->mask);
} else {
*((ushort*)pixel) = 0;
}
}
// otherwise if we're writing to screen format, still do it the green mask way
else {
if(*av == 0){
if(bit_32){
*((uint*)pixel) = (uint)Gr_current_green->mask;
} else {
*((ushort*)pixel) = (ushort)Gr_current_green->mask;
}
}
}
break;
}
}
*/
// get the rgba components of a pixel, any of the parameters can be NULL
void bm_gfx_get_components(ubyte *pixel, ubyte *r, ubyte *g, ubyte *b, ubyte *a)
{
int bit_32 = 0;
if((gr_screen.bits_per_pixel==32) && (Gr_current_red == &Gr_red)){
bit_32 = 1;
}
if(r != NULL){
if(bit_32){
*r = ubyte(( (*((uint*)pixel) & Gr_current_red->mask)>>Gr_current_red->shift)*Gr_current_red->scale);
} else {
*r = ubyte(( ( ((ushort*)pixel)[0] & Gr_current_red->mask)>>Gr_current_red->shift)*Gr_current_red->scale);
}
}
if(g != NULL){
if(bit_32){
*g = ubyte(( (*((uint*)pixel) & Gr_current_green->mask) >>Gr_current_green->shift)*Gr_current_green->scale);
} else {
*g = ubyte(( ( ((ushort*)pixel)[0] & Gr_current_green->mask) >>Gr_current_green->shift)*Gr_current_green->scale);
}
}
if(b != NULL){
if(bit_32){
*b = ubyte(( (*((uint*)pixel) & Gr_current_blue->mask)>>Gr_current_blue->shift)*Gr_current_blue->scale);
} else {
*b = ubyte(( ( ((ushort*)pixel)[0] & Gr_current_blue->mask)>>Gr_current_blue->shift)*Gr_current_blue->scale);
}
}
// get the alpha value
if(a != NULL){
*a = 1;
switch(Bm_pixel_format){
// glide has an alpha channel so we have to unset ir or set it each time
case BM_PIXEL_FORMAT_ARGB:
Assert(!bit_32);
if(!( ((ushort*)pixel)[0] & 0x8000)){
*a = 0;
}
break;
// this d3d format has no alpha channel, so only make it "transparent", never make it "non-transparent"
case BM_PIXEL_FORMAT_D3D:
Assert(!bit_32);
if( *((ushort*)pixel) == Gr_current_green->mask){
*a = 0;
}
break;
// nice 1555 texture format mode
case BM_PIXEL_FORMAT_ARGB_D3D:
// if we're writing to a normal texture, use nice alpha bits
if(Gr_current_red == &Gr_t_red){
Assert(!bit_32);
if(!(*((ushort*)pixel) & Gr_current_alpha->mask)){
*a = 0;
}
}
// otherwise do it as normal
else {
if(bit_32){
if(*((int*)pixel) == Gr_current_green->mask){
*a = 0;
}
} else {
if(*((ushort*)pixel) == Gr_current_green->mask){
*a = 0;
}
}
}
}
}
}
// get filename
void bm_get_filename(int bitmapnum, char *filename)
{
int n = bitmapnum % MAX_BITMAPS;
// return filename
strcpy(filename, bm_bitmaps[n].filename);
}
// given a bitmap and a section, return the size (w, h)
void bm_gfx_get_section_size(int bitmapnum, int sx, int sy, int *w, int *h)
{
int bw, bh;
bitmap_section_info *sections;
// bogus input?
Assert((w != NULL) && (h != NULL));
if((w == NULL) || (h == NULL)){
return;
}
// get bitmap info
bm_get_info(bitmapnum, &bw, &bh, NULL, NULL, NULL, §ions);
// determine the width and height of this section
*w = sx < (sections->num_x - 1) ? MAX_BMAP_SECTION_SIZE : bw - sections->sx[sx];
*h = sy < (sections->num_y - 1) ? MAX_BMAP_SECTION_SIZE : bh - sections->sy[sy];
}
int bm_is_compressed(int num)
{
int n=num % MAX_BITMAPS;
//duh
if (!Texture_compression_enabled)
return 0;
Assert(num==bm_bitmaps[n].handle);
switch (bm_bitmaps[n].type)
{
case BM_TYPE_DXT1:
return 1;
case BM_TYPE_DXT3:
return 2;
case BM_TYPE_DXT5:
return 3;
}
return 0;
}
//needed only for compressed bitmaps
int bm_get_size(int num)
{
int n=num % MAX_BITMAPS;
if (!bm_is_compressed(num))
return 0;
Assert(num==bm_bitmaps[n].handle);
return bm_bitmaps[n].mem_taken;
}
int bm_get_num_mipmaps(int num)
{
int n = num % MAX_BITMAPS;
Assert( num == bm_bitmaps[n].handle);
return bm_bitmaps[n].num_mipmaps;
}
|
[
"[email protected]"
] |
[
[
[
1,
3126
]
]
] |
b3d9e28b700d7f31e2f559e63e3bcad8a72814f0
|
c95a83e1a741b8c0eb810dd018d91060e5872dd8
|
/Game/ClientShellDLL/ClientShellShared/PlayerMgr.cpp
|
cc2477a9cb661e19b8ced8a616fe7e03d740c03f
|
[] |
no_license
|
rickyharis39/nolf2
|
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
|
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
|
refs/heads/master
| 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 150,834 |
cpp
|
// ----------------------------------------------------------------------- //
//
// MODULE : PlayerMgr.cpp
//
// PURPOSE : Implementation of class used to manage the client player
//
// (c) 2001-2002 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#include "stdafx.h"
#include "PlayerMgr.h"
#include "AttachButeMgr.h"
#include "BodyFX.h"
#include "CMoveMgr.h"
#include "CameraFX.h"
#include "CameraOffsetMgr.h"
#include "ClientUtilities.h"
#include "ClientWeaponMgr.h"
#include "FlashLight.h"
#include "GadgetDisabler.h"
#include "GameClientShell.h"
#include "HeadBobMgr.h"
#include "LeanMgr.h"
#include "MsgIDs.h"
#include "PlayerCamera.h"
#include "PlayerShared.h"
#include "Searcher.h"
#include "VarTrack.h"
#include "VehicleMgr.h"
#include "VisionModeMgr.h"
#include "VolumeBrushFX.h"
#include "TargetMgr.h"
#include "MissionMgr.h"
#include "ClientMultiplayerMgr.h"
#include "ClientButeMgr.h"
#include "DynamicOccluderVolumeFX.h"
#include "TriggerFX.h"
#include "PlayerLureFX.h"
#include "CharacterFX.h"
#include "PolyGridFX.h"
#include "PlayerViewAttachmentMgr.h"
#include "LTEulerAngles.h"
#include "DoomsDayPieceFX.h"
CPlayerMgr* g_pPlayerMgr = NULL;
#define MAX_SHAKE_AMOUNT 10.0f
#define FOVX_ZOOMED 20.0f
#define FOVX_ZOOMED1 7.0f
#define FOVX_ZOOMED2 2.0f
#define ZOOM_TIME 0.5f
#define LOD_ZOOMADJUST -5.0f
#define DEFAULT_LOD_OFFSET 0.0f
#define DEFAULT_CSENDRATE 15.0f
namespace
{
bool g_bCinChangedNumModelShadows = false;
int g_nCinSaveNumModelShadows = 0;
const g_kMaxNumberOfCinShadows = 10;
uint8 s_nLastCamType = CT_FULLSCREEN;
float s_fDeadTimer = 0.0f;
float s_fDeathDelay = 0.0f;
LTVector g_vSVModelColor; // model color modifier for spy vision
int g_nSaveSpyVisionShadows = 0;
}
LTVector g_vPlayerCameraOffset = g_kvPlayerCameraOffset;
extern bool g_bScreenShotMode;
void SVModelHook(ModelHookData *pData, void *pUser);
VarTrack g_CV_CSendRate; // The SendRate console variable.
VarTrack g_vtPlayerRotate; // The PlayerRotate console variable
VarTrack g_vtCamZoom1MaxDist;
VarTrack g_vtCamZoom2MaxDist;
VarTrack g_vtUseCamRecoil;
VarTrack g_vtCamRecoilRecover;
VarTrack g_vtBaseCamRecoilPitch;
VarTrack g_vtMaxCamRecoilPitch;
VarTrack g_vtBaseCamRecoilYaw;
VarTrack g_vtMaxCamRecoilYaw;
VarTrack g_vtFireJitterDecayTime;
VarTrack g_vtFireJitterMaxPitchDelta;
VarTrack g_vtFOVXNormal;
VarTrack g_vtFOVYNormal;
VarTrack g_vtFOVYMaxUW;
VarTrack g_vtFOVYMinUW;
VarTrack g_vtUWFOVRate;
VarTrack g_vtRespawnWaitTime;
VarTrack g_vtMultiplayerRespawnWaitTime;
VarTrack g_vtDoomsdayRespawnWaitTime;
VarTrack g_vtCamRotInterpTime;
VarTrack g_vtScreenFadeInTime;
VarTrack g_vtScreenFadeOutTime;
VarTrack g_vtChaseCamPitchAdjust;
VarTrack g_vtChaseCamOffset;
VarTrack g_vtChaseCamDistUp;
VarTrack g_vtChaseCamDistBack;
VarTrack g_vtNormalTurnRate;
VarTrack g_vtFastTurnRate;
VarTrack g_vtLookUpRate;
VarTrack g_vtCameraSwayXFreq;
VarTrack g_vtCameraSwayYFreq;
VarTrack g_vtCameraSwayXSpeed;
VarTrack g_vtCameraSwayYSpeed;
VarTrack g_vtCameraSwayDuckMult;
VarTrack g_vtModelGlowTime;
VarTrack g_vtModelGlowMin;
VarTrack g_vtModelGlowMax;
VarTrack g_vtActivateOverride;
VarTrack g_vtCamDamage;
VarTrack g_vtCamDamagePitch;
VarTrack g_vtCamDamageRoll;
VarTrack g_vtCamDamageTime1;
VarTrack g_vtCamDamageTime2;
VarTrack g_vtCamDamageMinPitchVal;
VarTrack g_vtCamDamageMaxPitchVal;
VarTrack g_vtCamDamageMinRollVal;
VarTrack g_vtCamDamageMaxRollVal;
VarTrack g_vtCamDamagePitchMin;
VarTrack g_vtCamDamageRollMin;
VarTrack g_vtCamDamageFXOffsetX;
VarTrack g_vtCamDamageFXOffsetY;
VarTrack g_vtCamDamageFXOffsetZ;
VarTrack g_vtAlwaysHUD;
VarTrack g_vtDamageFadeRate;
VarTrack g_vtAdaptiveMouse;
VarTrack g_vtAdaptiveMouseMaxOffset;
VarTrack g_vtShowSoundFilterInfo;
VarTrack g_vtMultiplayerDeathCamMoveTime;
VarTrack g_vtMultiAttachDeathCamMaxTime;
VarTrack g_vtAttachedCamInterpolationRate;
extern VarTrack g_vtUseSoundFilters;
// --------------------------------------------------------------------------- //
// Constructor & Destructor
// --------------------------------------------------------------------------- //
CPlayerMgr::CPlayerMgr()
: m_bServerAccurateRotation( false )
, m_bSendCameraOffsetToServer( false )
{
m_pHeadBobMgr = debug_new( CHeadBobMgr ); ASSERT( 0 != m_pHeadBobMgr );
m_pCameraOffsetMgr = debug_new( CCameraOffsetMgr ); ASSERT( 0 != m_pCameraOffsetMgr );
m_pFlashLight = debug_new( CFlashLightPlayer ); ASSERT( 0 != m_pFlashLight );
m_pGadgetDisabler = debug_new( CGadgetDisabler ); ASSERT( 0 != m_pGadgetDisabler );
m_pSearcher = debug_new( CSearcher ); ASSERT( 0 != m_pSearcher );
m_pMoveMgr = debug_new( CMoveMgr ); ASSERT( 0 != m_pMoveMgr );
m_pVisionModeMgr = debug_new( CVisionModeMgr ); ASSERT( 0 != m_pVisionModeMgr );
m_pAttachButeMgr = debug_new( CAttachButeMgr ); ASSERT( 0 != m_pAttachButeMgr );
m_pLeanMgr = debug_new( CLeanMgr ); ASSERT( 0 != m_pLeanMgr );
m_pClientWeaponMgr = debug_new( CClientWeaponMgr ); ASSERT( 0 != m_pClientWeaponMgr );
m_pPlayerCamera = debug_new( CPlayerCamera ); ASSERT( 0 != m_pPlayerCamera );
m_pPVAttachmentMgr = debug_new( CPlayerViewAttachmentMgr ); ASSERT( 0 != m_pPVAttachmentMgr );
// InitTargetMgr();
m_hCamera = NULL;
m_bStrafing = LTFALSE;
m_bHoldingMouseLook = LTFALSE;
m_fYawBackup = 0.0f;
m_fPitchBackup = 0.0f;
m_bRestoreOrientation = LTFALSE;
m_bAllowPlayerMovement = LTTRUE;
m_bLastAllowPlayerMovement = LTTRUE;
m_bWasUsingExternalCamera = LTFALSE;
m_bUsingExternalCamera = LTFALSE;
m_bCamIsListener = LTFALSE;
m_bCamera = LTFALSE;
m_bStartedPlaying = LTFALSE;
m_vSVLightScale.Init(1, 1, 1);
m_vShakeAmount.Init();
m_bSpectatorMode = LTFALSE;
m_bInvisibleMode = LTFALSE;
m_fEarliestRespawnTime = 0.0f;
m_bCancelRevive = false;
m_rRotation.Init();
m_fPitch = 0.0f;
m_fYaw = 0.0f;
m_fRoll = 0.0f;
m_fPlayerPitch = 0.0f;
m_fPlayerYaw = 0.0f;
m_fPlayerRoll = 0.0f;
m_fModelAttachPitch = 0.0f;
m_fModelAttachYaw = 0.0f;
m_fModelAttachRoll = 0.0f;
m_fFireJitterPitch = 0.0f;
m_fFireJitterYaw = 0.0f;
m_dwPlayerFlags = 0;
m_ePlayerState = PS_UNKNOWN;
m_nZoomView = 0;
m_bZooming = LTFALSE;
m_bZoomingIn = LTFALSE;
m_fSaveLODScale = DEFAULT_LOD_OFFSET;
m_eCurContainerCode = CC_NO_CONTAINER;
m_nSoundFilterId = 0;
m_nGlobalSoundFilterId = 0;
m_bInSafetyNet = false;
m_fContainerStartTime = -1.0f;
m_fFovXFXDir = 1.0f;
m_vCurModelGlow.Init(127.0f, 127.0f, 127.0f);
m_vMaxModelGlow.Init(255.0f, 255.0f, 255.0f);
m_vMinModelGlow.Init(50.0f, 50.0f, 50.f);
m_fModelGlowCycleTime = 0.0f;
m_bModelGlowCycleUp = LTTRUE;
m_bCameraPosInited = LTFALSE;
m_bPlayerUpdated = LTFALSE;
m_bCameraAttachedToHead = false;
m_bLerpAttachedCamera = false;
m_nPlayerInfoChangeFlags = 0;
m_fPlayerInfoLastSendTime = 0.0f;
m_bUseWorldFog = LTTRUE;
m_hContainerSound = NULL;
m_bStartedDuckingDown = LTFALSE;
m_bStartedDuckingUp = LTFALSE;
m_fCamDuck = 0.0f;
m_fDuckDownV = -75.0f;
m_fDuckUpV = 75.0f;
m_fMaxDuckDistance = -20.0f;
m_fStartDuckTime = 0.0f;
m_nCarryingObject = CFX_CARRY_NONE;
m_bCanDropCarriedObject = false;
m_fDistanceIndicatorPercent = -1.0f;
m_hDistanceIndicatorIcon = LTNULL;
m_nPreGadgetWeapon = WMGR_INVALID_ID;
m_bChangingToGadget = false;
m_bSwitchingWeapons = false;
m_fMultiplayerDeathCamMoveTimer = 0.0f;
m_fMultiAttachDeathCamTimer = 0.0f;
}
CPlayerMgr::~CPlayerMgr()
{
if ( m_pHeadBobMgr )
{
debug_delete( m_pHeadBobMgr );
m_pHeadBobMgr = 0;
}
if ( m_pCameraOffsetMgr )
{
debug_delete( m_pCameraOffsetMgr );
m_pCameraOffsetMgr = 0;
}
if ( m_pFlashLight )
{
debug_delete( m_pFlashLight );
m_pFlashLight = 0;
}
if ( m_pGadgetDisabler )
{
debug_delete( m_pGadgetDisabler );
m_pGadgetDisabler = 0;
}
if ( m_pSearcher )
{
debug_delete( m_pSearcher );
m_pSearcher = 0;
}
if ( m_pMoveMgr )
{
debug_delete( m_pMoveMgr );
m_pMoveMgr = 0;
}
if ( m_pVisionModeMgr )
{
debug_delete( m_pVisionModeMgr );
m_pVisionModeMgr = 0;
}
if ( m_pAttachButeMgr )
{
debug_delete( m_pAttachButeMgr );
m_pAttachButeMgr = 0;
}
if ( m_pLeanMgr )
{
debug_delete( m_pLeanMgr );
m_pLeanMgr = 0;
}
if ( m_pClientWeaponMgr )
{
debug_delete( m_pClientWeaponMgr );
m_pClientWeaponMgr = 0;
}
if ( m_pPlayerCamera )
{
debug_delete( m_pPlayerCamera );
m_pPlayerCamera = 0;
}
if( m_pPVAttachmentMgr )
{
debug_delete( m_pPVAttachmentMgr );
m_pPVAttachmentMgr = LTNULL;
}
g_pPlayerMgr = NULL;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::Init
//
// PURPOSE: Init the mgr
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::Init()
{
g_pPlayerMgr = this;
InitTargetMgr();
g_CV_CSendRate.Init(g_pLTClient, "CSendRate", NULL, DEFAULT_CSENDRATE);
g_vtPlayerRotate.Init(g_pLTClient, "PlayerRotate", NULL, 1.0f);
g_vtCamZoom1MaxDist.Init(g_pLTClient, "CamZoom1MaxDist", NULL, 600.0f);
g_vtCamZoom2MaxDist.Init(g_pLTClient, "CamZoom2MaxDist", NULL, 1000.0f);
g_vtFOVXNormal.Init(g_pLTClient, "FovX", NULL, 90.0f);
g_vtFOVYNormal.Init(g_pLTClient, "FovY", NULL, 78.0f);
g_vtFOVYMaxUW.Init(g_pLTClient, "FOVYUWMax", NULL, 78.0f);
g_vtFOVYMinUW.Init(g_pLTClient, "FOVYUWMin", NULL, 77.0f);
g_vtUWFOVRate.Init(g_pLTClient, "FOVUWRate", NULL, 0.3f);
g_vtUseCamRecoil.Init(g_pLTClient, "CamRecoil", NULL, 0.0f);
g_vtCamRecoilRecover.Init(g_pLTClient, "CamRecoilRecover", NULL, 0.3f);
g_vtBaseCamRecoilPitch.Init(g_pLTClient, "CamRecoilBasePitch", NULL, 5.0f);
g_vtMaxCamRecoilPitch.Init(g_pLTClient, "CamRecoilMaxPitch", NULL, 75.0f);
g_vtBaseCamRecoilYaw.Init(g_pLTClient, "CamRecoilBaseYaw", NULL, 3.0f);
g_vtMaxCamRecoilYaw.Init(g_pLTClient, "CamRecoilMaxYaw", NULL, 35.0f);
g_vtCamRotInterpTime.Init(g_pLTClient, "CamRotInterpTime", NULL, 0.15f);
g_vtRespawnWaitTime.Init(g_pLTClient, "RespawnWaitTime", NULL, 1.0f);
g_vtMultiplayerRespawnWaitTime.Init(g_pLTClient, "RespawnMultiWaitTime", NULL, 30.0f);
g_vtDoomsdayRespawnWaitTime.Init(g_pLTClient, "RespawnDoomsdayWaitTime", NULL, 15.0f);
g_vtScreenFadeInTime.Init(g_pLTClient, "ScreenFadeInTime", NULL, 3.0f);
g_vtScreenFadeOutTime.Init(g_pLTClient, "ScreenFadeOutTime", NULL, 5.0f);
g_vtChaseCamOffset.Init(g_pLTClient, "ChaseCamOffset", NULL, 50.0f);
g_vtChaseCamPitchAdjust.Init(g_pLTClient, "ChaseCamPitchAdjust", NULL, 0.0f);
g_vtChaseCamDistUp.Init(g_pLTClient, "ChaseCamDistUp", NULL, 10.0f);
g_vtChaseCamDistBack.Init(g_pLTClient, "ChaseCamDistBack", NULL, 100.0f);
g_vtFastTurnRate.Init(g_pLTClient, "FastTurnRate", NULL, 2.3f);
g_vtNormalTurnRate.Init(g_pLTClient, "NormalTurnRate", NULL, 1.5f);
g_vtLookUpRate.Init(g_pLTClient, "LookUpRate", NULL, 2.5f);
g_vtCameraSwayXFreq.Init(g_pLTClient, "CameraSwayXFreq", NULL, 13.0f);
g_vtCameraSwayYFreq.Init(g_pLTClient, "CameraSwayYFreq", NULL, 5.0f);
g_vtCameraSwayXSpeed.Init(g_pLTClient, "CameraSwayXSpeed", NULL, 12.0f);
g_vtCameraSwayYSpeed.Init(g_pLTClient, "CameraSwayYSpeed", NULL, 1.5f);
g_vtCameraSwayDuckMult.Init(g_pLTClient, "CameraSwayCrouchMultiplier", NULL, 0.5f);
g_vtModelGlowTime.Init(g_pLTClient, "ModelGlowTime", NULL, 1.5f);
g_vtModelGlowMin.Init(g_pLTClient, "ModelGlowMin", NULL, -25.0f);
g_vtModelGlowMax.Init(g_pLTClient, "ModelGlowMax", NULL, 75.0f);
g_vtActivateOverride.Init(g_pLTClient, "ActivateOverride", " ", 0.0f);
g_vtCamDamage.Init(g_pLTClient, "CamDamage", NULL, 1.0f);
g_vtCamDamagePitch.Init(g_pLTClient, "CamDamagePitch", NULL, 1.0f);
g_vtCamDamageRoll.Init(g_pLTClient, "CamDamageRoll", NULL, 1.0f);
g_vtCamDamageTime1.Init(g_pLTClient, "CamDamageTime1", NULL, 0.1f);
g_vtCamDamageTime2.Init(g_pLTClient, "CamDamageTime2", NULL, 0.25f);
g_vtCamDamageMinPitchVal.Init(g_pLTClient, "CamDamageMinPitchVal", NULL, 5.0f);
g_vtCamDamageMaxPitchVal.Init(g_pLTClient, "CamDamageMaxPitchVal", NULL, 20.0f);
g_vtCamDamageMinRollVal.Init(g_pLTClient, "CamDamageMinRollVal", NULL, 5.0f);
g_vtCamDamageMaxRollVal.Init(g_pLTClient, "CamDamageMaxRollVal", NULL, 20.0f);
g_vtCamDamagePitchMin.Init(g_pLTClient, "CamDamagePitchMin", NULL, 0.7f);
g_vtCamDamageRollMin.Init(g_pLTClient, "CamDamageRollMin", NULL, 0.7f);
g_vtCamDamageFXOffsetX.Init(g_pLTClient, "CamDamageFXOffsetX", NULL, 5.0f);
g_vtCamDamageFXOffsetY.Init(g_pLTClient, "CamDamageFXOffsetX", NULL, 5.0f);
g_vtCamDamageFXOffsetZ.Init(g_pLTClient, "CamDamageFXOffsetX", NULL, 5.0f);
g_vtAlwaysHUD.Init(g_pLTClient, "AlwaysHUD", NULL, 0.0f);
g_vtDamageFadeRate.Init(g_pLTClient, "DamageFadeRate", NULL, 0.5f);
g_vtAdaptiveMouse.Init(g_pLTClient, "AdaptiveMouse", NULL, 0.0f);
g_vtAdaptiveMouseMaxOffset.Init(g_pLTClient, "AdaptiveMouseMaxOffset", NULL, 0.1f);
g_vtShowSoundFilterInfo.Init(g_pLTClient, "SoundFilterInfo", NULL, 0.0f);
g_vtMultiplayerDeathCamMoveTime.Init( g_pLTClient, "MultiplayerDeathCamMoveTime", NULL, 0.5f );
g_vtMultiAttachDeathCamMaxTime.Init( g_pLTClient, "MultiplayerDeathAttachCamMaxTime", NULL, 5.0f );
g_vtAttachedCamInterpolationRate.Init( g_pLTClient, "AttachedCamIntrepolationRate", NULL, 0.1f );
// Default these to use values specified in the weapon...(just here for
// tweaking values...)
g_vtFireJitterDecayTime.Init(g_pLTClient, "FireJitterDecayTime", NULL, -1.0f);
g_vtFireJitterMaxPitchDelta.Init(g_pLTClient, "FireJitterMaxPitchDelta", NULL, -1.0f);
g_vSVModelColor = g_pLayoutMgr->GetSpyVisionModelColor();
m_vSVLightScale = g_pLayoutMgr->GetSpyVisionLightScale();
// Create the camera...
ObjectCreateStruct theStruct;
INIT_OBJECTCREATESTRUCT(theStruct);
theStruct.m_ObjectType = OT_CAMERA;
m_hCamera = g_pLTClient->CreateObject(&theStruct);
_ASSERT(m_hCamera);
ResetCamera();
m_pHeadBobMgr->Init();
m_pCameraOffsetMgr->Init();
//m_pFlashLight no init
//m_pGadgetDisabler no init
//m_pSearcher
m_pMoveMgr->Init();
//m_pVisionModeMgr no init
m_pAttachButeMgr->Init();
m_pLeanMgr->Init();
m_pClientWeaponMgr->Init();
m_pPVAttachmentMgr->Init();
s_fDeathDelay = g_pLayoutMgr->GetDeathDelay();
// Player camera (non-1st person) stuff...
if (m_pPlayerCamera->Init(g_pLTClient))
{
InitPlayerCamera();
m_pPlayerCamera->GoFirstPerson();
}
else
{
g_pGameClientShell->CSPrint ("Could not init player camera!");
}
ClearDamageSectors();
m_bSpyVision = false;
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::Term
//
// PURPOSE: Term the mgr
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::Term()
{
// terminate the weapon mgr
m_pClientWeaponMgr->Term();
m_pPVAttachmentMgr->Term();
g_pPlayerMgr = NULL;
if (m_hCamera)
{
g_pLTClient->RemoveObject(m_hCamera);
m_hCamera = NULL;
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CInterfaceMgr::Save
//
// PURPOSE: Save the interface info
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::Save(ILTMessage_Write *pMsg, SaveDataState eSaveDataState)
{
// save the class information
m_pMoveMgr->Save(pMsg, eSaveDataState);
m_pClientWeaponMgr->Save(pMsg);
pMsg->Writebool(m_bSpectatorMode != LTFALSE);
pMsg->WriteLTRotation(m_rRotation);
pMsg->Writebool(m_bLastSent3rdPerson != LTFALSE);
pMsg->Writebool(m_bAllowPlayerMovement != LTFALSE);
pMsg->Writebool(m_bLastAllowPlayerMovement != LTFALSE);
pMsg->Writebool(m_bWasUsingExternalCamera != LTFALSE);
pMsg->Writebool(m_bUsingExternalCamera != LTFALSE);
pMsg->Writeuint8(m_ePlayerState);
pMsg->Writeuint8(m_nSoundFilterId);
pMsg->Writeuint8(m_nGlobalSoundFilterId);
pMsg->Writebool(m_pFlashLight->IsOn() != LTFALSE);
pMsg->Writefloat(m_fPitch);
pMsg->Writefloat(m_fYaw);
pMsg->Writefloat(m_fRoll);
pMsg->Writefloat(m_fPlayerPitch);
pMsg->Writefloat(m_fPlayerYaw);
pMsg->Writefloat(m_fPlayerRoll);
pMsg->Writefloat(m_fModelAttachPitch);
pMsg->Writefloat(m_fModelAttachYaw);
pMsg->Writefloat(m_fModelAttachRoll);
m_fPitchBackup = m_fPitch;
m_fYawBackup = m_fYaw;
pMsg->Writefloat(m_fPitchBackup);
pMsg->Writefloat(m_fYawBackup);
pMsg->Writefloat(m_fFireJitterPitch);
pMsg->Writefloat(m_fFireJitterYaw);
pMsg->Writefloat(m_fContainerStartTime);
pMsg->Writefloat(m_fFovXFXDir);
pMsg->Writefloat(m_fSaveLODScale);
pMsg->Writeuint8( m_nCarryingObject );
pMsg->Writebool( m_bCanDropCarriedObject );
pMsg->Writebool( m_bCameraAttachedToHead );
pMsg->Writebool( m_pMoveMgr->DuckLock() ? true : false );
pMsg->Writebool( m_pMoveMgr->IsDucking() ? true : false );
pMsg->Writefloat( m_fMultiplayerDeathCamMoveTimer );
pMsg->Writefloat( m_fMultiAttachDeathCamTimer );
pMsg->Writebool( m_bLerpAttachedCamera );
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::Load
//
// PURPOSE: Load the interface info
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::Load(ILTMessage_Read *pMsg, SaveDataState eLoadDataState)
{
// load the contained member classes
m_pMoveMgr->Load(pMsg, eLoadDataState);
m_pClientWeaponMgr->Load(pMsg);
m_bSpectatorMode = pMsg->Readbool() ? LTTRUE : LTFALSE;
m_rRotation = pMsg->ReadLTRotation();
m_bLastSent3rdPerson = pMsg->Readbool() ? LTTRUE : LTFALSE;
m_bAllowPlayerMovement = pMsg->Readbool() ? LTTRUE : LTFALSE;
m_bLastAllowPlayerMovement = pMsg->Readbool() ? LTTRUE : LTFALSE;
m_bWasUsingExternalCamera = pMsg->Readbool() ? LTTRUE : LTFALSE;
m_bUsingExternalCamera = pMsg->Readbool() ? LTTRUE : LTFALSE;
m_ePlayerState = (PlayerState) pMsg->Readuint8();
m_nSoundFilterId = pMsg->Readuint8();
m_nGlobalSoundFilterId = pMsg->Readuint8();
if (pMsg->Readbool())
{
m_pFlashLight->TurnOn();
}
m_fPitch = pMsg->Readfloat();
m_fYaw = pMsg->Readfloat();
m_fRoll = pMsg->Readfloat();
m_fPlayerPitch = pMsg->Readfloat();
m_fPlayerYaw = pMsg->Readfloat();
m_fPlayerRoll = pMsg->Readfloat();
m_fModelAttachPitch = pMsg->Readfloat();
m_fModelAttachYaw = pMsg->Readfloat();
m_fModelAttachRoll = pMsg->Readfloat();
m_fPitchBackup = pMsg->Readfloat();
m_fYawBackup = pMsg->Readfloat();
m_fFireJitterPitch = pMsg->Readfloat();
m_fFireJitterYaw = pMsg->Readfloat();
m_fContainerStartTime = pMsg->Readfloat();
m_fFovXFXDir = pMsg->Readfloat();
m_fSaveLODScale = pMsg->Readfloat();
uint8 nCarryingObject = 0;
if( g_pVersionMgr->GetCurrentSaveVersion( ) < CVersionMgr::kSaveVersion__1_3 )
{
bool bCarryingObject = pMsg->Readbool();
if (bCarryingObject)
nCarryingObject = CFX_CARRY_BODY;
else
nCarryingObject = CFX_CARRY_NONE;
}
else
{
nCarryingObject = pMsg->Readuint8();
}
SetCarryingObject( nCarryingObject, false );
m_bCanDropCarriedObject = pMsg->Readbool();
m_bCameraAttachedToHead = pMsg->Readbool();
m_pMoveMgr->SetDuckLock( pMsg->Readbool() ? LTTRUE : LTFALSE );
m_pMoveMgr->SetDucking( pMsg->Readbool() ? LTTRUE : LTFALSE );
m_fMultiplayerDeathCamMoveTimer = pMsg->Readfloat();
m_fMultiAttachDeathCamTimer = pMsg->Readfloat();
if( g_pVersionMgr->GetCurrentSaveVersion( ) > CVersionMgr::kSaveVersion__1_2 )
{
m_bLerpAttachedCamera = pMsg->Readbool();
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::OnEnterWorld()
//
// PURPOSE: Handle entering world
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::OnEnterWorld()
{
m_vShakeAmount.Init();
m_ePlayerState = PS_UNKNOWN;
m_bPlayerUpdated = LTFALSE;
m_nZoomView = 0;
m_bZooming = LTFALSE;
m_bZoomingIn = LTFALSE;
m_eCurContainerCode = CC_NO_CONTAINER;
m_bInSafetyNet = false;
m_bCameraAttachedToHead = false;
m_bLerpAttachedCamera = false;
m_pHeadBobMgr->OnEnterWorld();
SetExternalCamera(LTFALSE);
m_bCameraPosInited = LTFALSE;
m_nPlayerInfoChangeFlags |= CLIENTUPDATE_PLAYERROT | CLIENTUPDATE_ALLOWINPUT;
m_pMoveMgr->OnEnterWorld();
m_nCarryingObject = CFX_CARRY_NONE;
m_bCanDropCarriedObject = false;
m_fDistanceIndicatorPercent = -1.0f;
g_pHUDMgr->QueueUpdate( kHUDDistance );
m_pClientWeaponMgr->OnEnterWorld();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::OnExitWorld()
//
// PURPOSE: Handle leaving world
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::OnExitWorld()
{
m_bStartedPlaying = LTFALSE;
ClearPlayerModes();
m_pPlayerCamera->AttachToObject(NULL); // Detatch camera
m_pFlashLight->TurnOff();
m_pMoveMgr->OnExitWorld();
if (m_hContainerSound)
{
g_pLTClient->SoundMgr()->KillSound(m_hContainerSound);
m_hContainerSound = NULL;
}
m_pClientWeaponMgr->OnExitWorld();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::OnMessage()
//
// PURPOSE: Handle client messages
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::OnMessage(uint8 messageID, ILTMessage_Read *pMsg)
{
switch(messageID)
{
case MID_SHAKE_SCREEN: HandleMsgShakeScreen (pMsg); break;
case MID_PLAYER_STATE_CHANGE: HandleMsgPlayerStateChange (pMsg); break;
case MID_CLIENT_PLAYER_UPDATE: HandleMsgClientPlayerUpdate (pMsg); break;
case MID_PLAYER_DAMAGE: HandleMsgPlayerDamage (pMsg); break;
case MID_PLAYER_ORIENTATION: HandleMsgPlayerOrientation (pMsg); break;
case MID_WEAPON_CHANGE: HandleMsgWeaponChange (pMsg); break;
case MID_CHANGE_WORLDPROPERTIES: HandleMsgChangeWorldProperties (pMsg); break;
case MID_GADGETTARGET: HandleMsgGadgetTarget (pMsg); break;
case MID_SEARCH: HandleMsgSearch (pMsg); break;
case MID_ADD_PUSHER: HandleMsgAddPusher (pMsg); break;
case MID_OBJECTIVES_DATA: HandleMsgObjectivesData (pMsg); break;
default: return LTFALSE; break;
}
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::OnKeyDown(int key, int rep)
//
// PURPOSE: Handle key down notification
// Try to avoid using OnKeyDown and OnKeyUp as they
// are not portable functions
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::OnKeyDown(int key, int rep)
{
if (!IsPlayerInWorld()) return LTFALSE;
if (IsPlayerDead())
{
// See if we can respawn. For SP, this just makes us wait
// a little bit before we can go to the mission failure screen.
if (g_pLTClient->GetTime() > m_fEarliestRespawnTime)
{
// Death is a mission failure in sp.
if (!IsMultiplayerGame())
{
g_pMissionMgr->HandleMissionFailed();
return LTTRUE;
}
}
}
// Are we playing a cinematic...
if (m_bUsingExternalCamera)
{
if (key == VK_SPACE)
{
// Send an activate message to stop the cinemaitc...
DoActivate();
g_pLTClient->ClearInput();
return LTTRUE;
}
}
return LTFALSE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::OnKeyUp(int key)
//
// PURPOSE: Handle key up notification
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::OnKeyUp(int key)
{
return LTFALSE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::PreUpdate()
//
// PURPOSE: Handle client pre-updates
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::PreUpdate()
{
// Conditions in which we don't want to clear the screen
if ((m_ePlayerState == PS_UNKNOWN && g_pGameClientShell->IsWorldLoaded()))
{
return;
}
// See if we're using an external camera now - if so, clear the screen
// immediately, and add to the clearscreen count
if (m_bUsingExternalCamera && !m_bWasUsingExternalCamera)
{
m_bWasUsingExternalCamera = LTTRUE;
g_pInterfaceMgr->AddToClearScreenCount();
}
else if (m_bWasUsingExternalCamera && !m_bUsingExternalCamera)
{
m_bWasUsingExternalCamera = LTFALSE;
g_pInterfaceMgr->AddToClearScreenCount();
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::Update()
//
// PURPOSE: Handle client updates
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::Update()
{
// Update models (powerups) glowing...
UpdateModelGlow();
UpdateDamage();
if (IsPlayerDead())
{
if (!IsMultiplayerGame() && !g_pGameClientShell->IsGamePaused())
{
if (s_fDeadTimer < s_fDeathDelay)
{
s_fDeadTimer += g_pGameClientShell->GetFrameTime();
}
else
{
LTBOOL bHandleMissionFailed = LTTRUE;
if (g_pInterfaceMgr->FadingScreen() && g_pInterfaceMgr->FadingScreenIn())
{
bHandleMissionFailed = g_pInterfaceMgr->ScreenFadeDone();
}
if (bHandleMissionFailed)
{
g_pMissionMgr->HandleMissionFailed();
}
}
}
}
if (g_pLTClient->IsCommandOn(COMMAND_ID_ACTIVATE))
{
//if the activate key is down,
// and we're in range
// and we have not started to auto-switch to a gadget i.e (m_nPreGadgetWeapon == WMGR_INVALID_ID)
// and we are not in the process of switching weapons
//then try to switch to a gadget
if (GetTargetMgr()->IsTargetInRange() && (m_nPreGadgetWeapon == WMGR_INVALID_ID) && !m_bSwitchingWeapons)
{
DamageType eDT = GetTargetMgr()->RequiredGadgetDamageType();
UseGadget(eDT);
}
}
else
{
//if the activate key is not down,
// and we have started to auto-switch to a gadget i.e (m_nPreGadgetWeapon != WMGR_INVALID_ID)
// and we are not in the process of switching weapons
//then switch back to the old weapon
if ((m_nPreGadgetWeapon != WMGR_INVALID_ID) && !m_bSwitchingWeapons)
{
m_bChangingToGadget = false;
ChangeWeapon(m_nPreGadgetWeapon);
}
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::FirstUpdate
//
// PURPOSE: Handle first update (each level)
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::FirstUpdate()
{
// Force the player camera to update...
UpdatePlayerCamera();
#ifdef USE_EAX20_HARDWARE_FILTERS
m_nGlobalSoundFilterId = 0;
char aGlobalSoundFilter[256] = {0};
char* pGlobalSoundFilter = NULL;
if (g_pLTClient->GetSConValueString("GlobalSoundFilter", aGlobalSoundFilter, sizeof(aGlobalSoundFilter)) == LT_OK)
{
pGlobalSoundFilter = aGlobalSoundFilter;
}
if (pGlobalSoundFilter && pGlobalSoundFilter[0])
{
SOUNDFILTER* pFilter = g_pSoundFilterMgr->GetFilter(pGlobalSoundFilter);
if (pFilter)
{
m_nGlobalSoundFilterId = pFilter->nId;
// set the global filter, if appropriate
if (g_vtUseSoundFilters.GetFloat())
{
bool bFilterOK = true;
ILTClientSoundMgr *pSoundMgr = (ILTClientSoundMgr *)g_pLTClient->SoundMgr();
if ( !g_pSoundFilterMgr->IsUnFiltered( pFilter ) )
{
if ( pSoundMgr->SetSoundFilter( pFilter->szFilterName ) == LT_OK )
{
for (int i=0; i < pFilter->nNumVars; i++)
{
if ( pSoundMgr->SetSoundFilterParam(pFilter->szVars[i], pFilter->fValues[i]) != LT_OK )
bFilterOK = false;
}
}
else
{
bFilterOK = false;
}
}
else
{
// Not filtered.
bFilterOK = false;
}
pSoundMgr->EnableSoundFilter( bFilterOK );
#ifndef _FINAL
if (g_vtShowSoundFilterInfo.GetFloat())
{
g_pLTClient->CPrint("Entering (Global) sound filter '%s' (%s)",
pFilter->szName, (bFilterOK ? "Enabled" : "Disabled"));
// Display detailed filter info if necessary...
if (g_vtShowSoundFilterInfo.GetFloat() > 1)
{
g_pLTClient->CPrint(" FilterName: '%s'", pFilter->szFilterName);
for (int i=0; i < pFilter->nNumVars; i++)
{
g_pLTClient->CPrint(" '%s' = '%f'", pFilter->szVars[i], pFilter->fValues[i]);
}
}
}
#endif // _FINAL
}
}
}
#endif // USE_EAX20_HARDWARE_FILTERS
// Force us to re-evaluate what container we're in. We call
// UpdateContainers() first to make sure any container changes
// have been accounted for, then we clear the container code
// and force an update (this is done for underwater situations like
// dying underwater and respawning, and also for picking up intelligence
// items underwater)...
UpdateContainers();
ClearCurContainerCode();
UpdateContainers();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::FirstPlayingUpdate()
//
// PURPOSE: Handle when the player first starts playing
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::FirstPlayingUpdate()
{
// Set Initial cheats...
if (g_pCheatMgr)
{
uint8 nNumCheats = g_pClientButeMgr->GetNumCheatAttributes();
char strCheat[64];
for (uint8 i=0; i < nNumCheats; i++)
{
strCheat[0] = '\0';
g_pClientButeMgr->GetCheat(i, strCheat, ARRAY_LEN(strCheat));
if (strCheat[0])
{
g_pCheatMgr->Check(strCheat);
}
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdatePlaying()
//
// PURPOSE: Handle updating playing (normal) game state
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdatePlaying()
{
// First time UpdatePlaying is called...
if (!m_bStartedPlaying)
{
m_bStartedPlaying = LTTRUE;
FirstPlayingUpdate();
}
// Update player movement...
m_pMoveMgr->Update();
// Update our camera offset mgr...
m_pCameraOffsetMgr->Update();
// Update Player...
UpdatePlayer();
// Keep track of what the player is doing...
UpdatePlayerFlags();
// Update head-bob/head-cant camera offsets...
m_pHeadBobMgr->Update();
// Update duck camera offset...
UpdateDuck();
// Update the camera's position...
UpdateCamera();
// See if we are tracking distance to an object..
UpdateDistanceIndicator();
// Update player leaning...
m_pLeanMgr->Update();
//updates dependant on camera position and rotation should be handled after this point
// Update the targetting info...
m_pTargetMgr->Update();
// Update the Gadget Disabler...
m_pGadgetDisabler->Update();
// Update the Searcher...
m_pSearcher->Update();
// Update the vision modes...
m_pVisionModeMgr->Update();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::PostUpdate()
//
// PURPOSE: Handle post updates - after the scene is rendered
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::PostUpdate()
{
// Update container effects...
if(m_bStartedPlaying)
{
UpdateContainers();
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateDuck()
//
// PURPOSE: Update ducking camera offset
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdateDuck()
{
// Can't duck when free movement...
if (g_pPlayerMgr->GetMoveMgr()->IsBodyInLiquid() ||
g_pPlayerMgr->GetMoveMgr()->IsBodyOnLadder() ||
g_pPlayerMgr->IsPlayerDead() ||
IsFreeMovement(m_eCurContainerCode))
{
// Reset ducking parameters...
m_fCamDuck = 0.0f;
m_bStartedDuckingDown = LTFALSE;
return;
}
float fTime = g_pLTClient->GetTime();
float fBodyMult = 1.0f;
if ( (m_dwPlayerFlags & BC_CFLG_DUCK) || m_bCameraDip)
{
m_bStartedDuckingUp = LTFALSE;
// Get the difference in crouch height...
float fCrouchDelta = g_pMoveMgr->GetCrouchHeightDifference();
// If dipping don't use the crouch distance...
if( m_bCameraDip )
fCrouchDelta = 0.0f;
// See if the duck just started...
if (!m_bStartedDuckingDown)
{
m_bStartedDuckingDown = LTTRUE;
m_fStartDuckTime = fTime - g_pLTClient->GetFrameTime();
}
m_fCamDuck += m_fDuckDownV * (fTime - m_fStartDuckTime);
if (m_fCamDuck < (m_fMaxDuckDistance - fCrouchDelta) )
{
m_bCameraDip = false;
m_fCamDuck = m_fMaxDuckDistance - fCrouchDelta;
}
}
else if (m_fCamDuck < 0.0) // Raise up
{
m_bStartedDuckingDown = LTFALSE;
if (!m_bStartedDuckingUp)
{
m_fStartDuckTime = fTime - g_pLTClient->GetFrameTime();
m_bStartedDuckingUp = LTTRUE;
}
if( IsCarryingHeavyObject() )
fBodyMult = 0.01f;
m_fCamDuck += m_fDuckUpV * (fTime - m_fStartDuckTime) * fBodyMult;
if (m_fCamDuck > 0.0f)
{
m_fCamDuck = 0.0f;
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleMsgShakeScreen()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgShakeScreen (ILTMessage_Read *pMsg)
{
LTVector vAmount = pMsg->ReadLTVector();
ShakeScreen(vAmount);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::ShakeScreen()
//
// PURPOSE: Shanke, rattle, and roll
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::ShakeScreen(LTVector vShake)
{
// Add...
VEC_ADD(m_vShakeAmount, m_vShakeAmount, vShake);
if (m_vShakeAmount.x > MAX_SHAKE_AMOUNT) m_vShakeAmount.x = MAX_SHAKE_AMOUNT;
if (m_vShakeAmount.y > MAX_SHAKE_AMOUNT) m_vShakeAmount.y = MAX_SHAKE_AMOUNT;
if (m_vShakeAmount.z > MAX_SHAKE_AMOUNT) m_vShakeAmount.z = MAX_SHAKE_AMOUNT;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleMsgClientPlayerUpdate()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgClientPlayerUpdate (ILTMessage_Read *pMsg)
{
uint16 changeFlags = pMsg->Readuint16();
m_pMoveMgr->OnPhysicsUpdate(changeFlags, pMsg);
if (changeFlags & PSTATE_INTERFACE)
{
uint8 nFlags = pMsg->Readuint8();
float fHideTime = pMsg->Readfloat();
LTBOOL bHiding = !!(nFlags & PSTATE_INT_HIDING);
LTBOOL bHidden = !!(nFlags & PSTATE_INT_HIDDEN);
LTBOOL bCantHide = !!(nFlags & PSTATE_INT_CANTHIDE);
g_pPlayerStats->UpdateHiding( bHiding, bHidden, bCantHide, fHideTime );
SetCanDropCarriedObject( !!(nFlags & PSTATE_INT_CAN_DROP) );
// Don't allow respawn meter to go 100% immediately, since
// there is no punishment for dying.
/*
if( IsPlayerDead( ) && IsRevivePlayerGameType( ))
{
// If we can't be revived, then allow respawn immediately.
bool bCanBeRevived = !!( nFlags & PSTATE_INT_CANREVIVE );
if( !bCanBeRevived )
{
SetRespawnTime( g_pLTClient->GetTime( ));
}
}
*/
}
m_bPlayerUpdated = LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleMsgWeaponChange()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgWeaponChange (ILTMessage_Read *pMsg)
{
ChangeWeapon(pMsg);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleMsgPlayerDamage()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgPlayerDamage (ILTMessage_Read *pMsg)
{
static const float kfSectorSize = MATH_PI * 2.0f / (float)kNumDamageSectors;
if (!pMsg || g_bScreenShotMode) return;
LTVector vDir = pMsg->ReadLTVector();
DamageType eType = (DamageType) pMsg->Readuint8();
LTBOOL bTookHealth = (LTBOOL) pMsg->Readuint8();
// No need to handle a damage message if the player is dead...
if( IsPlayerDead() )
return;
float fPercent = vDir.Mag();
uint8 damageSector = kNumDamageSectors;
// [KLS 3/5/02] - If we were damaged, determine the direction the damage came from...
if (fPercent > 0.0f)
{
LTRotation rRot;
GetPlayerRotation(rRot);
vDir.Normalize();
float fDF = rRot.Forward().Dot(vDir);
float fDR = rRot.Right().Dot(vDir);
float damageAngle = MATH_PI+(float)atan2(fDF,fDR);
damageSector = (uint8)(damageAngle / kfSectorSize);
m_fDamage[damageSector] += fPercent;
if (m_fDamage[damageSector] > 1.0f)
m_fDamage[damageSector] = 1.0f;
}
/*******************************
/****** Damage Sector Map ******
3
4 2
5 1
6 0
7 11
8 10
9
*******************************/
// Do some camera FX for taking armor and taking health...
// Tie this into the DamageSector at some point??
DamageFlags dmgFlag = DamageTypeToFlag( eType );
if( bTookHealth )
{
// Play the taking health fx for the DamageFX associated with the damage type...
DAMAGEFX *pDamageFX = g_pDamageFXMgr->GetFirstDamageFX();
while( pDamageFX )
{
// Test the damage flags against the DamageFX...
if( dmgFlag & pDamageFX->m_nDamageFlag || pDamageFX->m_vtTestFX.GetFloat() > 0.0f )
{
CLIENTFX_CREATESTRUCT fxInit( pDamageFX->m_szTakingHealthFXName, FXFLAG_REALLYCLOSE, LTVector(0,0,0) );
g_pClientFXMgr->CreateClientFX( LTNULL, fxInit, LTTRUE );
}
pDamageFX = g_pDamageFXMgr->GetNextDamageFX();
}
}
else
{
// Play the taking armor fx for the DamageFX associated with the damage type...
DAMAGEFX *pDamageFX = g_pDamageFXMgr->GetFirstDamageFX();
while( pDamageFX )
{
// Test the damage flags against the DamageFX...
if( dmgFlag & pDamageFX->m_nDamageFlag || pDamageFX->m_vtTestFX.GetFloat() > 0.0f )
{
CLIENTFX_CREATESTRUCT fxInit( pDamageFX->m_szTakingArmorFXName, FXFLAG_REALLYCLOSE, LTVector(0,0,0) );
g_pClientFXMgr->CreateClientFX( LTNULL, fxInit, LTTRUE );
}
pDamageFX = g_pDamageFXMgr->GetNextDamageFX();
}
}
// Tilt the camera based on the direction the damage came from...
if (kNumDamageSectors != damageSector && IsJarCameraType(eType) &&
m_pPlayerCamera->IsFirstPerson() && g_vtCamDamage.GetFloat() > 0.0f)
{
CameraDelta delta;
if (g_vtCamDamagePitch.GetFloat() > 0.0f)
{
float fPitchAngle = g_vtCamDamageMinPitchVal.GetFloat() + ((g_vtCamDamageMaxPitchVal.GetFloat() - g_vtCamDamageMinPitchVal.GetFloat()) * fPercent);
if (damageSector > 7 && damageSector <11)
{
delta.Pitch.fTime1 = g_vtCamDamageTime1.GetFloat();
delta.Pitch.fTime2 = g_vtCamDamageTime2.GetFloat();
delta.Pitch.eWave1 = Wave_SlowOff;
delta.Pitch.eWave2 = Wave_SlowOff;
delta.Pitch.fVar = DEG2RAD(fPitchAngle);
}
else if (damageSector > 1 && damageSector < 5)
{
delta.Pitch.fTime1 = g_vtCamDamageTime1.GetFloat();
delta.Pitch.fTime2 = g_vtCamDamageTime2.GetFloat();
delta.Pitch.eWave1 = Wave_SlowOff;
delta.Pitch.eWave2 = Wave_SlowOff;
delta.Pitch.fVar = -DEG2RAD(fPitchAngle);
}
}
if (g_vtCamDamageRoll.GetFloat() > 0.0f)
{
float fRollAngle = g_vtCamDamageMinRollVal.GetFloat() + ((g_vtCamDamageMaxRollVal.GetFloat() - g_vtCamDamageMinRollVal.GetFloat()) * fPercent);
if (damageSector > 4 && damageSector < 8)
{
delta.Roll.fTime1 = g_vtCamDamageTime1.GetFloat();
delta.Roll.fTime2 = g_vtCamDamageTime2.GetFloat();
delta.Roll.eWave1 = Wave_SlowOff;
delta.Roll.eWave2 = Wave_SlowOff;
delta.Roll.fVar = DEG2RAD(fRollAngle);
}
else if (damageSector < 2 || damageSector == 11)
{
delta.Roll.fTime1 = g_vtCamDamageTime1.GetFloat();
delta.Roll.fTime2 = g_vtCamDamageTime2.GetFloat();
delta.Roll.eWave1 = Wave_SlowOff;
delta.Roll.eWave2 = Wave_SlowOff;
delta.Roll.fVar = -DEG2RAD(fRollAngle);
}
}
m_pCameraOffsetMgr->AddDelta(delta);
}
float fSlow = SlowMovementDuration(eType);
if (fSlow > 0.0f)
{
m_pMoveMgr->AddDamagePenalty(fSlow);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::Handle()
//
// PURPOSE: This handles the message sent by the world properties
// indicating that they have changed and that the player needs
// to sync to the console variables on the server
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgChangeWorldProperties (ILTMessage_Read *pMsg)
{
g_pGameClientShell->ResetDynamicWorldProperties(m_bUseWorldFog);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::Handle()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgPlayerOrientation (ILTMessage_Read *pMsg)
{
// Set our pitch, yaw, and roll according to the players...
uint8 nID = pMsg->Readuint8();
LTVector vVec = pMsg->ReadLTVector();
switch( nID )
{
case MID_ORIENTATION_ALL :
{
m_fPitch = vVec.x;
m_fYaw = vVec.y;
m_fRoll = vVec.z;
}
break;
case MID_ORIENTATION_YAW :
{
m_fYaw = vVec.y;
}
break;
default : break;
};
m_fPlayerPitch = m_fPitch;
m_fPlayerYaw = m_fYaw;
m_fPlayerRoll = m_fRoll;
m_fYawBackup = m_fYaw;
m_fPitchBackup = m_fPitch;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleMsgGadgetTarget
//
// PURPOSE: Just pass the message on the the disabler object
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgGadgetTarget( ILTMessage_Read *pMsg )
{
m_pGadgetDisabler->OnGadgetTargetMessage( pMsg );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleMsgSearch
//
// PURPOSE: Just pass the message on the the searcher object
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgSearch( ILTMessage_Read *pMsg )
{
m_pSearcher->OnSearchMessage( pMsg );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleMsgAddPusher
//
// PURPOSE: Add a pusher to the MoveMgr.
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgAddPusher( ILTMessage_Read *pMsg )
{
LTVector vPos = pMsg->ReadCompLTVector();
float fRadius = pMsg->Readfloat();
float fStartDelay = pMsg->Readfloat();
float fDuration = pMsg->Readfloat();
float fStrength = pMsg->Readfloat();
g_pPlayerMgr->GetMoveMgr()->AddPusher( vPos, fRadius, fStartDelay, fDuration, fStrength );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleMsgObjectivesData
//
// PURPOSE: Set our objectives obtained from the server...
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgObjectivesData( ILTMessage_Read *pMsg )
{
g_pPlayerStats->OnObjectivesDataMessage( pMsg );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateCamera()
//
// PURPOSE: Update the camera position/rotation
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdateCamera()
{
//handle updating the camera, as long as we aren't paused
if(!g_pGameClientShell->IsGamePaused() || !m_bCameraPosInited)
{
// Update the sway...
if (IsZoomed())
{
UpdateCameraSway();
}
// Update the camera's position and rotation..
UpdateAlternativeCamera();
// Update the player camera...
UpdatePlayerCamera();
if (!m_bUsingExternalCamera)
{
if( IsMultiplayerGame() )
{
UpdateMultiplayerCameraPosition();
}
else if( g_pInterfaceMgr->AllowCameraMovement() )
{
UpdateCameraPosition();
}
}
if (g_pInterfaceMgr->AllowCameraRotation() )
{
// [RP] 11/14/02 - Don't calculate the rotation if we're not supposed to be allowing
// mouse inputs. But we do want to update the rotation incase the camera is
// attached to the head of the player.
if( g_pDamageFXMgr->AllowInput() )
{
CalculateCameraRotation();
}
UpdateCameraRotation();
}
if (m_bUsingExternalCamera)
{
HandleZoomChange(LTTRUE);
}
// Update zoom if applicable...
if (m_bZooming)
{
UpdateCameraZoom();
}
// Update any camera displacement.
UpdateCameraDisplacement();
// Make sure the player gets updated
if (IsMultiplayerGame() || g_pInterfaceMgr->AllowCameraMovement())
{
UpdatePlayerInfo(true);
}
}
// Remember to continue updating the server if we're in multiplayer
else if (IsMultiplayerGame() && g_pGameClientShell->IsGamePaused())
{
UpdatePlayerInfo(false);
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateCameraDisplacement
//
// PURPOSE: Update any camera displacement.
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateCameraDisplacement()
{
LTVector vDisplacement( 0.0f, 0.0f, 0.0f );
LTVector vAdd;
vAdd.Init( );
UpdateCameraShake( vAdd );
vDisplacement += vAdd;
vAdd.Init( );
UpdateVehicleCamera( vAdd );
vDisplacement += vAdd;
if (!g_pInterfaceMgr->AllowCameraMovement())
return;
// Check if no significant movement occurred.
if( vDisplacement.LengthSquared( ) < 0.01f )
return;
LTVector vPos;
g_pLTClient->GetObjectPos(m_hCamera, &vPos);
vPos += vDisplacement;
g_pLTClient->SetObjectPos(m_hCamera, &vPos);
//TODO: move this code into the weapon class
HLOCALOBJ hWeapon = 0;
IClientWeaponBase *pClientWeapon = m_pClientWeaponMgr->GetCurrentClientWeapon();
if ( pClientWeapon )
{
hWeapon = pClientWeapon->GetHandle();
}
if (!hWeapon) return;
g_pLTClient->GetObjectPos(hWeapon, &vPos);
vDisplacement += LTVector(0.95f, 0.95f, 0.95f);
vPos += vDisplacement;
g_pLTClient->SetObjectPos(hWeapon, &vPos);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateCameraShake
//
// PURPOSE: Update the camera's shake
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateCameraShake( LTVector& vDisplacement )
{
// Decay...
float fDecayAmount = 2.0f * g_pGameClientShell->GetFrameTime();
m_vShakeAmount.x -= fDecayAmount;
m_vShakeAmount.y -= fDecayAmount;
m_vShakeAmount.z -= fDecayAmount;
if (m_vShakeAmount.x < 0.0f) m_vShakeAmount.x = 0.0f;
if (m_vShakeAmount.y < 0.0f) m_vShakeAmount.y = 0.0f;
if (m_vShakeAmount.z < 0.0f) m_vShakeAmount.z = 0.0f;
if (m_vShakeAmount.x <= 0.0f && m_vShakeAmount.y <= 0.0f && m_vShakeAmount.z <= 0.0f) return;
// Apply...
float faddX = GetRandom(-1.0f, 1.0f) * m_vShakeAmount.x * 3.0f;
float faddY = GetRandom(-1.0f, 1.0f) * m_vShakeAmount.y * 3.0f;
float faddZ = GetRandom(-1.0f, 1.0f) * m_vShakeAmount.z * 3.0f;
LTVector vAdd;
vDisplacement.Init(faddX, faddY, faddZ);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateVehicleCamera
//
// PURPOSE: Update the vehicle's camera displacement
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateVehicleCamera( LTVector& vDisplacement )
{
// Check if we're not in vehicle mode.
if( !m_pMoveMgr->GetVehicleMgr()->IsVehiclePhysics())
return;
m_pMoveMgr->GetVehicleMgr()->CalculateVehicleCameraDisplacment( vDisplacement );
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateCameraSway
//
// PURPOSE: Update the camera's sway
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateCameraSway()
{
// Apply...
float swayAmount = g_pGameClientShell->GetFrameTime() / 1000.0f;
float tm = g_pLTClient->GetTime()/10.0f;
// Adjust if ducking...
float fMult = (m_dwPlayerFlags & BC_CFLG_DUCK) ? g_vtCameraSwayDuckMult.GetFloat() : 1.0f;
//Adjust for skills
fMult *= g_pPlayerStats->GetSkillModifier(SKL_AIM,AimModifiers::eZoomSway);
//Adjust for damage
if (g_pDamageFXMgr->IsFOVAffected())
fMult *= 5.0f;
float faddP = fMult * g_vtCameraSwayYSpeed.GetFloat() * (float)sin(tm*g_vtCameraSwayYFreq.GetFloat()) * swayAmount;
float faddY = fMult * g_vtCameraSwayXSpeed.GetFloat() * (float)sin(tm*g_vtCameraSwayXFreq.GetFloat()) * swayAmount;
m_fPitch += faddP;
m_fYaw += faddY;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::SetExternalCamera()
//
// PURPOSE: Turn on/off external camera mode
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::SetExternalCamera(LTBOOL bExternal)
{
if (bExternal && m_pPlayerCamera->IsFirstPerson())
{
g_pDamageFXMgr->Clear();
m_pClientWeaponMgr->DisableWeapons();
ShowPlayer(LTTRUE);
m_pPlayerCamera->GoChaseMode();
m_pPlayerCamera->CameraUpdate(0.0f);
g_pInterfaceMgr->EnableCrosshair(LTFALSE); // Disable cross hair in 3rd person...
}
else if (!bExternal && !m_pPlayerCamera->IsFirstPerson()) // Go Internal
{
m_pClientWeaponMgr->EnableWeapons();
// We don't want to accidently fire off a round or two comming out of a cinematic...
IClientWeaponBase *pWeapon = m_pClientWeaponMgr->GetCurrentClientWeapon();
if( pWeapon )
{
pWeapon->ClearFiring();
}
ShowPlayer(LTFALSE);
m_pPlayerCamera->GoFirstPerson();
m_pPlayerCamera->CameraUpdate(0.0f);
g_pInterfaceMgr->EnableCrosshair(LTTRUE);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateAlternativeCamera()
//
// PURPOSE: Update the camera using an alternative camera
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::UpdateAlternativeCamera()
{
m_bLastAllowPlayerMovement = m_bAllowPlayerMovement;
m_bAllowPlayerMovement = LTTRUE;
HOBJECT hObj = NULL;
// See if we should use an alternative camera position...
CSpecialFXList* pCameraList = g_pGameClientShell->GetSFXMgr()->GetCameraList();
if (pCameraList)
{
int nNum = pCameraList->GetSize();
for (int i=0; i < nNum; i++)
{
CCameraFX* pCamFX = (CCameraFX*)(*pCameraList)[i];
if (!pCamFX) continue;
hObj = pCamFX->GetServerObj();
if (hObj)
{
uint32 dwUsrFlags;
g_pCommonLT->GetObjectFlags(hObj, OFT_User, dwUsrFlags);
if (dwUsrFlags & USRFLG_CAMERA_LIVE)
{
g_pInterfaceMgr->SetHUDRenderLevel(kHUDRenderText);
SetExternalCamera(LTTRUE);
m_bAllowPlayerMovement = pCamFX->AllowPlayerMovement();
LTVector vPos;
g_pLTClient->GetObjectPos(hObj, &vPos);
g_pLTClient->SetObjectPos(m_hCamera, &vPos);
m_bCameraPosInited = LTTRUE;
LTRotation rRot;
g_pLTClient->GetObjectRotation(hObj, &rRot);
g_pLTClient->SetObjectRotation(m_hCamera, &rRot);
// Always set the camera as the listener, so ambient sounds are
// heard from the camera position.
m_bCamIsListener = LTTRUE;
((ILTClientSoundMgr*)g_pLTClient->SoundMgr())->SetListener(LTFALSE, &vPos, &rRot, (m_bCamIsListener ? true : false));
// Initialize the cinematic camera
s_nLastCamType = pCamFX->GetType();
pCamFX->UpdateFOV();
float fFovX = pCamFX->GetFovX();
float fFovY = pCamFX->GetFovY();
TurnOnAlternativeCamera(s_nLastCamType, fFovX, fFovY);
return LTTRUE;
}
}
}
}
// Okay, we're no longer using an external camera...
if (m_bUsingExternalCamera)
{
TurnOffAlternativeCamera(s_nLastCamType);
}
return LTFALSE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::TurnOnAlternativeCamera()
//
// PURPOSE: Set up using an alternative camera
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::TurnOnAlternativeCamera(uint8 nCamType, float fFovX, float fFovY)
{
g_pInterfaceMgr->SetLetterBox((nCamType == CT_CINEMATIC));
SetCameraFOV( DEG2RAD(fFovX), DEG2RAD(fFovY) );
if (!m_bUsingExternalCamera)
{
//g_pLTClient->CPrint("TURNING ALTERNATIVE CAMERA: ON");
// Make sure we clear whatever was on the screen before
// we switch to this camera...
HandleZoomChange( LTTRUE );
g_pInterfaceMgr->ClosePopup();
m_pClientWeaponMgr->DisableWeapons();
// Make sure we're using the highest model lods
g_pLTClient->RunConsoleString("+ModelLODOffset -10");
}
m_bUsingExternalCamera = LTTRUE;
// All the number of model shadows in cinematics to be much higher
if(!g_bCinChangedNumModelShadows)
{
g_nCinSaveNumModelShadows = GetConsoleInt("ModelShadow_Proj_MaxShadowsPerFrame", 0);
WriteConsoleInt("ModelShadow_Proj_MaxShadowsPerFrame", g_kMaxNumberOfCinShadows);
g_bCinChangedNumModelShadows = true;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::TurnOffAlternativeCamera()
//
// PURPOSE: Turn off the alternative camera mode
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::TurnOffAlternativeCamera(uint8 nCamType)
{
//g_pLTClient->CPrint("TURNING ALTERNATIVE CAMERA: OFF");
g_pInterfaceMgr->SetHUDRenderLevel(kHUDRenderFull);
m_bUsingExternalCamera = LTFALSE;
// Set the listener back to the client...
((ILTClientSoundMgr*)g_pLTClient->SoundMgr())->SetListener(LTTRUE, NULL, NULL, LTTRUE);
// Force 1st person...
SetExternalCamera(LTFALSE);
// enable the weapons
m_pClientWeaponMgr->EnableWeapons();
// turn off the letter box
g_pInterfaceMgr->SetLetterBox(LTFALSE);
// Reset the normal FOV
SetCameraFOV(DEG2RAD(g_vtFOVXNormal.GetFloat()), DEG2RAD(g_vtFOVYNormal.GetFloat()));
// Make sure we're using the normal model lod...
g_pLTClient->RunConsoleString("+ModelLODOffset 0");
// Set number of shadows back to whatever they were set to before...
if(g_bCinChangedNumModelShadows)
{
WriteConsoleInt("ModelShadow_Proj_MaxShadowsPerFrame", g_nCinSaveNumModelShadows);
g_bCinChangedNumModelShadows = false;
}
}
// ----------------------------------------------------------------------- //
//
// FUNCTION: CPlayerMgr::GetCurrentClientWeapon()
//
// PURPOSE: Return a pointer to the player's bucurrent weapon
//
// ----------------------------------------------------------------------- //
IClientWeaponBase* CPlayerMgr::GetCurrentClientWeapon() const
{
return m_pClientWeaponMgr->GetCurrentClientWeapon();
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::InCameraGadgetRange
//
// PURPOSE: See if the given object is in the camera gadget's range
//
// --------------------------------------------------------------------------- //
LTBOOL CPlayerMgr::InCameraGadgetRange(HOBJECT hObj)
{
if (!hObj || !m_hCamera) return LTFALSE;
IClientWeaponBase *pClientWeapon = m_pClientWeaponMgr->GetCurrentClientWeapon();
if ( pClientWeapon && !m_pClientWeaponMgr->WeaponsEnabled() )
{
return LTFALSE;
}
LTVector vCamPos, vObjPos;
g_pLTClient->GetObjectPos(m_hCamera, &vCamPos);
g_pLTClient->GetObjectPos(hObj, &vObjPos);
LTVector vDist = vCamPos - vObjPos;
float fDist = vDist.Length();
// g_pLTClient->CPrint("fDist = %.2f, Zoom View = %d", fDist, m_nZoomView);
if (fDist < g_vtCamZoom1MaxDist.GetFloat())
{
return LTTRUE;
}
else if (fDist < g_vtCamZoom2MaxDist.GetFloat())
{
if (m_nZoomView > 0) return LTTRUE;
}
else
{
if (m_nZoomView > 1) return LTTRUE;
}
// Not zoomed in enough...
return LTFALSE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateWeaponModel()
//
// PURPOSE: Update the weapon model
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdateWeaponModel()
{
HLOCALOBJ hPlayerObj = g_pLTClient->GetClientObject();
if (!hPlayerObj) return;
// Decay weapon recoil...
DecayWeaponRecoil();
// If possible, get these values from the camera, because it
// is more up-to-date...
LTRotation rRot;
LTVector vPos(0, 0, 0);
// Weapon model pos/rot is relative to camera now...
g_pLTClient->GetObjectPos(m_hCamera, &vPos);
g_pLTClient->GetObjectRotation(m_hCamera, &rRot);
if (!m_pPlayerCamera->IsFirstPerson() || m_bUsingExternalCamera)
{
// Use the gun's flash orientation...
GetAttachmentSocketTransform(hPlayerObj, "Flash", vPos, rRot);
}
// If we aren't dead, and we aren't in the middle of changing weapons,
// let us fire.
FireType eFireType = FT_NORMAL_FIRE;
bool bFire = false;
// only fire if:
// fire key down (alt firing is disabled) AND
// player is not choosing ammo AND
// player is not choosing a weapon AND
// player is not dead AND
// player is not in spectator mode
if ( ( m_dwPlayerFlags & BC_CFLG_FIRING ) &&
( !g_pInterfaceMgr->IsChoosingAmmo() ) &&
( !g_pInterfaceMgr->IsChoosingWeapon() ) &&
( !IsPlayerDead() ) &&
( !m_bSpectatorMode ) &&
( g_pInterfaceMgr->GetGameState() == GS_PLAYING ) )
{
bFire = true;
}
// Update the model position and state...
WeaponState eWeaponState = m_pClientWeaponMgr->Update( rRot, vPos, bFire, eFireType );
// Do fire camera jitter...
if (FiredWeapon(eWeaponState) && m_pPlayerCamera->IsFirstPerson())
{
StartWeaponRecoil();
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::StartWeaponRecoil()
//
// PURPOSE: Start the weapon recoiling...
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::StartWeaponRecoil()
{
float fMaxPitch = g_vtFireJitterMaxPitchDelta.GetFloat();
if (g_vtUseCamRecoil.GetFloat() > 0.0f)
{
// Move view up a bit...
float fPCorrect = 1.0f - (m_fFireJitterPitch / DEG2RAD(g_vtMaxCamRecoilPitch.GetFloat()));
float fPVal = GetRandom(0.5f,2.0f) * DEG2RAD(g_vtBaseCamRecoilPitch.GetFloat()) * fPCorrect;
m_fFireJitterPitch += fPVal;
m_fPitch -= fPVal;
// Move view left/right a bit...
float fYawDiff = (float)fabs(m_fFireJitterYaw);
float fYCorrect = 1.0f - (fYawDiff / DEG2RAD(g_vtMaxCamRecoilYaw.GetFloat()));
float fYVal = GetRandom(-2.0f,2.0f) * DEG2RAD(g_vtBaseCamRecoilYaw.GetFloat()) * fYCorrect;
m_fFireJitterYaw += fYVal;
m_fYaw -= fYVal;
}
else
{
// Move view up a bit...(based on the current weapon/ammo type)
WEAPON const *pWeaponData = 0;
AMMO const *pAmmoData = 0;
IClientWeaponBase *pClientWeapon = m_pClientWeaponMgr->GetCurrentClientWeapon();
if ( pClientWeapon )
{
pWeaponData = pClientWeapon->GetWeapon();
pAmmoData = pClientWeapon->GetAmmo();
}
if (pWeaponData && pAmmoData)
{
if (fMaxPitch < 0.0f)
{
fMaxPitch = pWeaponData->fFireRecoilPitch * pAmmoData->fFireRecoilMult;
}
}
float fVal = (float)DEG2RAD(fMaxPitch) - m_fFireJitterPitch;
m_fFireJitterPitch += fVal;
m_fPitch -= fVal;
}
if (fMaxPitch > 0.0f)
{
// Shake the screen if it isn't shaking...
if (m_vShakeAmount.x < 0.1f && m_vShakeAmount.y < 0.1f && m_vShakeAmount.z < 0.1f)
{
LTVector vShake(0.1f, 0.1f, 0.1f);
ShakeScreen(vShake);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::DecayWeaponRecoil()
//
// PURPOSE: Decay the weapon's recoil...
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::DecayWeaponRecoil()
{
// Decay firing jitter if necessary...
if (g_vtUseCamRecoil.GetFloat() > 0.0f)
{
if (m_fFireJitterPitch > 0.0f)
{
float fCorrect = 1.0f + m_fFireJitterPitch / DEG2RAD(g_vtMaxCamRecoilPitch.GetFloat());
float fVal = (g_pGameClientShell->GetFrameTime() * g_vtCamRecoilRecover.GetFloat()) * fCorrect;
if (m_fFireJitterPitch < fVal)
{
fVal = m_fFireJitterPitch;
}
m_fFireJitterPitch -= fVal;
m_fPitch += fVal;
}
float fYawDiff = (float)fabs(m_fFireJitterYaw);
if (fYawDiff > 0.0f)
{
float fCorrect = 1.0f + fYawDiff / DEG2RAD(g_vtMaxCamRecoilYaw.GetFloat());
float fVal = (g_pGameClientShell->GetFrameTime() * g_vtCamRecoilRecover.GetFloat()) * fCorrect;
if (fYawDiff < fVal)
{
fVal = fYawDiff;
}
if (m_fFireJitterYaw < 0.0f)
fVal *= -1.0f;
m_fFireJitterYaw -= fVal;
m_fYaw += fVal;
}
}
else
{
if (m_fFireJitterPitch > 0.0f)
{
float fVal = m_fFireJitterPitch;
// get the weapon and ammo data
WEAPON const *pWeaponData = 0;
AMMO const *pAmmoData = 0;
IClientWeaponBase *pClientWeapon = m_pClientWeaponMgr->GetCurrentClientWeapon();
if ( pClientWeapon )
{
pWeaponData = pClientWeapon->GetWeapon();
pAmmoData = pClientWeapon->GetAmmo();
}
float fMaxPitch = g_vtFireJitterMaxPitchDelta.GetFloat();
float fTotalTime = g_vtFireJitterDecayTime.GetFloat();
if (pWeaponData && pAmmoData)
{
if (fMaxPitch < 0.0f)
{
fMaxPitch = pWeaponData->fFireRecoilPitch * pAmmoData->fFireRecoilMult;
}
if (fTotalTime < 0.0f)
{
fTotalTime = pWeaponData->fFireRecoilDecay;
}
}
if (fTotalTime > 0.01)
{
fVal = g_pGameClientShell->GetFrameTime() * (DEG2RAD(fMaxPitch) / fTotalTime);
}
if (m_fFireJitterPitch - fVal < 0.0f)
{
fVal = m_fFireJitterPitch;
}
m_fFireJitterPitch -= fVal;
m_fPitch += fVal;
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::SetSpectatorMode()
//
// PURPOSE: Turn spectator mode on/off
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::SetSpectatorMode(LTBOOL bOn)
{
m_bSpectatorMode = bOn;
// Don't show stats in spectator mode...
// Unless "alwaysHUD" console variable is set.
if (bOn && ( g_vtAlwaysHUD.GetFloat() > 0.0f ) )
{
g_pInterfaceMgr->SetHUDRenderLevel(kHUDRenderNone);
}
else
{
g_pInterfaceMgr->SetHUDRenderLevel(kHUDRenderFull);
}
if (m_pPlayerCamera->IsFirstPerson())
{
m_pMoveMgr->SetSpectatorMode(bOn);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::ChangeWeapon()
//
// PURPOSE: Change the weapon model
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::ChangeWeapon(uint8 nWeaponId,
uint8 nAmmoId,/*= WMGR_INVALID_ID*/
int dwAmmo/*= -1*/)
{
if (m_pClientWeaponMgr->ChangeWeapon( nWeaponId, nAmmoId, dwAmmo ))
{
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleWeaponChanged()
//
// PURPOSE: Handle updating necessary player data after a weapon
// change occurs...(NOTE: this should only be called from the
// CClientWeaponMgr::ChangeWeapon() after a successful
// weapon change)
//
// ----------------------------------------------------------------------- //
// jrg 9/2/02 - this will get called twice most of the time when switching weapons:
// once when the weapon switch is started
// and again when it completes (if a switching animation was needed)
// bImmediateSwitch will be true on the second call (or the first if the switch is immediate)
// (I'm using the repeated call to track whether we are in mid switch)
void CPlayerMgr::HandleWeaponChanged(uint8 nWeaponId, uint8 nAmmoId, bool bImmediateSwitch)
{
// Turn off zooming...
HandleZoomChange( LTTRUE );
// Tell the server to change weapons...
LTRESULT ltResult;
CAutoMessage cMsg;
cMsg.Writeuint8( MID_WEAPON_CHANGE );
cMsg.Writeuint8( nWeaponId );
cMsg.Writeuint8( nAmmoId );
ltResult = g_pLTClient->SendToServer( cMsg.Read(), MESSAGE_GUARANTEED );
ASSERT( LT_OK == ltResult );
// this isn't strictly necessary, the hide should have been
// called when we entered the chase view
if ( m_pPlayerCamera->IsChaseView() )
{
m_pClientWeaponMgr->HideWeapons();
}
//shutdown the weapon or ammo choosers...
g_pInterfaceMgr->CloseChoosers();
//when the swicth is complete...
if (bImmediateSwitch)
{
//if we are changing to a gadget, we're done switching
if (m_bChangingToGadget)
{
m_bChangingToGadget = false;
}
else
{
//we are not changing to a gadget, so forget about any gadget related stuff...
if (m_nPreGadgetWeapon != WMGR_INVALID_ID )
{
m_nPreGadgetWeapon = WMGR_INVALID_ID;
}
}
}
m_bSwitchingWeapons = !bImmediateSwitch;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::ChangeWeapon()
//
// PURPOSE: Change the weapon model
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::ChangeWeapon(ILTMessage_Read *pMsg)
{
if (!pMsg) return;
uint8 nCommandId = pMsg->Readuint8();
LTBOOL bAuto = pMsg->Readuint8();
float fAmmoId = pMsg->Readfloat();
uint8 nWeaponId = g_pWeaponMgr->GetWeaponId(nCommandId);
WEAPON const *pWeapon = g_pWeaponMgr->GetWeapon(nWeaponId);
if (!pWeapon) return;
LTBOOL bChange = (bAuto && GetConsoleBool("AutoWeaponSwitch",LTTRUE));
// See what ammo the weapon should start with...
uint8 nAmmoId = pWeapon->nDefaultAmmoId;
if (fAmmoId >= 0)
{
nAmmoId = (uint8)fAmmoId;
}
if (bChange)
{
// Force a change to the approprite weapon...
if (g_pPlayerStats)
{
ChangeWeapon(nWeaponId, nAmmoId, g_pPlayerStats->GetAmmoCount(nAmmoId));
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::ToggleHolster()
//
// PURPOSE: Toggle the holster state of the weapon.
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::ToggleHolster( bool bPlayDeselect )
{
// toggle the holster
m_pClientWeaponMgr->ToggleHolster( bPlayDeselect );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::LastWeapon()
//
// PURPOSE: Swap to our previously used weapon.
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::LastWeapon()
{
// toggle the last weapon
m_pClientWeaponMgr->LastWeapon();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::BeginSpyVision
//
// PURPOSE: setup spy vision mode
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::BeginSpyVision()
{
/* KLS - 6/22/02 - Spy vision has been cut
// Turn on the glow effect (and set the necessary values)...
g_pLTClient->RunConsoleString("ScreenGlowEnable 1");
// Turn off shadows (if they're on)...
g_nSaveSpyVisionShadows = GetConsoleInt("MaxModelShadows", 0);
WriteConsoleInt("MaxModelShadows", 0);
g_pLTClient->SetModelHook((ModelHookFn)SVModelHook, g_pGameClientShell);
m_bSpyVision = true;
*/
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::EndSpyVision
//
// PURPOSE: end spy vision mode
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::EndSpyVision()
{
/* KLS - 6/22/02 - Spy vision has been cut
// Turn off the glow effect...
g_pLTClient->RunConsoleString("ScreenGlowEnable 0");
// Turn on shadows (if they were on)...NOTE: this assumes the user won't change
// the state of the shadows while in spy vision...
WriteConsoleInt("MaxModelShadows", g_nSaveSpyVisionShadows);
g_pLTClient->SetModelHook((ModelHookFn)DefaultModelHook, g_pGameClientShell);
m_bSpyVision = false;
*/
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::BeginZoom()
//
// PURPOSE: prepare for zooming
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::BeginZoom()
{
uint8 nScopeId = g_pPlayerStats->GetScope();
m_bCamera = LTFALSE;
uint8 nAmmoId = g_pPlayerStats->GetCurrentAmmo();
if (nAmmoId != WMGR_INVALID_ID)
{
AMMO const *pAmmo = g_pWeaponMgr->GetAmmo(nAmmoId);
if (pAmmo)
{
m_bCamera = (pAmmo->eInstDamageType == DT_GADGET_CAMERA);
}
}
g_pInterfaceMgr->BeginScope(m_bSpyVision, m_bCamera);
m_pClientWeaponMgr->HideWeapons();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::EndZoom()
//
// PURPOSE: done zooming
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::EndZoom()
{
g_pInterfaceMgr->EndScope();
m_bCamera = LTFALSE;
// show the weapon
m_pClientWeaponMgr->ShowWeapons();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleZoomChange()
//
// PURPOSE: Handle a potential zoom change
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleZoomChange(LTBOOL bReset)
{
// Reset to normal FOV...
if (bReset)
{
if (m_nZoomView == 0) return;
m_nZoomView = 0;
m_bZooming = LTFALSE;
m_bZoomingIn = LTFALSE;
g_pInterfaceMgr->EndZoom();
EndZoom();
SetCameraFOV(DEG2RAD(g_vtFOVXNormal.GetFloat()), DEG2RAD(g_vtFOVYNormal.GetFloat()));
char strConsole[40];
sprintf(strConsole, "+ModelLODOffset %f", m_fSaveLODScale);
g_pLTClient->RunConsoleString(strConsole);
}
uint8 nScopeId = g_pPlayerStats->GetScope();
if (nScopeId == WMGR_INVALID_ID) return;
MOD const *pMod = g_pWeaponMgr->GetMod(nScopeId);
if (!pMod) return;
// Play zoom in/out sounds...
if (m_bZoomingIn)
{
if (pMod->szZoomInSound[0])
{
g_pClientSoundMgr->PlaySoundLocal(pMod->szZoomInSound, SOUNDPRIORITY_MISC_MEDIUM);
}
}
else
{
if (pMod->szZoomOutSound[0])
{
g_pClientSoundMgr->PlaySoundLocal(pMod->szZoomOutSound, SOUNDPRIORITY_MISC_MEDIUM);
}
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::SetCameraFOV
//
// PURPOSE: Set the camera's FOV
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::SetCameraFOV(float fFovX, float fFovY)
{
if (!m_hCamera) return;
g_pLTClient->SetCameraFOV(m_hCamera, fFovX, fFovY);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateCameraZoom
//
// PURPOSE: Update the camera's field of view
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateCameraZoom()
{
char strConsole[30];
uint32 dwWidth = 640, dwHeight = 480;
g_pLTClient->GetSurfaceDims(g_pLTClient->GetScreenSurface(), &dwWidth, &dwHeight);
float fovX, fovY;
g_pLTClient->GetCameraFOV(m_hCamera, &fovX, &fovY);
float fOldFovX = fovX;
if (!fovX)
{
fovX = DEG2RAD(g_vtFOVXNormal.GetFloat());
}
m_bZooming = LTTRUE;
float fFovXZoomed, fZoomDist;
if (m_bZoomingIn)
{
if (m_nZoomView == 1)
{
fFovXZoomed = DEG2RAD(FOVX_ZOOMED);
fZoomDist = DEG2RAD(g_vtFOVXNormal.GetFloat()) - fFovXZoomed;
}
else if (m_nZoomView == 2)
{
fFovXZoomed = DEG2RAD(FOVX_ZOOMED1);
// KLS - Always zoom all the way in...
fZoomDist = DEG2RAD(g_vtFOVXNormal.GetFloat()) - fFovXZoomed;
// Remove above code and uncomment line below to do old
// step zoom behavoir
//fZoomDist = DEG2RAD(FOVX_ZOOMED) - fFovXZoomed;
}
else if (m_nZoomView == 3)
{
fFovXZoomed = DEG2RAD(FOVX_ZOOMED2);
// KLS - Always zoom all the way in...
fZoomDist = DEG2RAD(g_vtFOVXNormal.GetFloat()) - fFovXZoomed;
// Remove above code and uncomment line below to do old
// step zoom behavoir
//fZoomDist = DEG2RAD(FOVX_ZOOMED1) - fFovXZoomed;
}
}
else
{
if (m_nZoomView == 0)
{
fFovXZoomed = DEG2RAD(g_vtFOVXNormal.GetFloat());
fZoomDist = DEG2RAD(g_vtFOVXNormal.GetFloat()) - DEG2RAD(FOVX_ZOOMED);
}
else if (m_nZoomView == 1)
{
fFovXZoomed = DEG2RAD(FOVX_ZOOMED);
fZoomDist = fFovXZoomed - DEG2RAD(FOVX_ZOOMED1);
}
else if (m_nZoomView == 2)
{
fFovXZoomed = DEG2RAD(FOVX_ZOOMED1);
fZoomDist = fFovXZoomed - DEG2RAD(FOVX_ZOOMED2);
}
}
float fZoomVel = fZoomDist / ZOOM_TIME;
float fZoomAmount = fZoomVel * g_pGameClientShell->GetFrameTime();
// Zoom camera in or out...
if (m_bZoomingIn)
{
if (fovX > fFovXZoomed)
{
// Zoom camera in...
fovX -= fZoomAmount;
}
if (fovX <= fFovXZoomed)
{
fovX = fFovXZoomed;
m_bZooming = LTFALSE;
g_pInterfaceMgr->EndZoom();
}
}
else // Zoom camera out...
{
if (fovX < fFovXZoomed)
{
// Zoom camera out...
fovX += fZoomAmount;
}
if (fovX >= fFovXZoomed)
{
fovX = fFovXZoomed;
m_bZooming = LTFALSE;
g_pInterfaceMgr->EndZoom();
if (m_nZoomView == 0)
{
EndZoom();
}
}
}
if (fOldFovX != fovX)
{
fovY = (fovX * DEG2RAD(g_vtFOVYNormal.GetFloat())) / DEG2RAD(g_vtFOVXNormal.GetFloat());
SetCameraFOV(fovX, fovY);
// Update the lod adjustment for models...
float fZoomAmount = (DEG2RAD(g_vtFOVXNormal.GetFloat()) - fovX) / (DEG2RAD(g_vtFOVXNormal.GetFloat()) - DEG2RAD(FOVX_ZOOMED2));
float fNewLODOffset = m_fSaveLODScale + (LOD_ZOOMADJUST * fZoomAmount);
sprintf(strConsole, "+ModelLODOffset %f", fNewLODOffset);
g_pLTClient->RunConsoleString(strConsole);
//g_pLTClient->CPrint("Current FOV (%f, %f)", fovX, fovY);
//g_pLTClient->CPrint("Current Zoom LODOffset: %f", fNewLODOffset);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::OnCommandOn()
//
// PURPOSE: Handle client commands
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::OnCommandOn(int command)
{
// Make sure we're in the world...
if (!IsPlayerInWorld()) return LTFALSE;
// See if the vehiclemgr would like to trap this
if(m_pMoveMgr->GetVehicleMgr()->OnCommandOn(command))
{
return LTTRUE;
}
// Check for weapon change...
if (g_pWeaponMgr->GetFirstWeaponCommandId() <= command &&
command <= g_pWeaponMgr->GetLastWeaponCommandId())
{
ChangeWeapon( g_pWeaponMgr->GetWeaponId( command ) );
return LTTRUE;
}
// Take appropriate action
switch (command)
{
case COMMAND_ID_ACTIVATE :
{
if (IsPlayerDead())
{
if (IsMultiplayerGame())
{
if (g_pLTClient->GetTime() > m_fEarliestRespawnTime)
{
// Allow respawn after a certain amount of time. This way the Player
// can remain in 'limbo' for as long as they want and wait to be revived.
HandleRespawn();
}
else
{
// If waiting to respawn and they hit activate, then they will cancel
// their revive.
if( IsRevivePlayerGameType( ))
{
SetCancelRevive( true );
}
}
}
else if (g_pLTClient->GetTime() > m_fEarliestRespawnTime)
{
g_pMissionMgr->HandleMissionFailed();
}
}
else
{
// If we're pointed at something activate it if we're not
// riding a vehicle...
if (m_pMoveMgr->GetVehicleMgr()->CanDismount())
{
// Vehicle Mgr now handles calling DoActivate(), just tell
// the vehicle mgr to get off the vehicle...
m_pMoveMgr->GetVehicleMgr()->SetPhysicsModel(PPM_NORMAL);
return LTTRUE;
}
else if (GetTargetMgr()->IsTargetInRange())
{
DamageType eDT = GetTargetMgr()->RequiredGadgetDamageType();
if (eDT != DT_INVALID && !GetGadgetDisabler()->DisableOnActivate())
{
//jrg 9/2/02- moved this check to Update() because we might be in the middle
// of switching weapons and miss the OnCommandOn() and therefore not switch
// to the gadget even though we're holding down Activate
// if (!UseGadget(eDT))
// DoActivate();
}
else
{
//jrg 1/23/03 - if you're not allowed weapons, you can't activate stuff either
if (g_pDamageFXMgr->AllowWeapons( ))
DoActivate();
}
}
else
{
//we're not pointed at anything, so reload
IClientWeaponBase *pClientWeapon = g_pPlayerMgr->GetCurrentClientWeapon();
if ( pClientWeapon )
{
// Reload the clip and let the server know...
pClientWeapon->ReloadClip( true, -1, false, true );
}
}
}
}
break;
case COMMAND_ID_MOVE_BODY:
{
CActivationData data = GetTargetMgr()->GetActivationData();
if( GetCarryingObject() )
{
data.m_nType = MID_ACTIVATE_MOVE;
if( CanDropCarriedObject( ))
{
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_ACTIVATE);
data.Write(cMsg);
g_pLTClient->SendToServer(cMsg.Read(), MESSAGE_GUARANTEED);
}
else
{
g_pClientSoundMgr->PlayInterfaceSound("Interface\\Snd\\Nodrop.wav");
}
}
else if( CanCarryObject( ))
{
data.m_nType = MID_ACTIVATE_MOVE;
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_ACTIVATE);
data.Write(cMsg);
g_pLTClient->SendToServer(cMsg.Read(), MESSAGE_GUARANTEED);
}
}
break;
case COMMAND_ID_FIRING :
{
if (IsPlayerDead())
{
if (IsMultiplayerGame())
{
if (g_pLTClient->GetTime() > m_fEarliestRespawnTime)
{
// Allow respawn after a certain amount of time. This way the Player
// can remain in 'limbo' for as long as they want and wait to be revived.
HandleRespawn();
}
}
else if (g_pLTClient->GetTime() > m_fEarliestRespawnTime)
{
g_pMissionMgr->HandleMissionFailed();
}
}
}
break;
case COMMAND_ID_RELOAD :
{
IClientWeaponBase *pClientWeapon = g_pPlayerMgr->GetCurrentClientWeapon();
if ( pClientWeapon )
{
// Reload the clip and let the server know...
pClientWeapon->ReloadClip( true, -1, false, true );
}
}
break;
#ifndef _TO2DEMO
case COMMAND_ID_NEXT_VISMODE :
{
m_pVisionModeMgr->NextMode();
}
break;
#endif
case COMMAND_ID_ZOOM_IN :
{
if ( !m_pClientWeaponMgr->WeaponsEnabled() ) break;
uint8 nScopeId = g_pPlayerStats->GetScope();
if (nScopeId == WMGR_INVALID_ID) break;
MOD const * pMod = g_pWeaponMgr->GetMod(nScopeId);
if (!pMod) break;
int nZoomLevel = pMod->nZoomLevel;
// Figure out if our current weapon has a scope...
if (!m_bZooming && nZoomLevel > 0)
{
int nOldZoom = m_nZoomView;
// KLS - Always zoom all the way out or in...
if (nOldZoom == nZoomLevel)
{
m_nZoomView = 0;
}
else
{
m_nZoomView = nZoomLevel;
}
// Remove above code and uncomment line below to do old
// step zoom behavoir
// m_nZoomView = (m_nZoomView + 1) % (nZoomLevel+1);
if (m_nZoomView > nOldZoom)
{
m_bZooming = LTTRUE;
m_bZoomingIn = LTTRUE;
if (nOldZoom == 0)
{
BeginZoom();
}
g_pInterfaceMgr->BeginZoom(LTTRUE);
HandleZoomChange();
}
else if (m_nZoomView < nOldZoom)
{
m_bZooming = LTTRUE;
m_bZoomingIn = LTFALSE;
g_pInterfaceMgr->BeginZoom(LTFALSE);
HandleZoomChange();
}
}
}
break;
case COMMAND_ID_TURNAROUND :
{
m_fYaw += MATH_PI;
}
break;
case COMMAND_ID_CENTERVIEW :
{
m_fPitch = 0.0f;
}
break;
case COMMAND_ID_STRAFE:
{
m_bStrafing = LTTRUE;
}
break;
case COMMAND_ID_RUNLOCK :
{
if (!m_pMoveMgr->GetVehicleMgr()->IsVehiclePhysics())
{
m_pMoveMgr->SetRunLock(!m_pMoveMgr->RunLock());
}
}
break;
case COMMAND_ID_DUCKLOCK :
{
if( !IsCarryingHeavyObject() && !m_pMoveMgr->GetVehicleMgr()->IsVehiclePhysics())
{
m_pMoveMgr->SetDuckLock(!m_pMoveMgr->DuckLock());
}
}
break;
case COMMAND_ID_JUMP :
case COMMAND_ID_DUCK :
{
m_pMoveMgr->SetDuckLock(LTFALSE);
}
break;
default :
return LTFALSE;
break;
}
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::OnCommandOff()
//
// PURPOSE: Handle command off notification
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::OnCommandOff(int command)
{
// See if the vehiclemgr would like to trap this
if(m_pMoveMgr->GetVehicleMgr()->OnCommandOff(command))
{
return LTTRUE;
}
switch (command)
{
case COMMAND_ID_STRAFE :
{
m_bStrafing = LTFALSE;
}
break;
default :
return LTFALSE;
break;
}
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleMsgPlayerStateChange()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HandleMsgPlayerStateChange (ILTMessage_Read *pMsg)
{
m_ePlayerState = (PlayerState) pMsg->Readuint8();
switch (m_ePlayerState)
{
case PS_DYING:
{
// Clear out any damagefx...
// Do this first since we may be unattaching the camera from the head when clearing out a
// damage fx.
g_pDamageFXMgr->Clear();
AttachCameraToHead(LTTRUE);
if( IsMultiplayerGame() )
{
m_fMultiplayerDeathCamMoveTimer = 0.0f;
m_fMultiAttachDeathCamTimer = 0.0f;
switch (g_pGameClientShell->GetGameType())
{
case eGameTypeCooperative:
{
m_fEarliestRespawnTime = g_pLTClient->GetTime() + ((CCharacterFX::GetNumPlayersInGame() > 1) ?
g_vtMultiplayerRespawnWaitTime.GetFloat() :
g_vtRespawnWaitTime.GetFloat());
} break;
case eGameTypeDoomsDay:
{
m_fEarliestRespawnTime = g_pLTClient->GetTime() + ((g_pInterfaceMgr->GetClientInfoMgr()->GetNumPlayersOnTeam() > 1) ?
g_vtDoomsdayRespawnWaitTime.GetFloat() :
g_vtRespawnWaitTime.GetFloat());
} break;
case eGameTypeDeathmatch:
case eGameTypeTeamDeathmatch:
default:
{
m_fEarliestRespawnTime = g_pLTClient->GetTime() + g_vtRespawnWaitTime.GetFloat();
} break;
}
// Clear the cancel revive setting.
if( IsRevivePlayerGameType( ))
{
SetCancelRevive( false );
}
g_pInterfaceMgr->SetHUDRenderLevel(kHUDRenderDead);
g_pHUDMgr->QueueUpdate(kHUDRespawn);
}
else
{
m_fEarliestRespawnTime = g_pLTClient->GetTime() + g_vtRespawnWaitTime.GetFloat();
g_pInterfaceMgr->SetHUDRenderLevel(kHUDRenderNone);
}
if( g_pMoveMgr->GetVehicleMgr()->GetPhysicsModel() == PPM_LURE )
{
// Get the playerlurefx.
PlayerLureFX* pPlayerLureFX = PlayerLureFX::GetPlayerLureFX( g_pMoveMgr->GetVehicleMgr()->GetPlayerLureId() );
if( pPlayerLureFX )
{
char const* pszDeathFX = pPlayerLureFX->GetDeathFX( );
if( !pszDeathFX && pszDeathFX[0] != '\0' )
{
LTVector vPos;
g_pLTClient->GetObjectPos( g_pMoveMgr->GetObject(), &vPos );
CLIENTFX_CREATESTRUCT fxInit( pszDeathFX, 0, vPos );
g_pClientFXMgr->CreateClientFX( LTNULL, fxInit, LTTRUE );
}
}
}
ClearPlayerModes();
m_pClientWeaponMgr->OnPlayerDead();
g_pInterfaceMgr->AddToClearScreenCount();
if (!IsMultiplayerGame( ))
{
g_pGameClientShell->CSPrint(LoadTempString(IDS_YOUWEREKILLED));
g_pInterfaceMgr->StartScreenFadeOut(g_vtScreenFadeOutTime.GetFloat());
}
}
break;
case PS_ALIVE:
{
// g_pScores->Show(false);
g_pHUDMgr->QueueUpdate(kHUDRespawn);
g_pDamageFXMgr->Clear(); // Remove all the damage sfx
ClearDamageSectors();
g_pInterfaceMgr->ForceScreenFadeIn(g_vtScreenFadeInTime.GetFloat());
AttachCameraToHead(LTFALSE);
g_pInterfaceMgr->SetHUDRenderLevel(kHUDRenderFull);
SetExternalCamera(LTFALSE);
m_pClientWeaponMgr->OnPlayerAlive();
if( IsMultiplayerGame() )
{
AllowPlayerMovement( LTTRUE );
}
// Since we are alive, disassociate any body from us...
CSpecialFXList* pList = g_pGameClientShell->GetSFXMgr()->GetFXList(SFX_BODY_ID);
if( !pList ) return;
int nNumBodies = pList->GetSize();
uint32 dwId;
g_pLTClient->GetLocalClientID( &dwId );
for( int i = 0; i < nNumBodies; ++i )
{
if ((*pList)[i])
{
CBodyFX* pBody = (CBodyFX*)(*pList)[i];
if( pBody->GetClientId() == dwId )
{
pBody->RemoveClientAssociation( );
}
}
}
}
break;
case PS_DEAD:
{
g_pDamageFXMgr->Clear(); // Remove all the damage sfx
ClearDamageSectors();
s_fDeadTimer = 0.0f;
}
break;
case PS_GHOST:
{
AttachCameraToHead(LTFALSE);
m_pClientWeaponMgr->HideWeapons();
g_pInterfaceMgr->SetHUDRenderLevel(kHUDRenderNone);
g_pInterfaceMgr->ForceScreenFadeIn(g_vtScreenFadeInTime.GetFloat());
// SetExternalCamera(LTTRUE);
m_pClientWeaponMgr->DisableWeapons();
}
break;
default : break;
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleRespawn
//
// PURPOSE: Handle player respawn
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::HandleRespawn()
{
if (!IsPlayerDead()) return;
// if we're in multiplayer send the respawn command...
if (IsMultiplayerGame())
{
// send a message to the server telling it that it's ok to respawn us now...
SendEmptyServerMsg(MID_PLAYER_RESPAWN);
return;
}
else // Bring up load game menu...
{
g_pInterfaceMgr->SwitchToScreen(SCREEN_ID_LOAD);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::PreRender()
//
// PURPOSE: Sets up the client for rendering
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::PreRender()
{
if (!m_bCameraPosInited) return LTFALSE;
// Make sure the rendered player object is right where it should be.
UpdateServerPlayerModel();
// Make sure we process attachments before updating the weapon model
// and special fx...(some fx are based on attachment positions/rotations)
g_pLTClient->ProcessAttachments(g_pLTClient->GetClientObject());
// Make sure the weapon is updated before we render the camera...
UpdateWeaponModel();
// Make sure the move-mgr models are updated before we render...
m_pMoveMgr->UpdateModels();
// Update the flash light...
m_pFlashLight->Update();
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdatePlayerCamera()
//
// PURPOSE: Update the player camera
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::UpdatePlayerCamera()
{
// Make sure our player camera is attached...
if (m_pPlayerCamera->GetAttachedObject() != m_pMoveMgr->GetObject())
{
m_pPlayerCamera->AttachToObject(m_pMoveMgr->GetObject());
}
if (m_pPlayerCamera->IsChaseView())
{
// Init the camera so they can be adjusted via the console...
InitPlayerCamera();
Update3rdPersonInfo();
}
// Update our camera position based on the player camera...
m_pPlayerCamera->CameraUpdate(g_pGameClientShell->GetFrameTime());
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::InitPlayerCamera()
//
// PURPOSE: Update the player camera
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::InitPlayerCamera()
{
LTVector vOffset(0.0f, 0.0f, 0.0f);
vOffset.y = g_vtChaseCamOffset.GetFloat();
m_pPlayerCamera->SetDistUp(g_vtChaseCamDistUp.GetFloat());
m_pPlayerCamera->SetDistBack(g_vtChaseCamDistBack.GetFloat());
m_pPlayerCamera->SetPointAtOffset(vOffset);
m_pPlayerCamera->SetChaseOffset(vOffset);
m_pPlayerCamera->SetCameraState(CPlayerCamera::SOUTH);
// Determine the first person offset...
vOffset = g_vPlayerCameraOffset;
CCharacterFX* pChar = m_pMoveMgr->GetCharacterFX();
if (pChar)
{
vOffset = GetPlayerHeadOffset( );
}
m_pPlayerCamera->SetFirstPersonOffset(vOffset);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateCameraPosition()
//
// PURPOSE: Update the camera position
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdateCameraPosition()
{
LTVector vPos = m_pPlayerCamera->GetPos();
if (m_pPlayerCamera->IsFirstPerson())
{
// Special case of camera being attached to the player's head
// (i.e., death)...
if (m_bCameraAttachedToHead)
{
LTVector vHeadPos;
LTRotation rHeadRot;
HLOCALOBJ hPlayer = g_pLTClient->GetClientObject();
// Make sure we never go backwards in our animation...
uint32 dwCurTime = 0;
static uint32 dwPrevTime = 0;
g_pModelLT->GetCurAnimTime( hPlayer, MAIN_TRACKER, dwCurTime );
if( (dwCurTime > 0) && (dwCurTime < dwPrevTime) )
{
uint32 dwFrameTime = (uint32)(10000.0f * g_pGameClientShell->GetFrameTime());
g_pModelLT->SetCurAnimTime( hPlayer, MAIN_TRACKER, dwPrevTime + dwFrameTime );
}
dwPrevTime = dwCurTime;
GetPlayerHeadPosRot(vHeadPos, rHeadRot);
vPos = vHeadPos;
if( m_bLerpAttachedCamera )
{
m_rRotation.Slerp( m_rRotation, rHeadRot, g_vtAttachedCamInterpolationRate.GetFloat( 0.1f ) );
}
else
{
m_rRotation = rHeadRot;
}
//save this rotation into the yaw pitch and roll as well so that when we
//come out of the attached mode, our view won't pop
EulerAngles EA = Eul_FromQuat( m_rRotation, EulOrdYXZr );
m_fModelAttachYaw = EA.x;
m_fModelAttachPitch = EA.y;
m_fModelAttachRoll = EA.z;
}
else
{
//normal updating of the head position
m_pHeadBobMgr->AdjustCameraPos(vPos);
vPos.y += m_fCamDuck;
vPos += m_pCameraOffsetMgr->GetPosDelta();
}
}
else
{
m_rRotation = m_pPlayerCamera->GetRotation();
}
g_pLTClient->SetObjectPos(m_hCamera, &vPos);
m_bCameraPosInited = LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateMultiplayerCameraPosition()
//
// PURPOSE: Update the camera position while in a multiplayer game...
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdateMultiplayerCameraPosition()
{
// If the player is alive don't do anything special. Just treat like single player....
if( IsPlayerDead() )
{
HOBJECT hBody = NULL;
// We actually want to use the body prop, so...
CSpecialFXList* pList = g_pGameClientShell->GetSFXMgr()->GetFXList(SFX_BODY_ID);
if (!pList) return;
int nNumBodies = pList->GetSize();
uint32 dwId;
g_pLTClient->GetLocalClientID(&dwId);
float fNewestBodyTime = -1.0f;
for (int i=0; i < nNumBodies; i++)
{
if ((*pList)[i])
{
CBodyFX* pBody = (CBodyFX*)(*pList)[i];
if( (pBody->GetClientId() == dwId) && (pBody->GetTimeCreated() > fNewestBodyTime) )
{
// Keep the newest body belonging to this client...
fNewestBodyTime = pBody->GetTimeCreated();
hBody = pBody->GetServerObj();
}
}
}
if( hBody )
{
bool bTimesUp = (m_fMultiAttachDeathCamTimer > g_vtMultiAttachDeathCamMaxTime.GetFloat());
// Increment our attach camera timer...Always increment this even if we're
// not attached since we may become unattached at some point...
m_fMultiAttachDeathCamTimer += g_pLTClient->GetFrameTime();
// Check the body to see if the death animation has finished playing....
uint32 dwFlags;
g_pModelLT->GetPlaybackState( hBody, MAIN_TRACKER, dwFlags );
if( (dwFlags & MS_PLAYDONE) || bTimesUp )
{
// Detach from the head and float above the body...
LTVector vFinalCamPos;
LTRotation rAniCamRot;
LTVector vAniCamPos;
// Get the position of where the camera left off in the animation...
GetPlayerHeadPosRot( vAniCamPos, rAniCamRot );
// Offset the camera position from the position of the body...
g_pLTClient->GetObjectPos( hBody, &vFinalCamPos);
vFinalCamPos += GetPlayerHeadOffset( );
// Detach the camera and then get the rotation from the animation rotation...
AttachCameraToHead( LTFALSE );
LTRotation rRot( m_fPitch, m_fYaw, m_fRoll );
m_fMultiplayerDeathCamMoveTimer += g_pLTClient->GetFrameTime();
float fMoveDelta = g_vtMultiplayerDeathCamMoveTime.GetFloat( 3.0f );
float fPercent = (fMoveDelta > 0.0f ? m_fMultiplayerDeathCamMoveTimer / fMoveDelta : 0.0f);
float fT = Clamp( fPercent, 0.0f, 1.0f );
LTVector vLerped;
VEC_LERP( vLerped, vAniCamPos, vFinalCamPos, fT );
// Don't clip the camera into the world...
m_pPlayerCamera->CalcNonClipPos( vLerped, rRot );
g_pLTClient->SetObjectPos( m_hCamera, &vLerped );
m_bCameraPosInited = LTTRUE;
return;
}
else
{
// Sometimes the death animation is multiple animations, so we'll make
// sure to keep the camera attached if an animation is playing...
AttachCameraToHead(LTTRUE);
}
}
}
// The player is alive, has no body, or the body is still animating. Just use the normal position...
UpdateCameraPosition();
return;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::CalculateCameraRotation()
//
// PURPOSE: Calculate the new camera rotation
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::CalculateCameraRotation()
{
CGameSettings* pSettings = g_pInterfaceMgr->GetSettings();
if (!pSettings) return;
LTBOOL bIsVehicle = m_pMoveMgr->GetVehicleMgr()->IsVehiclePhysics();
float fVal = 1.0f + (float)(3 * m_nZoomView);
// Get axis offsets...
float offsets[3];
g_pLTClient->GetAxisOffsets(offsets);
if (m_bRestoreOrientation)
{
offsets[0] = offsets[1] = offsets[2] = 0.0f;
m_bRestoreOrientation = LTFALSE;
}
if (m_bStrafing)
{
// Clear yaw and pitch offsets if we're using mouse strafing...
offsets[0] = offsets[1] = 0.0f;
}
float fYawDelta = offsets[0] / fVal;
float fPitchDelta = offsets[1] / fVal;
if (g_vtAdaptiveMouse.GetFloat() && fYawDelta != 0.0f)
{
float fMaxOff = g_vtAdaptiveMouseMaxOffset.GetFloat();
float fAbsYawDelta = (float)fabs(fYawDelta);
bool bNegative = (fYawDelta < 0.0f);
g_pLTClient->CPrint("Initial fYawDelta = %.6f", fYawDelta);
if (fAbsYawDelta <= fMaxOff)
{
fVal = fAbsYawDelta / fMaxOff;
fYawDelta = (WaveFn_SlowOn(fVal) * fMaxOff);
fYawDelta = bNegative ? -fYawDelta : fYawDelta;
g_pLTClient->CPrint("Adjusted fYawDelta = %.6f", fYawDelta);
}
}
m_fYaw += fYawDelta;
// [kml] 12/26/00 Check varying degrees of strafe and look.
if(!(m_dwPlayerFlags & BC_CFLG_STRAFE))
{
if(m_dwPlayerFlags & BC_CFLG_LEFT)
{
m_fYaw -= g_pGameClientShell->GetFrameTime() * ((m_dwPlayerFlags & BC_CFLG_RUN) ? g_vtFastTurnRate.GetFloat() : g_vtNormalTurnRate.GetFloat());
}
if(m_dwPlayerFlags & BC_CFLG_RIGHT)
{
m_fYaw += g_pGameClientShell->GetFrameTime() * ((m_dwPlayerFlags & BC_CFLG_RUN) ? g_vtFastTurnRate.GetFloat() : g_vtNormalTurnRate.GetFloat());
}
}
if (pSettings->MouseLook() || (m_dwPlayerFlags & BC_CFLG_LOOKUP) || (m_dwPlayerFlags & BC_CFLG_LOOKDOWN)
|| m_bHoldingMouseLook)
{
if (pSettings->MouseLook() || m_bHoldingMouseLook)
{
if (pSettings->MouseInvertY())
{
m_fPitch -= fPitchDelta;
}
else
{
m_fPitch += fPitchDelta;
}
}
if(m_dwPlayerFlags & BC_CFLG_LOOKUP)
{
m_fPitch -= g_pGameClientShell->GetFrameTime() * g_vtLookUpRate.GetFloat();
}
if(m_dwPlayerFlags & BC_CFLG_LOOKDOWN)
{
m_fPitch += g_pGameClientShell->GetFrameTime() * g_vtLookUpRate.GetFloat();
}
// Don't allow much movement up/down if 3rd person...
if (!m_pPlayerCamera->IsFirstPerson())
{
float fMinY = DEG2RAD(45.0f) - 0.1f;
if (m_fPitch < -fMinY) m_fPitch = -fMinY;
if (m_fPitch > fMinY) m_fPitch = fMinY;
}
}
else if (m_fPitch != 0.0f && GetConsoleInt("AutoCenter",0))
{
float fPitchDelta = (g_pGameClientShell->GetFrameTime() * g_vtLookUpRate.GetFloat());
if (m_fPitch > 0.0f) m_fPitch -= Min(fPitchDelta, m_fPitch);
if (m_fPitch < 0.0f) m_fPitch += Min(fPitchDelta, -m_fPitch);
}
float fMinY = MATH_HALFPI - 0.1f;
if (m_fPitch < -fMinY) m_fPitch = -fMinY;
if (m_fPitch > fMinY) m_fPitch = fMinY;
// Set camera and player variables...
// Only use mouse values for yaw if the player isn't on a vehicle...
if (bIsVehicle)
{
// Can't look up/down on vehicles...
LTVector vPlayerPYR(m_fPlayerPitch, m_fPlayerYaw, m_fPlayerRoll);
LTVector vPYR(m_fPitch, m_fYaw, m_fRoll);
m_pMoveMgr->GetVehicleMgr()->CalculateVehicleRotation(vPlayerPYR, vPYR, fYawDelta);
m_fPlayerPitch = vPlayerPYR.x;
m_fPlayerYaw = vPlayerPYR.y;
m_fPlayerRoll = vPlayerPYR.z;
m_fPitch = vPYR.x;
m_fYaw = vPYR.y;
m_fRoll = vPYR.z;
}
else // Not vehicle...
{
m_fPlayerPitch = 0.0f;
m_fPlayerYaw = m_fYaw;
m_fPlayerRoll = m_fRoll;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateCameraRotation()
//
// PURPOSE: Set the new camera rotation
//
// ----------------------------------------------------------------------- //
LTBOOL CPlayerMgr::UpdateCameraRotation()
{
HLOCALOBJ hPlayerObj = g_pLTClient->GetClientObject();
if (!hPlayerObj) return LTFALSE;
// Update camera orientation vars...
LTVector vPitchYawRollDelta = m_pCameraOffsetMgr->GetPitchYawRollDelta();
if (m_bUsingExternalCamera)
{
// Just calculate the correct player rotation...
m_rRotation = LTRotation(m_fPitch, m_fYaw, m_fRoll);
}
else if (m_pPlayerCamera->IsFirstPerson())
{
if (!m_bCameraAttachedToHead)
{
float fPitch = m_fPitch + vPitchYawRollDelta.x;
float fYaw = m_fYaw + vPitchYawRollDelta.y;
float fRoll = m_fRoll + vPitchYawRollDelta.z;
m_rRotation = LTRotation(fPitch, fYaw, fRoll);
}
g_pLTClient->SetObjectRotation(m_hCamera, &m_rRotation);
}
else
{
// Set the camera to use the rotation calculated by the player camera,
// however we still need to calculate the correct rotation to be sent
// to the player...
float fAdjust = DEG2RAD(g_vtChaseCamPitchAdjust.GetFloat());
m_rRotation.Rotate(m_rRotation.Right(), m_fPitch + fAdjust);
g_pLTClient->SetObjectRotation(m_hCamera, &m_rRotation);
// Okay, now calculate the correct player rotation...
m_rRotation = LTRotation(m_fPitch, m_fYaw, m_fRoll);
}
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::Update3rdPersonInfo
//
// PURPOSE: Update the 3rd person cross hair / camera info
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::Update3rdPersonInfo()
{
HLOCALOBJ hPlayerObj = g_pLTClient->GetClientObject();
if (!hPlayerObj || IsPlayerDead()) return;
HOBJECT hFilterList[] = {hPlayerObj, m_pMoveMgr->GetObject(), NULL};
ClientIntersectInfo info;
ClientIntersectQuery query;
LTVector vPlayerPos, vForward;
g_pLTClient->GetObjectPos(hPlayerObj, &vPlayerPos);
float fCrosshairDist = -1.0f;
float fCameraOptZ = g_vtChaseCamDistBack.GetFloat();
// Figure out crosshair distance...
IClientWeaponBase* pClientWeapon = m_pClientWeaponMgr->GetCurrentClientWeapon();
if (g_pInterfaceMgr->IsCrosshairOn() && pClientWeapon)
{
WEAPON const *pWeapon = pClientWeapon->GetWeapon();
if (!pWeapon) return;
fCrosshairDist = (float) pWeapon->nRange;
vForward = m_rRotation.Forward();
// Determine where the cross hair should be...
LTVector vStart, vEnd, vPos;
VEC_COPY(vStart, vPlayerPos);
VEC_MULSCALAR(vEnd, vForward, fCrosshairDist);
VEC_ADD(vEnd, vEnd, vStart);
VEC_COPY(query.m_From, vStart);
VEC_COPY(query.m_To, vEnd);
query.m_Flags = INTERSECT_OBJECTS | IGNORE_NONSOLID;
query.m_FilterFn = ObjListFilterFn;
query.m_pUserData = hFilterList;
if (g_pLTClient->IntersectSegment (&query, &info))
{
VEC_COPY(vPos, info.m_Point);
}
else
{
VEC_COPY(vPos, vEnd);
}
LTVector vTemp;
VEC_SUB(vTemp, vPos, vStart);
fCrosshairDist = VEC_MAG(vTemp);
}
// Figure out optinal camera distance...
LTRotation rRot;
g_pLTClient->GetObjectRotation(hPlayerObj, &rRot);
vForward = rRot.Forward();
// Determine how far behind the player the camera can go...
LTVector vEnd;
vEnd = vForward * -fCameraOptZ + vPlayerPos;
query.m_From = vPlayerPos;
query.m_To = vEnd;
query.m_Flags = INTERSECT_OBJECTS | IGNORE_NONSOLID;
query.m_FilterFn = ObjListFilterFn;
query.m_pUserData = hFilterList;
if (g_pLTClient->IntersectSegment (&query, &info))
{
LTVector vTemp;
VEC_SUB(vTemp, info.m_Point, vPlayerPos);
float fDist = VEC_MAG(vTemp);
fCameraOptZ = fDist < fCameraOptZ ? -(fDist - 5.0f) : -fCameraOptZ;
}
else
{
fCameraOptZ = -fCameraOptZ;
}
m_pPlayerCamera->SetOptZ(fCameraOptZ);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdatePlayerFlags
//
// PURPOSE: Update our copy of the movement flags
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdatePlayerFlags()
{
// Update flags...
m_dwPlayerFlags = m_pMoveMgr->GetControlFlags();
if (g_pLTClient->IsCommandOn(COMMAND_ID_LOOKUP))
{
m_dwPlayerFlags |= BC_CFLG_LOOKUP;
}
if (g_pLTClient->IsCommandOn(COMMAND_ID_LOOKDOWN))
{
m_dwPlayerFlags |= BC_CFLG_LOOKDOWN;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdatePlayerInfo()
//
// PURPOSE: Tell the player about the new camera stuff
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdatePlayerInfo(bool bPlaying)
{
if (m_bAllowPlayerMovement != m_bLastAllowPlayerMovement)
{
g_pGameClientShell->SetInputState(!!m_bAllowPlayerMovement);
}
if (m_pPlayerCamera->IsChaseView() != m_bLastSent3rdPerson)
{
m_nPlayerInfoChangeFlags |= CLIENTUPDATE_3RDPERSON;
m_bLastSent3rdPerson = m_pPlayerCamera->IsChaseView();
if (m_pPlayerCamera->IsChaseView())
{
m_nPlayerInfoChangeFlags |= CLIENTUPDATE_3RDPERVAL;
}
}
if (m_bAllowPlayerMovement != m_bLastAllowPlayerMovement)
{
m_nPlayerInfoChangeFlags |= CLIENTUPDATE_ALLOWINPUT;
}
// Always send CLIENTUPDATE_ALLOWINPUT changes guaranteed...
if (m_nPlayerInfoChangeFlags & CLIENTUPDATE_ALLOWINPUT)
{
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_UPDATE);
cMsg.Writeuint16(CLIENTUPDATE_ALLOWINPUT);
cMsg.Writeuint8((uint8)m_bAllowPlayerMovement);
g_pLTClient->SendToServer(cMsg.Read(), MESSAGE_GUARANTEED);
m_nPlayerInfoChangeFlags &= ~CLIENTUPDATE_ALLOWINPUT;
}
float fCurTime = g_pLTClient->GetTime();
float fSendRate = 1.0f / g_CV_CSendRate.GetFloat(DEFAULT_CSENDRATE);
float fSendDelta = (fCurTime - m_fPlayerInfoLastSendTime);
if ( m_pMoveMgr->IsInWorld() && (!g_pClientMultiplayerMgr->IsConnectedToRemoteServer( ) || fSendDelta > fSendRate))
{
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_UPDATE);
if (g_vtPlayerRotate.GetFloat(1.0) > 0.0)
{
if( PPM_SNOWMOBILE == m_pMoveMgr->GetVehicleMgr()->GetPhysicsModel() )
{
m_nPlayerInfoChangeFlags |= CLIENTUPDATE_FULLPLAYERROT;
m_nPlayerInfoChangeFlags &= ~CLIENTUPDATE_ACCURATEPLAYERROT;
m_nPlayerInfoChangeFlags &= ~CLIENTUPDATE_PLAYERROT;
}
else if( m_bServerAccurateRotation )
{
m_nPlayerInfoChangeFlags |= CLIENTUPDATE_ACCURATEPLAYERROT;
m_nPlayerInfoChangeFlags &= ~CLIENTUPDATE_PLAYERROT;
m_nPlayerInfoChangeFlags &= ~CLIENTUPDATE_FULLPLAYERROT;
}
else
{
m_nPlayerInfoChangeFlags |= CLIENTUPDATE_PLAYERROT;
m_nPlayerInfoChangeFlags &= ~CLIENTUPDATE_ACCURATEPLAYERROT;
m_nPlayerInfoChangeFlags &= ~CLIENTUPDATE_FULLPLAYERROT;
}
}
if ( m_bSendCameraOffsetToServer )
{
m_nPlayerInfoChangeFlags |= CLIENTUPDATE_CAMERAOFFSET;
}
cMsg.Writeuint16(m_nPlayerInfoChangeFlags);
if (m_nPlayerInfoChangeFlags & CLIENTUPDATE_PLAYERROT)
{
// Set the player's rotation (don't allow model to rotate up/down).
LTRotation rPlayerRot(m_fPlayerPitch, m_fPlayerYaw, m_fPlayerRoll);
cMsg.Writeuint8(CompressRotationByte(&rPlayerRot));
}
else if ( m_nPlayerInfoChangeFlags & CLIENTUPDATE_ACCURATEPLAYERROT )
{
LTRotation rPlayerRot( m_fPlayerPitch, m_fPlayerYaw, m_fPlayerRoll );
cMsg.Writeuint16( CompressRotationShort( &rPlayerRot ) );
}
else if( m_nPlayerInfoChangeFlags & CLIENTUPDATE_FULLPLAYERROT )
{
LTRotation rPlayerRot( m_fPlayerPitch, m_fPlayerYaw, m_fPlayerRoll);
cMsg.WriteCompLTRotation( rPlayerRot );
}
if ( m_nPlayerInfoChangeFlags & ( CLIENTUPDATE_PLAYERROT | CLIENTUPDATE_ACCURATEPLAYERROT ) )
{
//
// pitch
//
// and write it to the message.
cMsg.Writeuint8( CompressAngleToByte( m_fPitch ) );
}
// write the camera offset
if ( m_nPlayerInfoChangeFlags & CLIENTUPDATE_CAMERAOFFSET )
{
LTRESULT ltResult;
// Get the fire position from the camera
LTVector vCameraPosition;
// get the camera
HOBJECT hCamera = g_pPlayerMgr->GetCamera();
if ( g_pPlayerMgr->IsFirstPerson() &&
( !g_pPlayerMgr->IsUsingExternalCamera() ) &&
( 0 != hCamera ) )
{
// we're in 1st person and not using an external camera,
// get the camera's position
ltResult = g_pLTClient->GetObjectPos( hCamera, &vCameraPosition );
ASSERT( LT_OK == ltResult );
}
else
{
HMODELNODE hPlayerHeadNode;
LTransform transHeadNode;
// external camera, figure out where the model's head
// is and use that. It won't be as accurate but it is
// better than nothing.
// get the head node
ltResult = g_pModelLT->GetNode( g_pLTClient->GetClientObject(),
"Head_node",
hPlayerHeadNode );
ASSERT( LT_OK == ltResult );
// get the node's transform
ltResult =
g_pModelLT->GetNodeTransform( g_pLTClient->GetClientObject(),
hPlayerHeadNode,
transHeadNode,
true );
ASSERT( LT_OK == ltResult );
// fake the camera position
ltResult =
g_pLTClient->GetTransformLT()->GetPos( transHeadNode,
vCameraPosition );
ASSERT( LT_OK == ltResult );
}
// get the player's position
LTVector vPlayerPosition;
ltResult = g_pLTClient->GetObjectPos( g_pMoveMgr->GetObject(),
&vPlayerPosition );
ASSERT( LT_OK == ltResult );
// get the camera offset
LTVector vOffset = vCameraPosition - vPlayerPosition;
TVector3< short > vCompressedOffset;
// compress the offset
bool result = CompressOffset( &vCompressedOffset, vOffset, 100 );
ASSERT( true == result );
// write the offset to the message
cMsg.Writeuint16( vCompressedOffset.x );
cMsg.Writeuint16( vCompressedOffset.y );
cMsg.Writeuint16( vCompressedOffset.z );
}
// Write the control flags
if (bPlaying)
cMsg.Writeuint32(g_pMoveMgr->GetControlFlags());
else
cMsg.Writeuint32(g_pMoveMgr->GetControlFlags() & BC_CFLG_DUCK);
// Write position info...
m_pMoveMgr->WritePositionInfo(cMsg);
g_pLTClient->SendToServer(cMsg.Read(), 0);
m_fPlayerInfoLastSendTime = fCurTime;
m_nPlayerInfoChangeFlags = 0;
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::IsFirstPerson()
//
// PURPOSE: See if we are in first person mode
//
// --------------------------------------------------------------------------- //
LTBOOL CPlayerMgr::IsFirstPerson()
{
return m_pPlayerCamera->IsFirstPerson();
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::IsPlayerInWorld()
//
// PURPOSE: See if the player is in the world
//
// --------------------------------------------------------------------------- //
LTBOOL CPlayerMgr::IsPlayerInWorld()
{
HLOCALOBJ hPlayerObj = g_pLTClient->GetClientObject();
if (!g_pGameClientShell->IsServerLoaded( ) || !g_pGameClientShell->IsWorldLoaded() || m_ePlayerState == PS_UNKNOWN || !hPlayerObj) return LTFALSE;
return LTTRUE;
}
void CPlayerMgr::GetCameraRotation(LTRotation &rRot)
{
rRot = LTRotation(m_fPitch, m_fYaw, m_fRoll);
}
void CPlayerMgr::GetPlayerRotation(LTRotation &rRot)
{
rRot = LTRotation(m_fPlayerPitch, m_fPlayerYaw, m_fPlayerRoll);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: UpdateModelGlow
//
// PURPOSE: Update the current model glow color
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateModelGlow()
{
float fColor = 0.0f;
float fMin = g_vtModelGlowMin.GetFloat();
float fMax = g_vtModelGlowMax.GetFloat();
float fColorRange = fMax - fMin;
float fTimeRange = g_vtModelGlowTime.GetFloat();
if (m_bModelGlowCycleUp)
{
if (m_fModelGlowCycleTime < fTimeRange)
{
fColor = fMin + (fColorRange * (m_fModelGlowCycleTime / fTimeRange));
m_vCurModelGlow.Init(fColor, fColor, fColor);
}
else
{
m_fModelGlowCycleTime = 0.0f;
m_vCurModelGlow.Init(fMax, fMax, fMax);
m_bModelGlowCycleUp = LTFALSE;
return;
}
}
else
{
if (m_fModelGlowCycleTime < fTimeRange)
{
fColor = fMax - (fColorRange * (m_fModelGlowCycleTime / fTimeRange));
m_vCurModelGlow.Init(fColor, fColor, fColor);
}
else
{
m_fModelGlowCycleTime = 0.0f;
m_vCurModelGlow.Init(fMin, fMin, fMin);
m_bModelGlowCycleUp = LTTRUE;
return;
}
}
if (!g_pGameClientShell->IsServerPaused())
{
m_fModelGlowCycleTime += g_pGameClientShell->GetFrameTime();
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::ClearCurContainerCode
//
// PURPOSE: Clear our current container info.
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::ClearCurContainerCode()
{
//make sure we clear out any tinting that the container may have been doing
g_pGameClientShell->GetLightScaleMgr()->ClearLightScale(CLightScaleMgr::eLightScaleEnvironment);
m_eCurContainerCode = CC_NO_CONTAINER;
m_nSoundFilterId = 0;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HandleWeaponDisable
//
// PURPOSE: Handle the weapon being disabled...
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::HandleWeaponDisable(LTBOOL bDisabled)
{
if (bDisabled)
{
ClearPlayerModes(LTTRUE);
}
else
{
// Force us to re-evaluate what container we're in. We call
// UpdateContainers() first to make sure any container changes
// have been accounted for, then we clear the container code
// and force an update (this is done for underwater situations like
// dying underwater and respawning, and also for picking up intelligence
// items underwater)...
if (IsPlayerInWorld())
{
UpdateContainers();
ClearCurContainerCode();
UpdateContainers();
}
m_pClientWeaponMgr->ShowWeapons();
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::ClearPlayerModes
//
// PURPOSE: Clear any special modes the player is in
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::ClearPlayerModes(LTBOOL bWeaponOnly)
{
HandleZoomChange( LTTRUE );
EndZoom();
if (!bWeaponOnly)
{
EndSpyVision();
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::RestorePlayerModes
//
// PURPOSE: Restore any special modes the player was in
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::RestorePlayerModes()
{
if (m_bSpyVision)
{
BeginSpyVision();
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::AttachCameraToHead
//
// PURPOSE: Attach the camera to a socket in the player's head
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::AttachCameraToHead( bool bAttach, bool bInterpolate )
{
// We don't want to reset our orientations if we are currently doing what was requested...
if( m_bCameraAttachedToHead == bAttach )
return;
//set the new value
m_bCameraAttachedToHead = bAttach;
m_bLerpAttachedCamera = bInterpolate;
//if we are enabling, then cache our values
if(bAttach)
{
m_fModelAttachPitch = m_fPitch;
m_fModelAttachYaw = m_fYaw;
m_fModelAttachRoll = m_fRoll;
}
else
{
//we are disabling, make our animation orientation our actual orientation
m_fPitch = m_fModelAttachPitch;
m_fYaw = m_fModelAttachYaw;
m_fRoll = m_fModelAttachRoll;
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::GetPlayerHeadPos
//
// PURPOSE: Get the player's head position
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::GetPlayerHeadPosRot(LTVector & vPos, LTRotation & rRot)
{
HMODELSOCKET hSocket = INVALID_MODEL_SOCKET;
HOBJECT hBody = NULL; // g_pLTClient->GetClientObject();
// We actually want to use the body prop, so...
CSpecialFXList* pList = g_pGameClientShell->GetSFXMgr()->GetFXList(SFX_BODY_ID);
if (!pList) return;
int nNumBodies = pList->GetSize();
uint32 dwId;
g_pLTClient->GetLocalClientID(&dwId);
float fNewestBodyTime = -1.0f;
for (int i=0; i < nNumBodies; i++)
{
if ((*pList)[i])
{
CBodyFX* pBody = (CBodyFX*)(*pList)[i];
if( (pBody->GetClientId() == dwId) && (pBody->GetTimeCreated() > fNewestBodyTime) )
{
// Keep the newest body belonging to this client...
fNewestBodyTime = pBody->GetTimeCreated();
hBody = pBody->GetServerObj();
}
}
}
if( !hBody )
{
// If we are alive then we don't have a body and we should use the client object...
hBody = g_pLTClient->GetClientObject();
}
if (hBody)
{
g_pModelLT->ApplyAnimations( hBody );
if (g_pModelLT->GetSocket(hBody, "Eyes", hSocket) == LT_OK)
{
LTransform transform;
if (g_pModelLT->GetSocketTransform(hBody, hSocket, transform, LTTRUE) == LT_OK)
{
vPos = transform.m_Pos;
rRot = transform.m_Rot;
m_pPlayerCamera->CalcNonClipPos(vPos, rRot);
}
}
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::DoActivate
//
// PURPOSE: Tell the server to do Activate
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::DoActivate()
{
char const* pActivateOverride = g_vtActivateOverride.GetStr();
if (pActivateOverride && pActivateOverride[0] != ' ')
{
g_pLTClient->RunConsoleString(( char* )pActivateOverride);
return;
}
CActivationData data = GetTargetMgr()->GetActivationData();
//don't revive if we are too close
if (data.m_nType == MID_ACTIVATE_REVIVE && !GetTargetMgr()->CanActivateTarget() )
return;
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_ACTIVATE);
data.Write(cMsg);
g_pLTClient->SendToServer(cMsg.Read(), MESSAGE_GUARANTEED);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::Teleport
//
// PURPOSE: Tell the server to teleport to the specified point
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::Teleport(const LTVector & vPos)
{
#ifndef _FINAL // Don't allow player teleporing in the final version...
LTVector vPitchYawRoll(m_fPlayerPitch, m_fPlayerYaw, m_fPlayerRoll);
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_TELEPORT);
cMsg.WriteLTVector(vPos);
cMsg.WriteLTVector(vPitchYawRoll);
g_pLTClient->SendToServer(cMsg.Read(), MESSAGE_GUARANTEED);
#endif // _FINAL
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateServerPlayerModel()
//
// PURPOSE: Puts the server's player model where our invisible one is
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdateServerPlayerModel()
{
HOBJECT hClientObj, hRealObj;
if (!(hClientObj = g_pLTClient->GetClientObject())) return;
if (!(hRealObj = m_pMoveMgr->GetObject())) return;
LTVector myPos;
g_pLTClient->GetObjectPos(hRealObj, &myPos);
g_pLTClient->SetObjectPos(hClientObj, &myPos);
if (g_vtPlayerRotate.GetFloat(1.0) > 0.0)
{
LTRotation myRot(m_fPlayerPitch, m_fPlayerYaw, m_fPlayerRoll);
g_pLTClient->SetObjectRotation(hClientObj, &myRot);
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateContainers
//
// PURPOSE: Update anything associated with being in a container
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateContainers()
{
LTVector vCamPos;
g_pLTClient->GetObjectPos(m_hCamera, &vCamPos);
LTVector vScale(1.0f, 1.0f, 1.0f), vLightAdd(0.0f, 0.0f, 0.0f);
char* pCurSound = NULL;
uint8 nSoundFilterId = 0;
uint32 dwUserFlags = USRFLG_VISIBLE;
m_bUseWorldFog = LTTRUE;
// We'll update this below...
m_bInSafetyNet = false;
// [KLS 4/16/02] Find container objects that we care about...
HLOCALOBJ hContainerObj = LTNULL;
ContainerCode eCode = CC_NO_CONTAINER;
HLOCALOBJ objList[MAX_OVERLAPPING_CONTAINERS];
uint32 nContainerFlags = (CC_ALL_FLAG & ~CC_PLAYER_IGNORE_FLAGS);
uint32 dwNum = ::GetPointContainers(vCamPos, objList, MAX_OVERLAPPING_CONTAINERS, nContainerFlags);
for (uint32 i=0; i < dwNum; i++)
{
uint16 code;
if (g_pLTClient->GetContainerCode(objList[i], &code))
{
ContainerCode eTempCode = (ContainerCode)code;
// Ignore dynamic occluder volumes...
if (CC_DYNAMIC_OCCLUDER_VOLUME != eTempCode)
{
// [KEF 9/03/02] Allow sound filter volumes to be overridden if needed
// [KLS 9/07/02] Modified so we look at all the containers on the list,
// and save off saftey nets separately...
if (CC_SAFTEY_NET == eTempCode)
{
// Don't count this as a normal container as it has one specific
// purpose ONLY (protect the player)...
m_bInSafetyNet = true;
}
else if (CC_NO_CONTAINER == eCode || CC_FILTER == eCode)
{
hContainerObj = objList[i];
eCode = eTempCode;
}
}
}
}
// Update Dynamic occluders...
UpdateDynamicOccluders(objList, dwNum);
if (hContainerObj)
{
// Check for weather volume brush first (weather volume brushes
// should never overlap normal volume brushes)
CVolumeBrushFX* pFX = dynamic_cast<CVolumeBrushFX*>(g_pGameClientShell->GetSFXMgr()->FindSpecialFX(SFX_WEATHER_ID, hContainerObj));
if (!pFX)
{
pFX = dynamic_cast<CVolumeBrushFX*>(g_pGameClientShell->GetSFXMgr()->FindSpecialFX(SFX_VOLUMEBRUSH_ID, hContainerObj));
}
pFX = UpdateVolumeBrushFX(pFX, eCode);
// See if we have entered/left a container...
float fTime = g_pLTClient->GetTime();
if (m_eCurContainerCode != eCode)
{
m_fContainerStartTime = fTime;
if (pFX)
{
// Set the sound filter override...
nSoundFilterId = pFX->GetSoundFilterId();
// See if this container has fog associated with it..
LTBOOL bFog = pFX->IsFogEnable();
if (bFog)
{
m_bUseWorldFog = LTFALSE;
char buf[30];
sprintf(buf, "FogEnable %d", (int)bFog);
g_pLTClient->RunConsoleString(buf);
sprintf(buf, "FogNearZ %d", (int)pFX->GetFogNearZ());
g_pLTClient->RunConsoleString(buf);
sprintf(buf, "FogFarZ %d", (int)pFX->GetFogFarZ());
g_pLTClient->RunConsoleString(buf);
LTVector vFogColor = pFX->GetFogColor();
sprintf(buf, "FogR %d", (int)vFogColor.x);
g_pLTClient->RunConsoleString(buf);
sprintf(buf, "FogG %d", (int)vFogColor.y);
g_pLTClient->RunConsoleString(buf);
sprintf(buf, "FogB %d", (int)vFogColor.z);
g_pLTClient->RunConsoleString(buf);
}
// Get the tint color...
vScale = pFX->GetTintColor();
vScale /= 255.0f;
vLightAdd = pFX->GetLightAdd();
vLightAdd /= 255.0f;
}
}
switch (eCode)
{
case CC_WATER:
case CC_CORROSIVE_FLUID:
case CC_FREEZING_WATER:
{
pCurSound = "Chars\\Snd\\Player\\unwater.wav";
}
break;
case CC_ENDLESS_FALL:
{
float fFallTime = 1.0f;
if (fTime > m_fContainerStartTime + fFallTime)
{
vScale.Init(0.0f, 0.0f, 0.0f);
}
else
{
float fScaleStart = .3f;
float fTimeLeft = (m_fContainerStartTime + fFallTime) - fTime;
float fScalePercent = fTimeLeft/fFallTime;
float fScale = fScaleStart * fScalePercent;
vScale.Init(fScale, fScale, fScale);
}
}
break;
default : break;
}
} // if (hContainerObj)
// See if we have entered/left a container...
if (m_eCurContainerCode != eCode)
{
// Adjust world properties as necessary...
g_pGameClientShell->ResetDynamicWorldProperties(m_bUseWorldFog);
g_pGameClientShell->GetLightScaleMgr()->ClearLightScale(CLightScaleMgr::eLightScaleEnvironment);
if (vScale.x != 1.0f || vScale.y != 1.0f || vScale.z != 1.0f)
{
g_pGameClientShell->GetLightScaleMgr()->SetLightScale(vScale, CLightScaleMgr::eLightScaleEnvironment);
}
// See if we are coming out of water...
if (IsLiquid(m_eCurContainerCode) && !IsLiquid(eCode))
{
UpdateUnderWaterFX(LTFALSE);
}
m_eCurContainerCode = eCode;
UpdateSoundFilters(nSoundFilterId);
if (m_hContainerSound)
{
g_pLTClient->SoundMgr()->KillSound(m_hContainerSound);
m_hContainerSound = NULL;
}
if (pCurSound)
{
uint32 dwFlags = PLAYSOUND_CLIENT | PLAYSOUND_LOOP | PLAYSOUND_GETHANDLE;
m_hContainerSound = g_pClientSoundMgr->PlaySoundLocal(pCurSound, SOUNDPRIORITY_PLAYER_MEDIUM, dwFlags);
}
g_pGameClientShell->GetScreenTintMgr()->Set(TINT_CONTAINER,&vLightAdd);
}
// See if we are under water (under any liquid)...
if (IsLiquid(m_eCurContainerCode))
{
UpdateUnderWaterFX();
}
else
{
UpdateBreathingFX();
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateVolumeBrushFX
//
// PURPOSE: Deterimine if we're really in a VolumeBrush that has
// a polygrid surface (i.e., water)
//
// NOTES: Passed in eCode may be updated
//
// --------------------------------------------------------------------------- //
CVolumeBrushFX* CPlayerMgr::UpdateVolumeBrushFX(CVolumeBrushFX* pFX,
ContainerCode & eCode)
{
if (!pFX) return LTNULL;
// Get the PolyGridFX associated with the VolumeBrush...
// Get a list of all the poly grids...
CSpecialFXList* pList = g_pGameClientShell->GetSFXMgr()->GetFXList( SFX_POLYGRID_ID );
if( pList )
{
int nNumPGrids = pList->GetSize();
HOBJECT hObj = pFX->GetServerObj();
// Try and find a polygrid that is the surface of our container...
for( int i = 0; i < nNumPGrids; ++i )
{
if( (*pList)[i] )
{
CPolyGridFX* pPGrid= (CPolyGridFX*)(*pList)[i];
if( pPGrid->GetVolumeBrush() == hObj )
{
float fDisplacement;
LTVector vIntersection;
LTRotation rRot;
g_pLTClient->GetObjectRotation( m_hCamera, &rRot );
LTVector vCamPos;
g_pLTClient->GetObjectPos(m_hCamera, &vCamPos);
// Develop a position out and down from the camera to test from...
LTVector vPos = vCamPos + (rRot.Forward() * 5.0f);
vPos.y -= 2.0f;
// See if we interected the polygrid...
if( pPGrid->GetOrientedIntersectionHeight( vPos, LTVector(0,1,0), fDisplacement, vIntersection ))
{
vIntersection.y += fDisplacement;
// If we are above it clear our container and fx...
if( vPos.y > vIntersection.y )
{
eCode = CC_NO_CONTAINER;
pFX = LTNULL;
}
}
break;
}
}
}
}
return pFX;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateSoundFilters
//
// PURPOSE: Update sound filters
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateSoundFilters(uint8 nSoundFilterId)
{
#ifndef USE_EAX20_HARDWARE_FILTERS
return;
#endif // USE_EAX20_HARDWARE_FILTERS
if (g_vtUseSoundFilters.GetFloat())
{
if ( m_nSoundFilterId != nSoundFilterId )
{
m_nSoundFilterId = nSoundFilterId;
bool bFilterOK = true;
ILTClientSoundMgr *pSoundMgr = (ILTClientSoundMgr *)g_pLTClient->SoundMgr();
SOUNDFILTER* pFilter = g_pSoundFilterMgr->GetFilter( nSoundFilterId );
// tell the sound engine about new filter, if a dynamic filter,
// use the global sound filter
bool bUsingDynamic = false;
if ( g_pSoundFilterMgr->IsDynamic( pFilter ) )
{
bUsingDynamic = true;
m_nSoundFilterId = m_nGlobalSoundFilterId;
pFilter = g_pSoundFilterMgr->GetFilter( m_nGlobalSoundFilterId );
}
if ( !g_pSoundFilterMgr->IsUnFiltered( pFilter ) )
{
if ( pSoundMgr->SetSoundFilter( pFilter->szFilterName ) == LT_OK )
{
for (int i=0; i < pFilter->nNumVars; i++)
{
if ( pSoundMgr->SetSoundFilterParam(pFilter->szVars[i], pFilter->fValues[i]) != LT_OK )
bFilterOK = false;
}
}
else
{
bFilterOK = false;
}
}
else
{
bFilterOK = false;
}
pSoundMgr->EnableSoundFilter( bFilterOK );
#ifndef _FINAL
if (g_vtShowSoundFilterInfo.GetFloat())
{
g_pLTClient->CPrint("Entering %s sound filter '%s' (%s)",
((bUsingDynamic && m_eCurContainerCode == CC_NO_CONTAINER)? "(Global)" : ""), pFilter->szName,
(bFilterOK ? "Enabled" : "Disabled"));
// Display detailed filter info if necessary...
if (g_vtShowSoundFilterInfo.GetFloat() > 1 && pFilter)
{
g_pLTClient->CPrint(" FilterName: '%s'", pFilter->szFilterName);
for (int i=0; i < pFilter->nNumVars; i++)
{
g_pLTClient->CPrint(" '%s' = '%f'", pFilter->szVars[i], pFilter->fValues[i]);
}
}
}
#endif // _FINAL
}
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateUnderWaterFX
//
// PURPOSE: Update under water fx
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateUnderWaterFX(LTBOOL bUpdate)
{
if (m_nZoomView) return;
uint32 dwWidth = 640, dwHeight = 480;
g_pLTClient->GetSurfaceDims(g_pLTClient->GetScreenSurface(), &dwWidth, &dwHeight);
if (dwWidth < 0 || dwHeight < 0) return;
// Initialize to default fov x and y...
float fFovX = g_vtFOVXNormal.GetFloat();
float fFovY = g_vtFOVYNormal.GetFloat();
//see if we are supposed to modify the FOV. Note that we can't modify it while any damage
//effects are active since they can modify the FOV as well which will cause cumulative issues
//and ultimately lead to a fairly messed up camera state until it is restored
if (bUpdate && (g_pDamageFXMgr->GetFirstActiveFX() == NULL))
{
g_pLTClient->GetCameraFOV(m_hCamera, &fFovX, &fFovY);
fFovX = RAD2DEG(fFovX);
fFovY = RAD2DEG(fFovY);
float fSpeed = g_vtUWFOVRate.GetFloat() * g_pGameClientShell->GetFrameTime();
if (m_fFovXFXDir > 0)
{
fFovX -= fSpeed;
fFovY += fSpeed;
if (fFovY > g_vtFOVYMaxUW.GetFloat())
{
fFovY = g_vtFOVYMaxUW.GetFloat();
m_fFovXFXDir = -m_fFovXFXDir;
}
}
else
{
fFovX += fSpeed;
fFovY -= fSpeed;
if (fFovY < g_vtFOVYMinUW.GetFloat())
{
fFovY = g_vtFOVYMinUW.GetFloat();
m_fFovXFXDir = -m_fFovXFXDir;
}
}
}
SetCameraFOV(DEG2RAD(fFovX), DEG2RAD(fFovY));
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateBreathingFX
//
// PURPOSE: Update breathing fx
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateBreathingFX(LTBOOL bUpdate)
{
//if (m_nZoomView) return;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateDynamicOccluders
//
// PURPOSE: Update dynamic occluders
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::UpdateDynamicOccluders(HLOCALOBJ* pContainerArray, uint32 nNumContainers)
{
CDynamicOccluderVolumeFX* enabledOccluderFX[50];
CDynamicOccluderVolumeFX* disabledOccluderFX[50];
uint32 nNumEnabledOccluderFX = 0;
uint32 nNumDisabledOccluderFX = 0;
// Find the occluder volumes fx that we wish to enable...
for (uint32 i=0; i < nNumContainers; i++)
{
// We only care about "visible" containers...
uint32 dwUserFlags = USRFLG_VISIBLE;
g_pCommonLT->GetObjectFlags(pContainerArray[i], OFT_User, dwUserFlags);
if (dwUserFlags & USRFLG_VISIBLE)
{
uint16 code;
if (g_pLTClient->GetContainerCode(pContainerArray[i], &code))
{
ContainerCode eTempCode = (ContainerCode)code;
if (CC_DYNAMIC_OCCLUDER_VOLUME == eTempCode)
{
enabledOccluderFX[nNumEnabledOccluderFX] = (CDynamicOccluderVolumeFX*)g_pGameClientShell->GetSFXMgr()->FindSpecialFX(SFX_DYNAMIC_OCCLUDER_ID, pContainerArray[i]);
nNumEnabledOccluderFX++;
}
}
}
}
// Find the occluder volume FX that we wish to disable...
CSpecialFXList* pDynOccluderList = g_pGameClientShell->GetSFXMgr()->GetFXList(SFX_DYNAMIC_OCCLUDER_ID);
if (pDynOccluderList)
{
uint32 nNum = pDynOccluderList->GetSize();
for (uint32 i=0; i < nNum; i++)
{
CDynamicOccluderVolumeFX* pFX = (CDynamicOccluderVolumeFX*)(*pDynOccluderList)[i];
if (!pFX) continue;
// Check to see if this fx is on the enabled list...
bool bEnabled = false;
for (uint32 j=0; j < nNumEnabledOccluderFX; j++)
{
if (pFX == enabledOccluderFX[j])
{
bEnabled = true;
break;
}
}
// Add the fx to the disabled list...
if (!bEnabled)
{
disabledOccluderFX[nNumDisabledOccluderFX] = pFX;
nNumDisabledOccluderFX++;
}
}
}
// Disable the necessary occluder volumes...
for (i=0; i < nNumDisabledOccluderFX; i++)
{
if (disabledOccluderFX[i])
{
(disabledOccluderFX[i])->Enable(false);
}
}
// Enable the necessary occluder volumes...
for (i=0; i < nNumEnabledOccluderFX; i++)
{
if (enabledOccluderFX[i])
{
(enabledOccluderFX[i])->Enable(true);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::SetMouseInput()
//
// PURPOSE: Allows or disallows mouse input on the client
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::SetMouseInput( LTBOOL bAllowInput, LTBOOL bRestoreBackupAngles )
{
if (bAllowInput)
{
m_bRestoreOrientation = LTTRUE;
if( bRestoreBackupAngles )
{
m_fYaw = m_fYawBackup;
m_fPitch = m_fPitchBackup;
}
}
else
{
m_fYawBackup = m_fYaw;
m_fPitchBackup = m_fPitch;
}
}
void CPlayerMgr::AllowPlayerMovement(LTBOOL bAllowPlayerMovement)
{
m_bAllowPlayerMovement = bAllowPlayerMovement;
SetMouseInput( bAllowPlayerMovement, LTFALSE );
}
void CPlayerMgr::ResetCamera()
{
// Make sure the FOV is set correctly...
uint32 dwWidth = 640;
uint32 dwHeight = 480;
g_pLTClient->GetSurfaceDims(g_pLTClient->GetScreenSurface(), &dwWidth, &dwHeight);
g_pLTClient->SetCameraRect(m_hCamera, LTTRUE, 0, 0, dwWidth, dwHeight);
SetCameraFOV(DEG2RAD(g_vtFOVXNormal.GetFloat()), DEG2RAD(g_vtFOVYNormal.GetFloat()));
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::ShowPlayer()
//
// PURPOSE: Show/Hide the player object
//
// --------------------------------------------------------------------------- //
void CPlayerMgr::ShowPlayer(LTBOOL bShow)
{
HLOCALOBJ hPlayerObj = g_pLTClient->GetClientObject();
if (!hPlayerObj) return;
g_pCommonLT->SetObjectFlags(hPlayerObj, OFT_Flags, (bShow ? FLAG_VISIBLE : 0), FLAG_VISIBLE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdatePlayer()
//
// PURPOSE: Update the player
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdatePlayer()
{
HLOCALOBJ hPlayerObj = g_pLTClient->GetClientObject();
if (!hPlayerObj || IsPlayerDead()) return;
// This is pretty much a complete kludge, but I can't really think of
// a better way to handle this...Okay, since the server can update the
// player's flags at any time (and override anything that we set), we'll
// make sure that the player's flags are always what we want them to be :)
uint32 dwPlayerFlags;
g_pCommonLT->GetObjectFlags(hPlayerObj, OFT_Flags, dwPlayerFlags);
if (m_pPlayerCamera->IsFirstPerson())
{
if (dwPlayerFlags & FLAG_VISIBLE)
{
ShowPlayer(LTFALSE);
}
}
else // Third person
{
if (!(dwPlayerFlags & FLAG_VISIBLE))
{
ShowPlayer(LTTRUE);
}
}
// Hide/Show our attachments...
HideShowAttachments(hPlayerObj);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::HideShowAttachments()
//
// PURPOSE: Recursively hide/show attachments...
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::HideShowAttachments(HOBJECT hObj)
{
if (!hObj) return;
HLOCALOBJ attachList[20];
uint32 dwListSize = 0;
uint32 dwNumAttach = 0;
g_pCommonLT->GetAttachments(hObj, attachList, 20, dwListSize, dwNumAttach);
int nNum = dwNumAttach <= dwListSize ? dwNumAttach : dwListSize;
for (int i=0; i < nNum; i++)
{
uint32 dwUsrFlags;
g_pCommonLT->GetObjectFlags(attachList[i], OFT_User, dwUsrFlags);
if (dwUsrFlags & USRFLG_ATTACH_HIDE1SHOW3)
{
if (m_pPlayerCamera->IsFirstPerson())
{
g_pCommonLT->SetObjectFlags(attachList[i], OFT_Flags, 0, FLAG_VISIBLE);
}
else
{
g_pCommonLT->SetObjectFlags(attachList[i], OFT_Flags, FLAG_VISIBLE, FLAG_VISIBLE);
}
}
else if (dwUsrFlags & USRFLG_ATTACH_HIDE1)
{
if (m_pPlayerCamera->IsFirstPerson())
{
g_pCommonLT->SetObjectFlags(attachList[i], OFT_Flags, 0, FLAG_VISIBLE);
}
}
if (g_pVersionMgr->IsLowViolence() && dwUsrFlags & USRFLG_ATTACH_HIDEGORE)
{
g_pCommonLT->SetObjectFlags(attachList[i], OFT_Flags, 0, FLAG_VISIBLE);
}
// Hide/Show this attachment's attachments...
HideShowAttachments(attachList[i]);
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: SVModelHook
//
// PURPOSE: Special Rendering Code for SpyVision Powerup
//
// --------------------------------------------------------------------------- //
/*
void SVModelHook(ModelHookData *pData, void *pUser)
{
CGameClientShell* pShell = (CGameClientShell*) pUser;
if (!pShell) return;
uint32 nUserFlags = 0;
g_pCommonLT->GetObjectFlags(pData->m_hObject, OFT_User, nUserFlags);
if (nUserFlags & USRFLG_SPY_VISION)
{
// Do the poor-man's glow if necessary...
bool bCanDoGlow = true; // NEED TO CALL API FUNCTION FOR THIS!!!!
if (!bCanDoGlow)
{
pData->m_HookFlags &= ~MHF_USETEXTURE;
pData->m_LightAdd = g_vSVModelColor;
}
// pData->m_ObjectColor = g_vSVModelColor;
// pData->m_ObjectFlags |= FLAG_NOLIGHT;
}
else
{
DefaultModelHook(pData, pUser);
}
}
*/
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::IsSearching()
//
// PURPOSE: Return whether or not the searcher object is searching
//
// ----------------------------------------------------------------------- //
bool CPlayerMgr::IsSearching()
{
return m_pSearcher->IsSearching();
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::IsDisabling()
//
// PURPOSE: Return whether or not the player is currently disabling a gadget target
//
// ----------------------------------------------------------------------- //
bool CPlayerMgr::IsDisabling()
{
return !!(m_pGadgetDisabler->IsDisabling());
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::SetCarryingObject()
//
// PURPOSE: Set the player to carry an object...
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::SetCarryingObject( uint8 nCarry, bool bUpdateCameraDip )
{
if( m_nCarryingObject != nCarry )
{
m_nCarryingObject = nCarry;
if(nCarry == CFX_CARRY_BODY || nCarry == CFX_CARRY_DD_CORE)
{
if( bUpdateCameraDip )
m_bCameraDip = true;
m_pMoveMgr->SetDuckLock(LTFALSE);
m_pClientWeaponMgr->DisableWeapons();
}
else
{
m_pClientWeaponMgr->EnableWeapons();
}
}
g_pHUDMgr->QueueUpdate(kHUDCarry);
}
//pulled target mgr initialization into a function so that it maybe overridden by
// a game specific TargetMgr
void CPlayerMgr::InitTargetMgr()
{
m_pTargetMgr = debug_new( CTargetMgr );
ASSERT( 0 != m_pTargetMgr );
}
void CPlayerMgr::ClearDamageSectors()
{
memset(m_fDamage,0,sizeof(m_fDamage));
}
void CPlayerMgr::UpdateDamage()
{
if (g_pGameClientShell->IsGamePaused()) return;
float fDelta = g_pGameClientShell->GetFrameTime() * g_vtDamageFadeRate.GetFloat();
for (int i = 0; i < kNumDamageSectors; i++)
{
if (m_fDamage[i] > fDelta)
m_fDamage[i] -= fDelta;
else
m_fDamage[i] = 0.0f;
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UpdateDistanceIndicator()
//
// PURPOSE: If we are close to a distance indicator object update the huditem...
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::UpdateDistanceIndicator()
{
float fLastDistPercent = m_fDistanceIndicatorPercent;
m_fDistanceIndicatorPercent = -1.0f;
// Currently the only distance indicator objects are triggers...
CSpecialFXList* pTriggerList = g_pGameClientShell->GetSFXMgr()->GetFXList( SFX_TRIGGER_ID );
if( pTriggerList )
{
uint32 nNum = pTriggerList->GetNumItems();
for( uint32 i = 0; i < nNum; ++i )
{
CTriggerFX* pFX = (CTriggerFX*)(*pTriggerList)[i];
if( !pFX || !pFX->WithinIndicatorRadius() ) continue;
// Just grab the first distance being tracked. The distance indicators
// shouldn't overlap. If they do it's an LD issue or this needs to change :)
m_fDistanceIndicatorPercent = pFX->GetDistancePercentage();
m_hDistanceIndicatorIcon = pFX->GetIcon();
break;
}
}
if( (m_fDistanceIndicatorPercent != fLastDistPercent) && m_hDistanceIndicatorIcon )
g_pHUDMgr->QueueUpdate( kHUDDistance );
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::CanCarryObject()
//
// PURPOSE: Check to see if we are able to carry an object or not....
//
// ----------------------------------------------------------------------- //
uint8 CPlayerMgr::CanCarryObject()
{
if( !GetCarryingObject() && GetTargetMgr()->IsTargetInRange() && GetTargetMgr()->IsMoveTarget() && !m_pMoveMgr->IsDucking() )
{
// Check if the target object is a body...
CBodyFX* pBody = g_pGameClientShell->GetSFXMgr()->GetBodyFX(GetTargetMgr()->GetTargetObject());
if( pBody )
{
// If the body can be revived then we can't carry it...
if (pBody->CanBeRevived())
return CFX_CARRY_NONE;
else
return CFX_CARRY_BODY;
}
CCharacterFX* pChar = g_pGameClientShell->GetSFXMgr()->GetCharacterFX(GetTargetMgr()->GetTargetObject());
if( pChar )
{
return CFX_CARRY_BODY;
}
CDoomsdayPieceFX* const pFX = (CDoomsdayPieceFX*)g_pGameClientShell->GetSFXMgr()->FindSpecialFX(SFX_DOOMSDAYPIECE_ID, GetTargetMgr()->GetTargetObject());
if( pFX )
{
switch (pFX->GetType())
{
case kDoomsDay_transmitter:
return (CFX_CARRY_DD_TRAN);
break;
case kDoomsDay_battery:
return (CFX_CARRY_DD_BATT);
break;
case kDoomsDay_Core:
return (CFX_CARRY_DD_CORE);
break;
}
}
}
return CFX_CARRY_NONE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::UseGadget()
//
// PURPOSE: Try to switch to a gadget that will use the specified damage type...
//
// ----------------------------------------------------------------------- //
bool CPlayerMgr::UseGadget(DamageType eDamageType)
{
if( IsCarryingHeavyObject() )
return false;
// if it's an invalid type we are either not pointing at a gadget target, or it doesn't require a gadget
if (eDamageType == DT_INVALID)
{
//if we had been using a weapon, switch back to it
if (m_nPreGadgetWeapon != WMGR_INVALID_ID && m_pClientWeaponMgr->CanChangeToWeapon(m_nPreGadgetWeapon))
{
m_bChangingToGadget = false;
ChangeWeapon(m_nPreGadgetWeapon);
return true;
}
return false;
}
uint8 nId = GetGadgetFromDamageType(eDamageType);
IClientWeaponBase *pClientWeapon = m_pClientWeaponMgr->GetCurrentClientWeapon();
uint8 nCurWeapon = WMGR_INVALID_ID;
if ( pClientWeapon )
nCurWeapon = pClientWeapon->GetWeaponId();
//if we found a weapon to use, and we aren't already using it
if (nId != WMGR_INVALID_ID && nCurWeapon != nId)
{
//found a match
m_bChangingToGadget = true;
ChangeWeapon(nId);
//switching to a gadget, so remember what we had
m_nPreGadgetWeapon = nCurWeapon;
return true;
}
return false;
}
uint8 CPlayerMgr::GetGadgetFromDamageType(DamageType eDamageType)
{
IClientWeaponBase *pClientWeapon = m_pClientWeaponMgr->GetCurrentClientWeapon();
uint8 nCurWeapon = WMGR_INVALID_ID;
if ( pClientWeapon )
{
// Check if we have ammo, we may have just run out...
if (pClientWeapon->HasAmmo())
{
nCurWeapon = pClientWeapon->GetWeaponId();
}
else
{
// Start with our next weapon that has ammo...
nCurWeapon = m_pClientWeaponMgr->GetNextWeaponId(nCurWeapon, 0);
}
}
uint8 nTestWeapon = nCurWeapon;
do
{
const WEAPON* pWpnData = g_pWeaponMgr->GetWeapon(nTestWeapon);
if (pWpnData)
{
const AMMO* pAmmoData = g_pWeaponMgr->GetAmmo(pWpnData->nDefaultAmmoId);
if (pAmmoData->eInstDamageType == eDamageType)
{
return nTestWeapon;
}
}
nTestWeapon = m_pClientWeaponMgr->GetNextWeaponId(nTestWeapon, 0);
} while (nTestWeapon != nCurWeapon && nTestWeapon != WMGR_INVALID_ID);
return WMGR_INVALID_ID;
}
bool CPlayerMgr::FireOnActivate()
{
if (!GetTargetMgr()->IsTargetGadgetActivatable()) return false;
if (GetGadgetDisabler()->DisableOnActivate()) return false;
DamageType eDT = GetTargetMgr()->RequiredGadgetDamageType();
IClientWeaponBase *pClientWeapon = m_pClientWeaponMgr->GetCurrentClientWeapon();
uint8 nCurWeapon = WMGR_INVALID_ID;
if ( pClientWeapon )
nCurWeapon = pClientWeapon->GetWeaponId();
const WEAPON* pWpnData = g_pWeaponMgr->GetWeapon(nCurWeapon);
if (pWpnData)
{
const AMMO* pAmmoData = g_pWeaponMgr->GetAmmo(pWpnData->nDefaultAmmoId);
if (pAmmoData->eInstDamageType == eDT)
{
return true;
}
}
return false;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerMgr::SetCancelRevive
//
// PURPOSE: Sets the cancel revive setting. While the player
// is waiting to respawn, they can be revived in certain
// game types. If they hit fire or activate during that time
// they will cancel their ability to revive.
//
// ----------------------------------------------------------------------- //
void CPlayerMgr::SetCancelRevive( bool bCancelRevive )
{
// Tell the server if we just cancelled revive.
if( bCancelRevive && m_bCancelRevive != bCancelRevive )
{
SendEmptyServerMsg( MID_PLAYER_CANCELREVIVE );
}
m_bCancelRevive = bCancelRevive;
}
|
[
"[email protected]"
] |
[
[
[
1,
5628
]
]
] |
d4c1f415249758afa59d8f0636e7438b520ed80c
|
0033659a033b4afac9b93c0ac80b8918a5ff9779
|
/game/client/c_effects.cpp
|
0b3a1ab2f21b0ce3d7314f02bd77d678e80dff7e
|
[] |
no_license
|
jonnyboy0719/situation-outbreak-two
|
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
|
50037e27e738ff78115faea84e235f865c61a68f
|
refs/heads/master
| 2021-01-10T09:59:39.214171 | 2011-01-11T01:15:33 | 2011-01-11T01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 68,553 |
cpp
|
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "cbase.h"
#include "c_tracer.h"
#include "view.h"
#include "initializer.h"
#include "particles_simple.h"
#include "env_wind_shared.h"
#include "engine/IEngineTrace.h"
#include "engine/ivmodelinfo.h"
#include "precipitation_shared.h"
#include "fx_water.h"
#include "c_world.h"
#include "iviewrender.h"
#include "engine/IVDebugOverlay.h"
#include "ClientEffectPrecacheSystem.h"
#include "collisionutils.h"
#include "tier0/vprof.h"
#include "viewrender.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar cl_winddir ( "cl_winddir", "0", FCVAR_CHEAT, "Weather effects wind direction angle" );
ConVar cl_windspeed ( "cl_windspeed", "0", FCVAR_CHEAT, "Weather effects wind speed scalar" );
Vector g_vSplashColor( 0.5, 0.5, 0.5 );
float g_flSplashScale = 0.15;
float g_flSplashLifetime = 0.5f;
float g_flSplashAlpha = 0.3f;
//////
// SO2 - James
// Add rain splashes to func_precipitation
//ConVar r_RainSplashPercentage( "r_RainSplashPercentage", "20", FCVAR_CHEAT ); // N% chance of a rain particle making a splash.
ConVar r_RainSplashPercentage( "r_RainSplashPercentage", "90", FCVAR_CHEAT ); // N% chance of a rain particle making a splash.
//////
float GUST_INTERVAL_MIN = 1;
float GUST_INTERVAL_MAX = 2;
float GUST_LIFETIME_MIN = 1;
float GUST_LIFETIME_MAX = 3;
float MIN_SCREENSPACE_RAIN_WIDTH = 1;
#ifndef _XBOX
ConVar r_RainHack( "r_RainHack", "0", FCVAR_CHEAT );
ConVar r_RainRadius( "r_RainRadius", "1500", FCVAR_CHEAT );
ConVar r_RainSideVel( "r_RainSideVel", "130", FCVAR_CHEAT, "How much sideways velocity rain gets." );
ConVar r_RainSimulate( "r_RainSimulate", "1", FCVAR_CHEAT, "Enable/disable rain simulation." );
ConVar r_DrawRain( "r_DrawRain", "1", FCVAR_CHEAT, "Enable/disable rain rendering." );
ConVar r_RainProfile( "r_RainProfile", "0", FCVAR_CHEAT, "Enable/disable rain profiling." );
//Precahce the effects
CLIENTEFFECT_REGISTER_BEGIN( PrecachePrecipitation )
CLIENTEFFECT_MATERIAL( "particle/rain" )
CLIENTEFFECT_MATERIAL( "particle/snow" )
CLIENTEFFECT_REGISTER_END()
//-----------------------------------------------------------------------------
// Precipitation particle type
//-----------------------------------------------------------------------------
class CPrecipitationParticle
{
public:
Vector m_Pos;
Vector m_Velocity;
float m_SpawnTime; // Note: Tweak with this to change lifetime
float m_Mass;
float m_Ramp;
float m_flCurLifetime;
float m_flMaxLifetime;
};
class CClient_Precipitation;
static CUtlVector<CClient_Precipitation*> g_Precipitations;
//===========
// Snow fall
//===========
class CSnowFallManager;
static CSnowFallManager *s_pSnowFallMgr = NULL;
bool SnowFallManagerCreate( CClient_Precipitation *pSnowEntity );
void SnowFallManagerDestroy( void );
class AshDebrisEffect : public CSimpleEmitter
{
public:
AshDebrisEffect( const char *pDebugName ) : CSimpleEmitter( pDebugName ) {}
static AshDebrisEffect* Create( const char *pDebugName );
virtual float UpdateAlpha( const SimpleParticle *pParticle );
virtual float UpdateRoll( SimpleParticle *pParticle, float timeDelta );
private:
AshDebrisEffect( const AshDebrisEffect & );
};
//-----------------------------------------------------------------------------
// Precipitation base entity
//-----------------------------------------------------------------------------
class CClient_Precipitation : public C_BaseEntity
{
class CPrecipitationEffect;
friend class CClient_Precipitation::CPrecipitationEffect;
public:
DECLARE_CLASS( CClient_Precipitation, C_BaseEntity );
DECLARE_CLIENTCLASS();
CClient_Precipitation();
virtual ~CClient_Precipitation();
// Inherited from C_BaseEntity
virtual void Precache( );
void Render();
private:
// Creates a single particle
CPrecipitationParticle* CreateParticle();
virtual void OnDataChanged( DataUpdateType_t updateType );
virtual void ClientThink();
void Simulate( float dt );
// Renders the particle
void RenderParticle( CPrecipitationParticle* pParticle, CMeshBuilder &mb );
void CreateWaterSplashes();
// Emits the actual particles
void EmitParticles( float fTimeDelta );
// Computes where we're gonna emit
bool ComputeEmissionArea( Vector& origin, Vector2D& size );
// Gets the tracer width and speed
float GetWidth() const;
float GetLength() const;
float GetSpeed() const;
// Gets the remaining lifetime of the particle
float GetRemainingLifetime( CPrecipitationParticle* pParticle ) const;
// Computes the wind vector
static void ComputeWindVector( );
// simulation methods
bool SimulateRain( CPrecipitationParticle* pParticle, float dt );
bool SimulateSnow( CPrecipitationParticle* pParticle, float dt );
void CreateAshParticle( void );
void CreateRainOrSnowParticle( Vector vSpawnPosition, Vector vVelocity );
// Information helpful in creating and rendering particles
IMaterial *m_MatHandle; // material used
float m_Color[4]; // precip color
float m_Lifetime; // Precip lifetime
float m_InitialRamp; // Initial ramp value
float m_Speed; // Precip speed
float m_Width; // Tracer width
float m_Remainder; // particles we should render next time
PrecipitationType_t m_nPrecipType; // Precip type
float m_flHalfScreenWidth; // Precalculated each frame.
float m_flDensity;
// Some state used in rendering and simulation
// Used to modify the rain density and wind from the console
static ConVar s_raindensity;
static ConVar s_rainwidth;
static ConVar s_rainlength;
static ConVar s_rainspeed;
static Vector s_WindVector; // Stores the wind speed vector
CUtlLinkedList<CPrecipitationParticle> m_Particles;
CUtlVector<Vector> m_Splashes;
CSmartPtr<AshDebrisEffect> m_pAshEmitter;
TimedEvent m_tAshParticleTimer;
TimedEvent m_tAshParticleTraceTimer;
bool m_bActiveAshEmitter;
Vector m_vAshSpawnOrigin;
int m_iAshCount;
private:
CClient_Precipitation( const CClient_Precipitation & ); // not defined, not accessible
};
// Just receive the normal data table stuff
IMPLEMENT_CLIENTCLASS_DT(CClient_Precipitation, DT_Precipitation, CPrecipitation)
RecvPropInt( RECVINFO( m_nPrecipType ) )
END_RECV_TABLE()
static ConVar r_SnowEnable( "r_SnowEnable", "1", FCVAR_CHEAT, "Snow Enable" );
static ConVar r_SnowParticles( "r_SnowParticles", "500", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowInsideRadius( "r_SnowInsideRadius", "256", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowOutsideRadius( "r_SnowOutsideRadius", "1024", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowSpeedScale( "r_SnowSpeedScale", "1", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowPosScale( "r_SnowPosScale", "1", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowFallSpeed( "r_SnowFallSpeed", "1.5", FCVAR_CHEAT, "Snow fall speed scale." );
static ConVar r_SnowWindScale( "r_SnowWindScale", "0.0035", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowDebugBox( "r_SnowDebugBox", "0", FCVAR_CHEAT, "Snow Debug Boxes." );
static ConVar r_SnowZoomOffset( "r_SnowZoomOffset", "384.0f", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowZoomRadius( "r_SnowZoomRadius", "512.0f", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowStartAlpha( "r_SnowStartAlpha", "25", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowEndAlpha( "r_SnowEndAlpha", "255", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowColorRed( "r_SnowColorRed", "150", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowColorGreen( "r_SnowColorGreen", "175", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowColorBlue( "r_SnowColorBlue", "200", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowStartSize( "r_SnowStartSize", "1", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowEndSize( "r_SnowEndSize", "0", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowRayLength( "r_SnowRayLength", "8192.0f", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowRayRadius( "r_SnowRayRadius", "256", FCVAR_CHEAT, "Snow." );
static ConVar r_SnowRayEnable( "r_SnowRayEnable", "1", FCVAR_CHEAT, "Snow." );
void DrawPrecipitation()
{
for ( int i=0; i < g_Precipitations.Count(); i++ )
{
g_Precipitations[i]->Render();
}
}
//-----------------------------------------------------------------------------
// determines if a weather particle has hit something other than air
//-----------------------------------------------------------------------------
static bool IsInAir( const Vector& position )
{
int contents = enginetrace->GetPointContents( position );
return (contents & CONTENTS_SOLID) == 0;
}
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
ConVar CClient_Precipitation::s_raindensity( "r_raindensity","0.001", FCVAR_CHEAT);
ConVar CClient_Precipitation::s_rainwidth( "r_rainwidth", "0.5", FCVAR_CHEAT );
ConVar CClient_Precipitation::s_rainlength( "r_rainlength", "0.1f", FCVAR_CHEAT );
ConVar CClient_Precipitation::s_rainspeed( "r_rainspeed", "600.0f", FCVAR_CHEAT );
ConVar r_rainalpha( "r_rainalpha", "0.4", FCVAR_CHEAT );
ConVar r_rainalphapow( "r_rainalphapow", "0.8", FCVAR_CHEAT );
Vector CClient_Precipitation::s_WindVector; // Stores the wind speed vector
void CClient_Precipitation::OnDataChanged( DataUpdateType_t updateType )
{
// Simulate every frame.
if ( updateType == DATA_UPDATE_CREATED )
{
SetNextClientThink( CLIENT_THINK_ALWAYS );
if ( m_nPrecipType == PRECIPITATION_TYPE_SNOWFALL )
{
SnowFallManagerCreate( this );
}
}
m_flDensity = RemapVal( m_clrRender->a, 0, 255, 0, 0.001 );
BaseClass::OnDataChanged( updateType );
}
void CClient_Precipitation::ClientThink()
{
Simulate( gpGlobals->frametime );
}
//-----------------------------------------------------------------------------
//
// Utility methods for the various simulation functions
//
//-----------------------------------------------------------------------------
inline bool CClient_Precipitation::SimulateRain( CPrecipitationParticle* pParticle, float dt )
{
if (GetRemainingLifetime( pParticle ) < 0.0f)
return false;
Vector vOldPos = pParticle->m_Pos;
// Update position
VectorMA( pParticle->m_Pos, dt, pParticle->m_Velocity,
pParticle->m_Pos );
// wind blows rain around
for ( int i = 0 ; i < 2 ; i++ )
{
if ( pParticle->m_Velocity[i] < s_WindVector[i] )
{
pParticle->m_Velocity[i] += ( 5 / pParticle->m_Mass );
// clamp
if ( pParticle->m_Velocity[i] > s_WindVector[i] )
pParticle->m_Velocity[i] = s_WindVector[i];
}
else if (pParticle->m_Velocity[i] > s_WindVector[i] )
{
pParticle->m_Velocity[i] -= ( 5 / pParticle->m_Mass );
// clamp.
if ( pParticle->m_Velocity[i] < s_WindVector[i] )
pParticle->m_Velocity[i] = s_WindVector[i];
}
}
// No longer in the air? punt.
if ( !IsInAir( pParticle->m_Pos ) )
{
//////
// SO2 - James
// Add rain splashes to func_precipitation
// Possibly make a splash if we hit a water surface and it's in front of the view.
/*if ( m_Splashes.Count() < 20 )
{
if ( RandomInt( 0, 100 ) < r_RainSplashPercentage.GetInt() )
{
trace_t trace;
UTIL_TraceLine(vOldPos, pParticle->m_Pos, MASK_WATER, NULL, COLLISION_GROUP_NONE, &trace);
if( trace.fraction < 1 )
{
m_Splashes.AddToTail( trace.endpos );
}
}
}*/
// Possibly make a splash if we hit a water surface and it's in front of the view.
if ( m_Splashes.Count() < 99 )
{
if ( RandomInt( 0, 100 ) < r_RainSplashPercentage.GetInt() )
{
trace_t trace;
UTIL_TraceLine(vOldPos, pParticle->m_Pos, MASK_ALL, NULL, COLLISION_GROUP_PLAYER, &trace);
if( trace.fraction < 1 )
{
DispatchParticleEffect( "rainsplash", trace.endpos, trace.m_pEnt->GetAbsAngles() , NULL );
m_Splashes.AddToTail( trace.endpos );
}
}
}
//////
// Tell the framework it's time to remove the particle from the list
return false;
}
// We still want this particle
return true;
}
inline bool CClient_Precipitation::SimulateSnow( CPrecipitationParticle* pParticle, float dt )
{
if ( IsInAir( pParticle->m_Pos ) )
{
// Update position
VectorMA( pParticle->m_Pos, dt, pParticle->m_Velocity,
pParticle->m_Pos );
// wind blows rain around
for ( int i = 0 ; i < 2 ; i++ )
{
if ( pParticle->m_Velocity[i] < s_WindVector[i] )
{
pParticle->m_Velocity[i] += ( 5.0f / pParticle->m_Mass );
// accelerating flakes get a trail
pParticle->m_Ramp = 0.5f;
// clamp
if ( pParticle->m_Velocity[i] > s_WindVector[i] )
pParticle->m_Velocity[i] = s_WindVector[i];
}
else if (pParticle->m_Velocity[i] > s_WindVector[i] )
{
pParticle->m_Velocity[i] -= ( 5.0f / pParticle->m_Mass );
// accelerating flakes get a trail
pParticle->m_Ramp = 0.5f;
// clamp.
if ( pParticle->m_Velocity[i] < s_WindVector[i] )
pParticle->m_Velocity[i] = s_WindVector[i];
}
}
return true;
}
// Kill the particle immediately!
return false;
}
void CClient_Precipitation::Simulate( float dt )
{
// NOTE: When client-side prechaching works, we need to remove this
Precache();
m_flHalfScreenWidth = (float)ScreenWidth() / 2;
// Our sim methods needs dt and wind vector
if ( dt )
{
ComputeWindVector( );
}
if ( m_nPrecipType == PRECIPITATION_TYPE_ASH )
{
CreateAshParticle();
return;
}
// The snow fall manager handles the simulation.
if ( m_nPrecipType == PRECIPITATION_TYPE_SNOWFALL )
return;
// calculate the max amount of time it will take this flake to fall.
// This works if we assume the wind doesn't have a z component
if ( r_RainHack.GetInt() )
m_Lifetime = (GetClientWorldEntity()->m_WorldMaxs[2] - GetClientWorldEntity()->m_WorldMins[2]) / m_Speed;
else
m_Lifetime = (WorldAlignMaxs()[2] - WorldAlignMins()[2]) / m_Speed;
if ( !r_RainSimulate.GetInt() )
return;
CFastTimer timer;
timer.Start();
// Emit new particles
EmitParticles( dt );
// Simulate all the particles.
int iNext;
if ( m_nPrecipType == PRECIPITATION_TYPE_RAIN )
{
for ( int i=m_Particles.Head(); i != m_Particles.InvalidIndex(); i=iNext )
{
iNext = m_Particles.Next( i );
if ( !SimulateRain( &m_Particles[i], dt ) )
m_Particles.Remove( i );
}
}
else if ( m_nPrecipType == PRECIPITATION_TYPE_SNOW )
{
for ( int i=m_Particles.Head(); i != m_Particles.InvalidIndex(); i=iNext )
{
iNext = m_Particles.Next( i );
if ( !SimulateSnow( &m_Particles[i], dt ) )
m_Particles.Remove( i );
}
}
if ( r_RainProfile.GetInt() )
{
timer.End();
engine->Con_NPrintf( 15, "Rain simulation: %du (%d tracers)", timer.GetDuration().GetMicroseconds(), m_Particles.Count() );
}
}
//-----------------------------------------------------------------------------
// tracer rendering
//-----------------------------------------------------------------------------
inline void CClient_Precipitation::RenderParticle( CPrecipitationParticle* pParticle, CMeshBuilder &mb )
{
float scale;
Vector start, delta;
if ( m_nPrecipType == PRECIPITATION_TYPE_ASH )
return;
if ( m_nPrecipType == PRECIPITATION_TYPE_SNOWFALL )
return;
// make streaks 0.1 seconds long, but prevent from going past end
float lifetimeRemaining = GetRemainingLifetime( pParticle );
if (lifetimeRemaining >= GetLength())
scale = GetLength() * pParticle->m_Ramp;
else
scale = lifetimeRemaining * pParticle->m_Ramp;
// NOTE: We need to do everything in screen space
Vector3DMultiplyPosition( CurrentWorldToViewMatrix(), pParticle->m_Pos, start );
if ( start.z > -1 )
return;
Vector3DMultiply( CurrentWorldToViewMatrix(), pParticle->m_Velocity, delta );
// give a spiraling pattern to snow particles
if ( m_nPrecipType == PRECIPITATION_TYPE_SNOW )
{
Vector spiral, camSpiral;
float s, c;
if ( pParticle->m_Mass > 1.0f )
{
SinCos( gpGlobals->curtime * M_PI * (1+pParticle->m_Mass * 0.1f) +
pParticle->m_Mass * 5.0f, &s , &c );
// only spiral particles with a mass > 1, so some fall straight down
spiral[0] = 28 * c;
spiral[1] = 28 * s;
spiral[2] = 0.0f;
Vector3DMultiply( CurrentWorldToViewMatrix(), spiral, camSpiral );
// X and Y are measured in world space; need to convert to camera space
VectorAdd( start, camSpiral, start );
VectorAdd( delta, camSpiral, delta );
}
// shrink the trails on spiraling flakes.
pParticle->m_Ramp = 0.3f;
}
delta[0] *= scale;
delta[1] *= scale;
delta[2] *= scale;
// See c_tracer.* for this method
float flAlpha = r_rainalpha.GetFloat();
float flWidth = GetWidth();
float flScreenSpaceWidth = flWidth * m_flHalfScreenWidth / -start.z;
if ( flScreenSpaceWidth < MIN_SCREENSPACE_RAIN_WIDTH )
{
// Make the rain tracer at least the min size, but fade its alpha the smaller it gets.
flAlpha *= flScreenSpaceWidth / MIN_SCREENSPACE_RAIN_WIDTH;
flWidth = MIN_SCREENSPACE_RAIN_WIDTH * -start.z / m_flHalfScreenWidth;
}
flAlpha = pow( flAlpha, r_rainalphapow.GetFloat() );
float flColor[4] = { 1, 1, 1, flAlpha };
Tracer_Draw( &mb, start, delta, flWidth, flColor, 1 );
}
void CClient_Precipitation::CreateWaterSplashes()
{
for ( int i=0; i < m_Splashes.Count(); i++ )
{
Vector vSplash = m_Splashes[i];
if ( CurrentViewForward().Dot( vSplash - CurrentViewOrigin() ) > 1 )
{
FX_WaterRipple( vSplash, g_flSplashScale, &g_vSplashColor, g_flSplashLifetime, g_flSplashAlpha );
}
}
m_Splashes.Purge();
}
void CClient_Precipitation::Render()
{
if ( !r_DrawRain.GetInt() )
return;
/////
// SO2 - James
// Enable func_precipitation rendering whilst in a point_viewcontrol
// http://developer.valvesoftware.com/wiki/HL2_snippets#Enabling_func_precipitation_rendering_whilst_in_a_point_viewcontrol
/*// Don't render in monitors or in reflections or refractions.
if ( CurrentViewID() == VIEW_MONITOR )
return;*/
/////
if ( view->GetDrawFlags() & (DF_RENDER_REFLECTION | DF_RENDER_REFRACTION) )
return;
if ( m_nPrecipType == PRECIPITATION_TYPE_ASH )
return;
if ( m_nPrecipType == PRECIPITATION_TYPE_SNOWFALL )
return;
// Create any queued up water splashes.
CreateWaterSplashes();
CFastTimer timer;
timer.Start();
CMatRenderContextPtr pRenderContext( materials );
// We want to do our calculations in view space.
VMatrix tempView;
pRenderContext->GetMatrix( MATERIAL_VIEW, &tempView );
pRenderContext->MatrixMode( MATERIAL_VIEW );
pRenderContext->LoadIdentity();
// Force the user clip planes to use the old view matrix
pRenderContext->EnableUserClipTransformOverride( true );
pRenderContext->UserClipTransform( tempView );
// Draw all the rain tracers.
pRenderContext->Bind( m_MatHandle );
IMesh *pMesh = pRenderContext->GetDynamicMesh();
if ( pMesh )
{
CMeshBuilder mb;
mb.Begin( pMesh, MATERIAL_QUADS, m_Particles.Count() );
for ( int i=m_Particles.Head(); i != m_Particles.InvalidIndex(); i=m_Particles.Next( i ) )
{
CPrecipitationParticle *p = &m_Particles[i];
RenderParticle( p, mb );
}
mb.End( false, true );
}
pRenderContext->EnableUserClipTransformOverride( false );
pRenderContext->MatrixMode( MATERIAL_VIEW );
pRenderContext->LoadMatrix( tempView );
if ( r_RainProfile.GetInt() )
{
timer.End();
engine->Con_NPrintf( 16, "Rain render : %du", timer.GetDuration().GetMicroseconds() );
}
}
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CClient_Precipitation::CClient_Precipitation() : m_Remainder(0.0f)
{
m_nPrecipType = PRECIPITATION_TYPE_RAIN;
m_MatHandle = INVALID_MATERIAL_HANDLE;
m_flHalfScreenWidth = 1;
g_Precipitations.AddToTail( this );
}
CClient_Precipitation::~CClient_Precipitation()
{
g_Precipitations.FindAndRemove( this );
SnowFallManagerDestroy();
}
//-----------------------------------------------------------------------------
// Precache data
//-----------------------------------------------------------------------------
#define SNOW_SPEED 80.0f
#define RAIN_SPEED 425.0f
#define RAIN_TRACER_WIDTH 0.35f
#define SNOW_TRACER_WIDTH 0.7f
void CClient_Precipitation::Precache( )
{
if ( !m_MatHandle )
{
// Compute precipitation emission speed
switch( m_nPrecipType )
{
case PRECIPITATION_TYPE_SNOW:
m_Speed = SNOW_SPEED;
m_MatHandle = materials->FindMaterial( "particle/snow", TEXTURE_GROUP_CLIENT_EFFECTS );
m_InitialRamp = 0.6f;
m_Width = SNOW_TRACER_WIDTH;
break;
case PRECIPITATION_TYPE_RAIN:
Assert( m_nPrecipType == PRECIPITATION_TYPE_RAIN );
m_Speed = RAIN_SPEED;
m_MatHandle = materials->FindMaterial( "particle/rain", TEXTURE_GROUP_CLIENT_EFFECTS );
m_InitialRamp = 1.0f;
m_Color[3] = 1.0f; // make translucent
m_Width = RAIN_TRACER_WIDTH;
break;
default:
m_InitialRamp = 1.0f;
m_Color[3] = 1.0f; // make translucent
break;
}
// Store off the color
m_Color[0] = 1.0f;
m_Color[1] = 1.0f;
m_Color[2] = 1.0f;
}
}
//-----------------------------------------------------------------------------
// Gets the tracer width and speed
//-----------------------------------------------------------------------------
inline float CClient_Precipitation::GetWidth() const
{
// return m_Width;
return s_rainwidth.GetFloat();
}
inline float CClient_Precipitation::GetLength() const
{
// return m_Length;
return s_rainlength.GetFloat();
}
inline float CClient_Precipitation::GetSpeed() const
{
// return m_Speed;
return s_rainspeed.GetFloat();
}
//-----------------------------------------------------------------------------
// Gets the remaining lifetime of the particle
//-----------------------------------------------------------------------------
inline float CClient_Precipitation::GetRemainingLifetime( CPrecipitationParticle* pParticle ) const
{
float timeSinceSpawn = gpGlobals->curtime - pParticle->m_SpawnTime;
return m_Lifetime - timeSinceSpawn;
}
//-----------------------------------------------------------------------------
// Creates a particle
//-----------------------------------------------------------------------------
inline CPrecipitationParticle* CClient_Precipitation::CreateParticle()
{
int i = m_Particles.AddToTail();
CPrecipitationParticle* pParticle = &m_Particles[i];
pParticle->m_SpawnTime = gpGlobals->curtime;
pParticle->m_Ramp = m_InitialRamp;
return pParticle;
}
//-----------------------------------------------------------------------------
// Compute the emission area
//-----------------------------------------------------------------------------
bool CClient_Precipitation::ComputeEmissionArea( Vector& origin, Vector2D& size )
{
// FIXME: Compute the precipitation area based on computational power
float emissionSize = r_RainRadius.GetFloat(); // size of box to emit particles in
Vector vMins = WorldAlignMins();
Vector vMaxs = WorldAlignMaxs();
if ( r_RainHack.GetInt() )
{
vMins = GetClientWorldEntity()->m_WorldMins;
vMaxs = GetClientWorldEntity()->m_WorldMaxs;
}
// calculate a volume around the player to snow in. Intersect this big magic
// box around the player with the volume of the current environmental ent.
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return false;
// Determine how much time it'll take a falling particle to hit the player
float emissionHeight = min( vMaxs[2], pPlayer->GetAbsOrigin()[2] + 512 );
float distToFall = emissionHeight - pPlayer->GetAbsOrigin()[2];
float fallTime = distToFall / GetSpeed();
// Based on the windspeed, figure out the center point of the emission
Vector2D center;
center[0] = pPlayer->GetAbsOrigin()[0] - fallTime * s_WindVector[0];
center[1] = pPlayer->GetAbsOrigin()[1] - fallTime * s_WindVector[1];
Vector2D lobound, hibound;
lobound[0] = center[0] - emissionSize * 0.5f;
lobound[1] = center[1] - emissionSize * 0.5f;
hibound[0] = lobound[0] + emissionSize;
hibound[1] = lobound[1] + emissionSize;
// Cull non-intersecting.
if ( ( vMaxs[0] < lobound[0] ) || ( vMaxs[1] < lobound[1] ) ||
( vMins[0] > hibound[0] ) || ( vMins[1] > hibound[1] ) )
return false;
origin[0] = max( vMins[0], lobound[0] );
origin[1] = max( vMins[1], lobound[1] );
origin[2] = emissionHeight;
hibound[0] = min( vMaxs[0], hibound[0] );
hibound[1] = min( vMaxs[1], hibound[1] );
size[0] = hibound[0] - origin[0];
size[1] = hibound[1] - origin[1];
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pDebugName -
// Output : AshDebrisEffect*
//-----------------------------------------------------------------------------
AshDebrisEffect* AshDebrisEffect::Create( const char *pDebugName )
{
return new AshDebrisEffect( pDebugName );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pParticle -
// timeDelta -
// Output : float
//-----------------------------------------------------------------------------
float AshDebrisEffect::UpdateAlpha( const SimpleParticle *pParticle )
{
return ( ((float)pParticle->m_uchStartAlpha/255.0f) * sin( M_PI * (pParticle->m_flLifetime / pParticle->m_flDieTime) ) );
}
#define ASH_PARTICLE_NOISE 0x4
float AshDebrisEffect::UpdateRoll( SimpleParticle *pParticle, float timeDelta )
{
float flRoll = CSimpleEmitter::UpdateRoll(pParticle, timeDelta );
if ( pParticle->m_iFlags & ASH_PARTICLE_NOISE )
{
Vector vTempEntVel = pParticle->m_vecVelocity;
float fastFreq = gpGlobals->curtime * 1.5;
float s, c;
SinCos( fastFreq, &s, &c );
pParticle->m_Pos = ( pParticle->m_Pos + Vector(
vTempEntVel[0] * timeDelta * s,
vTempEntVel[1] * timeDelta * s, 0 ) );
}
return flRoll;
}
void CClient_Precipitation::CreateAshParticle( void )
{
// Make sure the emitter is setup
if ( m_pAshEmitter == NULL )
{
if ( ( m_pAshEmitter = AshDebrisEffect::Create( "ashtray" ) ) == NULL )
return;
m_tAshParticleTimer.Init( 192 );
m_tAshParticleTraceTimer.Init( 15 );
m_bActiveAshEmitter = false;
m_iAshCount = 0;
}
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( pPlayer == NULL )
return;
Vector vForward;
pPlayer->GetVectors( &vForward, NULL, NULL );
vForward.z = 0.0f;
float curTime = gpGlobals->frametime;
Vector vPushOrigin;
Vector absmins = WorldAlignMins();
Vector absmaxs = WorldAlignMaxs();
//15 Traces a second.
while ( m_tAshParticleTraceTimer.NextEvent( curTime ) )
{
trace_t tr;
Vector vTraceStart = pPlayer->EyePosition();
Vector vTraceEnd = pPlayer->EyePosition() + vForward * MAX_TRACE_LENGTH;
UTIL_TraceLine( vTraceStart, vTraceEnd, MASK_SHOT_HULL & (~CONTENTS_GRATE), pPlayer, COLLISION_GROUP_NONE, &tr );
//debugoverlay->AddLineOverlay( vTraceStart, tr.endpos, 255, 0, 0, 0, 0.2 );
if ( tr.fraction != 1.0f )
{
trace_t tr2;
UTIL_TraceModel( vTraceStart, tr.endpos, Vector( -1, -1, -1 ), Vector( 1, 1, 1 ), this, COLLISION_GROUP_NONE, &tr2 );
if ( tr2.m_pEnt == this )
{
m_bActiveAshEmitter = true;
if ( tr2.startsolid == false )
{
m_vAshSpawnOrigin = tr2.endpos + vForward * 256;
}
else
{
m_vAshSpawnOrigin = vTraceStart;
}
}
else
{
m_bActiveAshEmitter = false;
}
}
}
if ( m_bActiveAshEmitter == false )
return;
Vector vecVelocity = pPlayer->GetAbsVelocity();
float flVelocity = VectorNormalize( vecVelocity );
Vector offset = m_vAshSpawnOrigin;
m_pAshEmitter->SetSortOrigin( offset );
PMaterialHandle hMaterial[4];
hMaterial[0] = ParticleMgr()->GetPMaterial( "effects/fleck_ash1" );
hMaterial[1] = ParticleMgr()->GetPMaterial( "effects/fleck_ash2" );
hMaterial[2] = ParticleMgr()->GetPMaterial( "effects/fleck_ash3" );
hMaterial[3] = ParticleMgr()->GetPMaterial( "effects/ember_swirling001" );
SimpleParticle *pParticle;
Vector vSpawnOrigin = vec3_origin;
if ( flVelocity > 0 )
{
vSpawnOrigin = ( vForward * 256 ) + ( vecVelocity * ( flVelocity * 2 ) );
}
// Add as many particles as we need
while ( m_tAshParticleTimer.NextEvent( curTime ) )
{
int iRandomAltitude = RandomInt( 0, 128 );
offset = m_vAshSpawnOrigin + vSpawnOrigin + RandomVector( -256, 256 );
offset.z = m_vAshSpawnOrigin.z + iRandomAltitude;
if ( offset[0] > absmaxs[0]
|| offset[1] > absmaxs[1]
|| offset[2] > absmaxs[2]
|| offset[0] < absmins[0]
|| offset[1] < absmins[1]
|| offset[2] < absmins[2] )
continue;
m_iAshCount++;
bool bEmberTime = false;
if ( m_iAshCount >= 250 )
{
bEmberTime = true;
m_iAshCount = 0;
}
int iRandom = random->RandomInt(0,2);
if ( bEmberTime == true )
{
offset = m_vAshSpawnOrigin + (vForward * 256) + RandomVector( -128, 128 );
offset.z = pPlayer->EyePosition().z + RandomFloat( -16, 64 );
iRandom = 3;
}
pParticle = (SimpleParticle *) m_pAshEmitter->AddParticle( sizeof(SimpleParticle), hMaterial[iRandom], offset );
if (pParticle == NULL)
continue;
pParticle->m_flLifetime = 0.0f;
pParticle->m_flDieTime = RemapVal( iRandomAltitude, 0, 128, 4, 8 );
if ( bEmberTime == true )
{
Vector vGoal = pPlayer->EyePosition() + RandomVector( -64, 64 );
Vector vDir = vGoal - offset;
VectorNormalize( vDir );
pParticle->m_vecVelocity = vDir * 75;
pParticle->m_flDieTime = 2.5f;
}
else
{
pParticle->m_vecVelocity = Vector( RandomFloat( -20.0f, 20.0f ), RandomFloat( -20.0f, 20.0f ), RandomFloat( -10, -15 ) );
}
float color = random->RandomInt( 125, 225 );
pParticle->m_uchColor[0] = color;
pParticle->m_uchColor[1] = color;
pParticle->m_uchColor[2] = color;
pParticle->m_uchStartSize = 1;
pParticle->m_uchEndSize = 1.5;
pParticle->m_uchStartAlpha = 255;
pParticle->m_flRoll = random->RandomInt( 0, 360 );
pParticle->m_flRollDelta = random->RandomFloat( -0.15f, 0.15f );
pParticle->m_iFlags = SIMPLE_PARTICLE_FLAG_WINDBLOWN;
if ( random->RandomInt( 0, 10 ) <= 1 )
{
pParticle->m_iFlags |= ASH_PARTICLE_NOISE;
}
}
}
void CClient_Precipitation::CreateRainOrSnowParticle( Vector vSpawnPosition, Vector vVelocity )
{
// Create the particle
CPrecipitationParticle* p = CreateParticle();
if (!p)
return;
VectorCopy( vVelocity, p->m_Velocity );
p->m_Pos = vSpawnPosition;
p->m_Velocity[ 0 ] += random->RandomFloat(-r_RainSideVel.GetInt(), r_RainSideVel.GetInt());
p->m_Velocity[ 1 ] += random->RandomFloat(-r_RainSideVel.GetInt(), r_RainSideVel.GetInt());
p->m_Mass = random->RandomFloat( 0.5, 1.5 );
}
//-----------------------------------------------------------------------------
// emit the precipitation particles
//-----------------------------------------------------------------------------
void CClient_Precipitation::EmitParticles( float fTimeDelta )
{
Vector2D size;
Vector vel, org;
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
Vector vPlayerCenter = pPlayer->WorldSpaceCenter();
// Compute where to emit
if (!ComputeEmissionArea( org, size ))
return;
// clamp this to prevent creating a bunch of rain or snow at one time.
if( fTimeDelta > 0.075f )
fTimeDelta = 0.075f;
// FIXME: Compute the precipitation density based on computational power
float density = m_flDensity;
if (density > 0.01f)
density = 0.01f;
// Compute number of particles to emit based on precip density and emission area and dt
float fParticles = size[0] * size[1] * density * fTimeDelta + m_Remainder;
int cParticles = (int)fParticles;
m_Remainder = fParticles - cParticles;
// calculate the max amount of time it will take this flake to fall.
// This works if we assume the wind doesn't have a z component
VectorCopy( s_WindVector, vel );
vel[2] -= GetSpeed();
// Emit all the particles
for ( int i = 0 ; i < cParticles ; i++ )
{
Vector vParticlePos = org;
vParticlePos[ 0 ] += size[ 0 ] * random->RandomFloat(0, 1);
vParticlePos[ 1 ] += size[ 1 ] * random->RandomFloat(0, 1);
// Figure out where the particle should lie in Z by tracing a line from the player's height up to the
// desired height and making sure it doesn't hit a wall.
Vector vPlayerHeight = vParticlePos;
vPlayerHeight.z = vPlayerCenter.z;
trace_t trace;
UTIL_TraceLine( vPlayerHeight, vParticlePos, MASK_SOLID_BRUSHONLY, NULL, COLLISION_GROUP_NONE, &trace );
if ( trace.fraction < 1 )
{
// If we hit a brush, then don't spawn the particle.
if ( trace.surface.flags & SURF_SKY )
{
vParticlePos = trace.endpos;
}
else
{
continue;
}
}
CreateRainOrSnowParticle( vParticlePos, vel );
}
}
//-----------------------------------------------------------------------------
// Computes the wind vector
//-----------------------------------------------------------------------------
void CClient_Precipitation::ComputeWindVector( )
{
// Compute the wind direction
QAngle windangle( 0, cl_winddir.GetFloat(), 0 ); // used to turn wind yaw direction into a vector
// Randomize the wind angle and speed slightly to get us a little variation
windangle[1] = windangle[1] + random->RandomFloat( -10, 10 );
float windspeed = cl_windspeed.GetFloat() * (1.0 + random->RandomFloat( -0.2, 0.2 ));
AngleVectors( windangle, &s_WindVector );
VectorScale( s_WindVector, windspeed, s_WindVector );
}
CHandle<CClient_Precipitation> g_pPrecipHackEnt;
class CPrecipHack : public CAutoGameSystemPerFrame
{
public:
CPrecipHack( char const *name ) : CAutoGameSystemPerFrame( name )
{
m_bLevelInitted = false;
}
virtual void LevelInitPostEntity()
{
if ( r_RainHack.GetInt() )
{
CClient_Precipitation *pPrecipHackEnt = new CClient_Precipitation;
pPrecipHackEnt->InitializeAsClientEntity( NULL, RENDER_GROUP_TRANSLUCENT_ENTITY );
g_pPrecipHackEnt = pPrecipHackEnt;
}
m_bLevelInitted = true;
}
virtual void LevelShutdownPreEntity()
{
if ( r_RainHack.GetInt() && g_pPrecipHackEnt )
{
g_pPrecipHackEnt->Release();
}
m_bLevelInitted = false;
}
virtual void Update( float frametime )
{
// Handle changes to the cvar at runtime.
if ( m_bLevelInitted )
{
if ( r_RainHack.GetInt() && !g_pPrecipHackEnt )
LevelInitPostEntity();
else if ( !r_RainHack.GetInt() && g_pPrecipHackEnt )
LevelShutdownPreEntity();
}
}
bool m_bLevelInitted;
};
CPrecipHack g_PrecipHack( "CPrecipHack" );
#else
void DrawPrecipitation()
{
}
#endif // _XBOX
//-----------------------------------------------------------------------------
// EnvWind - global wind info
//-----------------------------------------------------------------------------
class C_EnvWind : public C_BaseEntity
{
public:
C_EnvWind();
DECLARE_CLIENTCLASS();
DECLARE_CLASS( C_EnvWind, C_BaseEntity );
virtual void OnDataChanged( DataUpdateType_t updateType );
virtual bool ShouldDraw( void ) { return false; }
virtual void ClientThink( );
private:
C_EnvWind( const C_EnvWind & );
CEnvWindShared m_EnvWindShared;
};
// Receive datatables
BEGIN_RECV_TABLE_NOBASE(CEnvWindShared, DT_EnvWindShared)
RecvPropInt (RECVINFO(m_iMinWind)),
RecvPropInt (RECVINFO(m_iMaxWind)),
RecvPropInt (RECVINFO(m_iMinGust)),
RecvPropInt (RECVINFO(m_iMaxGust)),
RecvPropFloat (RECVINFO(m_flMinGustDelay)),
RecvPropFloat (RECVINFO(m_flMaxGustDelay)),
RecvPropInt (RECVINFO(m_iGustDirChange)),
RecvPropInt (RECVINFO(m_iWindSeed)),
RecvPropInt (RECVINFO(m_iInitialWindDir)),
RecvPropFloat (RECVINFO(m_flInitialWindSpeed)),
RecvPropFloat (RECVINFO(m_flStartTime)),
RecvPropFloat (RECVINFO(m_flGustDuration)),
// RecvPropInt (RECVINFO(m_iszGustSound)),
END_RECV_TABLE()
IMPLEMENT_CLIENTCLASS_DT( C_EnvWind, DT_EnvWind, CEnvWind )
RecvPropDataTable(RECVINFO_DT(m_EnvWindShared), 0, &REFERENCE_RECV_TABLE(DT_EnvWindShared)),
END_RECV_TABLE()
C_EnvWind::C_EnvWind()
{
}
//-----------------------------------------------------------------------------
// Post data update!
//-----------------------------------------------------------------------------
void C_EnvWind::OnDataChanged( DataUpdateType_t updateType )
{
// Whenever we get an update, reset the entire state.
// Note that the fields have already been stored by the datatables,
// but there's still work to be done in the init block
m_EnvWindShared.Init( entindex(), m_EnvWindShared.m_iWindSeed,
m_EnvWindShared.m_flStartTime, m_EnvWindShared.m_iInitialWindDir,
m_EnvWindShared.m_flInitialWindSpeed );
SetNextClientThink(0.0f);
BaseClass::OnDataChanged( updateType );
}
void C_EnvWind::ClientThink( )
{
// Update the wind speed
float flNextThink = m_EnvWindShared.WindThink( gpGlobals->curtime );
SetNextClientThink(flNextThink);
}
//==================================================
// EmberParticle
//==================================================
class CEmberEmitter : public CSimpleEmitter
{
public:
CEmberEmitter( const char *pDebugName );
static CSmartPtr<CEmberEmitter> Create( const char *pDebugName );
virtual void UpdateVelocity( SimpleParticle *pParticle, float timeDelta );
virtual Vector UpdateColor( const SimpleParticle *pParticle );
private:
CEmberEmitter( const CEmberEmitter & );
};
//-----------------------------------------------------------------------------
// Purpose:
// Input : fTimeDelta -
// Output : Vector
//-----------------------------------------------------------------------------
CEmberEmitter::CEmberEmitter( const char *pDebugName ) : CSimpleEmitter( pDebugName )
{
}
CSmartPtr<CEmberEmitter> CEmberEmitter::Create( const char *pDebugName )
{
return new CEmberEmitter( pDebugName );
}
void CEmberEmitter::UpdateVelocity( SimpleParticle *pParticle, float timeDelta )
{
float speed = VectorNormalize( pParticle->m_vecVelocity );
Vector offset;
speed -= ( 1.0f * timeDelta );
offset.Random( -0.025f, 0.025f );
offset[2] = 0.0f;
pParticle->m_vecVelocity += offset;
VectorNormalize( pParticle->m_vecVelocity );
pParticle->m_vecVelocity *= speed;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pParticle -
// timeDelta -
//-----------------------------------------------------------------------------
Vector CEmberEmitter::UpdateColor( const SimpleParticle *pParticle )
{
Vector color;
float ramp = 1.0f - ( pParticle->m_flLifetime / pParticle->m_flDieTime );
color[0] = ( (float) pParticle->m_uchColor[0] * ramp ) / 255.0f;
color[1] = ( (float) pParticle->m_uchColor[1] * ramp ) / 255.0f;
color[2] = ( (float) pParticle->m_uchColor[2] * ramp ) / 255.0f;
return color;
}
//==================================================
// C_Embers
//==================================================
class C_Embers : public C_BaseEntity
{
public:
DECLARE_CLIENTCLASS();
DECLARE_CLASS( C_Embers, C_BaseEntity );
C_Embers();
~C_Embers();
void Start( void );
virtual void OnDataChanged( DataUpdateType_t updateType );
virtual bool ShouldDraw( void );
virtual void AddEntity( void );
//Server-side
int m_nDensity;
int m_nLifetime;
int m_nSpeed;
bool m_bEmit;
protected:
void SpawnEmber( void );
PMaterialHandle m_hMaterial;
TimedEvent m_tParticleSpawn;
CSmartPtr<CEmberEmitter> m_pEmitter;
};
//Receive datatable
IMPLEMENT_CLIENTCLASS_DT( C_Embers, DT_Embers, CEmbers )
RecvPropInt( RECVINFO( m_nDensity ) ),
RecvPropInt( RECVINFO( m_nLifetime ) ),
RecvPropInt( RECVINFO( m_nSpeed ) ),
RecvPropInt( RECVINFO( m_bEmit ) ),
END_RECV_TABLE()
//-----------------------------------------------------------------------------
// Purpose:
// Input : bnewentity -
//-----------------------------------------------------------------------------
C_Embers::C_Embers()
{
m_pEmitter = CEmberEmitter::Create( "C_Embers" );
}
C_Embers::~C_Embers()
{
}
void C_Embers::OnDataChanged( DataUpdateType_t updateType )
{
BaseClass::OnDataChanged( updateType );
if ( updateType == DATA_UPDATE_CREATED )
{
m_pEmitter->SetSortOrigin( GetAbsOrigin() );
Start();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool C_Embers::ShouldDraw()
{
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_Embers::Start( void )
{
//Various setup info
m_tParticleSpawn.Init( m_nDensity );
m_hMaterial = m_pEmitter->GetPMaterial( "particle/fire" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_Embers::AddEntity( void )
{
if ( m_bEmit == false )
return;
float tempDelta = gpGlobals->frametime;
while( m_tParticleSpawn.NextEvent( tempDelta ) )
{
SpawnEmber();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_Embers::SpawnEmber( void )
{
Vector offset, mins, maxs;
modelinfo->GetModelBounds( GetModel(), mins, maxs );
//Setup our spawn position
offset[0] = random->RandomFloat( mins[0], maxs[0] );
offset[1] = random->RandomFloat( mins[1], maxs[1] );
offset[2] = random->RandomFloat( mins[2], maxs[2] );
//Spawn the particle
SimpleParticle *sParticle = (SimpleParticle *) m_pEmitter->AddParticle( sizeof( SimpleParticle ), m_hMaterial, offset );
if (sParticle == NULL)
return;
float cScale = random->RandomFloat( 0.75f, 1.0f );
//Set it up
sParticle->m_flLifetime = 0.0f;
sParticle->m_flDieTime = m_nLifetime;
sParticle->m_uchColor[0] = m_clrRender->r * cScale;
sParticle->m_uchColor[1] = m_clrRender->g * cScale;
sParticle->m_uchColor[2] = m_clrRender->b * cScale;
sParticle->m_uchStartAlpha = 255;
sParticle->m_uchEndAlpha = 0;
sParticle->m_uchStartSize = 1;
sParticle->m_uchEndSize = 0;
sParticle->m_flRollDelta = 0;
sParticle->m_flRoll = 0;
//Set the velocity
Vector velocity;
AngleVectors( GetAbsAngles(), &velocity );
sParticle->m_vecVelocity = velocity * m_nSpeed;
sParticle->m_vecVelocity[0] += random->RandomFloat( -(m_nSpeed/8), (m_nSpeed/8) );
sParticle->m_vecVelocity[1] += random->RandomFloat( -(m_nSpeed/8), (m_nSpeed/8) );
sParticle->m_vecVelocity[2] += random->RandomFloat( -(m_nSpeed/8), (m_nSpeed/8) );
UpdateVisibility();
}
//-----------------------------------------------------------------------------
// Quadratic spline beam effect
//-----------------------------------------------------------------------------
#include "beamdraw.h"
class C_QuadraticBeam : public C_BaseEntity
{
public:
DECLARE_CLIENTCLASS();
DECLARE_CLASS( C_QuadraticBeam, C_BaseEntity );
//virtual void OnDataChanged( DataUpdateType_t updateType );
virtual bool ShouldDraw( void ) { return true; }
virtual int DrawModel( int );
virtual void GetRenderBounds( Vector& mins, Vector& maxs )
{
ClearBounds( mins, maxs );
AddPointToBounds( vec3_origin, mins, maxs );
AddPointToBounds( m_targetPosition, mins, maxs );
AddPointToBounds( m_controlPosition, mins, maxs );
mins -= GetRenderOrigin();
maxs -= GetRenderOrigin();
}
protected:
Vector m_targetPosition;
Vector m_controlPosition;
float m_scrollRate;
float m_flWidth;
};
//Receive datatable
IMPLEMENT_CLIENTCLASS_DT( C_QuadraticBeam, DT_QuadraticBeam, CEnvQuadraticBeam )
RecvPropVector( RECVINFO(m_targetPosition) ),
RecvPropVector( RECVINFO(m_controlPosition) ),
RecvPropFloat( RECVINFO(m_scrollRate) ),
RecvPropFloat( RECVINFO(m_flWidth) ),
END_RECV_TABLE()
Vector Color32ToVector( const color32 &color )
{
return Vector( color.r * (1.0/255.0f), color.g * (1.0/255.0f), color.b * (1.0/255.0f) );
}
int C_QuadraticBeam::DrawModel( int )
{
Draw_SetSpriteTexture( GetModel(), 0, GetRenderMode() );
Vector color = Color32ToVector( GetRenderColor() );
DrawBeamQuadratic( GetRenderOrigin(), m_controlPosition, m_targetPosition, m_flWidth, color, gpGlobals->curtime*m_scrollRate );
return 1;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
class SnowFallEffect : public CSimpleEmitter
{
public:
SnowFallEffect( const char *pDebugName ) : CSimpleEmitter( pDebugName ) {}
static SnowFallEffect* Create( const char *pDebugName )
{
return new SnowFallEffect( pDebugName );
}
void UpdateVelocity( SimpleParticle *pParticle, float timeDelta )
{
float flSpeed = VectorNormalize( pParticle->m_vecVelocity );
flSpeed -= timeDelta;
pParticle->m_vecVelocity.x += RandomFloat( -0.025f, 0.025f );
pParticle->m_vecVelocity.y += RandomFloat( -0.025f, 0.025f );
VectorNormalize( pParticle->m_vecVelocity );
pParticle->m_vecVelocity *= flSpeed;
Vector vecWindVelocity;
GetWindspeedAtTime( gpGlobals->curtime, vecWindVelocity );
pParticle->m_vecVelocity += ( vecWindVelocity * r_SnowWindScale.GetFloat() );
}
void SimulateParticles( CParticleSimulateIterator *pIterator )
{
float timeDelta = pIterator->GetTimeDelta();
SimpleParticle *pParticle = (SimpleParticle*)pIterator->GetFirst();
while ( pParticle )
{
//Update velocity
UpdateVelocity( pParticle, timeDelta );
pParticle->m_Pos += pParticle->m_vecVelocity * timeDelta;
//Should this particle die?
pParticle->m_flLifetime += timeDelta;
UpdateRoll( pParticle, timeDelta );
if ( pParticle->m_flLifetime >= pParticle->m_flDieTime )
{
pIterator->RemoveParticle( pParticle );
}
else if ( !IsInAir( pParticle->m_Pos ) )
{
pIterator->RemoveParticle( pParticle );
}
pParticle = (SimpleParticle*)pIterator->GetNext();
}
}
int GetParticleCount( void )
{
return GetBinding().GetNumActiveParticles();
}
void SetBounds( const Vector &vecMin, const Vector &vecMax )
{
GetBinding().SetBBox( vecMin, vecMax, true );
}
bool IsTransparent( void ) { return false; }
private:
SnowFallEffect( const SnowFallEffect & );
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
class CSnowFallManager : public C_BaseEntity
{
public:
CSnowFallManager();
~CSnowFallManager();
bool CreateEmitter( void );
void SpawnClientEntity( void );
void ClientThink();
void AddSnowFallEntity( CClient_Precipitation *pSnowEntity );
// Snow Effect
enum
{
SNOWFALL_NONE = 0,
SNOWFALL_AROUND_PLAYER,
SNOWFALL_IN_ENTITY,
};
bool IsTransparent( void ) { return false; }
private:
bool CreateSnowFallEmitter( void );
void CreateSnowFall( void );
void CreateSnowFallParticles( float flCurrentTime, float flRadius, const Vector &vecEyePos, const Vector &vecForward, float flZoomScale );
void CreateOutsideVolumeSnowParticles( float flCurrentTime, float flRadius, float flZoomScale );
void CreateInsideVolumeSnowParticles( float flCurrentTime, float flRadius, const Vector &vecEyePos, const Vector &vecForward, float flZoomScale );
void CreateSnowParticlesSphere( float flRadius );
void CreateSnowParticlesRay( float flRadius, const Vector &vecEyePos, const Vector &vecForward );
void CreateSnowFallParticle( const Vector &vecParticleSpawn, int iBBox );
int StandingInSnowVolume( Vector &vecPoint );
void FindSnowVolumes( Vector &vecCenter, float flRadius, Vector &vecEyePos, Vector &vecForward );
void UpdateBounds( const Vector &vecSnowMin, const Vector &vecSnowMax );
private:
enum { MAX_SNOW_PARTICLES = 500 };
enum { MAX_SNOW_LIST = 32 };
TimedEvent m_tSnowFallParticleTimer;
TimedEvent m_tSnowFallParticleTraceTimer;
int m_iSnowFallArea;
CSmartPtr<SnowFallEffect> m_pSnowFallEmitter;
Vector m_vecSnowFallEmitOrigin;
float m_flSnowRadius;
Vector m_vecMin;
Vector m_vecMax;
int m_nActiveSnowCount;
int m_aActiveSnow[MAX_SNOW_LIST];
bool m_bRayParticles;
typedef struct SnowFall_t
{
PMaterialHandle m_hMaterial;
CClient_Precipitation *m_pEntity;
SnowFallEffect *m_pEffect;
Vector m_vecMin;
Vector m_vecMax;
};
CUtlVector<SnowFall_t> m_aSnow;
};
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CSnowFallManager::CSnowFallManager( void )
{
m_iSnowFallArea = SNOWFALL_NONE;
m_pSnowFallEmitter = NULL;
m_vecSnowFallEmitOrigin.Init();
m_flSnowRadius = 0.0f;
m_vecMin.Init( FLT_MAX, FLT_MAX, FLT_MAX );
m_vecMax.Init( FLT_MIN, FLT_MIN, FLT_MIN );
m_nActiveSnowCount = 0;
m_aSnow.Purge();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CSnowFallManager::~CSnowFallManager( void )
{
m_aSnow.Purge();
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CSnowFallManager::CreateEmitter( void )
{
return CreateSnowFallEmitter();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSnowFallManager::SpawnClientEntity( void )
{
m_tSnowFallParticleTimer.Init( 500 );
m_tSnowFallParticleTraceTimer.Init( 6 );
m_iSnowFallArea = SNOWFALL_NONE;
// Have the Snow Fall Manager think for all the snow fall entities.
SetNextClientThink( CLIENT_THINK_ALWAYS );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CSnowFallManager::CreateSnowFallEmitter( void )
{
if ( ( m_pSnowFallEmitter = SnowFallEffect::Create( "snowfall" ) ) == NULL )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSnowFallManager::ClientThink( void )
{
if ( !r_SnowEnable.GetBool() )
return;
// Make sure we have a snow fall emitter.
if ( !m_pSnowFallEmitter )
{
if ( !CreateSnowFallEmitter() )
return;
}
CreateSnowFall();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pSnowEntity -
//-----------------------------------------------------------------------------
void CSnowFallManager::AddSnowFallEntity( CClient_Precipitation *pSnowEntity )
{
if ( !pSnowEntity )
return;
int nSnowCount = m_aSnow.Count();
int iSnow = 0;
for ( iSnow = 0; iSnow < nSnowCount; ++iSnow )
{
if ( m_aSnow[iSnow].m_pEntity == pSnowEntity )
break;
}
if ( iSnow != nSnowCount )
return;
iSnow = m_aSnow.AddToTail();
m_aSnow[iSnow].m_pEntity = pSnowEntity;
m_aSnow[iSnow].m_pEffect = SnowFallEffect::Create( "snowfall" );
m_aSnow[iSnow].m_hMaterial = ParticleMgr()->GetPMaterial( "particle/snow" );
VectorCopy( pSnowEntity->WorldAlignMins(), m_aSnow[iSnow].m_vecMin );
VectorCopy( pSnowEntity->WorldAlignMaxs(), m_aSnow[iSnow].m_vecMax );
UpdateBounds( m_aSnow[iSnow].m_vecMin, m_aSnow[iSnow].m_vecMax );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSnowFallManager::UpdateBounds( const Vector &vecSnowMin, const Vector &vecSnowMax )
{
int iAxis = 0;
for ( iAxis = 0; iAxis < 3; ++iAxis )
{
if ( vecSnowMin[iAxis] < m_vecMin[iAxis] )
{
m_vecMin[iAxis] = vecSnowMin[iAxis];
}
if ( vecSnowMax[iAxis] > m_vecMax[iAxis] )
{
m_vecMax[iAxis] = vecSnowMax[iAxis];
}
}
Assert( m_pSnowFallEmitter );
m_pSnowFallEmitter->SetBounds( m_vecMin, m_vecMax );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &vecPoint -
// Output : int
//-----------------------------------------------------------------------------
int CSnowFallManager::StandingInSnowVolume( Vector &vecPoint )
{
trace_t traceSnow;
int nSnowCount = m_aSnow.Count();
int iSnow = 0;
for ( iSnow = 0; iSnow < nSnowCount; ++iSnow )
{
UTIL_TraceModel( vecPoint, vecPoint, vec3_origin, vec3_origin, static_cast<C_BaseEntity*>( m_aSnow[iSnow].m_pEntity ), COLLISION_GROUP_NONE, &traceSnow );
if ( traceSnow.startsolid )
return iSnow;
}
return -1;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &vecCenter -
// flRadius -
//-----------------------------------------------------------------------------
void CSnowFallManager::FindSnowVolumes( Vector &vecCenter, float flRadius, Vector &vecEyePos, Vector &vecForward )
{
// Reset.
m_nActiveSnowCount = 0;
m_bRayParticles = false;
int nSnowCount = m_aSnow.Count();
int iSnow = 0;
for ( iSnow = 0; iSnow < nSnowCount; ++iSnow )
{
// Check to see if the volume is in the PVS.
bool bInPVS = g_pClientLeafSystem->IsRenderableInPVS( m_aSnow[iSnow].m_pEntity->GetClientRenderable() );
if ( !bInPVS )
continue;
// Check to see if a snow volume is inside the given radius.
if ( IsBoxIntersectingSphere( m_aSnow[iSnow].m_vecMin, m_aSnow[iSnow].m_vecMax, vecCenter, flRadius ) )
{
m_aActiveSnow[m_nActiveSnowCount] = iSnow;
++m_nActiveSnowCount;
if ( m_nActiveSnowCount >= MAX_SNOW_LIST )
{
DevWarning( 1, "Max Active Snow Volume Count!\n" );
break;
}
}
// Check to see if a snow volume is outside of the sphere radius, but is along line-of-sight.
else
{
CBaseTrace trace;
Vector vecNewForward;
vecNewForward = vecForward * r_SnowRayLength.GetFloat();
vecNewForward.z = 0.0f;
IntersectRayWithBox( vecEyePos, vecNewForward, m_aSnow[iSnow].m_vecMin, m_aSnow[iSnow].m_vecMax, 0.325f, &trace );
if ( trace.fraction < 1.0f )
{
m_aActiveSnow[m_nActiveSnowCount] = iSnow;
++m_nActiveSnowCount;
if ( m_nActiveSnowCount >= MAX_SNOW_LIST )
{
DevWarning( 1, "Max Active Snow Volume Count!\n" );
break;
}
m_bRayParticles = true;
}
}
}
// Debugging code!
#ifdef _DEBUG
if ( r_SnowDebugBox.GetFloat() != 0.0f )
{
for ( iSnow = 0; iSnow < m_nActiveSnowCount; ++iSnow )
{
Vector vecCenter, vecMin, vecMax;
vecCenter = ( m_aSnow[iSnow].m_vecMin, m_aSnow[iSnow].m_vecMax ) * 0.5;
vecMin = m_aSnow[iSnow].m_vecMin - vecCenter;
vecMax = m_aSnow[iSnow].m_vecMax - vecCenter;
debugoverlay->AddBoxOverlay( vecCenter, vecMin, vecMax, QAngle( 0, 0, 0 ), 200, 0, 0, 25, r_SnowDebugBox.GetFloat() );
}
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSnowFallManager::CreateSnowFall( void )
{
#if 1
VPROF_BUDGET( "SnowFall", VPROF_BUDGETGROUP_PARTICLE_RENDERING );
#endif
// Check to see if we have a local player before starting the snow around a local player.
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( pPlayer == NULL )
return;
// Get the current frame time.
float flCurrentTime = gpGlobals->frametime;
// Get the players data to determine where the snow emitter should reside.
VectorCopy( pPlayer->EyePosition(), m_vecSnowFallEmitOrigin );
Vector vecForward;
pPlayer->GetVectors( &vecForward, NULL, NULL );
vecForward.z = 0.0f;
Vector vecVelocity = pPlayer->GetAbsVelocity();
float flSpeed = VectorNormalize( vecVelocity );
m_vecSnowFallEmitOrigin += ( vecForward * ( 64.0f + ( flSpeed * 0.4f * r_SnowPosScale.GetFloat() ) ) );
m_vecSnowFallEmitOrigin += ( vecVelocity * ( flSpeed * 1.25f * r_SnowSpeedScale.GetFloat() ) );
// Check to see if the player is zoomed.
bool bZoomed = ( pPlayer->GetFOV() != pPlayer->GetDefaultFOV() );
float flZoomScale = 1.0f;
if ( bZoomed )
{
flZoomScale = pPlayer->GetDefaultFOV() / pPlayer->GetFOV();
flZoomScale *= 0.5f;
}
// Time to test for a snow volume yet? (Only do this 6 times a second!)
if ( m_tSnowFallParticleTraceTimer.NextEvent( flCurrentTime ) )
{
// Reset the active snow emitter.
m_iSnowFallArea = SNOWFALL_NONE;
// Set the trace start and the emit origin.
Vector vecTraceStart;
VectorCopy( pPlayer->EyePosition(), vecTraceStart );
int iSnowVolume = StandingInSnowVolume( vecTraceStart );
if ( iSnowVolume != -1 )
{
m_flSnowRadius = r_SnowInsideRadius.GetFloat() + ( flSpeed * 0.5f );
m_iSnowFallArea = SNOWFALL_AROUND_PLAYER;
}
else
{
m_flSnowRadius = r_SnowOutsideRadius.GetFloat();
}
float flRadius = m_flSnowRadius;
if ( bZoomed )
{
if ( m_iSnowFallArea == SNOWFALL_AROUND_PLAYER )
{
flRadius = r_SnowOutsideRadius.GetFloat() * flZoomScale;
}
else
{
flRadius *= flZoomScale;
}
}
FindSnowVolumes( m_vecSnowFallEmitOrigin, flRadius, pPlayer->EyePosition(), vecForward );
if ( m_nActiveSnowCount != 0 && m_iSnowFallArea != SNOWFALL_AROUND_PLAYER )
{
// We found an active snow emitter.
m_iSnowFallArea = SNOWFALL_IN_ENTITY;
}
}
if ( m_iSnowFallArea == SNOWFALL_NONE )
return;
// Set the origin in the snow emitter.
m_pSnowFallEmitter->SetSortOrigin( m_vecSnowFallEmitOrigin );
// Create snow fall particles.
CreateSnowFallParticles( flCurrentTime, m_flSnowRadius, pPlayer->EyePosition(), vecForward, flZoomScale );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : flCurrentTime -
// flRadius -
// &vecEyePos -
// &vecForward -
// flZoomScale -
//-----------------------------------------------------------------------------
void CSnowFallManager::CreateSnowFallParticles( float flCurrentTime, float flRadius, const Vector &vecEyePos, const Vector &vecForward, float flZoomScale )
{
// Outside of a snow volume.
if ( m_iSnowFallArea == SNOWFALL_IN_ENTITY )
{
CreateOutsideVolumeSnowParticles( flCurrentTime, flRadius, flZoomScale );
}
// Inside of a snow volume.
else
{
CreateInsideVolumeSnowParticles( flCurrentTime, flRadius, vecEyePos, vecForward, flZoomScale );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : flCurrentTime -
// flRadius -
// flZoomScale -
//-----------------------------------------------------------------------------
void CSnowFallManager::CreateOutsideVolumeSnowParticles( float flCurrentTime, float flRadius, float flZoomScale )
{
Vector vecParticleSpawn;
// Outside of a snow volume.
int iSnow = 0;
float flRadiusScaled = flRadius * flZoomScale;
float flRadius2 = flRadiusScaled * flRadiusScaled;
// Add as many particles as we need
while ( m_tSnowFallParticleTimer.NextEvent( flCurrentTime ) )
{
// Check for a max particle count.
if ( m_pSnowFallEmitter->GetParticleCount() >= r_SnowParticles.GetInt() )
continue;
vecParticleSpawn.x = RandomFloat( m_aSnow[m_aActiveSnow[iSnow]].m_vecMin.x, m_aSnow[m_aActiveSnow[iSnow]].m_vecMax.x );
vecParticleSpawn.y = RandomFloat( m_aSnow[m_aActiveSnow[iSnow]].m_vecMin.y, m_aSnow[m_aActiveSnow[iSnow]].m_vecMax.y );
vecParticleSpawn.z = RandomFloat( m_aSnow[m_aActiveSnow[iSnow]].m_vecMin.z, m_aSnow[m_aActiveSnow[iSnow]].m_vecMax.z );
float flDistance2 = ( m_vecSnowFallEmitOrigin - vecParticleSpawn ).LengthSqr();
if ( flDistance2 < flRadius2 )
{
CreateSnowFallParticle( vecParticleSpawn, m_aActiveSnow[iSnow] );
}
iSnow = ( iSnow + 1 ) % m_nActiveSnowCount;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : flCurrentTime -
// flRadius -
// &vecEyePos -
// &vecForward -
// flZoomScale -
//-----------------------------------------------------------------------------
void CSnowFallManager::CreateInsideVolumeSnowParticles( float flCurrentTime, float flRadius, const Vector &vecEyePos, const Vector &vecForward, float flZoomScale )
{
Vector vecParticleSpawn;
// Check/Setup for zoom.
bool bZoomed = ( flZoomScale > 1.0f );
float flZoomRadius = 0.0f;
Vector vecZoomEmitOrigin;
if ( bZoomed )
{
vecZoomEmitOrigin = m_vecSnowFallEmitOrigin + ( vecForward * ( r_SnowZoomOffset.GetFloat() * flZoomScale ) );
flZoomRadius = flRadius * flZoomScale;
}
int iIndex = 0;
// Add as many particles as we need
while ( m_tSnowFallParticleTimer.NextEvent( flCurrentTime ) )
{
// Check for a max particle count.
if ( m_pSnowFallEmitter->GetParticleCount() >= r_SnowParticles.GetInt() )
continue;
// Create particle inside of sphere.
if ( iIndex > 0 )
{
CreateSnowParticlesSphere( flZoomRadius );
CreateSnowParticlesRay( flZoomRadius, vecEyePos, vecForward );
}
else
{
CreateSnowParticlesSphere( flRadius );
CreateSnowParticlesRay( flRadius, vecEyePos, vecForward );
}
// Increment if zoomed.
if ( bZoomed )
{
iIndex = ( iIndex + 1 ) % 3;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : flRadius -
//-----------------------------------------------------------------------------
void CSnowFallManager::CreateSnowParticlesSphere( float flRadius )
{
Vector vecParticleSpawn;
vecParticleSpawn.x = m_vecSnowFallEmitOrigin.x + RandomFloat( -flRadius, flRadius );
vecParticleSpawn.y = m_vecSnowFallEmitOrigin.y + RandomFloat( -flRadius, flRadius );
vecParticleSpawn.z = m_vecSnowFallEmitOrigin.z + RandomFloat( -flRadius, flRadius );
int iSnow = 0;
for ( iSnow = 0; iSnow < m_nActiveSnowCount; ++iSnow )
{
if ( ( vecParticleSpawn.x < m_aSnow[m_aActiveSnow[iSnow]].m_vecMin.x ) || ( vecParticleSpawn.x > m_aSnow[m_aActiveSnow[iSnow]].m_vecMax.x ) )
continue;
if ( ( vecParticleSpawn.y < m_aSnow[m_aActiveSnow[iSnow]].m_vecMin.y ) || ( vecParticleSpawn.y > m_aSnow[m_aActiveSnow[iSnow]].m_vecMax.y ) )
continue;
if ( ( vecParticleSpawn.z < m_aSnow[m_aActiveSnow[iSnow]].m_vecMin.z ) || ( vecParticleSpawn.z > m_aSnow[m_aActiveSnow[iSnow]].m_vecMax.z ) )
continue;
break;
}
if ( iSnow == m_nActiveSnowCount )
return;
CreateSnowFallParticle( vecParticleSpawn, m_aActiveSnow[iSnow] );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &vecEyePos -
// &vecForward -
//-----------------------------------------------------------------------------
void CSnowFallManager::CreateSnowParticlesRay( float flRadius, const Vector &vecEyePos, const Vector &vecForward )
{
// Check to see if we should create particles along line-of-sight.
if ( !m_bRayParticles && r_SnowRayEnable.GetBool() )
return;
Vector vecParticleSpawn;
// Create a particle down the player's view beyond the radius.
float flRayRadius = r_SnowRayRadius.GetFloat();
Vector vecNewForward;
vecNewForward = vecForward * RandomFloat( flRadius, r_SnowRayLength.GetFloat() );
vecParticleSpawn.x = vecEyePos.x + vecNewForward.x;
vecParticleSpawn.y = vecEyePos.y + vecNewForward.y;
vecParticleSpawn.z = vecEyePos.z + RandomFloat( 72, flRayRadius );
vecParticleSpawn.x += RandomFloat( -flRayRadius, flRayRadius );
vecParticleSpawn.y += RandomFloat( -flRayRadius, flRayRadius );
int iSnow = 0;
for ( iSnow = 0; iSnow < m_nActiveSnowCount; ++iSnow )
{
if ( ( vecParticleSpawn.x < m_aSnow[m_aActiveSnow[iSnow]].m_vecMin.x ) || ( vecParticleSpawn.x > m_aSnow[m_aActiveSnow[iSnow]].m_vecMax.x ) )
continue;
if ( ( vecParticleSpawn.y < m_aSnow[m_aActiveSnow[iSnow]].m_vecMin.y ) || ( vecParticleSpawn.y > m_aSnow[m_aActiveSnow[iSnow]].m_vecMax.y ) )
continue;
if ( ( vecParticleSpawn.z < m_aSnow[m_aActiveSnow[iSnow]].m_vecMin.z ) || ( vecParticleSpawn.z > m_aSnow[m_aActiveSnow[iSnow]].m_vecMax.z ) )
continue;
break;
}
if ( iSnow == m_nActiveSnowCount )
return;
CreateSnowFallParticle( vecParticleSpawn, m_aActiveSnow[iSnow] );
}
void CSnowFallManager::CreateSnowFallParticle( const Vector &vecParticleSpawn, int iSnow )
{
SimpleParticle *pParticle = ( SimpleParticle* )m_pSnowFallEmitter->AddParticle( sizeof( SimpleParticle ), m_aSnow[iSnow].m_hMaterial, vecParticleSpawn );
if ( pParticle == NULL )
return;
pParticle->m_flLifetime = 0.0f;
pParticle->m_vecVelocity = Vector( RandomFloat( -5.0f, 5.0f ), RandomFloat( -5.0f, 5.0f ), ( RandomFloat( -25, -35 ) * r_SnowFallSpeed.GetFloat() ) );
pParticle->m_flDieTime = fabs( ( vecParticleSpawn.z - m_aSnow[iSnow].m_vecMin.z ) / ( pParticle->m_vecVelocity.z - 0.1 ) );
// Probably want to put the color in the snow entity.
// pParticle->m_uchColor[0] = 150;//color;
// pParticle->m_uchColor[1] = 175;//color;
// pParticle->m_uchColor[2] = 200;//color;
pParticle->m_uchColor[0] = r_SnowColorRed.GetInt();
pParticle->m_uchColor[1] = r_SnowColorGreen.GetInt();
pParticle->m_uchColor[2] = r_SnowColorBlue.GetInt();
pParticle->m_uchStartSize = r_SnowStartSize.GetInt();
pParticle->m_uchEndSize = r_SnowEndSize.GetInt();
// pParticle->m_uchStartAlpha = 255;
pParticle->m_uchStartAlpha = r_SnowStartAlpha.GetInt();
pParticle->m_uchEndAlpha = r_SnowEndAlpha.GetInt();
pParticle->m_flRoll = random->RandomInt( 0, 360 );
pParticle->m_flRollDelta = random->RandomFloat( -0.15f, 0.15f );
pParticle->m_iFlags = SIMPLE_PARTICLE_FLAG_WINDBLOWN;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool SnowFallManagerCreate( CClient_Precipitation *pSnowEntity )
{
if ( !s_pSnowFallMgr )
{
s_pSnowFallMgr = new CSnowFallManager();
s_pSnowFallMgr->CreateEmitter();
s_pSnowFallMgr->InitializeAsClientEntity( NULL, RENDER_GROUP_OTHER );
if ( !s_pSnowFallMgr )
return false;
}
s_pSnowFallMgr->AddSnowFallEntity( pSnowEntity );
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void SnowFallManagerDestroy( void )
{
if ( s_pSnowFallMgr )
{
delete s_pSnowFallMgr;
s_pSnowFallMgr = NULL;
}
}
|
[
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
] |
[
[
[
1,
2260
]
]
] |
ccc498968dddbe2a36e67d9615b622f0203f171d
|
f13f46fbe8535a7573d0f399449c230a35cd2014
|
/JelloMan/DeferredPreEffect.h
|
7d3db02703667594b31317701eb828a250cfd51e
|
[] |
no_license
|
fangsunjian/jello-man
|
354f1c86edc2af55045d8d2bcb58d9cf9b26c68a
|
148170a4834a77a9e1549ad3bb746cb03470df8f
|
refs/heads/master
| 2020-12-24T16:42:11.511756 | 2011-06-14T10:16:51 | 2011-06-14T10:16:51 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 993 |
h
|
#pragma once
#include "Effect.h"
#include "Matrix.h"
#include "Texture2D.h"
class DeferredPreEffect : public Effect
{
public:
DeferredPreEffect(ID3D10Device* pDXDevice, ID3D10Effect* pEffect);
virtual ~DeferredPreEffect(void);
void SetWorld(const Matrix& world);
void SetWorldViewProjection(const Matrix& wvp);
void SetDiffuseMap(Texture2D* diffuseMap);
void SetSpecMap(Texture2D* specMap);
void SetGlossMap(Texture2D* glossMap);
void Selected(bool selected);
virtual ID3D10InputLayout* GetInputLayout() const;
virtual UINT GetVertexStride() const;
private:
ID3D10EffectMatrixVariable* m_pWorld;
ID3D10EffectMatrixVariable* m_pWVP;
ID3D10EffectShaderResourceVariable* m_pDiffuseMap;
ID3D10EffectShaderResourceVariable* m_pSpecMap;
ID3D10EffectShaderResourceVariable* m_pGlossMap;
ID3D10EffectScalarVariable* m_bSelected;
ID3D10InputLayout* m_pInputLayout;
UINT m_VertexStride;
};
|
[
"bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6",
"[email protected]"
] |
[
[
[
1,
18
],
[
20,
22
],
[
24,
30
],
[
32,
35
]
],
[
[
19,
19
],
[
23,
23
],
[
31,
31
]
]
] |
0962929eba3afd10a4782d45cc8fd17b69d4d1a0
|
5ac13fa1746046451f1989b5b8734f40d6445322
|
/minimangalore/Nebula2/code/nebula2/src/gui/nguiscenecontrolwindow_main.cc
|
1072c9ddcc786663539ec8bcc29192fdfe76bc21
|
[] |
no_license
|
moltenguy1/minimangalore
|
9f2edf7901e7392490cc22486a7cf13c1790008d
|
4d849672a6f25d8e441245d374b6bde4b59cbd48
|
refs/heads/master
| 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 9,205 |
cc
|
//------------------------------------------------------------------------------
// nguiscenecontrolwindow_main.cc
// (C) 2004 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "gui/nguiscenecontrolwindow.h"
#include "gui/nguihorislidergroup.h"
#include "gui/nguicolorslidergroup.h"
#include "scene/ntransformnode.h"
#include "scene/nlightnode.h"
nNebulaClass(nGuiSceneControlWindow, "nguiclientwindow");
//------------------------------------------------------------------------------
/**
*/
nGuiSceneControlWindow::nGuiSceneControlWindow():
diffuseColor(1.0f,1.0f,1.0f,1.0f),
specularColor(1.0f,1.0f,1.0f,1.0f),
ambientColor(1.0f,1.0f,1.0f,1.0f),
lightPath("/usr/scene/default/stdlight/l"),
lightTransformPath("/usr/scene/default/stdlight"),
refLightTransform("/usr/scene/default/stdlight"),
refLight("/usr/scene/default/stdlight/l")
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nGuiSceneControlWindow::~nGuiSceneControlWindow()
{
// make sure everything gets cleared
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiSceneControlWindow::OnShow()
{
// call parent class
nGuiClientWindow::OnShow();
// get client area form layout object
nGuiFormLayout* layout = this->refFormLayout;
kernelServer->PushCwd(layout);
// read current light values
if (this->refLight.isvalid())
{
// look up the current Light Colors and update Brightness Sliders
this->diffuseColor = this->refLight->GetVector(nShaderState::LightDiffuse);
this->specularColor = this->refLight->GetVector(nShaderState::LightSpecular);
this->ambientColor = this->refLight->GetVector(nShaderState::LightAmbient);
}
if (this->refLightTransform.isvalid())
{
this->lightAngles = this->refLightTransform->GetEuler();
}
// sliders and color labels ...
const float leftWidth = 0.3f;
const float rightWidth = 0.15f;
const float maxAngle = 360;
const float minHeight = -90;
const float maxHeight = 90;
const float border = 0.005f;
const float knobSize = 45.0f;
nGuiHoriSliderGroup* slider;
slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "LightHori");
slider->SetLeftText("Light Hori");
slider->SetRightText("%d");
slider->SetMinValue(0.0f);
slider->SetMaxValue(maxAngle);
slider->SetValue(n_rad2deg(this->lightAngles.y));
slider->SetKnobSize(36);
slider->SetIncrement(1.0f);
slider->SetLeftWidth(leftWidth);
slider->SetRightWidth(rightWidth);
layout->AttachForm(slider, nGuiFormLayout::Top, border);
layout->AttachForm(slider, nGuiFormLayout::Left, border);
layout->AttachForm(slider, nGuiFormLayout::Right, border);
slider->OnShow();
this->refLightDirection = slider;
slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "LightVert");
slider->SetLeftText("Light Vert");
slider->SetRightText("%d");
slider->SetMinValue(minHeight);
slider->SetMaxValue(maxHeight);
slider->SetValue(n_rad2deg(this->lightAngles.x));
slider->SetKnobSize(20);
slider->SetIncrement(1.0f);
slider->SetLeftWidth(leftWidth);
slider->SetRightWidth(rightWidth);
layout->AttachWidget(slider, nGuiFormLayout::Top, this->refLightDirection, border);
layout->AttachForm(slider, nGuiFormLayout::Left, border);
layout->AttachForm(slider, nGuiFormLayout::Right, border);
slider->OnShow();
this->refLightHeight = slider;
nGuiColorSliderGroup* colorSlider;
colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "Diffuse");
colorSlider->SetLabelText("Diffuse");
colorSlider->SetMaxIntensity(10.0f);
colorSlider->SetTextLabelWidth(leftWidth);
colorSlider->SetColor(this->diffuseColor);
layout->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refLightHeight, border);
layout->AttachForm(colorSlider, nGuiFormLayout::Left, border);
layout->AttachForm(colorSlider, nGuiFormLayout::Right, border);
colorSlider->OnShow();
this->refDiffuseSlider = colorSlider;
colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "Specular");
colorSlider->SetLabelText("Specular");
colorSlider->SetMaxIntensity(10.0f);
colorSlider->SetTextLabelWidth(leftWidth);
colorSlider->SetColor(this->specularColor);
layout->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refDiffuseSlider, border);
layout->AttachForm(colorSlider, nGuiFormLayout::Left, border);
layout->AttachForm(colorSlider, nGuiFormLayout::Right, border);
colorSlider->OnShow();
this->refSpecularSlider = colorSlider;
colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "Ambient");
colorSlider->SetLabelText("Ambient");
colorSlider->SetMaxIntensity(10.0f);
colorSlider->SetTextLabelWidth(leftWidth);
colorSlider->SetColor(this->ambientColor);
layout->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refSpecularSlider, border);
layout->AttachForm(colorSlider, nGuiFormLayout::Left, border);
layout->AttachForm(colorSlider, nGuiFormLayout::Right, border);
colorSlider->OnShow();
this->refAmbientSlider = colorSlider;
// Create SkyEditor
//nGuiSkyEditor* skyEditor = (nGuiSkyEditor*) kernelServer->New("nguiskyeditor","SkyEditor");
//layout->AttachWidget(skyEditor, nGuiFormLayout::Top, this->refAmbientSlider, 2*border);
//layout->AttachForm(skyEditor, nGuiFormLayout::Left, border);
//layout->AttachForm(skyEditor, nGuiFormLayout::Right, border);
//skyEditor->OnShow();
//this->refSkyEditor = skyEditor;
//if (this->refSkyEditor->SkyLoad())
//{
// windowRect = rectangle(vector2(0.0f, 0.0f), vector2(0.4f, 0.8f));
//}
this->kernelServer->PopCwd();
// set new window rect
this->SetTitle("Scene Control");
rectangle windowRect(vector2(0.0f, 0.0f), vector2(0.4f, 0.3f));
this->SetRect(windowRect);
// update all layouts
this->UpdateLayout(this->rect);
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiSceneControlWindow::OnHide()
{
this->refLightDirection->Release();
this->refLightHeight->Release();
this->refDiffuseSlider->Release();
this->refSpecularSlider->Release();
this->refAmbientSlider->Release();
//if (this->refSkyEditor.isvalid())
//{
// this->refSkyEditor->Release();
//}
nGuiClientWindow::OnHide();
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiSceneControlWindow::OnEvent(const nGuiEvent& event)
{
if (event.GetType() == nGuiEvent::SliderChanged)
{
// scene light menu
if (this->refLightDirection.isvalid() &&
this->refLightHeight.isvalid() &&
this->refDiffuseSlider.isvalid() &&
this->refSpecularSlider.isvalid() &&
this->refAmbientSlider.isvalid())
{
if (event.GetWidget() == this->refLightDirection || event.GetWidget() == this->refLightHeight)
{
this->UpdateLightPosition();
}
else if (event.GetWidget() == this->refDiffuseSlider)
{
this->diffuseColor = this->refDiffuseSlider->GetColor();
if (this->refLight.isvalid())
{
this->refLight->SetVector(nShaderState::LightDiffuse, this->diffuseColor);
}
}
else if (event.GetWidget() == this->refSpecularSlider)
{
this->specularColor = this->refSpecularSlider->GetColor();
if (this->refLight.isvalid())
{
this->refLight->SetVector(nShaderState::LightSpecular, this->specularColor);
}
}
else if (event.GetWidget() == this->refAmbientSlider)
{
this->ambientColor = this->refAmbientSlider->GetColor();
if (this->refLight.isvalid())
{
this->refLight->SetVector(nShaderState::LightAmbient, this->ambientColor);
}
}
}
}
//if (this->refSkyEditor.isvalid())
//{
// this->refSkyEditor->OnEvent(event);
//}
nGuiClientWindow::OnEvent(event);
}
//------------------------------------------------------------------------------
/**
Update Light Rotation and Height.
*/
void
nGuiSceneControlWindow::UpdateLightPosition()
{
if (this->refLightTransform.isvalid())
{
this->lightAngles = vector3(n_deg2rad(this->refLightHeight->GetValue()), n_deg2rad(this->refLightDirection->GetValue()), 0.0f);
this->refLightTransform->SetEuler(this->lightAngles);
}
}
|
[
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] |
[
[
[
1,
248
]
]
] |
bf399f8a98511ed0a47b44f200b74b3ecb2bf1ad
|
b7c505dcef43c0675fd89d428e45f3c2850b124f
|
/Util/alcommon/include/albrokermanager.h
|
62e12e2087bf773dbc67c7bbcd03812957a2db71
|
[
"BSD-2-Clause"
] |
permissive
|
pranet/bhuman2009fork
|
14e473bd6e5d30af9f1745311d689723bfc5cfdb
|
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
|
refs/heads/master
| 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,565 |
h
|
/**
* @author Aldebaran Robotics
* Aldebaran Robotics (c) 2007 All Rights Reserved - This file is confidential.\n
*
* Version : $Id$
*/
#ifndef AL_BROKERMANAGER_H
#define AL_BROKERMANAGER_H
#include "alsingleton.h"
#include "alptr.h"
#include "albroker.h"
#include "alerror.h"
#include <vector>
#include <string>
#include "almutex.h"
#include "alcriticalsectionread.h"
#include "alcriticalsectionwrite.h"
#define MAXBROKER 10
namespace AL
{
class ALBroker;
// should be only singleton with various main pointer
class ALBrokerManager : public ALSingleton<ALBrokerManager>
{
friend class ALSingleton<ALBrokerManager>;
protected:
ALBrokerManager();
public:
virtual ~ALBrokerManager();
/**
* addBroker
* add a broker in the map of broker
*/
void addBroker(ALPtr<ALBroker> pBroker);
/**
* remove a broker from the map of broker
* carrefull also shutdown the broker
*/
void removeBroker(ALPtr<ALBroker> pBroker);
/**
* remove a broker from the map of broker
* no shutdown of the broker
*/
void removeFromList(ALPtr<ALBroker> pBroker);
inline ALPtr<ALBroker> getRandomBroker(void)
{
ALCriticalSectionRead section(mutex);
if (fBrokerList.size()<=0)
throw ALERROR("ALBrokerManager", "getAnyBroker", "There is no current broker defined in BrokerManager.");
return (fBrokerList[0]);
}
/**
* get a broker from index
* no shutdown of the broker
*/
inline ALPtr<ALBroker> getBroker(int i)
{
ALCriticalSectionRead section(mutex);
AL_ASSERT(i<((int)(fBrokerList.size())));
return (fBrokerList[i]);
};
/**
* get a broker from endpoint
@param pModuleName name of the module no longer existing
*
*/
ALPtr<ALBroker> getBrokerByIPPort(const std::string &strEndPoint);
/**
* get a broker by ip and port
* @param ip of the broker
* @param port of the broker
*
*/
ALPtr<ALBroker> getBrokerByIPPort(const std::string &strIP, int pPort);
/**
* remove and shutdown all brokers (program should not work any more after that)
*
*/
void killAllBroker(void);
ALPtr<ALBroker> getReservedBroker(void);
private:
std::vector<ALPtr<ALBroker> >fBrokerList;
ALPtr<ALBroker> fBrokerReserved; // unique broker use for method that don't use broker in parameter
ALPtr<ALMutexRW> mutex;
};
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
114
]
]
] |
7a2f40d3a2038859d5234802fdd9485ca5f05cc6
|
0f8559dad8e89d112362f9770a4551149d4e738f
|
/Wall_Destruction/Havok/Source/Common/Base/Memory/Tracker/hkMemoryReporter.h
|
ab53ced3a430ac731b4045af93137341ada54d80
|
[] |
no_license
|
TheProjecter/olafurabertaymsc
|
9360ad4c988d921e55b8cef9b8dcf1959e92d814
|
456d4d87699342c5459534a7992f04669e75d2e1
|
refs/heads/master
| 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,012 |
h
|
/*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HKBASE_MEMORY_REPORTER_H
#define HKBASE_MEMORY_REPORTER_H
#include <Common/Base/Reflection/Rtti/hkCppRttiInfoUtil.h>
#include <Common/Base/Memory/Tracker/hkMemoryOwnershipCalculator.h>
class hkMemoryReporter
{
public:
HK_DECLARE_PLACEMENT_ALLOCATOR();
typedef hkMemoryOwnershipCalculator::Allocation Allocation;
typedef hkMemoryOwnershipCalculator::FilterFunction FilterFunction;
class VirtualType
{
virtual ~VirtualType() {}
};
struct MemorySize
{
MemorySize(hk_size_t size):m_size(size) {}
hk_size_t m_size;
};
struct Info
{
Info():
m_followFilter(HK_NULL),
m_startFilter(HK_NULL),
m_dumpRemaining(true)
{
}
FilterFunction m_followFilter; ///
FilterFunction m_startFilter; ///
hkBool m_dumpRemaining;
};
/// Report memory usage by time
static void HK_CALL reportTypeUsage(hkMemorySystem* system, hkMemoryOwnershipCalculator& calc, const Info& info, hkOstream& stream);
/// For printing memory sizes
friend hkOstream& HK_CALL operator<<(hkOstream& stream, const hkMemoryReporter::MemorySize& size);
/// Convert size into text
static void HK_CALL memorySizeToText(hk_size_t size, hkStringBuf& string);
protected:
struct TotalInfo
{
hk_size_t m_totalUsed;
hk_size_t m_totalAlloced;
hk_size_t m_totalShared;
};
static void HK_CALL _assignIndexOwnership(hkMemoryOwnershipCalculator& calc, hkArrayBase<const hkMemoryOwnershipCalculator::ClassInstance*>& instances);
static void HK_CALL _assignChildOwnership(hkMemoryOwnershipCalculator& calc, FilterFunction startFilter);
static void HK_CALL _assignOwnership(hkMemoryOwnershipCalculator& calc, FilterFunction startFilter, hkBool isVirtual);
};
#endif // HKBASE_MEMORY_TRACKER_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
|
[
"[email protected]"
] |
[
[
[
1,
91
]
]
] |
a3100fcfdea97a7fb8fcc6d2dc90d5679a5a439d
|
9a48be80edc7692df4918c0222a1640545384dbb
|
/Libraries/Boost1.40/libs/wave/test/testwave/testfiles/t_3_001.cpp
|
c85402ff1393a5171d248d195b6f8413bb878d80
|
[
"BSL-1.0"
] |
permissive
|
fcrick/RepSnapper
|
05e4fb1157f634acad575fffa2029f7f655b7940
|
a5809843f37b7162f19765e852b968648b33b694
|
refs/heads/master
| 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 764 |
cpp
|
/*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// Tests, if a diagnostic is emitted, if a predefined macro is to be undefined.
//R
//E t_3_001.cpp(14): warning: #undef may not be used on this predefined name: __cplusplus
#undef __cplusplus // should emit a warning
//H 10: t_3_001.cpp(14): #undef
//H 18: boost::wave::preprocess_exception
|
[
"metrix@Blended.(none)"
] |
[
[
[
1,
17
]
]
] |
30c1e2609d340fe7286ec71e239e205cb5f476fe
|
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
|
/CleanProject/luabind/version.hpp
|
93ef4a83fb0dbe465fa3a3e315cd7672e566920e
|
[] |
no_license
|
bahao247/apeengine2
|
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
|
f2617b2a42bdf2907c6d56e334c0d027fb62062d
|
refs/heads/master
| 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 529 |
hpp
|
// Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LUABIND_VERSION_090216_HPP
# define LUABIND_VERSION_090216_HPP
# define LUABIND_VERSION 801
// Each component uses two digits, so:
//
// major = LUABIND_VERSION / 10000
// minor = LUABIND_VERSION / 100 % 100
// patch = LUABIND_VERSION % 100
#endif // LUABIND_VERSION_090216_HPP
|
[
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
] |
[
[
[
1,
16
]
]
] |
c476cd03777a2e625cb87cd5be4289f0bcafd1df
|
777399eafeb952743fcb973fbba392842c2e9b14
|
/CyberneticWarrior/CyberneticWarrior/source/CEventSystem.h
|
f2569dd571a407592901b054d90aad7489e8c0b3
|
[] |
no_license
|
Warbeleth/cyberneticwarrior
|
7c0af33ada4d461b90dc843c6a25cd5dc2ba056a
|
21959c93d638b5bc8a881f75119d33d5708a3ea9
|
refs/heads/master
| 2021-01-10T14:31:27.017284 | 2010-11-23T23:16:28 | 2010-11-23T23:16:28 | 53,352,209 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,017 |
h
|
#ifndef EVENTSYSTEM_H_
#define EVENTSYSTEM_H_
#include "CEvent.h"
#include "IListener.h"
#include <map>
#include <list>
using std::list;
using std::multimap;
using std::pair;
class CEventSystem
{
private:
multimap<EVENTID, IListener*> m_Clients;
list<CEvent> m_lEvents;
void SendOutEvent(CEvent* pEvent);
bool AlreadyRegistered(EVENTID eventID, IListener* pClient);
inline CEventSystem() {};
CEventSystem(const CEventSystem&);
CEventSystem& operator=(const CEventSystem&);
inline ~CEventSystem() {};
static CEventSystem* sm_pEventSystemInstance;
public:
static CEventSystem* GetInstance(void);
static void DeleteInstance(void);
void RegisterClient(EVENTID eventID, IListener* pClient);
void UnregisterClient(EVENTID eventID, IListener* pClient);
void UnregisterAllClients(IListener* pClient);
void SendEvent(EVENTID eventID, void* pData);
void ProcessEvents(void);
void ClearEvents(void);
void ShutdownEventSystem(void);
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
51
]
]
] |
22497a0648dd7e0609c46bdaac42b510f76f4cd8
|
1960e1ee431d2cfd2f8ed5715a1112f665b258e3
|
/inc/com/sc/coatr.h
|
a1451c7c18acc4bc2bd6b0ff739672ff0666122e
|
[] |
no_license
|
BackupTheBerlios/bvr20983
|
c26a1379b0a62e1c09d1428525f3b4940d5bb1a7
|
b32e92c866c294637785862e0ff9c491705c62a5
|
refs/heads/master
| 2021-01-01T16:12:42.021350 | 2009-11-01T22:38:40 | 2009-11-01T22:38:40 | 39,518,214 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,539 |
h
|
/*
* $Id$
*
* Copyright (C) 2008 Dorothea Wachmann
*
* 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
#if !defined(COATR_H)
#define COATR_H
#include "sc/atr.h"
#include "com/codispatch.h"
#include "ibvr20983.h"
namespace bvr20983
{
namespace COM
{
class COATR : public CODispatch, public IATR
{
public:
// Main Object Constructor & Destructor.
COATR(IUnknown* pUnkOuter=NULL);
DECLARE_UNKNOWN
// IATR methods.
DECLARE_DISPATCH
STDMETHODIMP get_Raw(BSTR *pRaw);
STDMETHODIMP get_History(BSTR *pHistory);
STDMETHODIMP get_F(DWORD* pF);
STDMETHODIMP get_FMax(DWORD* pFMax);
STDMETHODIMP get_D(DWORD* pD);
void SetATR(const ATR& atr)
{ m_atr = atr; }
private:
ATR m_atr;
};
} // of namespace COM
} // of namespace bvr20983
#endif // COATR_H
|
[
"dwachmann@01137330-e44e-0410-aa50-acf51430b3d2"
] |
[
[
[
1,
54
]
]
] |
684be52315cce19e6fa296a4993bb68d02c516a0
|
6c8c4728e608a4badd88de181910a294be56953a
|
/UiModule/Inworld/ControlPanelManager.h
|
45d6539fc67544d960fcc90d7e72a0cf73d07c48
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
caocao/naali
|
29c544e121703221fe9c90b5c20b3480442875ef
|
67c5aa85fa357f7aae9869215f840af4b0e58897
|
refs/heads/master
| 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,810 |
h
|
// For conditions of distribution and use, see copyright notice in license.txt
#ifndef incl_UiModule_ControlPanelManager_h
#define incl_UiModule_ControlPanelManager_h
#include "UiModuleApi.h"
#include "UiDefines.h"
#include <QObject>
#include <QAction>
#include <QMap>
namespace UiServices
{
class UiAction;
}
namespace CoreUi
{
class AnchorLayoutManager;
class BackdropWidget;
class ControlPanelButton;
class SettingsWidget;
class UI_MODULE_API ControlPanelManager : public QObject
{
Q_OBJECT
public:
ControlPanelManager(QObject *parent, CoreUi::AnchorLayoutManager *layout_manager);
virtual ~ControlPanelManager();
public slots:
void SetHandler(UiDefines::ControlButtonType type, UiServices::UiAction *action);
ControlPanelButton *GetButtonForType(UiDefines::ControlButtonType type);
qreal GetContentHeight();
qreal GetContentWidth();
SettingsWidget *GetSettingsWidget() { return settings_widget_; }
private slots:
void CreateBasicControls();
void UpdateBackdrop();
void ControlButtonClicked(UiDefines::ControlButtonType type);
// Internal handling of settings widget
void ToggleSettingsVisibility(bool visible);
void CheckSettingsButtonStyle();
private:
AnchorLayoutManager *layout_manager_;
BackdropWidget *backdrop_widget_;
QList<ControlPanelButton *> control_buttons_;
QMap<UiDefines::ControlButtonType, ControlPanelButton *> backdrop_area_buttons_map_;
QMap<UiDefines::ControlButtonType, UiServices::UiAction *> action_map_;
// Contolled core widgets
SettingsWidget *settings_widget_;
};
}
#endif
|
[
"[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3"
] |
[
[
[
1,
69
]
]
] |
fd660ac39ff52b8a2a7555a2de39fb59888e4a8f
|
b08e948c33317a0a67487e497a9afbaf17b0fc4c
|
/LuaPlus/Src/LuaRemoteDebuggingServer/LuaNetworkServer.h
|
20f7da6816b7bbc36370d9246c1f12ca71d3a885
|
[
"MIT"
] |
permissive
|
15831944/bastionlandscape
|
e1acc932f6b5a452a3bd94471748b0436a96de5d
|
c8008384cf4e790400f9979b5818a5a3806bd1af
|
refs/heads/master
| 2023-03-16T03:28:55.813938 | 2010-05-21T15:00:07 | 2010-05-21T15:00:07 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,210 |
h
|
#pragma once
namespace LuaDebugger {
class LuaNetworkSocket;
class LuaNetworkServer
{
public:
template<typename T>
static void LuaPlus_ProcessCommand(const char* /*id*/, void* userData, const unsigned char* command)
{
lua_State* state = (lua_State*)userData;
if (*(unsigned short*)command == 0xfffe)
lua_dowstring(state, (const lua_WChar*)(command + 2), "Command");
else
lua_dostring(state, (const char*)command);
}
typedef void (*fnProcessCommand)(const char* id, void* userData, const unsigned char* command);
static LuaNetworkServer* CreateInstance();
static void DestroyInstance(LuaNetworkServer* server);
virtual bool Open( const char* serverInfoFileName, unsigned long serverPort = 5001 ) = 0;
virtual void Close() = 0;
virtual LuaNetworkSocket* GetSocket( const char* id ) = 0;
virtual void SendCommand( const char* id, const char* command ) = 0;
virtual void ProcessPackets() = 0;
virtual void RegisterID( const char* id, void* userData, fnProcessCommand processCommand ) = 0;
virtual void* GetIDUserData( const char* id ) = 0;
protected:
LuaNetworkServer() {};
virtual ~LuaNetworkServer() {};
};
} // namespace LuaDebugger
|
[
"voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329"
] |
[
[
[
1,
40
]
]
] |
bacafa2ae91c05891275a209a6d0ae45e08a8ab9
|
f177993b13e97f9fecfc0e751602153824dfef7e
|
/ImPro/ImProBaseClass/MSD3DLib/stdafx.cpp
|
85377a13c30f2fea1a6c22f2c955dfc7ae57fcc4
|
[] |
no_license
|
svn2github/imtophooksln
|
7bd7412947d6368ce394810f479ebab1557ef356
|
bacd7f29002135806d0f5047ae47cbad4c03f90e
|
refs/heads/master
| 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 295 |
cpp
|
// stdafx.cpp : source file that includes just the standard includes
// MSD3DLib.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
|
[
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
] |
[
[
[
1,
8
]
]
] |
0177decc60d5f5d57e742cb67068c31e63c430b8
|
fbe2cbeb947664ba278ba30ce713810676a2c412
|
/iptv_root/iptv_media_util/ASFDataPacket.h
|
ed6f2ad503f2fec8b95a9e8858a3a6f8d08fc6f9
|
[] |
no_license
|
abhipr1/multitv
|
0b3b863bfb61b83c30053b15688b070d4149ca0b
|
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
|
refs/heads/master
| 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 779 |
h
|
#ifndef ASF_DATA_PACKET_H
#define ASF_DATA_PACKET_H
#include "ASFObject.h"
#include "defs.h"
class ASFDataPacket : public ASFObject
{
struct PAYLOAD_INFO
{
BOOL bVideoKeyFrame;
DWORD dwSequence;
DWORD dwSendTime;
WORD wDuration;
WORD wPacketSize;
WORD wVideoStream;
};
public:
ASFDataPacket(DWORD dwSize, DWORD dwSeq = -1, WORD wVideoStream = 0);
virtual ~ASFDataPacket();
QWORD GetObjectSize() { return (QWORD) m_info.wPacketSize; }
DWORD GetPresentationTime() { return m_info.dwSendTime; }
BOOL HasKeyFrame() { return m_info.bVideoKeyFrame; }
// overriden from ASFObject
void Refresh();
private:
PAYLOAD_INFO m_info;
};
#endif
|
[
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
] |
[
[
[
1,
36
]
]
] |
dc16989c33413e6059ac2a1297dda59540c977fa
|
478570cde911b8e8e39046de62d3b5966b850384
|
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctesteikbctrl/src/bctesteikbctrlcontainer.cpp
|
b31ca1492a2a156a0bf797c3bc1f317c3476d455
|
[] |
no_license
|
SymbianSource/oss.FCL.sftools.ana.compatanamdw
|
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
|
1169475bbf82ebb763de36686d144336fcf9d93b
|
refs/heads/master
| 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,653 |
cpp
|
/*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: container
*
*/
#include "bctesteikbctrlcontainer.h"
#include "bctestmiscellcase.h"
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// C++ default Constructor
// ---------------------------------------------------------------------------
//
CBCTesteikbctrlContainer::CBCTesteikbctrlContainer()
{
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
//
CBCTesteikbctrlContainer::~CBCTesteikbctrlContainer()
{
ResetControl();
}
// ---------------------------------------------------------------------------
// Symbian 2nd Constructor
// ---------------------------------------------------------------------------
//
void CBCTesteikbctrlContainer::ConstructL( const TRect& aRect )
{
CreateWindowL();
SetRect( aRect );
ActivateL();
}
// ----------------------------------------------------------------------------
// CBCTesteikbctrlContainer::Draw
// Fills the window's rectangle.
// ----------------------------------------------------------------------------
//
void CBCTesteikbctrlContainer::Draw( const TRect& aRect ) const
{
CWindowGc& gc = SystemGc();
gc.SetPenStyle( CGraphicsContext::ENullPen );
gc.SetBrushColor( KRgbGray );
gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
gc.DrawRect( aRect );
}
// ---------------------------------------------------------------------------
// CBCTesteikbctrlContainer::CountComponentControls
// ---------------------------------------------------------------------------
//
TInt CBCTesteikbctrlContainer::CountComponentControls() const
{
if ( iControl )
{
return 1;
}
else
{
return 0;
}
}
// ---------------------------------------------------------------------------
// CBCTesteikbctrlContainer::ComponentControl
// ---------------------------------------------------------------------------
//
CCoeControl* CBCTesteikbctrlContainer::ComponentControl( TInt ) const
{
return iControl;
}
// ---------------------------------------------------------------------------
// CBCTesteikbctrlContainer::SetControl
// ---------------------------------------------------------------------------
void CBCTesteikbctrlContainer::SetControl( CCoeControl* aControl )
{
iControl = aControl;
if ( iControl )
{
// You can change the position and size
iControl->SetExtent( Rect().iTl, Rect().Size() );
iControl->ActivateL();
DrawNow();
}
}
// ---------------------------------------------------------------------------
// CBCTesteikbctrlContainer::ResetControl
// ---------------------------------------------------------------------------
//
void CBCTesteikbctrlContainer::ResetControl()
{
delete iControl;
iControl = NULL;
}
CWindowGc& CBCTesteikbctrlContainer::GetSystemGc()
{
return CCoeEnv::Static()->SystemGc();
}
|
[
"none@none"
] |
[
[
[
1,
123
]
]
] |
0b7111bddc2297333469e1dd07e4ff14ca7850b1
|
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
|
/core/slam_data_adapter_i.h
|
0260c5be83374fc0501216caefaaab0140fd1b97
|
[] |
no_license
|
chenbk85/alcordev
|
41154355a837ebd15db02ecaeaca6726e722892a
|
bdb9d0928c80315d24299000ca6d8c492808f1d5
|
refs/heads/master
| 2021-01-10T13:36:29.338077 | 2008-10-22T15:57:50 | 2008-10-22T15:57:50 | 44,953,286 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 921 |
h
|
#ifndef slam_data_adapter_i_H_INCLUDED
#define slam_data_adapter_i_H_INCLUDED
//---------------------------------------------------------------------------
#include "alcor/math/angle.h"
namespace all { namespace core {
//---------------------------------------------------------------------------
///slam_data_adapter_i.
class slam_data_adapter_i
{
public:
///Localized rotation angle in degrees.
virtual double get_current_rot(math::deg_t) = 0;
///Localized rotation angle in radians.
virtual double get_current_rot(math::rad_t) = 0;
///
virtual double get_current_x(){return 0;};
virtual double get_current_y(){return 0;};
virtual double get_current_z(){return 0;};
};
//---------------------------------------------------------------------------
}}//namespaces
//---------------------------------------------------------------------------
#endif //slam_data_adapter_i_H_INCLUDED
|
[
"andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81"
] |
[
[
[
1,
23
]
]
] |
0e2abb758cf98866ee0e0d123b11d22ffad11c2d
|
2f72d621e6ec03b9ea243a96e8dd947a952da087
|
/lol4edit/gui/PSSelectDialog.cpp
|
b1ffef7b5fafb9b954336f9057710703d8a11c6e
|
[] |
no_license
|
gspu/lol4fg
|
752358c3c3431026ed025e8cb8777e4807eed7a0
|
12a08f3ef1126ce679ea05293fe35525065ab253
|
refs/heads/master
| 2023-04-30T05:32:03.826238 | 2011-07-23T23:35:14 | 2011-07-23T23:35:14 | 364,193,504 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 709 |
cpp
|
#include "PSSelectDialog.h"
#include "h/SelectDialog.h"
#include <QtGui/QLineEdit>
#include "Ogre.h"
int PSSelectDialog::exec(QLineEdit *target)
{
this->target = target;
return QDialog::exec();
}
void PSSelectDialog::acceptSelection(QListWidgetItem *item)
{
if(!item)
return;
target->setText(item->text());
}
void PSSelectDialog::fillList()
{
ui->listWidget->clear();
Ogre::ParticleSystemManager::ParticleSystemTemplateIterator psitr = Ogre::ParticleSystemManager::getSingletonPtr()->getTemplateIterator();
while(psitr.hasMoreElements())
{
QString name = psitr.peekNextValue()->getName().c_str();
ui->listWidget->addItem(name);
psitr.moveNext();
}
}
|
[
"praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac"
] |
[
[
[
1,
31
]
]
] |
f2c5f449109b8df65826bd1ece99dd7da563e00c
|
cd387cba6088f351af4869c02b2cabbb678be6ae
|
/lib/geometry/concepts/point_concept.hpp
|
5efdeed208b76d307fbaaa7ec9507e2a5ca0218e
|
[
"BSL-1.0"
] |
permissive
|
pedromartins/mew-dev
|
e8a9cd10f73fbc9c0c7b5bacddd0e7453edd097e
|
e6384775b00f76ab13eb046509da21d7f395909b
|
refs/heads/master
| 2016-09-06T14:57:00.937033 | 2009-04-13T15:16:15 | 2009-04-13T15:16:15 | 32,332,332 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,122 |
hpp
|
// Geometry Library Point concept
//
// Copyright Bruno Lalande 2008
// Copyright Barend Gehrels, Geodan Holding B.V. Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef _GEOMETRY_POINT_CONCEPT_HPP
#define _GEOMETRY_POINT_CONCEPT_HPP
#include <boost/concept_check.hpp>
#include <geometry/concepts/coordinate.hpp>
#include <geometry/concepts/dimension.hpp>
#include <geometry/concepts/access.hpp>
/*!
\defgroup Concepts Concepts: concept definitions
Concepts are used to check if pointtypes provide required implementation. Concept checking
is done using BCCL (Boost Concept Check Library) and MPL (Meta Programming Library)
*/
namespace geometry
{
/*!
\brief Defines point concept, using Boost Concept Check Library and metafunctions
\ingroup Concepts
\details The concept is separated into 3 metafunctions:
- \ref geometry::traits::coordinate "coordinate": provides the type of the coordinates of a point
- \ref geometry::traits::dimension "dimension": provides the number of coordinates of a point
- \ref geometry::traits::access "access": provides access to the coordinates of a point
In MPL, a metafunction that provides a type must expose is as "type"
and a metafunction that provides a value must expose it as "value", so
here the same convention are used: coordinate<P>::type and
dimension<P>::value provide the type and number of coordinates. This
makes them compatible with any MPL and Fusion algorithm and
metafunction.
\par Example:
First example, using an own pointtype, for example a legacy point, defining the necessary
properties outside the pointtype in a traits class
\dontinclude doxygen_examples.cpp
\skip example_point_1
\until //:\\
\par Example:
Second example, deriving a pointtype from boost::tuple. It defines the necessary properties
itself, so a separate traits class is not necessary.
\dontinclude doxygen_examples.cpp
\skip example_own_point2
\line {
\until //:\\
*/
template <typename X>
struct Point
{
private :
typedef typename support::coordinate<X>::type ctype;
enum { ccount = support::dimension<X>::value };
/// Internal structure to check if access is OK for all dimensions
template <typename P, int I, int Count>
struct dimension_checker
{
static void check()
{
P* p;
geometry::get<I>(*p) = ctype();
dimension_checker<P, I+1, Count>::check();
}
};
/// Internal structure to check if access is OK for all dimensions
template <typename P, int Count>
struct dimension_checker<P, Count, Count>
{
static void check() {}
};
public :
/// BCCL macro to check the Point concept
BOOST_CONCEPT_USAGE(Point)
{
dimension_checker<X, 0, ccount>::check();
}
};
/*!
\brief Defines Point concept (const version)
\ingroup Concepts
\details The ConstPoint concept check the same as the Point concept,
but does not check write access.
*/
template <typename X>
struct ConstPoint
{
private :
typedef typename support::coordinate<X>::type ctype;
enum { ccount = support::dimension<X>::value };
/// Internal structure to check if access is OK for all dimensions
template <typename P, int I, int Count>
struct dimension_checker
{
static void check()
{
const P* p = 0;
ctype coord(geometry::get<I>(*p));
(void)sizeof(coord); // To avoid "unused variable" warnings
dimension_checker<P, I+1, Count>::check();
}
};
/// Internal structure to check if access is OK for all dimensions
template <typename P, int Count>
struct dimension_checker<P, Count, Count>
{
static void check() {}
};
public :
/// BCCL macro to check the ConstPoint concept
BOOST_CONCEPT_USAGE(ConstPoint)
{
dimension_checker<X, 0, ccount>::check();
}
};
}
#endif
|
[
"fushunpoon@1fd432d8-e285-11dd-b2d9-215335d0b316"
] |
[
[
[
1,
138
]
]
] |
7fbd242fa68878d2e80c4b443deb9231f6c6d4ca
|
3856c39683bdecc34190b30c6ad7d93f50dce728
|
/LastProject/Source/Combo2.cpp
|
69ea3e5fea09bc751ab46a2376cda74460b3264f
|
[] |
no_license
|
yoonhada/nlinelast
|
7ddcc28f0b60897271e4d869f92368b22a80dd48
|
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
|
refs/heads/master
| 2021-01-20T09:07:11.577111 | 2011-12-21T22:12:36 | 2011-12-21T22:12:36 | 34,231,967 | 0 | 0 | null | null | null | null |
UHC
|
C++
| false | false | 880 |
cpp
|
#include "stdafx.h"
#include "Combo2.h"
#include "Combo2Stiffen.h"
#include "Monster.h"
Combo2* Combo2::GetInstance()
{
static Combo2 Instance;
return &Instance;
}
VOID Combo2::Enter( CMonster* a_pMonster )
{
// Melee 공격 애니메이션으로 바꾼다.
a_pMonster->ChangeAnimation( CMonster::ANIM_COMBO_ATTACK2 );
#ifdef _DEBUG
////CDebugConsole::GetInstance()->Messagef( L"Melee2 : ANIM_COMBO_ATTACK2 \n" );
#endif
CSound::GetInstance()->PlayEffect( CSound::EFFECT_CLOWN_ATTACK1 + rand() % 3 );
}
VOID Combo2::Execute( CMonster* a_pMonster )
{
if( a_pMonster->Get_AnimationEndCheck() == FALSE )
{
// 공격 충돌 박스 생성
a_pMonster->CreateAttackBoundBox();
// 경직 상태로
a_pMonster->GetFSM()->ChangeState( Combo2Stiffen::GetInstance() );
}
}
VOID Combo2::Exit( CMonster* a_pMonster )
{
}
|
[
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0",
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0"
] |
[
[
[
1,
20
],
[
22,
44
]
],
[
[
21,
21
]
]
] |
142cacdcda032f3fd00d7bb16df5740e42b2910f
|
ce28ec891a0d502e7461fd121b4d96a308c9dab7
|
/graph/GraphEdge.h
|
8664886d3494c85ce58b06ebb165c5367994ccf6
|
[] |
no_license
|
aktau/Tangerine
|
fe84f6578ce918d1fa151138c0cc5780161b3b8f
|
179ac9901513f90b17c5cd4add35608a7101055b
|
refs/heads/master
| 2020-06-08T17:07:53.860642 | 2011-08-14T09:41:41 | 2011-08-14T09:41:41 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 746 |
h
|
#ifndef GRAPHEDGE_H_
#define GRAPHEDGE_H_
#include <QGraphicsPathItem>
#include <QPen>
#include <QBrush>
class GraphEdge : public QGraphicsPathItem {
public:
GraphEdge(const QPainterPath &path, QGraphicsItem * parent = 0);
GraphEdge(const QPainterPath &path, const QPen &pen = QPen(), const QBrush &brush = QBrush());
virtual ~GraphEdge();
void setInfo(const QString& message);
protected:
virtual void mousePressEvent(QGraphicsSceneMouseEvent *event);
virtual void hoverEnterEvent (QGraphicsSceneHoverEvent * event);
virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent * event);
void init();
private:
QGraphicsEllipseItem *mPopup;
QGraphicsTextItem *mInfo;
};
#endif /* GRAPHEDGE_H_ */
|
[
"[email protected]"
] |
[
[
[
1,
28
]
]
] |
0f9c88b64ea510e82ff2cb8b6fb28cb5f55f3555
|
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
|
/depends/ClanLib/src/Core/XML/xml_writer.cpp
|
13afcd98d198126148844b1ce9983c10e09ce59a
|
[] |
no_license
|
ptrefall/smn6200fluidmechanics
|
841541a26023f72aa53d214fe4787ed7f5db88e1
|
77e5f919982116a6cdee59f58ca929313dfbb3f7
|
refs/heads/master
| 2020-08-09T17:03:59.726027 | 2011-01-13T22:39:03 | 2011-01-13T22:39:03 | 32,448,422 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,254 |
cpp
|
/*
** ClanLib SDK
** Copyright (c) 1997-2010 The ClanLib Team
**
** 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.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#include "precomp.h"
#include "API/Core/XML/xml_writer.h"
#include "API/Core/XML/xml_token.h"
#include "API/Core/Text/string_format.h"
#include "API/Core/Text/string_help.h"
#include "xml_writer_generic.h"
/////////////////////////////////////////////////////////////////////////////
// CL_XMLWriter construction:
CL_XMLWriter::CL_XMLWriter()
{
}
CL_XMLWriter::CL_XMLWriter(const CL_XMLWriter ©) : impl(copy.impl)
{
}
CL_XMLWriter::CL_XMLWriter(CL_IODevice &output) : impl(new CL_XMLWriter_Generic)
{
impl->output = output;
impl->str.reserve(4096);
impl->escaped_string.reserve(4096);
}
CL_XMLWriter::~CL_XMLWriter()
{
}
/////////////////////////////////////////////////////////////////////////////
// CL_XMLWriter attributes:
bool CL_XMLWriter::get_insert_whitespace() const
{
return impl->insert_whitespace;
}
void CL_XMLWriter::set_insert_whitespace(bool enable)
{
impl->insert_whitespace = enable;
}
/////////////////////////////////////////////////////////////////////////////
// CL_XMLWriter operations:
void CL_XMLWriter::write(const CL_XMLToken &token)
{
if (!impl) return;
// We are reusing a CL_String here to build up a capacity that fits
// all strings we write.
CL_String &str = impl->str;
str.clear();
if (token.variant == CL_XMLToken::END)
{
impl->indent--;
}
if (impl->insert_whitespace)
{
str.append(impl->indent, L'\t');
}
switch (token.type)
{
case CL_XMLToken::NULL_TOKEN:
return; // should this throw exception instead?
case CL_XMLToken::ELEMENT_TOKEN:
if (token.variant == CL_XMLToken::END)
{
str.append("</");
str.append(impl->insert_escapes_fast(token.name));
str.append(">");
}
else
{
str.append("<");
str.append(impl->insert_escapes_fast(token.name));
int size = (int) token.attributes.size();
for (int i=0; i<size; i++)
{
str.append(" ");
str.append(token.attributes[i].first);
str.append("=\"");
str.append(impl->insert_escapes_fast(token.attributes[i].second));
str.append("\"");
}
if (token.variant == CL_XMLToken::SINGLE)
str.append("/>");
else
str.append(">");
}
break;
case CL_XMLToken::TEXT_TOKEN:
str.append(impl->insert_escapes_fast(token.value));
break;
case CL_XMLToken::CDATA_SECTION_TOKEN:
str.append("<![CDATA[");
str.append(token.value);
str.append("]]>");
break;
case CL_XMLToken::COMMENT_TOKEN:
str.append("<!--");
str.append(token.value);
str.append("-->");
break;
case CL_XMLToken::ENTITY_REFERENCE_TOKEN:
case CL_XMLToken::ENTITY_TOKEN:
case CL_XMLToken::PROCESSING_INSTRUCTION_TOKEN:
case CL_XMLToken::DOCUMENT_TYPE_TOKEN:
case CL_XMLToken::NOTATION_TOKEN:
return; // not implemented yet.
}
if (impl->insert_whitespace)
{
#ifdef WIN32
str.append("\r\n");
#else
str.append("\n");
#endif
}
if (token.variant == CL_XMLToken::BEGIN)
{
impl->indent++;
}
impl->output.send(str.data(), str.size());
}
/////////////////////////////////////////////////////////////////////////////
// CL_XMLWriter implementation:
CL_StringRef CL_XMLWriter_Generic::insert_escapes_fast(const CL_StringRef &str)
{
static CL_StringRef const amp("&");
static CL_StringRef const quot(""");
static CL_StringRef const apos("'");
static CL_StringRef const lt("<");
static CL_StringRef const gt(">");
escaped_string = str;
CL_StringRef::size_type pos = 0;
while (pos < escaped_string.size())
{
switch(escaped_string[pos])
{
case '&':
escaped_string.replace(pos, 1, amp);
pos += amp.size();
break;
case '\'':
escaped_string.replace(pos, 1, apos);
pos += apos.size();
break;
case '\"':
escaped_string.replace(pos, 1, quot);
pos += quot.size();
break;
case '<':
escaped_string.replace(pos, 1, lt);
pos += lt.size();
break;
case '>':
escaped_string.replace(pos, 1, gt);
pos += gt.size();
break;
default:
++pos;
break;
}
}
return escaped_string;
}
|
[
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
] |
[
[
[
1,
211
]
]
] |
461331a8fa1f7d08dc743a948731cbb3a42866b1
|
bef7d0477a5cac485b4b3921a718394d5c2cf700
|
/dingus/dingus/kernel/EffectLoader.cpp
|
0035f871e9e7b32d49af317448914fbc82152b78
|
[
"MIT"
] |
permissive
|
TomLeeLive/aras-p-dingus
|
ed91127790a604e0813cd4704acba742d3485400
|
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
|
refs/heads/master
| 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 29,089 |
cpp
|
// --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#include "stdafx.h"
#include "EffectLoader.h"
#include "ProxyEffect.h"
#include "D3DDevice.h"
#include "../console/Console.h"
#include "../utils/Errors.h"
#include "../lua/LuaSingleton.h"
#include "../lua/LuaHelper.h"
#include "../lua/LuaIterator.h"
using namespace dingus;
#define DEBUG_SHADERS 0
// --------------------------------------------------------------------------
// render state definitions
namespace {
enum eFxStateType {
FXST_RENDERSTATE,
FXST_TSS,
FXST_NPATCH,
FXST_SAMPLER,
FXST_VERTEXSHADER,
FXST_PIXELSHADER,
};
struct SFxState {
eFxStateType type;
const char* name; // state name
DWORD code; // D3D code
};
// State definitions. Required so that we can convert from D3D state codes
// to text and vice versa.
// NOTE: almost no fixed function T&L states are defined here. Just don't use
// T&L and effects at the same time, it's really messy.
SFxState FX_STATES[] = {
{ FXST_VERTEXSHADER, "VertexShader", 0 },
{ FXST_PIXELSHADER, "PixelShader", 0 },
{ FXST_NPATCH, "PatchSegments", 0 },
{ FXST_RENDERSTATE, "ZEnable", D3DRS_ZENABLE },
{ FXST_RENDERSTATE, "FillMode", D3DRS_FILLMODE },
{ FXST_RENDERSTATE, "ShadeMode", D3DRS_SHADEMODE },
{ FXST_RENDERSTATE, "ZWriteEnable", D3DRS_ZWRITEENABLE },
{ FXST_RENDERSTATE, "AlphaTestEnable", D3DRS_ALPHATESTENABLE },
{ FXST_RENDERSTATE, "LastPixel", D3DRS_LASTPIXEL },
{ FXST_RENDERSTATE, "SrcBlend", D3DRS_SRCBLEND },
{ FXST_RENDERSTATE, "DestBlend", D3DRS_DESTBLEND },
{ FXST_RENDERSTATE, "CullMode", D3DRS_CULLMODE },
{ FXST_RENDERSTATE, "ZFunc", D3DRS_ZFUNC },
{ FXST_RENDERSTATE, "AlphaRef", D3DRS_ALPHAREF },
{ FXST_RENDERSTATE, "AlphaFunc", D3DRS_ALPHAFUNC },
{ FXST_RENDERSTATE, "DitherEnable", D3DRS_DITHERENABLE },
{ FXST_RENDERSTATE, "AlphaBlendEnable", D3DRS_ALPHABLENDENABLE },
{ FXST_RENDERSTATE, "FogEnable", D3DRS_FOGENABLE },
{ FXST_RENDERSTATE, "SpecularEnable", D3DRS_SPECULARENABLE },
{ FXST_RENDERSTATE, "FogColor", D3DRS_FOGCOLOR },
{ FXST_RENDERSTATE, "FogTableMode", D3DRS_FOGTABLEMODE },
{ FXST_RENDERSTATE, "FogStart", D3DRS_FOGSTART },
{ FXST_RENDERSTATE, "FogEnd", D3DRS_FOGEND },
{ FXST_RENDERSTATE, "FogDensity", D3DRS_FOGDENSITY },
{ FXST_RENDERSTATE, "RangeFogEnable", D3DRS_RANGEFOGENABLE },
{ FXST_RENDERSTATE, "StencilEnable", D3DRS_STENCILENABLE },
{ FXST_RENDERSTATE, "StencilFail", D3DRS_STENCILFAIL },
{ FXST_RENDERSTATE, "StencilZFail", D3DRS_STENCILZFAIL },
{ FXST_RENDERSTATE, "StencilPass", D3DRS_STENCILPASS },
{ FXST_RENDERSTATE, "StencilFunc", D3DRS_STENCILFUNC },
{ FXST_RENDERSTATE, "StencilRef", D3DRS_STENCILREF },
{ FXST_RENDERSTATE, "StencilMask", D3DRS_STENCILMASK },
{ FXST_RENDERSTATE, "StencilWriteMask", D3DRS_STENCILWRITEMASK },
{ FXST_RENDERSTATE, "TextureFactor", D3DRS_TEXTUREFACTOR },
{ FXST_RENDERSTATE, "Wrap0", D3DRS_WRAP0 },
{ FXST_RENDERSTATE, "Wrap1", D3DRS_WRAP1 },
{ FXST_RENDERSTATE, "Wrap2", D3DRS_WRAP2 },
{ FXST_RENDERSTATE, "Wrap3", D3DRS_WRAP3 },
{ FXST_RENDERSTATE, "Wrap4", D3DRS_WRAP4 },
{ FXST_RENDERSTATE, "Wrap5", D3DRS_WRAP5 },
{ FXST_RENDERSTATE, "Wrap6", D3DRS_WRAP6 },
{ FXST_RENDERSTATE, "Wrap7", D3DRS_WRAP7 },
{ FXST_RENDERSTATE, "Clipping", D3DRS_CLIPPING },
{ FXST_RENDERSTATE, "Lighting", D3DRS_LIGHTING },
{ FXST_RENDERSTATE, "Ambient", D3DRS_AMBIENT },
{ FXST_RENDERSTATE, "FogVertexMode", D3DRS_FOGVERTEXMODE },
{ FXST_RENDERSTATE, "ColorVertex", D3DRS_COLORVERTEX },
{ FXST_RENDERSTATE, "LocalViewer", D3DRS_LOCALVIEWER },
{ FXST_RENDERSTATE, "NormalizeNormals", D3DRS_NORMALIZENORMALS },
{ FXST_RENDERSTATE, "DiffuseMaterialSource", D3DRS_DIFFUSEMATERIALSOURCE },
{ FXST_RENDERSTATE, "SpecularMaterialSource", D3DRS_SPECULARMATERIALSOURCE },
{ FXST_RENDERSTATE, "AmbientMaterialSource", D3DRS_AMBIENTMATERIALSOURCE },
{ FXST_RENDERSTATE, "EmissiveMaterialSource", D3DRS_EMISSIVEMATERIALSOURCE },
{ FXST_RENDERSTATE, "VertexBlend", D3DRS_VERTEXBLEND },
{ FXST_RENDERSTATE, "ClipPlaneEnable", D3DRS_CLIPPLANEENABLE },
{ FXST_RENDERSTATE, "PointSize", D3DRS_POINTSIZE },
{ FXST_RENDERSTATE, "PointSize_Min", D3DRS_POINTSIZE_MIN },
{ FXST_RENDERSTATE, "PointSpriteEnable", D3DRS_POINTSPRITEENABLE },
{ FXST_RENDERSTATE, "PointScaleEnable", D3DRS_POINTSCALEENABLE },
{ FXST_RENDERSTATE, "PointScale_A", D3DRS_POINTSCALE_A },
{ FXST_RENDERSTATE, "PointScale_B", D3DRS_POINTSCALE_B },
{ FXST_RENDERSTATE, "PointScale_C", D3DRS_POINTSCALE_C },
{ FXST_RENDERSTATE, "MultiSampleAntiAlias", D3DRS_MULTISAMPLEANTIALIAS },
{ FXST_RENDERSTATE, "MultiSampleMask", D3DRS_MULTISAMPLEMASK },
{ FXST_RENDERSTATE, "PatchEdgeStyle", D3DRS_PATCHEDGESTYLE },
{ FXST_RENDERSTATE, "DebugMonitorToken", D3DRS_DEBUGMONITORTOKEN },
{ FXST_RENDERSTATE, "PointSize_Max", D3DRS_POINTSIZE_MAX },
{ FXST_RENDERSTATE, "IndexedVertexBlendEnable",D3DRS_INDEXEDVERTEXBLENDENABLE},
{ FXST_RENDERSTATE, "ColorWriteEnable", D3DRS_COLORWRITEENABLE },
{ FXST_RENDERSTATE, "TweenFactor", D3DRS_TWEENFACTOR },
{ FXST_RENDERSTATE, "BlendOp", D3DRS_BLENDOP },
{ FXST_RENDERSTATE, "PositionDegree", D3DRS_POSITIONDEGREE },
{ FXST_RENDERSTATE, "NormalDegree", D3DRS_NORMALDEGREE },
{ FXST_RENDERSTATE, "ScissorTestEnable", D3DRS_SCISSORTESTENABLE },
{ FXST_RENDERSTATE, "SlopeScaleDepthBias", D3DRS_SLOPESCALEDEPTHBIAS },
{ FXST_RENDERSTATE, "AntiAliasedLineEnable", D3DRS_ANTIALIASEDLINEENABLE },
{ FXST_RENDERSTATE, "MinTessellationLevel", D3DRS_MINTESSELLATIONLEVEL },
{ FXST_RENDERSTATE, "MaxTessellationLevel", D3DRS_MAXTESSELLATIONLEVEL },
{ FXST_RENDERSTATE, "TwoSidedStencilMode", D3DRS_TWOSIDEDSTENCILMODE },
{ FXST_RENDERSTATE, "CCW_StencilFAIL", D3DRS_CCW_STENCILFAIL },
{ FXST_RENDERSTATE, "CCW_StencilZFAIL", D3DRS_CCW_STENCILZFAIL },
{ FXST_RENDERSTATE, "CCW_StencilPASS", D3DRS_CCW_STENCILPASS },
{ FXST_RENDERSTATE, "CCW_StencilFUNC", D3DRS_CCW_STENCILFUNC },
{ FXST_RENDERSTATE, "ColorWriteEnable1", D3DRS_COLORWRITEENABLE1 },
{ FXST_RENDERSTATE, "ColorWriteEnable2", D3DRS_COLORWRITEENABLE2 },
{ FXST_RENDERSTATE, "ColorWriteEnable3", D3DRS_COLORWRITEENABLE3 },
{ FXST_RENDERSTATE, "BlendFactor", D3DRS_BLENDFACTOR },
{ FXST_RENDERSTATE, "SRGBWriteEnable", D3DRS_SRGBWRITEENABLE },
{ FXST_RENDERSTATE, "DepthBias", D3DRS_DEPTHBIAS },
{ FXST_RENDERSTATE, "Wrap8", D3DRS_WRAP8 },
{ FXST_RENDERSTATE, "Wrap9", D3DRS_WRAP9 },
{ FXST_RENDERSTATE, "Wrap10", D3DRS_WRAP10 },
{ FXST_RENDERSTATE, "Wrap11", D3DRS_WRAP11 },
{ FXST_RENDERSTATE, "Wrap12", D3DRS_WRAP12 },
{ FXST_RENDERSTATE, "Wrap13", D3DRS_WRAP13 },
{ FXST_RENDERSTATE, "Wrap14", D3DRS_WRAP14 },
{ FXST_RENDERSTATE, "Wrap15", D3DRS_WRAP15 },
{ FXST_RENDERSTATE, "SeparateAlphaBlendEnable",D3DRS_SEPARATEALPHABLENDENABLE},
{ FXST_RENDERSTATE, "SrcBlendAlpha", D3DRS_SRCBLENDALPHA },
{ FXST_RENDERSTATE, "DestBlendAlpha", D3DRS_DESTBLENDALPHA },
{ FXST_RENDERSTATE, "BlendOpAlpha", D3DRS_BLENDOPALPHA },
{ FXST_TSS, "ColorOp", D3DTSS_COLOROP },
{ FXST_TSS, "ColorArg1", D3DTSS_COLORARG1 },
{ FXST_TSS, "ColorArg2", D3DTSS_COLORARG2 },
{ FXST_TSS, "AlphaOp", D3DTSS_ALPHAOP },
{ FXST_TSS, "AlphaArg1", D3DTSS_ALPHAARG1 },
{ FXST_TSS, "AlphaArg2", D3DTSS_ALPHAARG2 },
{ FXST_TSS, "BumpEnvMat00", D3DTSS_BUMPENVMAT00 },
{ FXST_TSS, "BumpEnvMat01", D3DTSS_BUMPENVMAT01 },
{ FXST_TSS, "BumpEnvMat10", D3DTSS_BUMPENVMAT10 },
{ FXST_TSS, "BumpEnvMat11", D3DTSS_BUMPENVMAT11 },
{ FXST_TSS, "TexCoordIndex", D3DTSS_TEXCOORDINDEX },
{ FXST_TSS, "BumpEnvLScale", D3DTSS_BUMPENVLSCALE },
{ FXST_TSS, "BumpEnvLOffset", D3DTSS_BUMPENVLOFFSET},
{ FXST_TSS, "TextureTransformFlags", D3DTSS_TEXTURETRANSFORMFLAGS},
{ FXST_TSS, "ColorArg0", D3DTSS_COLORARG0 },
{ FXST_TSS, "AlphaArg0", D3DTSS_ALPHAARG0 },
{ FXST_TSS, "ResultArg", D3DTSS_RESULTARG },
{ FXST_TSS, "Constant", D3DTSS_CONSTANT },
{ FXST_SAMPLER, "AddressU", D3DSAMP_ADDRESSU },
{ FXST_SAMPLER, "AddressV", D3DSAMP_ADDRESSV },
{ FXST_SAMPLER, "AddressW", D3DSAMP_ADDRESSW },
{ FXST_SAMPLER, "BorderColor", D3DSAMP_BORDERCOLOR },
{ FXST_SAMPLER, "MagFilter", D3DSAMP_MAGFILTER },
{ FXST_SAMPLER, "MinFilter", D3DSAMP_MINFILTER },
{ FXST_SAMPLER, "MipFilter", D3DSAMP_MIPFILTER },
{ FXST_SAMPLER, "MipMapLodBias", D3DSAMP_MIPMAPLODBIAS},
{ FXST_SAMPLER, "MaxMipLevel", D3DSAMP_MAXMIPLEVEL },
{ FXST_SAMPLER, "MaxAnisotropy", D3DSAMP_MAXANISOTROPY},
{ FXST_SAMPLER, "SRGBTexture", D3DSAMP_SRGBTEXTURE },
{ FXST_SAMPLER, "ElementIndex", D3DSAMP_ELEMENTINDEX },
{ FXST_SAMPLER, "DMapOffset", D3DSAMP_DMAPOFFSET },
};
const int FX_STATES_SIZE = sizeof(FX_STATES) / sizeof(FX_STATES[0]);
/// @return State index into FX_STATES, given its type and code.
int findState( eFxStateType type, DWORD code )
{
for( int i = 0; i < FX_STATES_SIZE; ++i ) {
if( FX_STATES[i].type == type && FX_STATES[i].code == code )
return i;
}
ASSERT_FAIL_MSG( "Supplied effect state not found" );
return -1;
}
/// @return State index into FX_STATES, given its name.
int findState( const char* name )
{
for( int i = 0; i < FX_STATES_SIZE; ++i ) {
if( 0 == stricmp( FX_STATES[i].name, name ) )
return i;
}
ASSERT_FAIL_MSG( "Supplied effect state not found" );
return -1;
}
}; // end anonymous namespace
// --------------------------------------------------------------------------
// effect state inspector
class CEffectStateInspector : public ID3DXEffectStateManager {
public:
struct SState {
SState( int pass_, int index_, int stage_, DWORD value_ )
: pass(pass_), index(index_), stage(stage_), value(value_)
{
assert( index >= 0 && index < FX_STATES_SIZE );
}
int pass; ///< Effect pass
int index; ///< Index into FX_STATES
int stage; ///< For TSS, sampler etc.
DWORD value; ///< Value
};
typedef std::vector<SState> TStateVector;
public:
CEffectStateInspector()
{
beginEffect();
}
void beginEffect()
{
mCurrentPass = -1;
mStates.clear();
mStates.reserve( 32 );
mPassStart.clear();
mPassCounts.clear();
}
void beginPass()
{
assert( mPassStart.size() == mPassCounts.size() );
if( !mPassCounts.empty() ) {
mPassCounts.back() = (int)mStates.size() - mPassStart.back();
}
++mCurrentPass;
mPassStart.push_back( (int)mStates.size() );
mPassCounts.push_back( 0 );
}
void endEffect()
{
assert( mPassStart.size() == mPassCounts.size() );
if( !mPassCounts.empty() ) {
mPassCounts.back() = (int)mStates.size() - mPassStart.back();
}
++mCurrentPass;
}
const TStateVector& getStates() const { return mStates; }
int getPassStateStart( int pass ) const { assert(pass>=0&&pass<(int)mPassStart.size()); return mPassStart[pass]; }
int getPassStateCount( int pass ) const { assert(pass>=0&&pass<(int)mPassCounts.size()); return mPassCounts[pass]; }
/**
* Debug: print inspected effect to the given file.
*/
void debugPrintFx( const char* fileName )
{
FILE* f = fopen( fileName, "wt" );
fprintf( f, "pass P0 {\n" );
size_t n = mStates.size();
for( size_t i = 0; i < n; ++i ) {
const SState& s = mStates[i];
// new pass?
if( i > 0 && s.pass != mStates[i-1].pass ) {
fprintf( f, "}\n" );
fprintf( f, "pass P%i {\n", s.pass );
}
// dump states
if( s.stage < 0 ) {
fprintf( f, "\t%s = %i\n",
FX_STATES[s.index].name,
s.value
);
} else {
fprintf( f, "\t%s[%i] = %i\n",
FX_STATES[s.index].name,
s.stage,
s.value
);
}
}
fprintf( f, "}\n" );
}
// ------------------------------------------
// ID3DXEffectStateManager
STDMETHOD(SetTransform)( D3DTRANSFORMSTATETYPE state, const D3DMATRIX* matrix )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetMaterial)( const D3DMATERIAL9* material )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetLight)( DWORD index, const D3DLIGHT9* light )
{
// don't inspect
return S_OK;
}
STDMETHOD(LightEnable)( DWORD index, BOOL enable )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetRenderState)( D3DRENDERSTATETYPE state, DWORD value )
{
int index = findState( FXST_RENDERSTATE, state );
mStates.push_back( SState( mCurrentPass, index, -1, value ) );
return S_OK;
}
STDMETHOD(SetTexture)( DWORD stage, IDirect3DBaseTexture9* texture )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetTextureStageState)( DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value )
{
int index = findState( FXST_TSS, type );
mStates.push_back( SState( mCurrentPass, index, stage, value ) );
return S_OK;
}
STDMETHOD(SetSamplerState)( DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value )
{
int index = findState( FXST_SAMPLER, type );
mStates.push_back( SState( mCurrentPass, index, sampler, value ) );
return S_OK;
}
STDMETHOD(SetNPatchMode)( float numSegments )
{
int index = findState( FXST_NPATCH, 0 );
mStates.push_back( SState( mCurrentPass, index, -1, (DWORD)numSegments ) );
return S_OK;
}
STDMETHOD(SetFVF)( DWORD fvf )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetVertexShader)( IDirect3DVertexShader9* shader )
{
int index = findState( FXST_VERTEXSHADER, 0 );
mStates.push_back( SState( mCurrentPass, index, -1, shader ? 1 : 0 ) );
return S_OK;
}
STDMETHOD(SetVertexShaderConstantF)( UINT registerIdx, const float* data, UINT registerCount )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetVertexShaderConstantI)(THIS_ UINT registerIdx, const int *data, UINT registerCount )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetVertexShaderConstantB)(THIS_ UINT registerIdx, const BOOL *data, UINT registerCount )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetPixelShader)( IDirect3DPixelShader9* shader )
{
int index = findState( FXST_PIXELSHADER, 0 );
mStates.push_back( SState( mCurrentPass, index, -1, shader ? 1 : 0 ) );
return S_OK;
}
STDMETHOD(SetPixelShaderConstantF)( UINT registerIdx, const float *data, UINT registerCount )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetPixelShaderConstantI)( UINT registerIdx, const int *data, UINT registerCount )
{
// don't inspect
return S_OK;
}
STDMETHOD(SetPixelShaderConstantB)( UINT registerIdx, const BOOL *data, UINT registerCount )
{
// don't inspect
return S_OK;
}
// IUnknown
STDMETHOD(QueryInterface)( REFIID iid, LPVOID *ppv ) {
if( iid == IID_ID3DXEffectStateManager ) {
*ppv = this;
AddRef();
return NOERROR;
}
return ResultFromScode(E_NOINTERFACE);
}
STDMETHOD_(ULONG, AddRef)() {
return 1;
}
STDMETHOD_(ULONG, Release)() {
return 1;
}
private:
/// Inspected states
TStateVector mStates;
/// Starting state index for each pass
std::vector<int> mPassStart;
/// State count for each pass
std::vector<int> mPassCounts;
/// Current pass
int mCurrentPass;
};
// --------------------------------------------------------------------------
// restore pass generator and state checker
class CEffectRestorePassGenerator : public boost::noncopyable {
public:
/**
* Load states configuration file.
*/
bool loadConfig( const char* fileName );
/**
* Check effect for missing required/dependent state assignments.
* @return Errors string. Empty if all ok.
*/
std::string checkEffect( const CEffectStateInspector& fx ) const;
/**
* Generate state restore pass for given inspected effect.
* @return Generated pass text.
*/
std::string generateRestorePass( const CEffectStateInspector& fx ) const;
private:
struct SStateRestored {
SStateRestored( int idx, const std::string& val )
: index(idx), value(val)
{
assert( index >= 0 && index < FX_STATES_SIZE );
assert( !value.empty() );
}
int index; ///< Index into FX_STATES
std::string value; ///< Restored to value (plain text, will be interpreted by Effect).
};
struct SStateRequired {
SStateRequired( int idx )
: index(idx)
{
assert( index >= 0 && index < FX_STATES_SIZE );
}
int index; ///< Index into FX_STATES
};
struct SStateDependent {
SStateDependent( int idx, DWORD val )
: index(idx), value(val)
{
assert( index >= 0 && index < FX_STATES_SIZE );
}
int index; ///< If this state (index into FX_STATES)
DWORD value; ///< Is set to this value
std::vector<int> needed; ///< All these states are needed (indices into FX_STATES)
};
private:
const SStateRestored* findRestoredState( int index ) const {
size_t n = mStatesRestored.size();
for( size_t i = 0; i < n; ++i ) {
if( mStatesRestored[i].index == index )
return &mStatesRestored[i];
}
return NULL;
}
private:
std::vector<SStateRestored> mStatesRestored;
std::vector<SStateRequired> mStatesRequired;
std::vector<SStateDependent> mStatesDependent;
};
bool CEffectRestorePassGenerator::loadConfig( const char* fileName )
{
// clear
mStatesRestored.clear();
mStatesRestored.reserve( 64 );
mStatesRequired.clear();
mStatesRequired.reserve( 16 );
mStatesDependent.clear();
mStatesDependent.reserve( 16 );
// execute file
CLuaSingleton& lua = CLuaSingleton::getInstance();
int errorCode = lua.doFile( fileName, false );
if( errorCode )
return false; // error
// read restored states
CLuaValue luaRestored = lua.getGlobal("restored");
CLuaArrayIterator itRestored( luaRestored );
while( itRestored.hasNext() ) {
CLuaValue& luaSt = itRestored.next();
std::string name = luaSt.getElement(1).getString();
luaSt.discard();
std::string value = luaSt.getElement(2).getString();
luaSt.discard();
int index = findState( name.c_str() );
mStatesRestored.push_back( SStateRestored( index, value ) );
}
luaRestored.discard();
// read required states
CLuaValue luaRequired = lua.getGlobal("required");
CLuaArrayIterator itRequired( luaRequired );
while( itRequired.hasNext() ) {
CLuaValue& luaSt = itRequired.next();
std::string name = luaSt.getString();
int index = findState( name.c_str() );
mStatesRequired.push_back( SStateRequired( index ) );
}
luaRequired.discard();
// read dependent states
CLuaValue luaDependent = lua.getGlobal("dependent");
CLuaArrayIterator itDependent( luaDependent );
while( itDependent.hasNext() ) {
CLuaValue& luaSt = itDependent.next();
std::string name = luaSt.getElement(1).getString();
luaSt.discard();
int value = int( luaSt.getElement(2).getNumber() );
luaSt.discard();
int index = findState( name.c_str() );
mStatesDependent.push_back( SStateDependent( index, value ) );
SStateDependent& st = mStatesDependent.back();
CLuaValue luaNames = luaSt.getElement(3);
CLuaArrayIterator itNames( luaNames );
while( itNames.hasNext() ) {
CLuaValue& luaN = itNames.next();
st.needed.push_back( findState( luaN.getString().c_str() ) );
}
luaNames.discard();
}
luaDependent.discard();
return true;
}
std::string CEffectRestorePassGenerator::checkEffect( const CEffectStateInspector& fx ) const
{
size_t i;
size_t nstates = fx.getStates().size();
std::string errs = "";
// Check required states: the first pass must contain all
// required states.
for( i = 0; i < mStatesRequired.size(); ++i ) {
int reqState = mStatesRequired[i].index;
bool found = false;
for( size_t j = 0; j < nstates; ++j ) {
const CEffectStateInspector::SState& st = fx.getStates()[j];
if( st.pass != 0 ) // only check first pass
break;
if( st.index == reqState ) {
found = true;
break;
}
}
if( !found ) {
errs += "First fx pass must assign ";
errs += FX_STATES[reqState].name;
errs += ". ";
}
}
// Check dependent states: in the first occurrance of state set
// to some value; each dependent state must also be set in the same
// pass. In subsequent passes, don't care about these states anymore -
// the effect author should know what he's doing.
for( i = 0; i < mStatesDependent.size(); ++i ) {
const SStateDependent& depState = mStatesDependent[i];
bool found = false;
size_t foundAt;
for( foundAt = 0; foundAt < nstates; ++foundAt ) {
const CEffectStateInspector::SState& st = fx.getStates()[foundAt];
if( st.index == depState.index && st.value == depState.value ) {
found = true;
break;
}
}
if( found ) {
// Found a state that implies some dependent states. Check if
// all of them are present in the current pass.
bool hasErrStart = false;
int pass = fx.getStates()[foundAt].pass;
int passStart = fx.getPassStateStart(pass);
int passEnd = passStart + fx.getPassStateCount(pass);
for( size_t j = 0; j < depState.needed.size(); ++j ) {
int neededState = depState.needed[j];
bool foundNeeded = false;
for( int k = passStart; k < passEnd; ++k ) {
if( fx.getStates()[k].index == neededState ) {
foundNeeded = true;
break;
}
}
if( !foundNeeded ) {
// error
if( !hasErrStart ) {
errs += "Using ";
errs += FX_STATES[depState.index].name;
errs += '=';
char buf[100];
itoa( depState.value, buf, 10 );
errs += buf;
errs += " requires setting ";
hasErrStart = true;
}
errs += FX_STATES[neededState].name;
errs += ',';
}
}
if( hasErrStart ) {
errs[errs.size()-1] = '.';
}
}
}
return errs;
}
std::string CEffectRestorePassGenerator::generateRestorePass( const CEffectStateInspector& fx ) const
{
size_t i;
size_t nstates = fx.getStates().size();
// generate restoring pass
// NOTE: it seems that (Oct 2004 SDK) fx macros don't support newlines.
// Oh well, generate one long line...
std::string res;
res.reserve( 128 );
res = std::string("pass ") + DINGUS_FX_RESTORE_PASS + " {";
// fill restored states
// TBD: remove duplicates
for( i = 0; i < nstates; ++i ) {
const CEffectStateInspector::SState& state = fx.getStates()[i];
const SStateRestored* st = findRestoredState( state.index );
if( !st )
continue;
res += " ";
res += FX_STATES[state.index].name;
if( state.stage >= 0 ) {
char buf[10];
res += '[';
itoa( state.stage, buf, 10 );
res += buf;
res += ']';
}
res += '=';
if( st->value == "@index@" ) {
assert( state.stage >= 0 );
char buf[10];
itoa( state.stage, buf, 10 );
res += buf;
} else {
res += st->value;
}
res += ';';
}
res += " }";
return res;
}
namespace {
CEffectRestorePassGenerator* gFxRestorePassGen = 0;
}; // end of anonymous namespace
bool fxloader::initialize( const char* cfgFileName )
{
assert( !gFxRestorePassGen );
gFxRestorePassGen = new CEffectRestorePassGenerator();
return gFxRestorePassGen->loadConfig( cfgFileName );
}
void fxloader::shutdown()
{
safeDelete( gFxRestorePassGen );
}
// --------------------------------------------------------------------------
// main effect loading code
bool dingus::fxloader::load(
const std::string& id, const std::string& fileName,
const char* skipConstants,
CD3DXEffect& dest, std::string& errorMsgs,
ID3DXEffectPool* pool, ID3DXEffectStateManager* stateManager,
const D3DXMACRO* macros, size_t macroCount, bool optimizeShaders, CConsoleChannel& console )
{
// 1. load effect from file, find valid technique
// 2. if it has restoring pass, exit: all is done
// 3. inspect the valid technique
// 4. generate restoring pass
// 5. supply restoring pass as macro; load effect again
// 6. check that it has a restoring pass
assert( dest.getObject() == NULL );
console.write( "loading fx '" + id + "'" );
// add macro RESTORE_PASS to supplied ones, initially empty
assert( macroCount > 0 );
D3DXMACRO* newMacros = new D3DXMACRO[macroCount+1];
memcpy( newMacros, macros, macroCount * sizeof(macros[0]) );
newMacros[macroCount] = newMacros[macroCount-1];
newMacros[macroCount-1].Name = "RESTORE_PASS";
newMacros[macroCount-1].Definition = "";
// load the effect initially
ID3DXEffect* fx = NULL;
ID3DXBuffer* errors = NULL;
errorMsgs = "";
assert( pool );
#ifdef DINGUS_HAVE_D3DX_FEB_2005
HRESULT hres = D3DXCreateEffectFromFileEx(
#else
HRESULT hres = D3DXCreateEffectFromFile(
#endif
&CD3DDevice::getInstance().getDevice(),
fileName.c_str(),
newMacros,
NULL,
#ifdef DINGUS_HAVE_D3DX_FEB_2005
skipConstants,
#endif
#if DEBUG_SHADERS
D3DXSHADER_SKIPOPTIMIZATION | D3DXSHADER_DEBUG,
#else
optimizeShaders ? 0 : D3DXSHADER_SKIPOPTIMIZATION,
#endif
pool, &fx, &errors );
if( errors && errors->GetBufferSize() > 1 ) {
std::string msg = "messages compiling effect '" + fileName + "': ";
errorMsgs = (const char*)errors->GetBufferPointer();
msg += errorMsgs;
CConsole::CON_ERROR.write( msg );
}
if( FAILED( hres ) ) {
delete[] newMacros;
return false;
}
assert( fx );
if( errors )
errors->Release();
// initialize effect object
dest.setObject( fx );
// examine effect state assignments
static CEffectStateInspector inspector;
fx->SetStateManager( &inspector );
inspector.beginEffect();
int passes = dest.beginFx();
for( int i = 0; i < passes; ++i ) {
inspector.beginPass();
dest.beginPass( i );
dest.endPass();
}
dest.endFx();
inspector.endEffect();
//inspector.debugPrintFx( (fileName+".ins.fx").c_str() );
// check the effect
std::string chkErrors = gFxRestorePassGen->checkEffect( inspector );
if( !chkErrors.empty() ) {
errorMsgs = chkErrors;
CConsole::CON_ERROR.write( errorMsgs );
dest.getObject()->Release();
dest.setObject( NULL );
delete[] newMacros;
return false;
}
// if already has restoring pass, return
if( dest.hasRestoringPass() ) {
// set state manager
if( stateManager )
fx->SetStateManager( stateManager );
console.write( "fx loaded, already has restoring pass" );
delete[] newMacros;
return true;
}
// generate restore pass
console.write( "fx loaded, generating state restore pass" );
assert( gFxRestorePassGen );
std::string restorePass = gFxRestorePassGen->generateRestorePass( inspector );
// debug
/*{
FILE* f = fopen( (fileName+".res.fx").c_str(), "wt" );
fputs( restorePass.c_str(), f );
fclose( f );
}*/
// supply restore pass text as RESTORE_PASS value
newMacros[macroCount-1].Definition = restorePass.c_str();
// compile the effect again
dest.getObject()->Release();
dest.setObject( NULL );
fx = NULL;
errors = NULL;
errorMsgs = "";
assert( pool );
hres = D3DXCreateEffectFromFile(
&CD3DDevice::getInstance().getDevice(),
fileName.c_str(), newMacros, NULL,
optimizeShaders ? 0 : D3DXSHADER_SKIPOPTIMIZATION,
pool, &fx, &errors );
if( errors && errors->GetBufferSize() > 1 ) {
std::string msg = "messages compiling effect #2 '" + fileName + "': ";
errorMsgs = (const char*)errors->GetBufferPointer();
msg += errorMsgs;
CConsole::CON_ERROR.write( msg );
}
if( FAILED( hres ) ) {
delete[] newMacros;
return false;
}
assert( fx );
if( errors )
errors->Release();
// finally initialize effect object
dest.setObject( fx );
// it must have the restore pass now
if( !dest.hasRestoringPass() ) {
errorMsgs = "Effect does not have restore pass after generation. Perhaps RESTORE_PASS macro missing?";
CConsole::CON_ERROR.write( errorMsgs );
dest.getObject()->Release();
dest.setObject( NULL );
delete[] newMacros;
return false;
}
// set state manager
if( stateManager )
fx->SetStateManager( stateManager );
delete[] newMacros;
return true;
}
|
[
"[email protected]"
] |
[
[
[
1,
903
]
]
] |
293510233ff23b07a9137608c67745642d4d4f62
|
51e1cf5dc3b99e8eecffcf5790ada07b2f03f39c
|
/SMC/src/include/framerate.h
|
115073a0db367a1a16abc98452b1a3f84f831484
|
[] |
no_license
|
jdek/jim-pspware
|
c3e043b59a69cf5c28daf62dc9d8dca5daf87589
|
fd779e1148caac2da4c590844db7235357b47f7e
|
refs/heads/master
| 2021-05-31T06:45:03.953631 | 2007-06-25T22:45:26 | 2007-06-25T22:45:26 | 56,973,047 | 2 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,324 |
h
|
/***************************************************************************
framerate.h - Framerate independant class and a time correcting function
The Speedfactor is the heart of this class. When it is set by SetSpeedFactor,
it becomes a number with that you multiply all your motions. For instance, if the targetfps is 100,
and the actual fps is 85, the speedfactor will be set to 100/85, or about 1.2.
You then multiply all your motion is the game, at its lowest level, by this number.
copyright : (C) 2003-2005 by FluXy
V 2.0
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the LGPL. *
* *
***************************************************************************/
#ifndef __EP_FRAMERATE_H__
#define __EP_FRAMERATE_H__
#include <SDL_framerate.h>
extern FPSmanager fpsmgr; // fight crapware with crapware
class cFramerate
{
public:
cFramerate( int tfps )
{
speedfactor = 1;
fps = 0;
Init( tfps );
}
~cFramerate ( void )
{
//
}
void Init( int tfps )
{
targetfps = tfps;
maxspeedfactor = tfps/5;
framedelay = SDL_GetTicks();
SDL_initFramerate(&fpsmgr);
SDL_setFramerate(&fpsmgr, tfps);
}
void Update( void )
{
currentticks = SDL_GetTicks();
speedfactor = (double)( currentticks - framedelay ) / ( (double)1000/targetfps );
fps = targetfps/speedfactor;
if( speedfactor <= 0 )
{
speedfactor = 1;
}
else if( speedfactor > maxspeedfactor )
{
speedfactor = maxspeedfactor;
}
framedelay = currentticks;
}
void Reset( void )
{
framedelay = SDL_GetTicks();
speedfactor = 0;
}
void SetMaxSpeedFactor( double maxsf )
{
maxspeedfactor = maxsf;
}
double targetfps;
double fps;
Uint32 currentticks;
Uint32 framedelay;
double speedfactor;
double maxspeedfactor;
};
/* Fixed framerate method */
inline void CorrectFrameTime( unsigned int fps = 32 )
{
SDL_framerateDelay(&fpsmgr);
}
#endif
|
[
"rinco@ff2c0c17-07fa-0310-a4bd-d48831021cb5"
] |
[
[
[
1,
99
]
]
] |
bced96a0eeff5385c32793f62840280ba8ba18a3
|
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
|
/_统计专用/陈年旧芝麻_完成的未完成的集合/《算法导论》/第2章 算法入门/20090402-binary-search.cpp
|
9b8f26e9c7cfe49b17fc88bb68c7097a0042c86e
|
[] |
no_license
|
lzq123218/guoyishi-works
|
dbfa42a3e2d3bd4a984a5681e4335814657551ef
|
4e78c8f2e902589c3f06387374024225f52e5a92
|
refs/heads/master
| 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,999 |
cpp
|
//20090402 BINARY SEARCH AND MERGE SORT
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//merge function
template <typename T>
void merge(T a[], int mid, int n)
{
T *temp = new T[n];
int i = 0;
int j = mid;
int k = 0;
while (i < mid && j < n) {
temp[k++] = (a[i] < a[j]) ? a[i++] : a[j++];
}
while (i < mid)
temp[k++] = a[i++];
while (j < n)
temp[k++] = a[j++];
for (i = 0; i != n; ++i)
a[i] = temp[i];
delete[] temp;
}
//merge sort main function
template <typename T>
void merge_sort(T a[], int n)
{
if (n == 1)
return;
int mid = n / 2;
merge_sort(a, mid);
merge_sort(a + mid, n - mid);
merge(a, mid, n);
}
//binary search main function
template <typename T>
bool binary_search(T a[], T value, int low, int high)
{
if (low <= high) {
int mid = (low + high) / 2;
if (value == a[mid])
return true;
else if (value > a[mid])
binary_search(a, value, mid + 1, high);
else
binary_search(a, value, low, mid - 1);
}
else
return false;
}
int main()
{
cout << "BINARY SEARCH" << endl;
srand((unsigned)time(NULL)); //get random seed
int n;
cout << "Enter number:";
cin >> n;
int *array = new int[n];
int i;
for (i = 0; i != n; ++i) {
array[i] = rand() % n; //create random number
cout << array[i] << " ";
if ((i + 1) % 10 == 0)
cout << endl;
}
cout << endl;
merge_sort(array, n); //sort the array first
cout << "MERGE SORTED:" << endl;
//print the sorted array
for (i = 0; i != n; ++i) {
cout << array[i] << " ";
if ((i + 1) % 10 == 0)
cout << endl;
}
cout << endl;
//get the searchValue
int searchValue;
cout << "Enter the search value:";
cin >> searchValue;
int low = 0, high = n - 1;
if (binary_search(array, searchValue, low, high)) //search the array
cout << "Find " << searchValue << endl;
else
cout << "Could not find " << searchValue << endl;
return 0;
}
|
[
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
] |
[
[
[
1,
108
]
]
] |
e2fa5fd613d9184bb8a2383d872a0c70bb51f0ea
|
e2f961659b90ff605798134a0a512f9008c1575b
|
/Example-09/MODEL_REG.INC
|
f3e7f0de8e9d29d50bda5e2a6ad359a6bd94a42e
|
[] |
no_license
|
bs-eagle/test-models
|
469fe485a0d9aec98ad06d39b75901c34072cf60
|
d125060649179b8e4012459c0a62905ca5235ba7
|
refs/heads/master
| 2021-01-22T22:56:50.982294 | 2009-11-10T05:49:22 | 2009-11-10T05:49:22 | 1,266,143 | 1 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 44 |
inc
|
FIPNUM
3864*2
/
BNDNUM
3864*2
/
|
[
"[email protected]"
] |
[
[
[
1,
8
]
]
] |
345588e1ba801716695ee4ac5829b8bf7d98bdaa
|
77957df975b0b622fdbfede798b83c1d30ae117d
|
/EntradaDelUsuario/EntradaDelUsuario/Game/Game.h
|
5d28e6eb6a8f4cbb1c14a6a562968f3a796dd4b4
|
[] |
no_license
|
Juanmaramon/aplicacion-practica-basica
|
92f80b0699c8450c3c32a6cdaff395bb257d3a95
|
9d7776dcc55c7de4cf03085c998d6c7461f4cae5
|
refs/heads/master
| 2016-08-12T19:49:55.787837 | 2011-07-10T15:34:01 | 2011-07-10T15:34:01 | 43,250,262 | 0 | 0 | null | null | null | null |
ISO-8859-1
|
C++
| false | false | 1,242 |
h
|
#ifndef Game_H
#define Game_H
#include "..\Utility\Singleton.h"
#include "..\Window\ApplicationProperties.h"
#include "..\Graphics\Camera.h"
//Clase que hace uso del Patrón Singleton definido en Singleton.h, para iniciar, actualizar, dibujar
// y finalizar el juego
class cGame : public cSingleton<cGame>
{
friend class cSingleton<cGame>;
protected:
cGame() { ; } // Protected constructor
//Variable privada para gestionar si tenemos que salir de la aplicación.
bool mbFinish;
//Clase para los atributos de la ventana (cWindow) que se creará en el método Init.
cApplicationProperties mProperties;
//Instancia de la clase cCamera que representa la camera de nuestro juego.
cCamera m3DCamera;
public:
//Función para inicializar el juego
bool Init();
//Función para actualizar el juego
void Update( float lfTimestep );
//Función para renderizar el juego
void Render();
//Función para finalizar el juego
bool Deinit();
//Función que devuelve el valor de mbFinish, para chequear el final del juego.
inline bool HasFinished() { return mbFinish; }
//Función para cargar los recursos necesarios para el juego.
bool LoadResources( void );
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
44
]
]
] |
e03770e3d235799a25d53ccf6c709285cdfaf4fd
|
85e50a5e068a800973d57be93d8edc15a580325d
|
/Listener.cpp
|
5fd76fa60b19d81f81aacdc61d59bea926fae28c
|
[] |
no_license
|
jjzhang166/markessien-p2p.
|
9715a2b05bd129bce4798d2ad8b8d51684c05543
|
a691f47fc198f76f7fd5e66cdab1be7f39c0fbf1
|
refs/heads/master
| 2021-08-12T01:36:01.851011 | 2010-10-23T12:26:52 | 2010-10-23T12:26:52 | 110,662,175 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,019 |
cpp
|
// Listener.cpp : Implementation of CListener
#include "stdafx.h"
#include "P2P.h"
#include "Listener.h"
/////////////////////////////////////////////////////////////////////////////
// CListener
STDMETHODIMP CListener::Listen(long nPort)
{
// We start listening here, so if we come
// accross any error (like port already used)
// we can tell the user at once
try
{
if (nPort == 0)
return S_OK;
if (m_wndNotify.IsWindow() == FALSE)
{
m_wndNotify.SetDrainFunction(NotifyFunc, (long)this);
RECT rect;
rect.left = 0; rect.top = 0; rect.right = 5; rect.bottom = 5;
m_wndNotify.Create(NULL, rect, _T("NotifyWnd"), WS_POPUP);
}
m_nListenPort = nPort;
DWORD dwThreadID = 0;
CreateThread(NULL, // Security attributes
0, // Initial stack size
ListenThreadEntry, // Thread start address
(LPVOID) this, // Thread parameter
(DWORD) 0, // Creation flags
&dwThreadID); // Thread identifier
}
catch( ... )
{
Fire_FatalError(L"Exception in CListener::Listen");
}
return S_OK;
}
DWORD __stdcall CListener::ListenThreadEntry(LPVOID lpvThreadParm)
{
CListener* pThis = (CListener*)lpvThreadParm;
return pThis->Listen();
}
DWORD CListener::Listen()
{
m_listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_listenSocket == INVALID_SOCKET)
{
// StopListenAndTerminate();
ShootError(err_SocketCreationFailed);
return err_SocketCreationFailed;
}
_ASSERT(m_nListenPort);
SOCKADDR_IN saServer;
saServer.sin_family = AF_INET;
saServer.sin_addr.s_addr = INADDR_ANY;
saServer.sin_port = htons((unsigned short)m_nListenPort);
int nRet;
nRet = bind(m_listenSocket, (LPSOCKADDR)&saServer, sizeof(struct sockaddr));
if (nRet == SOCKET_ERROR)
{
// StopListenAndTerminate();
closesocket(m_listenSocket);
m_listenSocket = 0;
ShootError(err_SocketBindFailed);
return err_SocketBindFailed;
}
nRet = listen(m_listenSocket, 10); // 10 is the number of clients that can be queued
if (nRet == SOCKET_ERROR)
{
closesocket(m_listenSocket);
m_listenSocket = 0;
// StopListenAndTerminate();
ShootError(err_SocketListenFailed);
return err_SocketListenFailed;
}
//
// Wait for a client
//
SOCKET sckClient;
while (TRUE)
{
if (IsRemoteConnectionAvailable(m_listenSocket, 1))
{
sckClient = accept(m_listenSocket, NULL, NULL);
if (sckClient != INVALID_SOCKET)
{
// We fire connected event
m_wndNotify.SendMessage(WM_NEWCONN, sckClient);
}
}
// We check here if the thread has beeen killed
if (m_syncListen.IsLocked())
{
break;
}
}
// Send/receive from the client, and finally:
if (m_listenSocket)
{
closesocket(m_listenSocket);
m_listenSocket = 0;
}
m_syncListen.Unlock();
return 0;
}
BOOL CListener::NotifyFunc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, long pClass)
{
switch (uMsg)
{
case WM_NEWCONN:
CListener* pThis = (CListener*)pClass;
pThis->Fire_OnConnection(L"", 0, wParam);
break;
}
return FALSE;
}
BOOL CListener::IsRemoteConnectionAvailable(SOCKET s, int timeout)
{
FD_SET fdset;
TIMEVAL defTimeout;
int result;
defTimeout.tv_sec = timeout;
defTimeout.tv_usec = 0;
FD_ZERO(&fdset);
FD_SET(s, &fdset);
result = select(0, &fdset, 0, 0, &defTimeout);
return (result == 1);
}
STDMETHODIMP CListener::StopListenAndTerminate()
{
m_syncListen.Lock(); // this causes the listen loop to exit
m_syncListen.WaitForUnlock(3000); // after 3 secs, we exit anyway
return S_OK;
}
void CListener::ShootError(EnumErrorState error)
{
}
STDMETHODIMP CListener::OneRingToBindThemAll(BSTR Ring)
{
// TODO: Add your implementation code here
return E_NOTIMPL;
}
STDMETHODIMP CListener::ConvertNumericIP(double nAddr, BSTR *pResult)
{
return E_NOTIMPL;
}
|
[
"[email protected]"
] |
[
[
[
1,
184
]
]
] |
23b1c470efb07a4f2aa37102b645e76680c62117
|
fac8de123987842827a68da1b580f1361926ab67
|
/inc/physics/Physics/Dynamics/Entity/hkpRigidBodyCinfo.h
|
88c284d54f35115d80120cd16c894e4e2544affa
|
[] |
no_license
|
blockspacer/transporter-game
|
23496e1651b3c19f6727712a5652f8e49c45c076
|
083ae2ee48fcab2c7d8a68670a71be4d09954428
|
refs/heads/master
| 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,795 |
h
|
/*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HKDYNAMICS_ENTITY_HKRIGIDBODYCINFO_XML_H
#define HKDYNAMICS_ENTITY_HKRIGIDBODYCINFO_XML_H
#include <Physics/Collide/Agent/Collidable/hkpCollidableQualityType.h>
#include <Physics/Dynamics/Motion/hkpMotion.h>
#include <Physics/Dynamics/Entity/hkpRigidBodyDeactivator.h>
#include <Physics/Dynamics/Entity/hkpEntity.h>
/// A struct containing all the information needed to construct a rigid body.
class hkpRigidBodyCinfo
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_ENTITY, hkpRigidBodyCinfo);
/// A list of possible solver deactivation settings. This value defines how the
/// solver deactivates objects. The solver works on a per object basis.
/// Note: Solver deactivation does not save CPU, but reduces creeping of
/// movable objects in a pile quite dramatically.
enum SolverDeactivation
{
///
SOLVER_DEACTIVATION_INVALID,
/// No solver deactivation
SOLVER_DEACTIVATION_OFF,
/// Very conservative deactivation, typically no visible artifacts.
SOLVER_DEACTIVATION_LOW,
/// Normal deactivation, no serious visible artifacts in most cases
SOLVER_DEACTIVATION_MEDIUM,
/// Fast deactivation, visible artifacts
SOLVER_DEACTIVATION_HIGH,
/// Very fast deactivation, visible artifacts
SOLVER_DEACTIVATION_MAX
};
/// Default constructor - initializes all default values.
hkpRigidBodyCinfo();
//
// Members
//
public:
/// This value can be used by collision filters to identify the entity - for
/// example, if a group collision filter is used, this value would specify the
/// entity's collision group.
/// This defaults to 0.
hkUint32 m_collisionFilterInfo;
/// The collision detection representation for this entity.
/// This defaults to HK_NULL, and must be set before constructing a hkpRigidBody.
const hkpShape* m_shape;
/// The collision response. See hkpMaterial::hkResponseType for hkpWorld default
/// implementations.
/// This defaults to hkpMaterial::RESPONSE_SIMPLE_CONTACT.
hkEnum<hkpMaterial::ResponseType, hkInt8> m_collisionResponse;
/// Lowers the frequency for processContactCallbacks. A value of 5 means that a
/// callback is raised every 5th frame.
/// This defaults to 0xffff.
hkUint16 m_processContactCallbackDelay;
/// The initial position of the body.
/// This defaults to 0,0,0.
hkVector4 m_position;
/// The initial rotation of the body.
/// This defaults to the Identity quaternion.
hkQuaternion m_rotation;
/// The initial linear velocity of the body.
/// This defaults to 0,0,0.
hkVector4 m_linearVelocity;
/// The initial angular velocity of the body.
/// This defaults to 0,0,0.
hkVector4 m_angularVelocity;
/// The inertia tensor of the rigid body. Use the hkpInertiaTensorComputer class to
/// set the inertia to suitable values.
/// This defaults to the identity matrix.
hkMatrix3 m_inertiaTensor;
/// The center of mass in the local space of the rigid body.
/// This defaults to 0,0,0.
hkVector4 m_centerOfMass;
/// The mass of the body.
/// This defaults to 1.
hkReal m_mass;
/// The initial linear damping of the body.
/// This defaults to 0.
hkReal m_linearDamping;
/// The initial angular damping of the body.
/// This defaults to 0.05.
hkReal m_angularDamping;
/// The initial friction of the body.
/// This defaults to 0.5.
hkReal m_friction;
/// The initial restitution of the body.
/// This defaults to 0.4.
/// If the restitution is not 0.0 the object will need extra CPU
/// for all new collisions. Try to set restitution to 0 for maximum
/// performance (e.g. collapsing buildings)
hkReal m_restitution;
/// The maximum linear velocity of the body (in m/s).
/// This defaults to 200.
hkReal m_maxLinearVelocity;
/// The maximum angular velocity of the body (in rad/s).
/// This defaults to 200.
hkReal m_maxAngularVelocity;
/// The maximum allowed penetration for this object. The default is -1.
/// This is a hint to the engine to see how much CPU the engine should
/// invest to keep this object from penetrating. A good choice is 5% - 20% of the
/// smallest diameter of the object. Setting the initial value less than zero
/// allows the penetration depth to be estimated by the RigidBody upon creation.
/// This estimated value is 1/5th of the smallest dimension of the object's radius.
hkReal m_allowedPenetrationDepth;
/// The initial motion type of the body.
/// This defaults to hkpMotion::MOTION_DYNAMIC
hkEnum<hkpMotion::MotionType, hkInt8> m_motionType;
/// The initial deactivator type of the body.
/// This defaults to hkpRigidBodyDeactivator::DEACTIVATOR_SPATIAL.
hkEnum<hkpRigidBodyDeactivator::DeactivatorType, hkInt8> m_rigidBodyDeactivatorType;
/// Allows you to enable an extra single object deactivation schema.
/// That means the engine will try to "deactivate" single objects (not just entire islands)
/// if those objects get very slow.
/// This does not save CPU, however it can reduce small movements in big stacks of objects dramatically.
/// This defaults to SOLVER_DEACTIVATION_LOW.
hkEnum<SolverDeactivation, hkInt8> m_solverDeactivation;
/// The quality type, used to specify when to use continuous physics
/// This defaults to HK_COLLIDABLE_QUALITY_INVALID
/// If you add a hkpRigidBody to the hkpWorld, this type automatically gets converted to either
/// HK_COLLIDABLE_QUALITY_FIXED, HK_COLLIDABLE_QUALITY_KEYFRAMED or HK_COLLIDABLE_QUALITY_DEBRIS
hkEnum<hkpCollidableQualityType, hkInt8> m_qualityType;
/// This is a user flag which you can set to give you a hint as to which objects to remove from
/// the simulation if the memory overhead becomes too high. It defaults to 0.
hkInt8 m_autoRemoveLevel;
/// Requests a number of extra fields in each hkpContactPointProperties for this rigid body.
/// By default the first elements of those extra field will be filled with the shape hierarchy.
hkInt8 m_numUserDatasInContactPointProperties;
/// Ps3 only: If this flag is set, all collision agents attached to this body will run on the ppu only.
/// If this flag is set it will set the FORCE_PPU_USER_REQUEST bit in hkpCollidable::m_forceCollideOntoPpu bitfield
hkBool m_forceCollideOntoPpu;
};
#endif // HKDYNAMICS_ENTITY_HKRIGIDBODYCINFO_XML_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
|
[
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] |
[
[
[
1,
185
]
]
] |
a19e815ec9755d20ab8decfe4f326f9b90c895e4
|
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
|
/Common/Scd/ScHist/hstqyinf.h
|
77cc78d14becc2e0340f28d6f91903b5a3d94199
|
[] |
no_license
|
abcweizhuo/Test3
|
0f3379e528a543c0d43aad09489b2444a2e0f86d
|
128a4edcf9a93d36a45e5585b70dee75e4502db4
|
refs/heads/master
| 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,426 |
h
|
//================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#ifndef __HSTQYINF_H
#define __HSTQYINF_H
#include "resource.h"
//-------------------------------------------------------------------------
const short MaxQueryInfoStats = 10;
class CQueryInfo : public CDialog
{
public:
CQueryInfo(CWnd* pParent = NULL); // standard constructor
//{{AFX_DATA(CQueryInfo)
enum { IDD = IDD_QUERYINFO };
int m_LocalCnt;
int m_RemoteCnt;
CString m_LocalPer;
CString m_RemotePer;
CString m_LocalPerBest;
CString m_RemotePerBest;
//}}AFX_DATA
protected:
CQueryInfoStats LocalStats[MaxQueryInfoStats];
CQueryInfoStats RemoteStats[MaxQueryInfoStats];
int FindLocal(long ID);
int FindRemote(long ID);
int FindLocalMin();
int FindLocalMax();
int FindRemoteMin();
int FindRemoteMax();
//{{AFX_VIRTUAL(CQueryInfo)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
protected:
//{{AFX_MSG(CQueryInfo)
afx_msg LRESULT OnUpdateData(WPARAM wParam, LPARAM lParam);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
extern CQueryInfo* gs_pQueryInfo;
#endif
//-------------------------------------------------------------------------
|
[
"[email protected]"
] |
[
[
[
1,
55
]
]
] |
51d24d2c0f6b2b85598a51d691e348fa7fb69087
|
3e69b159d352a57a48bc483cb8ca802b49679d65
|
/tags/release-2006-01-13/3d-viewer/3d_viewer.h
|
1c3202db2fa121afc561128b58346de8cd7ac626
|
[] |
no_license
|
BackupTheBerlios/kicad-svn
|
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
|
4c97bbde4b1b12ec5616a57c17298c77a9790398
|
refs/heads/master
| 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,309 |
h
|
/////////////////////////////////////////////////////////////////////////////
// Name: 3d_viewer.h
/////////////////////////////////////////////////////////////////////////////
#if !wxUSE_GLCANVAS
#error Please set wxUSE_GLCANVAS to 1 in setup.h.
#endif
#include "wx/glcanvas.h"
#ifdef __WXMAC__
# ifdef __DARWIN__
# include <OpenGL/gl.h>
# include <OpenGL/glu.h>
# else
# include <gl.h>
# include <glu.h>
# endif
#else
# include <GL/gl.h>
# include <GL/glu.h>
#endif
#ifdef VIEWER_MAIN
#define global_3d
#else
#define global_3d extern
#endif
#include "pcbstruct.h"
#define LIB3D_PATH wxT("packages3d/")
class Pcb3D_GLCanvas;
class WinEDA3D_DrawFrame;
class Info_3D_Visu;
class S3D_Vertex;
class SEGVIA;
#define m_ROTX m_Rot[0]
#define m_ROTY m_Rot[1]
#define m_ROTZ m_Rot[2]
/* information needed to display 3D board */
class Info_3D_Visu
{
public:
float m_Beginx, m_Beginy; /* position of mouse */
float m_Quat[4]; /* orientation of object */
float m_Rot[4]; /* man rotation of object */
float m_Zoom; /* field of view in degrees */
wxPoint m_BoardPos;
wxSize m_BoardSize;
int m_Layers;
EDA_BoardDesignSettings * m_BoardSettings; // Link to current board design settings
float m_Epoxy_Width; /* Epoxy tickness (normalized) */
float m_BoardScale; /* Normalisation scale for coordinates:
when scaled tey are between -1.0 and +1.0 */
float m_LayerZcoord[32];
public:
Info_3D_Visu(void);
~Info_3D_Visu(void);
};
class Pcb3D_GLCanvas: public wxGLCanvas
{
public:
WinEDA3D_DrawFrame * m_Parent;
private:
bool m_init;
GLuint m_gllist;
public:
Pcb3D_GLCanvas(WinEDA3D_DrawFrame *parent, const wxWindowID id = -1,
int* gl_attrib = NULL);
~Pcb3D_GLCanvas(void);
void ClearLists(void);
void OnPaint(wxPaintEvent& event);
void OnSize(wxSizeEvent& event);
void OnEraseBackground(wxEraseEvent& event);
void OnChar(wxKeyEvent& event);
void OnMouseEvent(wxMouseEvent& event);
void OnRightClick(wxMouseEvent& event);
void OnPopUpMenu(wxCommandEvent & event);
void TakeScreenshot(wxCommandEvent & event);
void SetView3D(int keycode);
void DisplayStatus(void);
void Redraw(void);
GLuint DisplayCubeforTest(void);
void OnEnterWindow( wxMouseEvent& event );
void Render( void );
GLuint CreateDrawGL_List(void);
void InitGL(void);
void SetLights(void);
void Draw3D_Track(TRACK * track);
void Draw3D_Via(SEGVIA * via);
void Draw3D_DrawSegment(DRAWSEGMENT * segment);
DECLARE_EVENT_TABLE()
};
class WinEDA3D_DrawFrame: public wxFrame
{
public:
WinEDA_BasePcbFrame * m_Parent;
WinEDA_App * m_ParentAppl;
Pcb3D_GLCanvas * m_Canvas;
wxToolBar * m_HToolBar;
wxToolBar * m_VToolBar;
int m_InternalUnits;
wxPoint m_FramePos;
wxSize m_FrameSize;
private:
wxString m_FrameName; // name used for writting and reading setup
// It is "Frame3D"
public:
WinEDA3D_DrawFrame::WinEDA3D_DrawFrame(WinEDA_BasePcbFrame * parent, WinEDA_App *app_parent,
const wxString& title );
void Exit3DFrame(wxCommandEvent& event);
void OnCloseWindow(wxCloseEvent & Event);
void ReCreateMenuBar(void);
void ReCreateHToolbar(void);
void ReCreateVToolbar(void);
void SetToolbars(void);
void GetSettings(void);
void SaveSettings(void);
void OnLeftClick(wxDC * DC, const wxPoint& MousePos);
void OnRightClick(const wxPoint& MousePos, wxMenu * PopMenu);
void OnKeyEvent(wxKeyEvent& event);
int BestZoom(void); // Retourne le meilleur zoom
void RedrawActiveWindow(wxDC * DC, bool EraseBg);
void Process_Special_Functions(wxCommandEvent& event);
void Process_Zoom(wxCommandEvent& event);
void NewDisplay(void);
DECLARE_EVENT_TABLE()
};
void SetGLColor(int color);
void Set_Object_Data(const S3D_Vertex * coord, int nbcoord );
global_3d Info_3D_Visu g_Parm_3D_Visu;
global_3d double Draw3d_dx, Draw3d_dy;
global_3d double ZBottom, ZTop;
global_3d double DataScale3D; // coeff de conversion unites utilsateut -> unites 3D
global_3d int gl_attrib[]
#ifdef VIEWER_MAIN
= { WX_GL_RGBA, WX_GL_MIN_RED, 8, WX_GL_MIN_GREEN, 8,
WX_GL_MIN_BLUE, 8, WX_GL_DEPTH_SIZE, 16,
WX_GL_DOUBLEBUFFER,
GL_NONE }
#endif
;
|
[
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] |
[
[
[
1,
169
]
]
] |
74c11cc1dd9bb8ed73c5ac875c4a25d968a27fb6
|
bc3073755ed70dd63a7c947fec63ccce408e5710
|
/src/Game/Graphics/VertexBufferObject.h
|
c2e761527fa0516499d4163cbc07a9bb981ef44e
|
[] |
no_license
|
ptrefall/ste6274gamedesign
|
9e659f7a8a4801c5eaa060ebe2d7edba9c31e310
|
7d5517aa68910877fe9aa98243f6bb2444d533c7
|
refs/heads/master
| 2016-09-07T18:42:48.012493 | 2011-10-13T23:41:40 | 2011-10-13T23:41:40 | 32,448,466 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,055 |
h
|
#pragma once
#include "IBufferObject.h"
#include "Utils.h"
namespace Graphics
{
class VertexBufferObject : public IBufferObject
{
public:
/// VertexBufferObject constructor.
VertexBufferObject(const U32 size,
const U32 index_count,
const U32 *indices,
const U32 draw_type);
VertexBufferObject(const U32 size,
const U32 draw_type);
/// VertexBufferObject destructor.
virtual ~VertexBufferObject();
///
virtual bool bind(const U32 &shader_id);
///
void buffer(const T_String &attrib,
const U32 &attrib_count,
const U32 &type,
const U32 &count,
const void *data,
const S32 &attrib_location = -1);
void buffer(const U32 &type,
const U32 &count,
const void *data);
///
virtual void unbind();
U32 getBoundOffset() const { return bound_offset; }
void bindIndices();
void unbindIndices();
protected:
bool has_indices;
U32 index_id;
U32 bound_shader_id;
U32 bound_offset;
bool indices_bound;
};
typedef VertexBufferObject VBO;
}
|
[
"[email protected]@2c5777c1-dd38-1616-73a3-7306c0addc79"
] |
[
[
[
1,
53
]
]
] |
16c2384ca33786d697f258901c749d72d9373406
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/multi_index/test/test_hash_ops.cpp
|
a0662066d4c7c26174217c3c768e6de428b15e9b
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
willrebuild/flyffsf
|
e5911fb412221e00a20a6867fd00c55afca593c7
|
d38cc11790480d617b38bb5fc50729d676aef80d
|
refs/heads/master
| 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null |
ISO-8859-1
|
C++
| false | false | 2,473 |
cpp
|
/* Boost.MultiIndex test for standard hash operations.
*
* Copyright 2003-2005 Joaquín M López Muñoz.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/libs/multi_index for library home page.
*/
#include "test_hash_ops.hpp"
#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <iterator>
#include "pre_multi_index.hpp"
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>
#include <iostream>
using namespace boost::multi_index;
template<typename HashedContainer>
void check_load_factor(const HashedContainer& hc)
{
float lf=(float)hc.size()/hc.bucket_count();
BOOST_CHECK_CLOSE(lf,hc.load_factor(),1.E-6f);
BOOST_CHECK(lf<=hc.max_load_factor()+1.E-6);
}
typedef multi_index_container<
int,
indexed_by<
hashed_unique<identity<int> >
>
> hash_container;
void test_hash_ops()
{
hash_container hc;
BOOST_CHECK(hc.max_load_factor()==1.0f);
BOOST_CHECK(hc.bucket_count()<=hc.max_bucket_count());
hc.insert(1000);
hash_container::size_type buc=hc.bucket(1000);
hash_container::local_iterator it0=hc.begin(buc);
hash_container::local_iterator it1=hc.end(buc);
BOOST_CHECK(
(hash_container::size_type)std::distance(it0,it1)==hc.bucket_size(buc)&&
hc.bucket_size(buc)==1&&*it0==1000);
hc.clear();
for(hash_container::size_type s=2*hc.bucket_count();s--;){
hc.insert((int)s);
}
check_load_factor(hc);
hc.max_load_factor(0.5f);
BOOST_CHECK(hc.max_load_factor()==0.5f);
hc.insert(-1);
check_load_factor(hc);
hc.rehash(1);
BOOST_CHECK(hc.bucket_count()>=1);
check_load_factor(hc);
hc.max_load_factor(0.25f);
hc.rehash(1);
BOOST_CHECK(hc.bucket_count()>=1);
check_load_factor(hc);
hash_container::size_type bc=4*hc.bucket_count();
hc.max_load_factor(0.125f);
hc.rehash(bc);
BOOST_CHECK(hc.bucket_count()>=bc);
check_load_factor(hc);
bc=2*hc.bucket_count();
hc.rehash(bc);
BOOST_CHECK(hc.bucket_count()>=bc);
check_load_factor(hc);
hc.clear();
hc.insert(0);
hc.rehash(1);
BOOST_CHECK(hc.bucket_count()>=1);
check_load_factor(hc);
}
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
93
]
]
] |
dfdfb0ce778fe48e5ed9a7d4bf0e5891bca3b254
|
f177993b13e97f9fecfc0e751602153824dfef7e
|
/ImProSln/TouchLibFilter/Touchlib/src/RectifyFilter.cpp
|
86c6cab302a15cb8edc02256de736e8af6bbe71e
|
[] |
no_license
|
svn2github/imtophooksln
|
7bd7412947d6368ce394810f479ebab1557ef356
|
bacd7f29002135806d0f5047ae47cbad4c03f90e
|
refs/heads/master
| 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,631 |
cpp
|
#include <RectifyFilter.h>
#include <highgui.h>
#include <Image.h>
RectifyFilter::RectifyFilter(char* s) : Filter(s)
{
level = (unsigned int) DEFAULT_RECTIFYLEVEL;
level_slider = level;
bAutoSet = false;
}
RectifyFilter::~RectifyFilter()
{
}
void RectifyFilter::getParameters(ParameterMap& pMap)
{
pMap[std::string("level")] = bAutoSet ? std::string("auto") : toString(level);
}
void RectifyFilter::setParameter(const char *name, const char *value)
{
if(strcmp(name, "level") == 0)
{
if(strcmp(value, "auto") == 0)
{
bAutoSet = true;
printf("Auto set\n");
} else
{
level = (int) atof(value);
level_slider = level;
if(show)
cvSetTrackbarPos("level", this->name.c_str(), level);
}
}
}
void RectifyFilter::showOutput(bool value, int windowx, int windowy)
{
Filter::showOutput(value, windowx, windowy);
if(value)
{
cvCreateTrackbar( "level", name.c_str(), &level_slider, 255, NULL);
}
}
void RectifyFilter::kernel()
{
level = level_slider;
// derived class responsible for allocating storage for filtered image
if( !destination )
{
destination = cvCreateImage(cvSize(source->width,source->height), source->depth, 1);
destination->origin = source->origin; // same vertical flip as source
}
if(bAutoSet)
{
touchlib::BwImage img(source);
int h, w;
h = img.getHeight();
w = img.getWidth();
unsigned char highest = 0;
for(int y=0; y<h; y++)
for(int x=0; x<w; x++)
{
if(img[y][x] > highest)
highest = img[y][x];
}
setLevel((unsigned int)highest);
bAutoSet = false;
}
cvThreshold(source, destination, level, 255, CV_THRESH_TOZERO); //CV_THRESH_BINARY
}
void RectifyFilter::kernelWithROI()
{
level = level_slider;
// derived class responsible for allocating storage for filtered image
if( !destination )
{
destination = cvCreateImage(cvSize(source->width,source->height), source->depth, 1);
destination->origin = source->origin; // same vertical flip as source
}
cvZero(destination);
CvRect roiRECT = cvGetImageROI(source);
cvSetImageROI(destination, roiRECT);
if(bAutoSet)
{
touchlib::BwImage img(source);
int h, w;
h = img.getHeight();
w = img.getWidth();
unsigned char highest = 0;
for(int y=0; y<h; y++)
for(int x=0; x<w; x++)
{
if(img[y][x] > highest)
highest = img[y][x];
}
setLevel((unsigned int)highest);
bAutoSet = false;
}
cvThreshold(source, destination, level, 255, CV_THRESH_TOZERO); //CV_THRESH_BINARY
}
|
[
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
] |
[
[
[
1,
123
]
]
] |
0a0347e1a996d20f6f1b1653dc7ad0f19456518b
|
55196303f36aa20da255031a8f115b6af83e7d11
|
/private/external/gameswf/base/tu_timer.cpp
|
34e75c410e9e514c8b5944303f19afa5040ae6fa
|
[] |
no_license
|
Heartbroken/bikini
|
3f5447647d39587ffe15a7ae5badab3300d2a2ff
|
fe74f51a3a5d281c671d303632ff38be84d23dd7
|
refs/heads/master
| 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,066 |
cpp
|
// tu_timer.cpp -- by Thatcher Ulrich <[email protected]>
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
// Utility/profiling timer.
#include <time.h> // [ANSI/System V]
#include "base/tu_timer.h"
Uint64 tu_timer::get_systime()
// Returns the time as seconds elapsed since midnight, January 1, 1970.
{
time_t ltime;
time(<ime);
return ltime;
}
int tu_timer::get_date(Uint64 t)
// Returns the day of the month (an integer from 1 to 31)
{
time_t ltime = t;
struct tm* gmt = localtime(<ime);
return gmt->tm_mday;
}
int tu_timer::get_day(Uint64 t)
// Returns the day of the week (0 for Sunday, 1 for Monday, and so on)
{
time_t ltime = t;
struct tm* gmt = localtime(<ime);
return gmt->tm_wday;
}
int tu_timer::get_hours(Uint64 t)
// Returns the hour (an integer from 0 to 23)
{
time_t ltime = t;
struct tm* gmt = localtime(<ime);
return gmt->tm_hour;
}
int tu_timer::get_fullyear(Uint64 t)
// Returns the full year (a four-digit number, such as 2000)
{
time_t ltime = t;
struct tm* gmt = localtime(<ime);
return gmt->tm_year + 1900;
}
int tu_timer::get_milli(Uint64 t)
// Returns the milliseconds (an integer from 0 to 999)
{
return 0; // TODO
}
int tu_timer::get_month(Uint64 t)
// Returns the month (0 for January, 1 for February, and so on)
{
time_t ltime = t;
struct tm* gmt = localtime(<ime);
return gmt->tm_mon;
}
int tu_timer::get_minutes(Uint64 t)
// Returns the minutes (an integer from 0 to 59)
{
time_t ltime = t;
struct tm* gmt = localtime(<ime);
return gmt->tm_min;
}
int tu_timer::get_seconds(Uint64 t)
// Returns the seconds (an integer from 0 to 59)
{
time_t ltime = t;
struct tm* gmt = localtime(<ime);
return gmt->tm_sec;
}
int tu_timer::get_year(Uint64 t)
// Returns the seconds (an integer from 0 to 59)
{
time_t ltime = t;
struct tm* gmt = localtime(<ime);
return gmt->tm_year;
}
Uint64 tu_timer::get_time(Uint64 t)
// Returns the number of milliseconds since midnight January 1, 1970, universal time
{
time_t ltime = t;
struct tm* gmt = localtime(<ime);
return t * 1000; // TODO: add milliseconds
}
#ifdef _WIN32
#include <windows.h>
uint64 tu_timer::get_ticks()
{
return timeGetTime();
}
double tu_timer::ticks_to_seconds(uint64 ticks)
{
return ticks * (1.0f / 1000.f);
}
double tu_timer::ticks_to_seconds()
{
return get_ticks() * (1.0f / 1000.f);
}
void tu_timer::sleep(int milliseconds)
{
::Sleep(milliseconds);
}
uint64 tu_timer::get_profile_ticks()
{
// @@ use rdtsc?
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return li.QuadPart;
}
double tu_timer::profile_ticks_to_seconds(uint64 ticks)
{
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
double seconds = (double) ticks;
seconds /= (double) freq.QuadPart;
return seconds;
}
#else // not _WIN32
#include <sys/time.h>
#include <unistd.h>
// The profile ticks implementation is just fine for a normal timer.
uint64 tu_timer::get_ticks()
{
return profile_ticks_to_milliseconds(get_profile_ticks());
}
double tu_timer::ticks_to_seconds(uint64 ticks)
{
return profile_ticks_to_seconds(ticks);
}
void tu_timer::sleep(int milliseconds)
{
usleep(milliseconds * 1000);
}
uint64 tu_timer::get_profile_ticks()
{
// @@ TODO prefer rdtsc when available?
// Return microseconds.
struct timeval tv;
uint64 result;
gettimeofday(&tv, 0);
result = tv.tv_sec * 1000000;
result += tv.tv_usec;
return result;
}
double tu_timer::profile_ticks_to_seconds(uint64 ticks)
{
// ticks is microseconds. Convert to seconds.
return ticks / 1000000.0;
}
double tu_timer::profile_ticks_to_milliseconds(uint64 ticks)
{
// ticks is microseconds. Convert to milliseconds.
return ticks / 1000.0;
}
#endif // not _WIN32
// Local Variables:
// mode: C++
// c-basic-offset: 8
// tab-width: 8
// indent-tabs-mode: t
// End:
|
[
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
] |
[
[
[
1,
215
]
]
] |
42617972d83593da75874478a97cb71bd134f710
|
6e563096253fe45a51956dde69e96c73c5ed3c18
|
/dhnetsdk/Demo/ExtPtzCtrl.h
|
f5945f07bed9948d8d06aa1da1bd36efcc871923
|
[] |
no_license
|
15831944/phoebemail
|
0931b76a5c52324669f902176c8477e3bd69f9b1
|
e10140c36153aa00d0251f94bde576c16cab61bd
|
refs/heads/master
| 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,309 |
h
|
#if !defined(_ExtPtzCtrl_H_)
#define _ExtPtzCtrl_H_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// ExtPtzCtrl.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CExtPtzCtrl dialog
class CExtPtzCtrl : public CDialog
{
LONG m_DeviceID ;
DWORD m_Channel ;
// Construction
public:
CExtPtzCtrl(CWnd* pParent = NULL); // standard constructor
void SetExtPtzParam(LONG iHandle, int iChannel);
void PtzExtControl(DWORD dwCommand, DWORD dwParam = 0);
// Dialog Data
//{{AFX_DATA(CExtPtzCtrl)
enum { IDD = IDD_EXT_PTZCTRL };
CComboBox m_auxNosel;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CExtPtzCtrl)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CExtPtzCtrl)
virtual BOOL OnInitDialog();
afx_msg void OnSelchangePtzTab(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnPresetAdd();
afx_msg void OnPresetDele();
afx_msg void OnPresetSet();
afx_msg void OnCruiseAddPoint();
afx_msg void OnCruiseDelPoint();
afx_msg void OnCruiseDelGroup();
afx_msg void OnStartCruise();
afx_msg void OnStopCruise();
afx_msg void OnLampActivate();
afx_msg void OnLampDeactivate();
afx_msg void OnRotateStart();
afx_msg void OnRotateStop();
afx_msg void OnLineSetLeft();
afx_msg void OnLineSetRight();
afx_msg void OnLineStart();
afx_msg void OnLineStop();
afx_msg void OnModeSetBegin();
afx_msg void OnModeSetDelete();
afx_msg void OnModeSetEnd();
afx_msg void OnModeStart();
afx_msg void OnModeStop();
afx_msg void OnQueryAlarm();
afx_msg void OnFastGo();
afx_msg void OnAuxOpen();
afx_msg void OnAuxClose();
afx_msg void OnLightOpen();
afx_msg void OnLightClose();
afx_msg void OnTest();
afx_msg void OnTest2();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
UINT m_presetPoint;
UINT m_cruiseGroup;
UINT m_modeNo;
UINT m_pos_x;
UINT m_pos_y;
UINT m_pos_zoom;
UINT m_auxNo;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(_ExtPtzCtrl_H_)
|
[
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
] |
[
[
[
1,
91
]
]
] |
7248b57b9ebe1fadf7588eb8b6b9e1c208467515
|
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
|
/code/inc/util/nstl.h
|
a70c4c42e61c74284dbe0696e233d16a9d5fe6f9
|
[] |
no_license
|
DSPNerd/m-nebula
|
76a4578f5504f6902e054ddd365b42672024de6d
|
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
|
refs/heads/master
| 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,847 |
h
|
#ifndef N_STL_H
#define N_STL_H
#ifndef NO_STLPORT
#include "stlport/vector"
#include "stlport/algorithm"
#include "stlport/deque"
#include "stlport/list"
#include "stlport/string"
#include "stlport/map"
#include "stlport/stack"
#else
#include <vector>
#include <algorithm>
#include <deque>
#include <list>
#include <string>
#include <map>
#include <stack>
#endif
#ifdef ULONG_MAX
#define UNSETU ULONG_MAX
#else
#define UNSETU 0xffffffffUL
#endif
typedef std::wstring stl_wstring;
typedef std::deque<float> floats_q;
typedef std::vector<long> longs_v;
typedef std::deque<long> longs_q;
typedef std::list<long> longs_l;
typedef std::vector<short> shorts_t;
#define STRING_RESERVE 256
class stl_string : public std::string
{
public:
stl_string() { this->reserve(STRING_RESERVE); }
stl_string(const char* s)
{
this->reserve(STRING_RESERVE);
this->assign(s);
}
stl_string(const stl_string& s)
{
this->reserve(STRING_RESERVE);
this->assign(s);
}
stl_string(const std::string& s)
{
this->reserve(STRING_RESERVE);
this->assign(s);
}
stl_string& operator=(const stl_string& s)
{
this->assign(s); return *this;
}
stl_string& operator=(const std::string& s)
{
this->assign(s); return *this;
}
stl_string& operator=(const char* s)
{
this->assign(s); return *this;
}
const char* c_str() const
{
if (!this->empty())
return std::string::c_str();
else
return 0;
}
};
typedef std::vector<stl_string> strings_v;
class byte_buffer : public std::vector<unsigned char> {
public:
unsigned char* get_buffer() {
return &((*this)[0]);
}
};
class char_buffer : public std::vector<char> {
public:
char* get_buffer() {
return &((*this)[0]);
}
};
#endif
|
[
"plushe@411252de-2431-11de-b186-ef1da62b6547"
] |
[
[
[
1,
100
]
]
] |
4d8af79302499eb348b2200635765eaa853ea1b4
|
25493e63fc39f89bcc09efd697c840756a5d1d47
|
/SeaBattle/SeaBattle.Cpp/MainForm.cpp
|
fb6ca84da7bb448da4c5b408a34bfa8dcbd57f44
|
[] |
no_license
|
Strialck/Sea-Battle-Game
|
ada96874328860a4b45cc307f97e0537df932937
|
05c4fdf317c88e6ef22cd0b37b5a94076f7c8674
|
refs/heads/master
| 2022-02-14T01:17:42.530402 | 2011-12-26T23:49:43 | 2011-12-26T23:49:43 | null | 0 | 0 | null | null | null | null |
ISO-8859-13
|
C++
| false | false | 3,748 |
cpp
|
#include "stdafx.h"
#include "MainForm.h"
MainForm::MainForm()
{
SuspendLayout();
_humanBoard = gcnew Board();
_computerBoard = gcnew Board(false);
_humanPlayer = gcnew HumanPlayer("Žaidėjas", _computerBoard);
_computerPlayer = gcnew ComputerPlayer("Kompiuteris");
_scoreboard = gcnew ScoreBoard(_humanPlayer, _computerPlayer, 10, 100);
_controller = gcnew GameController(_humanPlayer, _computerPlayer, _humanBoard, _computerBoard, _scoreboard);
_shuffleButton = CreateButton(ShuffleCharacter.ToString(), ButtonBackColor);
_newGameButton = CreateButton(NewGameCharacter.ToString(), ButtonBackColor);
_startGameButton = CreateButton(StartGameCharacter.ToString(), ButtonBackColor);
SetupWindow();
LayoutControls();
_scoreboard->GameEnded += gcnew EventHandler(this, &MainForm::OnGameEnded);
_shuffleButton->Click += gcnew System::EventHandler(this, &MainForm::OnShuffleButtonClick);
_startGameButton->Click += gcnew System::EventHandler(this, &MainForm::OnStartGameButtonClick);
_newGameButton->Click += gcnew System::EventHandler(this, &MainForm::OnNewGameButtonClick);
ResumeLayout();
StartNewGame();
};
void MainForm::OnNewGameButtonClick(Object^ sender, EventArgs^ e)
{
StartNewGame();
};
void MainForm::StartNewGame()
{
_shuffleButton->Visible = true;
_startGameButton->Visible = true;
_newGameButton->Visible = false;
_controller->NewGame();
};
void MainForm::OnStartGameButtonClick(Object^ sender, EventArgs^ e)
{
_shuffleButton->Visible = false;
_newGameButton->Visible = false;
_startGameButton->Visible = false;
_controller->StartGame();
};
void MainForm::OnShuffleButtonClick(Object^ sender, EventArgs^ e)
{
_humanBoard->AddRandomShips();
};
void MainForm::OnGameEnded(Object^ sender, EventArgs^ e)
{
_shuffleButton->Visible = false;
_startGameButton->Visible = false;
_newGameButton->Visible = true;
_computerBoard->ShowShips();
};
void MainForm::SetupWindow()
{
AutoScaleDimensions = SizeF(8, 19);
AutoScaleMode = Windows::Forms::AutoScaleMode::Font;
Font = gcnew Drawing::Font("Calibri", 10, FontStyle::Regular, GraphicsUnit::Point, 186);
Margin = Windows::Forms::Padding::Empty;
Text = "SeaBattle.C++";
BackColor = Color::FromArgb(235, 235, 235);
FormBorderStyle = Windows::Forms::FormBorderStyle::FixedSingle;
StartPosition = FormStartPosition::CenterScreen;
MaximizeBox = false;
};
Button^ MainForm::CreateButton(String^ text, Color backColor)
{
Button^ button = gcnew Button;
button->FlatStyle = FlatStyle::Flat;
button->ForeColor = Color::White;
button->BackColor = backColor;
button->UseVisualStyleBackColor = false;
button->Size = Drawing::Size(40, 40);
button->Text = text;
button->Font = gcnew Drawing::Font("Webdings", 24, FontStyle::Regular, GraphicsUnit::Point);
button->TextAlign = ContentAlignment::TopCenter;
button->FlatAppearance->BorderSize = 0;
return button;
};
void MainForm::LayoutControls()
{
_humanBoard->Location = Point(0, 0);
_computerBoard->Location = Point(_humanBoard->Right, 0);
_scoreboard->Location = Point(25, _humanBoard->Bottom);
_scoreboard->Width = _computerBoard->Right - 25;
_newGameButton->Location = Point(_computerBoard->Right - _newGameButton->Width, _scoreboard->Bottom);
_startGameButton->Location = _newGameButton->Location;
_shuffleButton->Location = Point(_newGameButton->Location.X - _shuffleButton->Width - 25, _newGameButton->Location.Y);
Controls->AddRange(gcnew array<Control^> {_humanBoard, _computerBoard, _scoreboard, _newGameButton, _startGameButton, _shuffleButton});
ClientSize = Drawing::Size(_computerBoard->Right + 25, _startGameButton->Bottom + 25);
}
|
[
"[email protected]"
] |
[
[
[
1,
112
]
]
] |
9abb240c2720b7ed08060b5937466b02051579cd
|
13f30850677b4b805aeddbad39cd9369d7234929
|
/ astrocytes --username [email protected]/CT_tutorial/VboMesh.h
|
6e0665189ca55aaaf6585781a70e7499870934d4
|
[] |
no_license
|
hksonngan/astrocytes
|
2548c73bbe45ea4db133e465fa8a90d29dc60f64
|
e14544d21a077cdbc05356b05148cc408c255e04
|
refs/heads/master
| 2021-01-10T10:04:14.265392 | 2011-11-09T07:42:06 | 2011-11-09T07:42:06 | 46,898,541 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 457 |
h
|
#ifndef VBO_MESH_INC
#define VBO_MESH_INC
#include "GeomFunc.h"
#include "mat34.h"
#include "vec4.h"
#include "vec.h"
#include "CS3.h"
#include "AllInc.h"
#include "wxIncludes.h"
class VboMesh
{
public:
VboMesh();
~VboMesh();
void Build(v3vec& vert, v3vec& norm, v4vec& col, iv3vec& id);
void Clear();
void Draw();
bool Enabled(){return vertexID;};
private:
unsigned vertexID,colorID,normalID, indexID, iNum;
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
27
]
]
] |
a6334d5b96a347f61113361b107565b014802f9f
|
9a48be80edc7692df4918c0222a1640545384dbb
|
/Libraries/Boost1.40/libs/asio/test/buffered_read_stream.cpp
|
7f80f583f514bbe1b98a4ffaf1ffb298378c2a48
|
[
"BSL-1.0"
] |
permissive
|
fcrick/RepSnapper
|
05e4fb1157f634acad575fffa2029f7f655b7940
|
a5809843f37b7162f19765e852b968648b33b694
|
refs/heads/master
| 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,909 |
cpp
|
//
// buffered_read_stream.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include <boost/asio/buffered_read_stream.hpp>
#include <boost/bind.hpp>
#include <cstring>
#include <boost/asio.hpp>
#include "unit_test.hpp"
typedef boost::asio::buffered_read_stream<
boost::asio::ip::tcp::socket> stream_type;
void test_sync_operations()
{
using namespace std; // For memcmp.
boost::asio::io_service io_service;
boost::asio::ip::tcp::acceptor acceptor(io_service,
boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0));
boost::asio::ip::tcp::endpoint server_endpoint = acceptor.local_endpoint();
server_endpoint.address(boost::asio::ip::address_v4::loopback());
stream_type client_socket(io_service);
client_socket.lowest_layer().connect(server_endpoint);
stream_type server_socket(io_service);
acceptor.accept(server_socket.lowest_layer());
const char write_data[]
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const boost::asio::const_buffer write_buf = boost::asio::buffer(write_data);
std::size_t bytes_written = 0;
while (bytes_written < sizeof(write_data))
{
bytes_written += client_socket.write_some(
boost::asio::buffer(write_buf + bytes_written));
}
char read_data[sizeof(write_data)];
const boost::asio::mutable_buffer read_buf = boost::asio::buffer(read_data);
std::size_t bytes_read = 0;
while (bytes_read < sizeof(read_data))
{
bytes_read += server_socket.read_some(
boost::asio::buffer(read_buf + bytes_read));
}
BOOST_CHECK(bytes_written == sizeof(write_data));
BOOST_CHECK(bytes_read == sizeof(read_data));
BOOST_CHECK(memcmp(write_data, read_data, sizeof(write_data)) == 0);
bytes_written = 0;
while (bytes_written < sizeof(write_data))
{
bytes_written += server_socket.write_some(
boost::asio::buffer(write_buf + bytes_written));
}
bytes_read = 0;
while (bytes_read < sizeof(read_data))
{
bytes_read += client_socket.read_some(
boost::asio::buffer(read_buf + bytes_read));
}
BOOST_CHECK(bytes_written == sizeof(write_data));
BOOST_CHECK(bytes_read == sizeof(read_data));
BOOST_CHECK(memcmp(write_data, read_data, sizeof(write_data)) == 0);
server_socket.close();
boost::system::error_code error;
bytes_read = client_socket.read_some(
boost::asio::buffer(read_buf), error);
BOOST_CHECK(bytes_read == 0);
BOOST_CHECK(error == boost::asio::error::eof);
client_socket.close(error);
}
void handle_accept(const boost::system::error_code& e)
{
BOOST_CHECK(!e);
}
void handle_write(const boost::system::error_code& e,
std::size_t bytes_transferred,
std::size_t* total_bytes_written)
{
BOOST_CHECK(!e);
if (e)
throw boost::system::system_error(e); // Terminate test.
*total_bytes_written += bytes_transferred;
}
void handle_read(const boost::system::error_code& e,
std::size_t bytes_transferred,
std::size_t* total_bytes_read)
{
BOOST_CHECK(!e);
if (e)
throw boost::system::system_error(e); // Terminate test.
*total_bytes_read += bytes_transferred;
}
void handle_read_eof(const boost::system::error_code& e,
std::size_t bytes_transferred)
{
BOOST_CHECK(e == boost::asio::error::eof);
BOOST_CHECK(bytes_transferred == 0);
}
void test_async_operations()
{
using namespace std; // For memcmp.
boost::asio::io_service io_service;
boost::asio::ip::tcp::acceptor acceptor(io_service,
boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0));
boost::asio::ip::tcp::endpoint server_endpoint = acceptor.local_endpoint();
server_endpoint.address(boost::asio::ip::address_v4::loopback());
stream_type client_socket(io_service);
client_socket.lowest_layer().connect(server_endpoint);
stream_type server_socket(io_service);
acceptor.async_accept(server_socket.lowest_layer(), handle_accept);
io_service.run();
io_service.reset();
const char write_data[]
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const boost::asio::const_buffer write_buf = boost::asio::buffer(write_data);
std::size_t bytes_written = 0;
while (bytes_written < sizeof(write_data))
{
client_socket.async_write_some(
boost::asio::buffer(write_buf + bytes_written),
boost::bind(handle_write, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred, &bytes_written));
io_service.run();
io_service.reset();
}
char read_data[sizeof(write_data)];
const boost::asio::mutable_buffer read_buf = boost::asio::buffer(read_data);
std::size_t bytes_read = 0;
while (bytes_read < sizeof(read_data))
{
server_socket.async_read_some(
boost::asio::buffer(read_buf + bytes_read),
boost::bind(handle_read, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred, &bytes_read));
io_service.run();
io_service.reset();
}
BOOST_CHECK(bytes_written == sizeof(write_data));
BOOST_CHECK(bytes_read == sizeof(read_data));
BOOST_CHECK(memcmp(write_data, read_data, sizeof(write_data)) == 0);
bytes_written = 0;
while (bytes_written < sizeof(write_data))
{
server_socket.async_write_some(
boost::asio::buffer(write_buf + bytes_written),
boost::bind(handle_write, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred, &bytes_written));
io_service.run();
io_service.reset();
}
bytes_read = 0;
while (bytes_read < sizeof(read_data))
{
client_socket.async_read_some(
boost::asio::buffer(read_buf + bytes_read),
boost::bind(handle_read, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred, &bytes_read));
io_service.run();
io_service.reset();
}
BOOST_CHECK(bytes_written == sizeof(write_data));
BOOST_CHECK(bytes_read == sizeof(read_data));
BOOST_CHECK(memcmp(write_data, read_data, sizeof(write_data)) == 0);
server_socket.close();
client_socket.async_read_some(boost::asio::buffer(read_buf), handle_read_eof);
}
test_suite* init_unit_test_suite(int, char*[])
{
test_suite* test = BOOST_TEST_SUITE("buffered_read_stream");
test->add(BOOST_TEST_CASE(&test_sync_operations));
test->add(BOOST_TEST_CASE(&test_async_operations));
return test;
}
|
[
"metrix@Blended.(none)"
] |
[
[
[
1,
218
]
]
] |
cf04db93ce0cc96b01b9cef5c088c35665c79735
|
0ede2660af1a4a0e17415c5a2ab0d5da2108d2c4
|
/Header Files/FILE_OPERATIONS_H.h
|
f94728c864a65f7063d81188442d752dbcf93475
|
[] |
no_license
|
arcshock/uaf-cs-f202-rush-hour
|
9222c55f9efd683d6497f49abf7a834bc849a186
|
ad9428b786c075d1ff87fc07cd4b1470b46012b7
|
refs/heads/master
| 2020-06-04T07:10:37.171480 | 2011-12-06T04:49:52 | 2011-12-06T04:49:52 | 33,420,443 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 100 |
h
|
#ifndef FILE_OPERATIONS_H
#include <fstream>
using std::ofstream;
using std::ifstream;
#endif
|
[
"[email protected]@422ca6b0-c5e4-5437-1708-20c6819369f4"
] |
[
[
[
1,
5
]
]
] |
d550c4890ee22f4937a2c4dc684eca6dd153115c
|
77d0b0ac21a9afdf667099c3cad0f9bbb483dc25
|
/include/document.h
|
fcc2df7d20c8abdd734221fb3ccc29c90c7f15d0
|
[] |
no_license
|
martinribelotta/oneshot
|
21e218bbdfc310bad4a531dcd401ad28625ead75
|
81bde2718b6dac147282cce8a1c945187b0b2ccf
|
refs/heads/master
| 2021-05-27T23:29:43.732068 | 2010-05-24T04:36:10 | 2010-05-24T04:36:10 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 787 |
h
|
#ifndef Oneshot_QDocument_h
#define Oneshot_QDocument_h
#include <iglu/structs.h>
#include <iglu/tcanvas.h>
class QNode;
class QNodePoint;
class QComponent;
class QDocument {
public:
char *fileName;
QComponent *comps;
QNode *nodes;
bool modified;
QDocument();
~QDocument();
void newDoc();
bool save (char *name); // Para "Guardar"
bool load (char *name); // Para "Abrir"
void addComponent( QComponent *c );
void delComponent( QComponent *c );
void addNode( QNode *n );
void delNode( QNode *n );
int inNode( int x, int y, QNode **n=NULL, QNodePoint **p=NULL );
QNode *getNode( int idn );
QComponent *inComponent( int x, int y );
void joinNodes( QNode *n1, QNode *n2 );
void purgeNodes();
};
#endif /* Oneshot_Document_h */
|
[
"[email protected]"
] |
[
[
[
1,
38
]
]
] |
52fea4d9afef5c5d4307d0939ba7cb10fc1f3584
|
6064f8a5d4a9fc6c38420cd4350ae6e2708bd985
|
/histogramvisualizer.cpp
|
2de62adb3ca46ba991177876e36cebcf182ecd97
|
[] |
no_license
|
EmilHernvall/candify
|
33da9b53821f0548be4e03723083c26d22cbddf8
|
553ae71bcf446d79d6d18916eb65c64896784507
|
refs/heads/master
| 2016-09-05T18:09:54.609174 | 2011-05-03T18:44:03 | 2011-05-03T18:44:03 | 1,697,528 | 6 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,195 |
cpp
|
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <d2d1.h>
#include <d2d1helper.h>
#include <dwrite.h>
#include <math.h>
#include <string>
#include <sstream>
#include "audio.h"
#include "spotifyplayer.h"
#include "histogramvisualizer.h"
#include "complex.h"
#include "fft.h"
// Calculate the a value using a quadratic formula
// with root at l and u, and a maximum value of max.
float f(float v, float l, float u, float max)
{
float m = (l + u) / 2.0f;
float k = max / ((l - m) * (u - m));
return max(0, k * (l - v) * (u - v));
}
// Return the maximum value if the requested coordinate
// is within the range [l, u] and 0 if otherwise.
float g(float v, float l, float u, float max)
{
if (v >= l && v <= u) {
return max;
}
return 0.0f;
}
HistogramVisualizer::HistogramVisualizer()
: Visualizer(), m_pPrevImage(NULL), m_iColorSeq(0),
m_pDirectWriteFactory(NULL), m_pTextFormat(NULL)
{
m_pAvgFreqDomain = new float[FFT_SIZE];
for (int i = 0; i < FFT_SIZE; i++) {
m_pAvgFreqDomain[i] = 0.0f;
}
m_fNorm = 0.0f;
}
HistogramVisualizer::~HistogramVisualizer()
{
SafeRelease(&m_pTextFormat);
SafeRelease(&m_pDirectWriteFactory);
Visualizer::~Visualizer();
}
HRESULT HistogramVisualizer::CreateDeviceIndependentResources()
{
HRESULT hr;
hr = Visualizer::CreateDeviceIndependentResources();
if (FAILED(hr)) {
return hr;
}
hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown**>(&m_pDirectWriteFactory));
if (FAILED(hr)) {
return hr;
}
hr = m_pDirectWriteFactory->CreateTextFormat(
L"Georgia",
NULL,
DWRITE_FONT_WEIGHT_REGULAR,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
48.0f,
L"en-us",
&m_pTextFormat);
m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
return hr;
}
// Return a rgb color based on an integer counter.
INT HistogramVisualizer::getColor(float i, float max)
{
float segment = max / 6.0f;
float bc = g(i, 1 * segment, 3 * segment, 0xFF)
+ g(i, 0 * segment, 1 * segment, f(i, 0 * segment, 2 * segment, 0xFF))
+ g(i, 3 * segment, 4 * segment, f(i, 2 * segment, 4 * segment, 0xFF));
float gc = g(i, 3 * segment, 5 * segment, 0xFF)
+ g(i, 2 * segment, 3 * segment, f(i, 2 * segment, 4 * segment, 0xFF))
+ g(i, 5 * segment, 6 * segment, f(i, 4 * segment, 6 * segment, 0xFF));
float rc = g(i, 0 * segment, 1 * segment, 0xFF)
+ g(i, 1 * segment, 2 * segment, f(i, 0 * segment, 2 * segment, 0xFF))
+ g(i, 5 * segment, 6 * segment, 0xFF)
+ g(i, 4 * segment, 5 * segment, f(i, 4 * segment, 6 * segment, 0xFF));
int res =
(((int)bc & 0xFF) << 16) |
(((int)gc & 0xFF) << 8) |
((int)rc & 0xFF);
return res;
}
HRESULT HistogramVisualizer::Render()
{
HRESULT hr;
RECT rc;
audio_fifo_data_t *apt;
int width, height;
if (!m_pRenderTarget) {
hr = CreateDeviceResources();
} else {
hr = S_OK;
}
if (SUCCEEDED(hr)) {
GetClientRect(m_hWnd, &rc);
width = rc.right - rc.left;
height = rc.bottom - rc.top;
apt = m_pCurrentAfd;
if (apt == NULL) {
goto enddraw;
}
m_dwLastSeq = apt->seqid;
// Setup for the fourier transform
complex *data1 = new complex[apt->nframes];
for (int i = 0; i < apt->nframes; i++) {
data1[i] = complex::complex(apt->frames[i*2]);
}
// Calculate the FFT of the packet piece by piece. Use an
// exponential moving average with a weight factor alpha
// to average the results together.
int pos = 0;
float alpha = 0.1f;
while (pos < apt->nframes) {
// Take the transform of FFT_SIZE values if possible, or
// whatever remains otherwise.
int fftSize = apt->nframes > FFT_SIZE + pos ? FFT_SIZE : apt->nframes - pos;
CFFT::Forward(&data1[pos], fftSize);
// Calculate the EMA
for (int i = 0; i < FFT_SIZE; i++) {
float re;
if (i > fftSize) {
re = 0.0f;
} else {
re = (float)data1[pos+i].re();
}
m_pAvgFreqDomain[i] = re * alpha + (1 - alpha) * m_pAvgFreqDomain[i];
}
pos += FFT_SIZE;
}
delete[] data1;
// Calculate a norm for the current frequency domain
float norm = 0.0f;
for (int i = 10; i < FFT_SIZE; i++) {
float re = m_pAvgFreqDomain[i];
if (re > norm) {
norm = re;
}
}
// Use the exponential moving average again to even
// out sudden changes.
m_fNorm = alpha * norm + (1 - alpha) * m_fNorm;
// Retrieve the song info from the spotify object
std::wstringstream songInfo;
LPSTR szArtist, szTrackName;
szArtist = m_lpSpotify->getCurrentTrackArtist();
szTrackName = m_lpSpotify->getCurrentTrackName();
if (szArtist != NULL && szTrackName != NULL) {
songInfo << szArtist << " - " << szTrackName;
free(szArtist);
free(szTrackName);
}
std::wstring strSongInfo = songInfo.str();
// Start drawing onto cached image
ID2D1BitmapRenderTarget *pNewImage;
{
m_pRenderTarget->CreateCompatibleRenderTarget(&pNewImage);
pNewImage->BeginDraw();
// Scale the previous visualization frame to
// a fraction of the real image size, and
// draw it to the center of the new image
// to create an effect of "flying over"
// the histogram
if (m_pPrevImage) {
ID2D1Bitmap *pBitmap;
m_pPrevImage->GetBitmap(&pBitmap);
float diff = 0.98f;
float left = width - width * diff;
float right = width * diff;
float top = height - height * diff;
float bottom = height * diff;
pNewImage->DrawBitmap(pBitmap,
D2D1::RectF(left, top, right, bottom),
0.9f,
D2D1_BITMAP_INTERPOLATION_MODE_LINEAR,
D2D1::RectF(0.0f, 0.0f, (float)width, (float)height));
SafeRelease(&pBitmap);
SafeRelease(&m_pPrevImage);
}
hr = pNewImage->Flush(NULL, NULL);
// Allocate a brush with a color based on the current
// position in the color sequence.
int color = getColor((float)m_iColorSeq, 100.0f);
ID2D1SolidColorBrush *pBrush;
pNewImage->CreateSolidColorBrush(
D2D1::ColorF(color),
&pBrush);
// Draw histogram based on the current frequency domain
float re = 0.0f;
int magnitude;
int pillarWidth = width / FFT_SIZE + 1;
for (int i = 10; (i+1)*pillarWidth < width - pillarWidth*10; i++) {
magnitude = (int)(m_pAvgFreqDomain[i] / m_fNorm * height);
pNewImage->FillRectangle(
D2D1::RectF((float)(i*pillarWidth), (float)height, (float)((i + 1) *pillarWidth), (float)(height - magnitude)), pBrush);
}
// Draw artist and track name
pNewImage->DrawTextA(strSongInfo.c_str(), strSongInfo.length(), m_pTextFormat,
D2D1::RectF(0.0f, (float)height / 6.0f, (float)width, (float)height / 3.0f), pBrush);
SafeRelease(&pBrush);
pNewImage->EndDraw();
}
m_pPrevImage = pNewImage;
// Draw it all on to the window
{
m_pRenderTarget->BeginDraw();
// Clear drawing area
ID2D1SolidColorBrush *pBrush;
m_pRenderTarget->CreateSolidColorBrush(
D2D1::ColorF(D2D1::ColorF::Black, 1.0),
&pBrush);
m_pRenderTarget->FillRectangle(D2D1::RectF(0.0f, 0.0f, (float)width, (float)height), pBrush);
// Draw the current visualization frame onto the surface
ID2D1Bitmap *pBitmap;
pNewImage->GetBitmap(&pBitmap);
m_pRenderTarget->DrawBitmap(pBitmap, D2D1::RectF(0.0f, 0.0f, (float)width, (float)height));
// Draw the song info again, but this time in white, to make it easier to read.
pBrush->SetColor(D2D1::ColorF(D2D1::ColorF::White));
m_pRenderTarget->DrawTextA(strSongInfo.c_str(), strSongInfo.length(), m_pTextFormat,
D2D1::RectF(0.0f, (float)height / 6.0f, (float)width, (float)height / 3.0f), pBrush);
SafeRelease(&pBitmap);
SafeRelease(&pBrush);
m_pRenderTarget->EndDraw();
}
if (++m_iColorSeq > 100) {
m_iColorSeq = 0;
}
//Sleep(100);
}
enddraw:
if (hr == D2DERR_RECREATE_TARGET) {
DiscardDeviceResources();
}
return hr;
}
|
[
"[email protected]"
] |
[
[
[
1,
308
]
]
] |
897cc73b488c70651a7d8abd01d8614522eba3d6
|
fc7dbcb3bcdb16010e9b1aad4ecba41709089304
|
/BeagleBoardPkg/Debugger_scripts/rvi_symbols_macros.inc
|
ccd1ea068f9e68f520b849b0fd6384e58481ecda
|
[] |
no_license
|
Itomyl/loongson-uefi
|
5eb0ece5875406b00dbd265d28245208d6bbc99a
|
70b7d5495e2b451899e2ba2ef677384de075d984
|
refs/heads/master
| 2021-05-28T04:38:29.989074 | 2010-05-31T02:47:26 | 2010-05-31T02:47:26 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,072 |
inc
|
//
// Copyright (c) 2008-2009, Apple Inc. All rights reserved.
//
// All rights reserved. This program and the accompanying materials
// are licensed and made available under the terms and conditions of the BSD License
// which accompanies this distribution. The full text of the license may be found at
// http://opensource.org/licenses/bsd-license.php
//
// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
//
define /R int compare_guid(guid1, guid2)
unsigned char *guid1;
unsigned char *guid2;
{
return strncmp(guid1, guid2, 16);
}
.
define /R unsigned char * find_system_table(mem_start, mem_size)
unsigned char *mem_start;
unsigned long mem_size;
{
unsigned char *mem_ptr;
mem_ptr = mem_start + mem_size;
do
{
mem_ptr -= 0x400000; // 4 MB
if (strncmp(mem_ptr, "IBI SYST", 8) == 0)
{
return *(unsigned long *)(mem_ptr + 8); // EfiSystemTableBase
}
} while (mem_ptr > mem_start);
return 0;
}
.
define /R unsigned char * find_debug_info_table_header(system_table)
unsigned char *system_table;
{
unsigned long configuration_table_entries;
unsigned char *configuration_table;
unsigned long index;
unsigned char debug_table_guid[16];
// Fill in the debug table's guid
debug_table_guid[ 0] = 0x77;
debug_table_guid[ 1] = 0x2E;
debug_table_guid[ 2] = 0x15;
debug_table_guid[ 3] = 0x49;
debug_table_guid[ 4] = 0xDA;
debug_table_guid[ 5] = 0x1A;
debug_table_guid[ 6] = 0x64;
debug_table_guid[ 7] = 0x47;
debug_table_guid[ 8] = 0xB7;
debug_table_guid[ 9] = 0xA2;
debug_table_guid[10] = 0x7A;
debug_table_guid[11] = 0xFE;
debug_table_guid[12] = 0xFE;
debug_table_guid[13] = 0xD9;
debug_table_guid[14] = 0x5E;
debug_table_guid[15] = 0x8B;
configuration_table_entries = *(unsigned long *)(system_table + 64);
configuration_table = *(unsigned long *)(system_table + 68);
for (index = 0; index < configuration_table_entries; index++)
{
if (compare_guid(configuration_table, debug_table_guid) == 0)
{
return *(unsigned long *)(configuration_table + 16);
}
configuration_table += 20;
}
return 0;
}
.
define /R int valid_pe_header(header)
unsigned char *header;
{
if ((header[0x00] == 'M') &&
(header[0x01] == 'Z') &&
(header[0x80] == 'P') &&
(header[0x81] == 'E'))
{
return 1;
}
return 0;
}
.
define /R unsigned long pe_headersize(header)
unsigned char *header;
{
unsigned long *size;
size = header + 0x00AC;
return *size;
}
.
define /R unsigned char *pe_filename(header)
unsigned char *header;
{
unsigned long *debugOffset;
unsigned char *stringOffset;
if (valid_pe_header(header))
{
debugOffset = header + 0x0128;
stringOffset = header + *debugOffset + 0x002C;
return stringOffset;
}
return 0;
}
.
define /R int char_is_valid(c)
unsigned char c;
{
if (c >= 32 && c < 127)
return 1;
return 0;
}
.
define /R write_symbols_file(filename, mem_start, mem_size)
unsigned char *filename;
unsigned char *mem_start;
unsigned long mem_size;
{
unsigned char *system_table;
unsigned char *debug_info_table_header;
unsigned char *debug_info_table;
unsigned long debug_info_table_size;
unsigned long index;
unsigned char *debug_image_info;
unsigned char *loaded_image_protocol;
unsigned char *image_base;
unsigned char *debug_filename;
unsigned long header_size;
int status;
system_table = find_system_table(mem_start, mem_size);
if (system_table == 0)
{
return;
}
status = fopen(88, filename, "w");
debug_info_table_header = find_debug_info_table_header(system_table);
debug_info_table = *(unsigned long *)(debug_info_table_header + 8);
debug_info_table_size = *(unsigned long *)(debug_info_table_header + 4);
for (index = 0; index < (debug_info_table_size * 4); index += 4)
{
debug_image_info = *(unsigned long *)(debug_info_table + index);
if (debug_image_info == 0)
{
break;
}
loaded_image_protocol = *(unsigned long *)(debug_image_info + 4);
image_base = *(unsigned long *)(loaded_image_protocol + 32);
debug_filename = pe_filename(image_base);
header_size = pe_headersize(image_base);
$fprintf 88, "%s 0x%08x\n", debug_filename, image_base + header_size$;
}
fclose(88);
}
.
|
[
"[email protected]"
] |
[
[
[
1,
194
]
]
] |
0500c96b3e0d11fa1db540986d7cfdf2430705f4
|
33cdd09e352529963fe8b28b04e0d2e33483777b
|
/trunk/ReportAsistent/ListSort.cpp
|
2a5066c93481c8b54e8bd2a19cc4953dbfd328e8
|
[] |
no_license
|
BackupTheBerlios/reportasistent-svn
|
20e386c86b6990abafb679eeb9205f2aef1af1ac
|
209650c8cbb0c72a6e8489b0346327374356b57c
|
refs/heads/master
| 2020-06-04T16:28:21.972009 | 2010-05-18T12:06:48 | 2010-05-18T12:06:48 | 40,804,982 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,265 |
cpp
|
/******************************************************************************
* Filename: ListSort.cpp
* Copyright (c) 2000, UAF Development Team (email [email protected])
*
* 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 2
* 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Code downloaded from http://www.codeguru.com
******************************************************************************/
#include "stdafx.h"
#ifdef UAFEDITOR
#endif
#include "ListSort.h"
#include <afxdisp.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//*****************************************************************************
// NAME: CListSort::CListSort
//
// PURPOSE: Constructor
//
// PARMETERS:
// CListCtrl * pWnd : pointer to the CListCtrl
// const int nCol : the column number to be sorted
//
// RETURNS: N/A
//*****************************************************************************
CListSort::CListSort(CListCtrl * pWnd, const int nCol)
{
m_pWnd = pWnd;
ASSERT(m_pWnd);
int max = m_pWnd->GetItemCount();
DWORD dw;
CString txt;
// replace Item data with pointer to CSortItem structure
for (int t = 0; t < max; t++)
{
dw = m_pWnd->GetItemData(t); // save current data to restore it later
txt = m_pWnd->GetItemText(t, nCol);
m_pWnd->SetItemData(t, (DWORD) new CSortItem(dw, txt));
}
}
//*****************************************************************************
// NAME: CListSort::~CListSort
//
// PURPOSE: Destructor
//*****************************************************************************
CListSort::~CListSort()
{
ASSERT(m_pWnd);
int max = m_pWnd->GetItemCount();
CSortItem * pItem;
for (int t = 0; t < max; t++)
{
pItem = (CSortItem *) m_pWnd->GetItemData(t);
ASSERT(pItem);
m_pWnd->SetItemData(t, pItem->dw);
delete pItem;
}
}
//*****************************************************************************
// NAME: CListSort::Sort
//
// PURPOSE: To call CListCtrl::SortItems with the dwData argument properly
// encoded
//
// PARMETERS:
// bool bAsc : Sort order: true = ascending, false = descending
// EDataType dtype: The type of data to be sorted and the sort type
//
// RETURNS: void
//*****************************************************************************
void CListSort::Sort(bool bAsc, EDataType dtype)
{
long lParamSort = dtype;
// if lParamSort positive - ascending sort order, negative - descending
if (!bAsc)
{
lParamSort *= -1;
}
// Call sortItems on the CListCtrl which calls Compare to
// do the sort
// If lParamSort is negative then the sort is descending
// If lParamSort is positive then the sort is ascending
// abs(lParamSort) indicates the data type, will be one of values from
// the enumeration EDataType
m_pWnd->SortItems(Compare, lParamSort);
}
//*****************************************************************************
// NAME: CListSort::Compare
//
// PURPOSE: Compares lParam1 to lParam2
//
// PARMETERS:
// LPARAM lParam1 : data for item 1
// LPARAM lParam2 : data for item 2
// LPARAM lParamSort : data passed through the dwData argument from the
// CListCtrl::SortItems method
//
// RETURNS: int - The comparison function must return a negative value if the
// first item should precede the second, a positive value if
// the first item should follow the second, or zero if the two
// items are equivalent.
//*****************************************************************************
int CALLBACK CListSort::Compare(LPARAM lParam1, LPARAM lParam2,
LPARAM lParamSort)
{
CSortItem * item1 = (CSortItem *) lParam1;
CSortItem * item2 = (CSortItem *) lParam2;
ASSERT(item1 && item2);
// restore data type and sort order from lParamSort
// if lParamSort positive - ascending sort order, negative - descending
short sOrder = lParamSort < 0 ? -1 : 1;
EDataType dType = (EDataType) (lParamSort * sOrder); // get rid of sign
// declare typed buffers
COleDateTime t1, t2;
int result = FALSE;
switch (dType)
{
case EDataType::dtINT:
result = ((atol(item1->txt) - atol(item2->txt))*sOrder);
break;
case EDataType::dtDEC:
result = ((atof(item1->txt) < atof(item2->txt) ? -1 : 1)*sOrder);
break;
case EDataType::dtDATETIME:
if (t1.ParseDateTime(item1->txt) && t2.ParseDateTime(item2->txt))
result = ((t1 < t2 ? -1 : 1 )*sOrder);
break;
case EDataType::dtSTRING:
result = (item1->txt.CompareNoCase(item2->txt)*sOrder);
break;
default:
ASSERT("Error: attempt to sort a column without type.");
break;
}
return result;
}
//*****************************************************************************
// NAME: CListSort::GetItemPosition
//
// PURPOSE: Return the position in the list where pItem should be inserted
// base upon the lParamSort value.
//
// PARMETERS:
// LVITEM *pItem : The item to be inserted
// LONG lParamSort : If lParamSort is negative then the sort is descending
// If lParamSort is positive then the sort is ascending
// abs(lParamSort) indicates the data type, will be one
// of values from the enumeration EDataType
//
// RETURNS: int
//*****************************************************************************
int CListSort::GetItemPosition(LVITEM *pItem, LONG lParamSort)
{
CSortItem sortItem(0, pItem->pszText);
int max = m_pWnd->GetItemCount();
int i = 0;
for(i = 0; i < max; i++)
{
int x = Compare(reinterpret_cast<LONG>(&sortItem), m_pWnd->GetItemData(i), lParamSort);
if(x <= 0)
{
break;
}
}
return i;
}
//*****************************************************************************
// NAME: CListSort::CSortItem::CSortItem
//
// PURPOSE: Constructor
//
// PARMETERS:
// const DWORD _dw : Place to store the result from GetItemData
// const CString & _txt : Place to store the result from GetItemText
//
// RETURNS: CSortItem - Is used as a temporary holding place while Sort is
// executing.
//*****************************************************************************
CListSort::CSortItem::CSortItem(const DWORD _dw, const CString & _txt)
{
dw = _dw;
txt = _txt;
}
|
[
"ibart@fded5620-0c03-0410-a24c-85322fa64ba0",
"kodyj1am@fded5620-0c03-0410-a24c-85322fa64ba0"
] |
[
[
[
1,
197
],
[
201,
227
]
],
[
[
198,
200
]
]
] |
5fdd5071e21e393c561d6618c066a9efa42e793e
|
0f8559dad8e89d112362f9770a4551149d4e738f
|
/Wall_Destruction/Havok/Source/Physics/Dynamics/Constraint/Contact/hkpSimpleContactConstraintData.inl
|
67fc1c215cb8ce89e4d9b83f91e141891e9cae2e
|
[] |
no_license
|
TheProjecter/olafurabertaymsc
|
9360ad4c988d921e55b8cef9b8dcf1959e92d814
|
456d4d87699342c5459534a7992f04669e75d2e1
|
refs/heads/master
| 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,616 |
inl
|
/*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
hkpSimpleContactConstraintData::~hkpSimpleContactConstraintData()
{
if ( m_atom )
{
hkpSimpleContactConstraintAtomUtil::deallocateAtom(m_atom);
}
}
inline int hkpSimpleContactConstraintData::getNumContactPoints() const
{
return m_atom->m_numContactPoints;
}
hkContactPointId hkpSimpleContactConstraintData::getContactPointIdAt( int id ) const
{
int rid = m_idMgrA.indexOf( id );
return hkContactPointId( rid );
}
inline const hkContactPoint& hkpSimpleContactConstraintData::getContactPoint( int /*hkContactPointId*/ id ) const
{
int index = m_idMgrA.getValueAt(id);
HK_ASSERT2( 0x456e434e, index != hkpDynamicsCpIdMgr::FREE_VALUE, "Invalid contact point");
return HK_GET_LOCAL_CONTACT_ATOM(m_atom)->getContactPoints()[ index ];
}
inline hkContactPoint& hkpSimpleContactConstraintData::getContactPoint( int /*hkContactPointId*/ id )
{
int index = m_idMgrA.getValueAt(id);
HK_ASSERT2( 0x456e434e, index != hkpDynamicsCpIdMgr::FREE_VALUE, "Invalid contact point");
return HK_GET_LOCAL_CONTACT_ATOM(m_atom)->getContactPoints()[ index ];
}
inline hkpContactPointProperties* hkpSimpleContactConstraintData::getContactPointProperties( int /*hkContactPointId*/ id )
{
int index = m_idMgrA.getValueAt(id);
if ( index == hkpDynamicsCpIdMgr::FREE_VALUE )
{
return HK_NULL;
}
return HK_GET_LOCAL_CONTACT_ATOM(m_atom)->getContactPointPropertiesStream(index)->asProperties();
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
|
[
"[email protected]"
] |
[
[
[
1,
70
]
]
] |
772162850904492ada3af0bf9785cd7fc2d50319
|
478570cde911b8e8e39046de62d3b5966b850384
|
/apicompatanamdw/bcdrivers/mw/locationsrv/landmarks_search_api/inc/testposlmidlistcriteria.h
|
19c6a3fb5dd2a34dd9a15f23cedd585a02c03227
|
[] |
no_license
|
SymbianSource/oss.FCL.sftools.ana.compatanamdw
|
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
|
1169475bbf82ebb763de36686d144336fcf9d93b
|
refs/heads/master
| 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,661 |
h
|
/*
* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: CTestPosLmIdListCriteria class
*
*/
#ifndef C_TESTPOSLMIDLISTCRITERIA_H
#define C_TESTPOSLMIDLISTCRITERIA_H
#include <e32base.h>
/**
* This class will test methods of CPosLmIdListCriteria class
* @p CTestPosLmIdListCriteria clss contians functions to test methods of
* CPosLmIdListCriteria class
*
* @lib testlmksearchapi.lib
* @since S60 v3.2
*/
class CTestPosLmIdListCriteria : public CBase
{
public:
/**
* Two-phased constructor.
*/
static CTestPosLmIdListCriteria* NewLC();
/**
* Destructor.
*/
virtual ~CTestPosLmIdListCriteria();
/**
* This function is used to check NewLC function of CPosLmIdListCriteria class.
*/
void TestNewLC();
/**
* This function is used to check SetLandmarkIdsL function of CPosLmIdListCriteria class.
*/
void TestSetLandmarkIdsL();
/**
* This function is used to check GetLandmarkIdsL function of CPosLmIdListCriteria class.
*/
void TestGetLandmarkIdsL();
private:
/**
* Constructor.
*/
CTestPosLmIdListCriteria();
};
#endif // C_TESTPOSLMIDLISTCRITERIA_H
|
[
"none@none"
] |
[
[
[
1,
79
]
]
] |
e5b28dbfb19cdea3c33986f0485c76a56892de27
|
b3f6e84f764d13d5bd49fadb00171f7cd191e2b8
|
/src/CraneaBase.cpp
|
1d35b334a151d9410ff07ca15cff06167d645440
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
youngj/cranea
|
f55a93d2c7b97479a2f9c7f63ac72f1dd419e9f6
|
5411a9374a7dc29dd33e4445ef9277ed2b72c835
|
refs/heads/master
| 2020-05-18T15:13:03.623874 | 2008-04-23T08:50:20 | 2008-04-23T08:50:20 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,840 |
cpp
|
#include "CraneaBase.h"
using namespace std;
#include "sha.h"
using namespace CryptoPP;
#include <iostream>
void debugBinary(const byte *buf, size_t len)
{
for (size_t i = 0; i < len; i++)
{
cout << (int)buf[i] << " ";
}
cout << endl;
}
void transformLower(string &text)
{
transformString(text, (int(*)(int))tolower);
}
bool isOkFilenameChar(char c)
{
return isOkPathChar(c) && c != '\\' && c != '/';
}
bool isOkPathChar(char c)
{
if (c < 32)
return false;
if (c == '*' || c == '<' || c == '>' || c == '"')
return false;
if (c == ':' || c == ';' || c == '?' || c == '|')
return false;
return true;
}
void cleanFilename(string &filename, bool allowSubdir)
{
string cleaned;
for (size_t i = 0; i < filename.size(); i++)
{
char ch = filename[i];
cleaned += (allowSubdir ? isOkPathChar(ch) : isOkFilenameChar(ch)) ? ch : '_';
}
}
std::string baseFileName(const std::string &path)
{
size_t slashPos = path.rfind('/');
if (slashPos == string::npos)
{
slashPos = path.rfind('\\');
}
return (slashPos != string::npos) ? path.substr(slashPos+1) : path;
}
void concatenateTokens(const std::vector<std::string> &tokens, std::string &str)
{
size_t numTokens = tokens.size();
for (size_t j = 0; j < numTokens; j++)
{
str.append(tokens[j]);
if (j + 1 < numTokens)
{
str += ' ';
}
}
}
void hashKey(const byte *key, byte *keyhash)
{
SHA1().CalculateDigest(keyhash, key, KEY_SIZE);
}
void commandKey(const string &cmd, byte *outputKey)
{
byte buf[SHA1::DIGESTSIZE];
SHA1 sha1;
std::string someStuff = "command!";
sha1.Update((byte *)someStuff.c_str(), someStuff.length());
sha1.Update((byte *)cmd.c_str(), cmd.length());
sha1.Final(buf);
memcpy(outputKey, buf, KEY_SIZE);
}
byte *CraneaBase::keyhash()
{
if (!keyhash_)
{
keyhash_ = new byte[KEYHASH_SIZE];
hashKey(key(), keyhash_);
}
return keyhash_;
}
bool CraneaLocation::isIgnoredInternal(const std::string &token)
{
return ignoredSet_.find(token) != ignoredSet_.end();
}
bool CraneaLocation::isIgnored(const std::string &token)
{
CraneaLocation *curLoc = this;
while (curLoc)
{
if (curLoc->isIgnoredInternal(token))
{
return true;
}
curLoc = curLoc->parent_;
}
return false;
}
void CraneaLocation::tokenize(const string &cmd, vector<string> &tokens)
{
string spaces = " \t\n\r";
size_t start = 0;
string token;
string lowerCmd = cmd;
transformLower(lowerCmd);
while (true)
{
size_t startWord = lowerCmd.find_first_not_of(spaces, start);
if (startWord == string::npos)
{
break;
}
size_t endWord = lowerCmd.find_first_of(spaces, startWord);
if (endWord != string::npos)
{
token = lowerCmd.substr(startWord, endWord - startWord);
}
else
{
token = lowerCmd.substr(startWord);
}
if (!isIgnored(token))
{
tokens.push_back(token);
}
if (endWord == string::npos)
{
break;
}
start = endWord + 1;
}
}
void CraneaLocation::normalize(std::string &cmd)
{
vector<string> tokens;
tokenize(cmd, tokens);
cmd = "";
concatenateTokens(tokens, cmd);
}
byte *CraneaItem::takeyhash()
{
if (!takeyhash_)
{
takeyhash_ = new byte[KEYHASH_SIZE];
hashKey(takey(), takeyhash_);
}
return takeyhash_;
}
|
[
"adunar@1d512d32-bd3c-0410-8fef-f7bcb4ce661b"
] |
[
[
[
1,
178
]
]
] |
fd5206180db5f95137045b2bd04fa6af157a0b8a
|
c7120eeec717341240624c7b8a731553494ef439
|
/src/cplusplus/freezone-samp/src/core/geo/detail/geo_info_getter_city.cpp
|
5a41cbe93e945fa90791ed15eaf88b4e3c409c92
|
[] |
no_license
|
neverm1ndo/gta-paradise-sa
|
d564c1ed661090336621af1dfd04879a9c7db62d
|
730a89eaa6e8e4afc3395744227527748048c46d
|
refs/heads/master
| 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null |
UTF-8
|
C++
| false | false | 1,381 |
cpp
|
#include "config.hpp"
#include "geo_info_getter_city.hpp"
#include "../geo_ip_info.hpp"
#include "maxmind-geoip/GeoIP.h"
#include "maxmind-geoip/GeoIPCity.h"
namespace geo {
info_getter_city::info_getter_city(GeoIPTag* gi):info_getter_db(gi) {
}
info_getter_city::~info_getter_city() {
}
void info_getter_city::process_ip_info(ip_info& info) {
if (GeoIPRecord *gir = GeoIP_record_by_addr(db, info.ip_string.c_str())) {
if (!info.country_code2 && gir->country_code) {
info.country_code2.reset(gir->country_code);
}
if (!info.country_code3 && gir->country_code3) {
info.country_code3.reset(gir->country_code3);
}
if (!info.country_name_en && gir->country_name) {
info.country_name_en.reset(gir->country_name);
}
if (!info.city_en && gir->city) {
info.city_en.reset(gir->city);
}
if (!info.latitude) {
info.latitude.reset(gir->latitude);
}
if (!info.longitude) {
info.longitude.reset(gir->longitude);
}
GeoIPRecord_delete(gir);
}
}
std::string info_getter_city::get_db_info_prefix() const {
return "City";
}
} // namespace geo {
|
[
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] |
[
[
[
1,
42
]
]
] |
d449815164fff10f4ef6cb7f6c86ea3cf2bd37e6
|
02ffe34054155a76c1e4612d4f0772c796bedb77
|
/TCC_NDS/flib/source/FBackground.cpp
|
4012eff6f44977d5593cd40c236251dabbb682d4
|
[] |
no_license
|
btuduri/programming-nds
|
5fe58bbb768c517ae2ae2b07e6df9b13376a276e
|
81e6b9e0d4afaba1178b1fb0d8e4b000c5fdaf22
|
refs/heads/master
| 2020-06-09T07:21:31.930053 | 2009-12-08T17:39:17 | 2009-12-08T17:39:17 | 32,271,835 | 0 | 0 | null | null | null | null |
ISO-8859-2
|
C++
| false | false | 5,849 |
cpp
|
#include "FLib.h"
FBackground::FBackground(const void* tilemap, int width, int height)
{
this->width = width;
this->height = height;
this->tilemap = (u16*)tilemap;
bitmapMode = false;
screen_x = screen_y = 0;
limit_x = width * 256 - 256;
limit_y = height * 256 - 256 + 64;
alternate_x = alternate_y = false;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
FBackground::FBackground(const void* bitmap)
{
bitmapMode = true;
this->tilemap = (u16*)bitmap;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//FBackground::~FBackground()
//{
// bgHide(id);
//}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FBackground::Load(bool mainEngine, int layer, int init_x, int init_y)
{
this->mainEngine = mainEngine;
this->layer = layer;
if (bitmapMode)
{
if (mainEngine)
{
dmaCopy(&tilemap[init_y * 256 + init_x], BG_TILE_RAM(3), 49152);
id = bgInit(3, BgType_Bmp8, BgSize_B8_256x256, 3, 0);
}
else
{
dmaCopy(&tilemap[init_y * 256 + init_x], BG_TILE_RAM_SUB(3), 49152);
id = bgInitSub(3, BgType_Bmp8, BgSize_B8_256x256, 3, 0);
}
}
else
{
// Inicializa variáveis
// --------------------
ram_base = layer * 4;
x = init_x;
y = init_y;
screen_x = x % 256;
screen_y = y % 256;
// Ajusta tela no limite
// ---------------------
bool adjust_x = false;
if (width == 1 || x < 0)
x = screen_x = 0;
else if (x > limit_x)
{
x = limit_x;
screen_x = 256;
adjust_x = true;
}
if (y < 0)
y = screen_y = 0;
else if (y > limit_y)
{
y = limit_y;
screen_y = 64;
}
// Inicializa background
// ---------------------
BgSize size;
if (width == 1)
if (height == 1)
size = BgSize_T_256x256;
else
size = BgSize_T_256x512;
else
if (height == 1)
size = BgSize_T_512x256;
else
size = BgSize_T_512x512;
if (mainEngine)
id = bgInit(layer, BgType_Text8bpp, size, ram_base, 3);
else
id = bgInitSub(layer, BgType_Text8bpp, size, ram_base, 3);
// Copia mapas de memória
// ----------------------
map_base = ((y / 256) * width) + (x / 256);
if (adjust_x) map_base--;
dmaCopy(&tilemap[Offset(map_base)], BgMapRam(ram_base), 2048);
dmaCopy(&tilemap[Offset(map_base + 1)], BgMapRam(ram_base + 1), 2048);
dmaCopy(&tilemap[Offset(map_base + width)], BgMapRam(ram_base + 2), 2048);
dmaCopy(&tilemap[Offset(map_base + width + 1)], BgMapRam(ram_base + 3), 2048);
bgSetScroll(id, screen_x, screen_y);
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FBackground::Scroll(int offset_x, int offset_y)
{
if (!bitmapMode)
{
// Incrementa coordenadas
// ----------------------
x += offset_x;
y += offset_y;
screen_x += offset_x;
screen_y += offset_y;
// Ajusta tela no limite
// ---------------------
if (x > limit_x)
{
x = limit_x;
screen_x = 256;
}
else if (x < 0)
x = screen_x = 0;
if (y > limit_y)
{
y = limit_y;
screen_y = 64;
}
else if (y < 0)
y = screen_y = 0;
// Copia mapas de memória
// ----------------------
if (screen_x > 256)
{
screen_x -= 256;
map_base++;
dmaCopy(&tilemap[Offset(map_base + (alternate_y * width) + 1)], BgMapRam(ram_base + alternate_x), 2048);
dmaCopy(&tilemap[Offset(map_base + (!alternate_y * width) + 1)], BgMapRam(ram_base + 2 + alternate_x), 2048);
alternate_x = !alternate_x;
}
else if (screen_x < 0)
{
screen_x += 256;
map_base--;
alternate_x = !alternate_x;
dmaCopy(&tilemap[Offset(map_base + (alternate_y * width))], BgMapRam(ram_base + alternate_x), 2048);
dmaCopy(&tilemap[Offset(map_base + (!alternate_y * width))], BgMapRam(ram_base + 2 + alternate_x), 2048);
}
if (screen_y > 256)
{
screen_y -= 256;
map_base += width;
dmaCopy(&tilemap[Offset(map_base + width + alternate_x)], BgMapRam(ram_base + (2 * alternate_y)), 2048);
dmaCopy(&tilemap[Offset(map_base + width + !alternate_x)], BgMapRam(ram_base + (2 * alternate_y) + 1), 2048);
alternate_y = !alternate_y;
}
else if (screen_y < 0)
{
screen_y += 256;
map_base -= width;
alternate_y = !alternate_y;
dmaCopy(&tilemap[Offset(map_base + alternate_x)], BgMapRam(ram_base + (2 * alternate_y)), 2048);
dmaCopy(&tilemap[Offset(map_base + !alternate_x)], BgMapRam(ram_base + (2 * alternate_y) + 1), 2048);
}
// Efetua o scroll
// ---------------
bgSetScroll(id, (alternate_x * 256) + screen_x, (alternate_y * 256) + screen_y);
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FBackground::InfiniteScroll(int offset_x, int offset_y)
{
if (!bitmapMode)
{
screen_x += offset_x;
screen_y += offset_y;
bgSetScroll(id, screen_x, screen_y);
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FBackground::Hide()
{
bgHide(id);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FBackground::Show()
{
bgShow(id);
}
|
[
"thiagoauler@f17e7a6a-8b71-11de-b664-3b115b7b7a9b"
] |
[
[
[
1,
226
]
]
] |
55dc61dfabd651d78997b6018aedd2ed7ff93e48
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/example/container_device_example.cpp
|
7946b6d5af09a718e07bd6cb0e446e158dc9098a
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
willrebuild/flyffsf
|
e5911fb412221e00a20a6867fd00c55afca593c7
|
d38cc11790480d617b38bb5fc50729d676aef80d
|
refs/heads/master
| 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 921 |
cpp
|
// (C) Copyright Jonathan Turkanis 2005.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
#include <cassert>
#include <string>
#include <boost/iostreams/stream_facade.hpp>
#include <boost/iostreams/detail/ios.hpp> // ios_base::beg.
#include <libs/iostreams/example/container_device.hpp>
namespace io = boost::iostreams;
namespace ex = boost::iostreams::example;
int main()
{
using namespace std;
typedef ex::container_device<string> string_device;
string one, two;
io::stream_facade<string_device> io(one);
io << "Hello World!";
io.flush();
io.seekg(0, BOOST_IOS::beg);
getline(io, two);
assert(one == "Hello World!");
assert(two == "Hello World!");
}
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
29
]
]
] |
3ee2408005ff459767497503eb64d3b13216d5de
|
f94f9d54bf316a15d9e1962b1514bba80ad226c9
|
/ServiceBase.cpp
|
d357377921c7d583f2fd95884e6152915cfcd565
|
[
"Apache-2.0"
] |
permissive
|
bbyk/devsmtp
|
2b015a31a41657f8677bfdb4326e3dac2bf53bcd
|
b98b4267cc4bc7808180367e92d5efe299297767
|
refs/heads/master
| 2021-01-19T10:11:05.366080 | 2010-08-18T10:07:51 | 2010-08-18T10:08:51 | 845,840 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,185 |
cpp
|
/*
* Copyright 2010 Boris Byk.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "StdAfx.h"
#include "ServiceBase.h"
namespace DevSmtp
{
ServiceBase* gInst;
ServiceBase::ServiceBase(_TCHAR* r_pSrvName) : m_hSvcStopEvent(NULL), m_dwCheckPoint(1)
{
m_pSrvName = r_pSrvName;
}
ServiceBase::~ServiceBase(void)
{
}
void ServiceBase::Start()
{
gInst = this;
// TO_DO: Add any additional services for the process to this table.
SERVICE_TABLE_ENTRY dispatch_table[] =
{
{ m_pSrvName, (LPSERVICE_MAIN_FUNCTION)SvcMain },
{ NULL, NULL }
};
// This call returns when the service has stopped.
// The process should simply terminate when the call returns.
if ( !StartServiceCtrlDispatcher( dispatch_table ) )
{
LOG1(_T("Can't connect to service control manager (%d)."), GetLastError());
}
}
void ServiceBase::OnSvcMain()
{
// Register the handler function for the service
m_hSvcStatus = RegisterServiceCtrlHandler(
m_pSrvName,
SvcCtrlHandler);
// These SERVICE_STATUS members remain as set here
m_svcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
m_svcStatus.dwServiceSpecificExitCode = 0;
// Report initial status to the SCM
ReportSvcStatus( SERVICE_START_PENDING, NO_ERROR, 3000 );
// Perform service-specific initialization and work.
SvcInit();
}
void ServiceBase::SvcInit()
{
m_hSvcStopEvent = CreateEvent(
NULL, // default security attributes
TRUE, // manual reset event
FALSE, // not signaled
NULL); // no name
if ( m_hSvcStopEvent == NULL)
{
ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
return;
}
if ( !OnStart() )
{
ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
return;
}
// Report running status when initialization is complete.
ReportSvcStatus( SERVICE_RUNNING, NO_ERROR, 0 );
while(TRUE)
{
// Check whether to stop the service.
WaitForSingleObject(m_hSvcStopEvent, INFINITE);
OnStop();
ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
return;
}
}
void CALLBACK ServiceBase::SvcMain( DWORD dwArgc, _TCHAR** lpszArgv )
{
gInst->OnSvcMain();
}
void ServiceBase::ReportSvcStatus( DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwWaitHint)
{
// Fill in the SERVICE_STATUS structure.
m_svcStatus.dwCurrentState = dwCurrentState;
m_svcStatus.dwWin32ExitCode = dwWin32ExitCode;
m_svcStatus.dwWaitHint = dwWaitHint;
if (dwCurrentState == SERVICE_START_PENDING)
m_svcStatus.dwControlsAccepted = 0;
else m_svcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
if ( (dwCurrentState == SERVICE_RUNNING) ||
(dwCurrentState == SERVICE_STOPPED) )
m_svcStatus.dwCheckPoint = 0;
else m_svcStatus.dwCheckPoint = m_dwCheckPoint++;
// Report the status of the service to the SCM.
SetServiceStatus( m_hSvcStatus, &m_svcStatus );
}
void ServiceBase::OnSvcCtrlHandler( DWORD dwCtrl )
{
// Handle the requested control code.
switch(dwCtrl)
{
case SERVICE_CONTROL_STOP:
ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
// Signal the service to stop.
SetEvent(m_hSvcStopEvent);
return;
case SERVICE_CONTROL_INTERROGATE:
// Fall through to send current status.
break;
default:
break;
}
ReportSvcStatus(m_svcStatus.dwCurrentState, NO_ERROR, 0);
}
void CALLBACK ServiceBase::SvcCtrlHandler( DWORD dwCtrl )
{
gInst->OnSvcCtrlHandler( dwCtrl );
}
void ServiceBase::Stop()
{
OnSvcCtrlHandler(SERVICE_CONTROL_STOP);
}
}
|
[
"[email protected]"
] |
[
[
[
1,
171
]
]
] |
a066bf061e9b137da7a31c2652ab5b11b585c6a6
|
d411188fd286604be7670b61a3c4c373345f1013
|
/zomgame/ZGame/effect.h
|
7951959ffbdc505010552b35262015035b4aef04
|
[] |
no_license
|
kjchiu/zomgame
|
5af3e45caea6128e6ac41a7e3774584e0ca7a10f
|
1f62e569da4c01ecab21a709a4a3f335dff18f74
|
refs/heads/master
| 2021-01-13T13:16:58.843499 | 2008-09-13T05:11:16 | 2008-09-13T05:11:16 | 1,560,000 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 340 |
h
|
#ifndef _EFFECT_H_
#define _EFFECT_H_
#include "attribute.h"
class Effect {
protected:
std::string name;
static int count;
int id;
int duration;
int start_tick;
int last_tick;
public:
Effect();
bool tick(int tick);
virtual int modify(Attributes type, int value) = 0;
void setTickCount(int tick);
};
#endif
|
[
"krypes@9b66597e-bb4a-0410-bce4-15c857dd0990"
] |
[
[
[
1,
22
]
]
] |
b8df6a633ffb4e983917d76586f1b4a748f1360e
|
58ef4939342d5253f6fcb372c56513055d589eb8
|
/OpenGLParticles/inc/Particles.h
|
d2f098a9ea777f4df7b5bf586188701ee568081f
|
[] |
no_license
|
flaithbheartaigh/lemonplayer
|
2d77869e4cf787acb0aef51341dc784b3cf626ba
|
ea22bc8679d4431460f714cd3476a32927c7080e
|
refs/heads/master
| 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,386 |
h
|
/*
============================================================================
Name : Particles.h
Author : zengcity
Version : 1.0
Copyright : Your copyright notice
Description : CParticles declaration
============================================================================
*/
#ifndef PARTICLES_H
#define PARTICLES_H
// INCLUDES
#include <e32std.h>
#include <e32base.h>
#include <w32std.h>
#include <coecntrl.h>
#include <GLES\egl.h>
#include "Utils3d.h" // Utilities (texmanager, textures etc.)
#include "Glutils.h" // Misc GLU and GLUT functions
//LIBRARY libgles_cm.lib ws32.lib imageconversion.lib fbscli.lib
// CLASS DECLARATION
/**
* CParticles
*
*/
class CParticles : public CFiniteStateMachine,public MTextureLoadingListener
{
public:
// Constructors and destructor
enum
{
ELoadingTextures,
ERunning
};
/**
* Destructor.
*/
virtual ~CParticles();
/**
* Two-phased constructor.
*/
static CParticles
* NewL(CCoeControl* aParentControl, RWindow* aParentWindow);
/**
* Two-phased constructor.
*/
static CParticles* NewLC(CCoeControl* aParentControl,
RWindow* aParentWindow);
private:
/**
* Constructor for performing 1st stage construction
*/
CParticles(CCoeControl* aParentControl, RWindow* aParentWindow);
/**
* EPOC default constructor for performing 2nd stage construction
*/
void ConstructL();
private:
void OnEnterStateL( TInt aState);
void OnStartLoadingTexturesL() ;
void OnEndLoadingTexturesL() ;
public:
TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType);
void SetRedererState();
void Render();
private:
void SetScreenSize( TUint aWidth, TUint aHeight );
void DrawTangram();
void DrawGLScene();
public:
GLint iCameraDistance;
GLint iFrame;
GLint iRotate[7];
GLint iTranslateX;
GLint iTranslateY;
GLint iTranslate[7][2];
private:
CCoeControl* iParentControl;
RWindow* iParentWindow;
EGLDisplay iEglDisplay; // display where the graphics are drawn
EGLContext iEglContext; // rendering context
EGLSurface iEglSurface; // window where the graphics are blitted
TInt iScreenWidth;
TInt iScreenHeight;
CTextureManager * iTextureManager;
TTexture iOpenGLES;
TTexture iTextureParticle;
};
#endif // Particles_H
|
[
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] |
[
[
[
1,
113
]
]
] |
1568e886706c588599f3941d0984348181d1e65c
|
478570cde911b8e8e39046de62d3b5966b850384
|
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libm/testldouble_blr/inc/tldouble_blr.h
|
c9a08df5522607115aa37f7889bca49ca89561f0
|
[] |
no_license
|
SymbianSource/oss.FCL.sftools.ana.compatanamdw
|
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
|
1169475bbf82ebb763de36686d144336fcf9d93b
|
refs/heads/master
| 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,133 |
h
|
/*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
/*
* ==============================================================================
* Name : tldouble_blr.h
* Part of : testldouble_blr
*
* Description : ?Description
* Version: 0.5
*
*/
#ifndef __TLDOUBLE_BLR_H__
#define __TLDOUBLE_BLR_H__
// INCLUDES
#include <e32math.h>
#include <float.h>
#include <math.h>
#include <string.h>
#include <test/TestExecuteStepBase.h>
#define MAX_SIZE 50
#ifdef TESTING_FLOAT
#define FUNC(function) function##f
#define FLOAT float
#define CHOOSE(Clongdouble,Cdouble,Cfloat,Cinlinelongdouble,Cinlinedouble,Cinlinefloat) Cfloat
#elif TESTING_LDOUBLE
#define FUNC(function) function##l
#define FLOAT long double
#define CHOOSE(Clongdouble,Cdouble,Cfloat,Cinlinelongdouble,Cinlinedouble,Cinlinefloat) Clongdouble
#else
#define FUNC(function) function
#define FLOAT double
#define CHOOSE(Clongdouble,Cdouble,Cfloat,Cinlinelongdouble,Cinlinedouble,Cinlinefloat) Cdouble
#endif //TESTING_FLOAT
#define IGNORE_ZERO_INF_SIGN 0x10
#define MANT_DIG CHOOSE ((LDBL_MANT_DIG-1), (DBL_MANT_DIG-1), (FLT_MANT_DIG-1), \
(LDBL_MANT_DIG-1), (DBL_MANT_DIG-1), (FLT_MANT_DIG-1))
_LIT(Kcbrt_test, "cbrtl_test");
_LIT(Kceil_test, "ceill_test");
_LIT(Kerf_test, "erfl_test");
_LIT(Kerfc_test, "erfcl_test");
_LIT(Kexp_test, "expl_test");
_LIT(Kexp2_test, "exp2l_test");
_LIT(Kexpm1_test, "expm1l_test");
_LIT(Kfabs_test, "fabsl_test");
_LIT(Kilogb_test, "ilogbl_test");
_LIT(Kj0_test, "j0l_test");
_LIT(Kj1_test, "j1l_test");
_LIT(Klrint_test, "lrintl_test");
_LIT(Kllrint_test, "llrintl_test");
_LIT(Kfpclassify_test, "fpclassifyl_test");
_LIT(Klog_test, "logl_test");
_LIT(Klog10_test, "log10l_test");
_LIT(Klog1p_test, "log1pl_test");
_LIT(Klogb_test, "logbl_test");
_LIT(Kround_test, "roundl_test");
_LIT(Klround_test, "lroundl_test");
_LIT(Kllround_test, "llroundl_test");
_LIT(Krint_test, "rintl_test");
_LIT(Ksqrt_test, "sqrtl_test");
_LIT(Ktrunc_test, "truncl_test");
_LIT(Ky0_test, "y0l_test");
_LIT(Ky1_test, "y1l_test");
_LIT(Kfloor_test, "floorl_test");
_LIT(Ksignificand_test, "significandl_test");
_LIT(Knearbyint_test, "nearbyintl_test");
_LIT(Kisinf_test, "isinfl_test");
_LIT(Kisnan_test, "isnanl_test");
_LIT(Kfdim_test, "fdiml_test");
_LIT(Kfmax_test, "fmaxl_test");
_LIT(Kfmin_test, "fminl_test");
_LIT(Kfmod_test, "fmodl_test");
_LIT(Khypot_test, "hypotl_test");
_LIT(Kremainder_test, "remainderl_test");
_LIT(Knexttoward_test, "nexttowardl_test");
_LIT(Knextafter_test, "nextafterl_test");
_LIT(Kcopysign_test, "copysignl_test");
_LIT(Kfjn_test, "jnl_test");
_LIT(Kfyn_test, "ynl_test");
_LIT(Kscalb_test, "scalbl_test");
_LIT(Kscalbn_test, "scalbnl_test");
_LIT(Kpow_test, "powl_test");
_LIT(Kacos_test, "acosl_test");
_LIT(Kacosh_test, "acoshl_test");
_LIT(Kasin_test, "asinl_test");
_LIT(Kasinh_test, "asinhl_test");
_LIT(Katan_test, "atanl_test");
_LIT(Katanh_test, "atanhl_test");
_LIT(KCos_test, "Cosl_test");
_LIT(Kcosh_test, "coshl_test");
_LIT(Ksin_test, "sinl_test");
_LIT(Ksinh_test, "sinhl_test");
_LIT(Ktan_test, "tanl_test");
_LIT(Ktanh_test, "tanhl_test");
_LIT(Katan2_test, "atan2l_test");
_LIT(Kfma_test, "fmal_test");
_LIT(Kisfinite_test, "isfinitel_test");
_LIT(Kisnormal_test, "isnormall_test");
_LIT(Ksignbit_test, "signbitl_test");
_LIT(Kscalbln_test, "scalblnl_test");
_LIT(Kfinite_test, "finitel_test");
_LIT(Kmodf_test, "modfl_test");
_LIT(Kldexp_test, "ldexpl_test");
_LIT(Kdrem_test, "dreml_test");
_LIT(Kfrexp_test, "frexpl_test");
_LIT(Kremquo_test, "remquol_test");
_LIT(Kremquo_remcheck_test, "remquo_remcheckl_test");
_LIT(Kgamma_test, "gammal_test");
_LIT(Klgamma_test, "lgammal_test");
class CTLongDouble_blr : public CTestStep
{
public:
~CTLongDouble_blr ();
CTLongDouble_blr (const TDesC& aStepName);
TInt iParamCnt;
TInt iStrCnt;
TVerdict doTestStepL();
TVerdict doTestStepPreambleL();
TVerdict doTestStepPostambleL();
private:
/**
* C++ default constructor.
*/
CTLongDouble_blr();
// Utility functions for handling parameters etc.
void ReadIntParam(TInt &aInt);
void ReadStringParam(char* aString);
void ReadFloatParam(FLOAT &aDbl);
void ReadLIntParam(TInt32 &aLInt);
void ReadLLIntParam(TInt64 &aLInt);
//Test Functions
int check_float (FLOAT computed, FLOAT expected, FLOAT max_ulp, FLOAT &gen_ulp);
int check_longlong (TInt64 computed, TInt64 expected, FLOAT max_ulp, FLOAT &gen_ulp);
int check_int (int computed, int expected, int max_ulp);
int check_long (TInt32 computed, TInt32 expected, FLOAT max_ulp, FLOAT &gen_ulp);
int check_bool (int computed, int expected);
TInt cbrtl_test();
TInt ceill_test();
TInt erfl_test();
TInt erfcl_test();
TInt expl_test();
TInt exp2l_test();
TInt expm1l_test();
TInt fabsl_test();
TInt ilogbl_test();
TInt j0l_test();
TInt j1l_test();
TInt lrintl_test();
TInt llrintl_test();
TInt fpclassifyl_test();
TInt logl_test();
TInt log10l_test();
TInt log1pl_test();
TInt logbl_test();
TInt roundl_test();
TInt lroundl_test();
TInt llroundl_test();
TInt rintl_test();
TInt sqrtl_test();
TInt truncl_test();
TInt y0l_test();
TInt y1l_test();
TInt floorl_test();
TInt significandl_test();
TInt nearbyintl_test();
TInt isinfl_test();
TInt isnanl_test();
TInt acosl_test();
TInt acoshl_test();
TInt asinl_test();
TInt asinhl_test();
TInt Cosl_test();
TInt atanl_test();
TInt atanhl_test();
TInt coshl_test();
TInt sinl_test();
TInt sinhl_test();
TInt tanl_test();
TInt tanhl_test();
TInt isfinitel_test();
TInt isnormall_test();
TInt signbitl_test();
TInt finitel_test();
TInt modfl_test();
// Apis which take two arguments
TInt fdiml_test();
TInt fmaxl_test();
TInt fminl_test();
TInt fmodl_test();
TInt hypotl_test();
TInt remainderl_test();
TInt nexttowardl_test();
TInt nextafterl_test();
TInt copysignl_test();
TInt jnl_test();
TInt ynl_test();
TInt scalbl_test();
TInt scalbnl_test();
TInt scalblnl_test();
TInt powl_test();
TInt atan2l_test();
TInt ldexpl_test();
TInt dreml_test();
TInt frexpl_test();
TInt remquol_test();
TInt remquo_remcheckl_test();
TInt fmal_test();
TInt gammal_test();
TInt lgammal_test();
public: // Friend classes
//?friend_class_declaration;
protected: // Friend classes
//?friend_class_declaration;
private: // Friend classes
//?friend_class_declaration;
};
#endif // TDOUBLE_BLR_H
// End of File
|
[
"none@none"
] |
[
[
[
1,
251
]
]
] |
29b9861b7378641999bcf57f21b9ca1db76af286
|
03750072f2f37f21cd2d0f12432757149027dfdc
|
/ scard --username [email protected]/main.cpp
|
52052bb371ecb28903cbf5d233fca11139450778
|
[] |
no_license
|
Ioannish/scard
|
c6830958f13609b0a1fe1dadfeb829b3e9431220
|
bf4f836317e549e1d097468e96c2c2785abf58c3
|
refs/heads/master
| 2021-01-10T17:55:01.532224 | 2011-06-30T17:26:06 | 2011-06-30T17:26:06 | 44,372,977 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 806 |
cpp
|
#include <iostream>
#include "scard.h"
#include "stringx.h"
using namespace std;
int main() {
SCard card;
try {
card.setContext(SCARD_SCOPE_SYSTEM);
card.connect();
cout << card.getReader() << endl;
char input[256];
for (;;) {
cout << "apdu> ";
cin.getline(input, sizeof(input));
String in(input);
in = in.trim().toLower();
if (in == "quit") {
cout << "Bye" << endl;
break;
}
APDU cmd(in,APDU::Separator::SPACE);
APDU resp;
try {
card.transmit(cmd,resp);
cout << resp.toString() << endl;
} catch (SCardException& e) {
cerr << e.what() << endl;
}
}
} catch (SCardException& e) {
cerr << e.what() << endl;
}
return 0;
}
|
[
"maralosil@49ee3937-5266-4f4a-e7b9-40f6dfc295be"
] |
[
[
[
1,
62
]
]
] |
0435981a42ec1e4d20ccdf5c74fe53d315e71192
|
c7120eeec717341240624c7b8a731553494ef439
|
/src/cplusplus/freezone-samp/src/core/utility/erase_if.hpp
|
9d4f2f2861db774278963630a195dfc35e7b237e
|
[] |
no_license
|
neverm1ndo/gta-paradise-sa
|
d564c1ed661090336621af1dfd04879a9c7db62d
|
730a89eaa6e8e4afc3395744227527748048c46d
|
refs/heads/master
| 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null |
UTF-8
|
C++
| false | false | 1,049 |
hpp
|
#ifndef ERASE_IF_HPP
#define ERASE_IF_HPP
#include <map>
#include <set>
#include <algorithm>
template <typename container_t, typename predicate_t>
inline void erase_if(container_t& container, predicate_t predicate) {
container.erase(remove_if(container.begin(), container.end(), predicate), container.end());
}
template <typename item_t, typename item_pred_t, typename predicate_t>
inline void erase_if(std::set<item_t, item_pred_t> & container, predicate_t predicate) {
for (typename std::set<item_t, item_pred_t>::iterator it = container.begin(); container.end() != it;) {
if (predicate(*it)) {
container.erase(it++);
}
else {
++it;
}
}
}
/*
template<class K, class V, class Predicate>
void eraseIf( map<K,V>& container, Predicate predicate ) {
for(typename map<K,V>::iterator iter=container.begin() ; iter!=container.end() ; ++iter ) {
if(predicate(iter))
container.erase(iter);
}
}
*/
#endif // ERASE_IF_HPP
|
[
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] |
[
[
[
1,
33
]
]
] |
2ed8bb31bc5321b397af98302820556175d35690
|
f8403b6b1005f80d2db7fad9ee208887cdca6aec
|
/Source/Main.cpp
|
c3af8e0ccad595a65ddde0c61eb542312b523c13
|
[] |
no_license
|
sonic59/JuceText
|
25544cb07e5b414f9d7109c0826a16fc1de2e0d4
|
5ac010ffe59c2025d25bc0f9c02fc829ada9a3d2
|
refs/heads/master
| 2021-01-15T13:18:11.670907 | 2011-10-29T19:03:25 | 2011-10-29T19:03:25 | 2,507,112 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,903 |
cpp
|
/*
==============================================================================
This file was auto-generated by the Introjucer!
It contains the basic startup code for a Juce application.
==============================================================================
*/
#include "../JuceLibraryCode/JuceHeader.h"
#include "MainWindow.h"
//==============================================================================
class JuceTextApplication : public JUCEApplication
{
public:
//==============================================================================
JuceTextApplication()
{
}
~JuceTextApplication()
{
}
//==============================================================================
void initialise (const String& commandLine)
{
// Do your application's initialisation code here..
mainWindow = new MainAppWindow();
}
void shutdown()
{
// Do your application's shutdown code here..
mainWindow = 0;
}
//==============================================================================
void systemRequestedQuit()
{
quit();
}
//==============================================================================
const String getApplicationName()
{
return "JuceText";
}
const String getApplicationVersion()
{
return ProjectInfo::versionString;
}
bool moreThanOneInstanceAllowed()
{
return true;
}
void anotherInstanceStarted (const String& commandLine)
{
}
private:
ScopedPointer <MainAppWindow> mainWindow;
};
//==============================================================================
// This macro generates the main() routine that starts the app.
START_JUCE_APPLICATION(JuceTextApplication)
|
[
"[email protected]"
] |
[
[
[
1,
74
]
]
] |
3f90b3a8165847df9cd7492b0873f1cd020643a8
|
2957c5a47105deb75f2af0a78feaf6f01bebd0f5
|
/InvadedSpace/constant.cpp
|
38c9fc86b1be8519badac34feadac9c61d51e645
|
[] |
no_license
|
akidarsa/ak-pu-school
|
a20e7f742a262a37011a60e8f20866f4d4b2a704
|
fbe72462db4b0fe08e06674249c61eb7ead0641a
|
refs/heads/master
| 2021-01-15T17:29:33.472717 | 2009-12-07T20:50:32 | 2009-12-07T20:50:32 | 32,253,320 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,481 |
cpp
|
#include "constant.h"
const int Db_updateDelay = 5;
const int Db_arenaWidth = 400;
const int Db_arenaHeight = 400;
const int Db_arenaMargin = 100;
const int Db_moveAreaMinX = Db_arenaMargin;
const int Db_moveAreaMaxX = Db_arenaWidth - Db_arenaMargin;
const int Db_cannonY = 350;
const int Db_cannonIndY = 10;
const int Db_cannonIndX3 = Db_arenaWidth - 20;
const int Db_cannonIndX2 = Db_arenaWidth - 40;
const int Db_cannonIndX1 = Db_arenaWidth - 60;
const int Db_bulletLength = 5;
const int Db_cannonRadius = 8;
const int Db_cannonDiameter = 2 * Db_cannonRadius;
const int Db_alienMaxNumber = 50;
const int Db_aliensPerRows = 10;
const int Db_aliensPerColumns = Db_alienMaxNumber / Db_aliensPerRows;
const int Db_alienStartX = 105;
const int Db_alienStartY = 100;
const int Db_aliensGap = 10;
const int Db_alienXSpeed = 1;
const int Db_alienYSpeed = 1;
const int Db_alienRadius = 5;
const int Db_alienDiameter = 2 * Db_alienRadius;
const int Db_beamRandSeed = 100;
const int Db_scoreX = 5;
const int Db_scoreY = 20;
const int Db_scoreInc = 10;
const int Db_hiScoreX = 5;
const int Db_hiScoreY = 30;
const QColor Db_backgroundColor = Qt::black;
const QColor Db_cannonColor3 = Qt::blue;
const QColor Db_cannonColor2 = Qt::green;
const QColor Db_cannonColor1 = Qt::red;
const QColor Db_bulletColor = Qt::white;
const QColor Db_alienColor = Qt::gray;
const QColor Db_beamColor = Qt::darkYellow;
const QColor Db_textColor = Qt::white;
|
[
"akidarsa@a8046f88-d622-11de-89a3-7d4a0ca7bf7e"
] |
[
[
[
1,
45
]
]
] |
49ce7aea75ececa6a44587014d3edeac6752523c
|
2b80036db6f86012afcc7bc55431355fc3234058
|
/src/core/audio/Transport.h
|
8b873f905ffcf122479351fcc192b437da8985bf
|
[
"BSD-3-Clause"
] |
permissive
|
leezhongshan/musikcube
|
d1e09cf263854bb16acbde707cb6c18b09a0189f
|
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
|
refs/heads/master
| 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null |
ISO-8859-9
|
C++
| false | false | 3,825 |
h
|
//////////////////////////////////////////////////////////////////////////////
// Copyright © 2007, Daniel Önnerby
//
// All rights reserved.
//
// 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 author nor the names of other 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 OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include <core/config.h>
#include <core/audio/Player.h>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <sigslot/sigslot.h>
//////////////////////////////////////////////////////////////////////////////
namespace musik { namespace core { namespace audio {
//////////////////////////////////////////////////////////////////////////////
/**
* Interface between application and Player objects
*/
class Transport : public sigslot::has_slots<>{
public:
Transport();
~Transport();
void PrepareNextTrack(utfstring trackUrl);
void Start(utfstring trackUrl);
void Stop();
bool Pause();
bool Resume();
double Position();
void SetPosition(double seconds);
double Volume();
void SetVolume(double volume);
public:
typedef enum {
Started = 1,
Ended = 2,
Error = 3
} PlaybackStatus;
typedef sigslot::signal1<int> PlaybackStatusEvent;
PlaybackStatusEvent PlaybackStatusChange;
typedef sigslot::signal0<> PlaybackEvent;
PlaybackEvent PlaybackAlmostDone;
// PlaybackEvent PlaybackChange;
PlaybackEvent PlaybackStarted;
PlaybackEvent PlaybackEnded;
PlaybackEvent PlaybackPause;
PlaybackEvent PlaybackResume;
PlaybackEvent PlaybackError;
private:
void OnPlaybackStarted(Player *player);
void OnPlaybackAlmostEnded(Player *player);
void OnPlaybackEnded(Player *player);
void OnPlaybackError(Player *player);
private:
double volume;
bool gapless;
typedef std::list<PlayerPtr> PlayerList;
PlayerList players;
PlayerPtr currentPlayer;
PlayerPtr nextPlayer;
};
//////////////////////////////////////////////////////////////////////////////
} } }
//////////////////////////////////////////////////////////////////////////////
|
[
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e",
"[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e",
"bjorn.olievier@6a861d04-ae47-0410-a6da-2d49beace72e",
"urioxis@6a861d04-ae47-0410-a6da-2d49beace72e"
] |
[
[
[
1,
1
],
[
3,
34
],
[
40,
40
],
[
42,
42
],
[
44,
44
],
[
67,
67
],
[
71,
71
],
[
99,
100
]
],
[
[
2,
2
],
[
35,
36
],
[
38,
38
],
[
41,
41
],
[
43,
43
],
[
49,
66
],
[
68,
70
],
[
72,
82
],
[
84,
85
],
[
90,
98
],
[
101,
104
]
],
[
[
37,
37
],
[
39,
39
]
],
[
[
45,
48
],
[
83,
83
],
[
86,
89
]
]
] |
0f6ddcbd54bc135ad80d721301fad33cbc8c4610
|
0f8559dad8e89d112362f9770a4551149d4e738f
|
/Wall_Destruction/Havok/Source/Physics/Dynamics/Phantom/hkpPhantom.inl
|
2a93916617021f5039cadd1cedd3a6452b283e28
|
[] |
no_license
|
TheProjecter/olafurabertaymsc
|
9360ad4c988d921e55b8cef9b8dcf1959e92d814
|
456d4d87699342c5459534a7992f04669e75d2e1
|
refs/heads/master
| 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,980 |
inl
|
/*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
/// Helper function that returns a hkpPhantom if the collidable's broadphase handle is of type hkpWorldObject::BROAD_PHASE_PHANTOM
inline hkpPhantom* HK_CALL hkpGetPhantom(const hkpCollidable* collidable)
{
if ( collidable->getType() == hkpWorldObject::BROAD_PHASE_PHANTOM )
{
return static_cast<hkpPhantom*>( hkGetWorldObject(collidable) );
}
return HK_NULL;
}
hkpCollidableAccept hkpPhantom::fireCollidableAdded( const hkpCollidable* collidable )
{
hkpCollidableAddedEvent event;
event.m_collidable = collidable;
event.m_phantom = this;
event.m_collidableAccept = HK_COLLIDABLE_ACCEPT;
for ( int i = m_overlapListeners.getSize()-1; i >= 0; i-- )
{
if (m_overlapListeners[i] != HK_NULL)
{
m_overlapListeners[i]->collidableAddedCallback( event );
}
}
// cleanupNullPointers done at the end of updateBroadPhase
return event.m_collidableAccept;
}
void hkpPhantom::fireCollidableRemoved( const hkpCollidable* collidable, hkBool collidableWasAdded )
{
hkpCollidableRemovedEvent event;
event.m_collidable = collidable;
event.m_phantom = this;
event.m_collidableWasAdded = collidableWasAdded;
for ( int i = m_overlapListeners.getSize()-1; i >= 0; i-- )
{
if (m_overlapListeners[i] != HK_NULL)
{
m_overlapListeners[i]->collidableRemovedCallback( event );
}
}
// cleanupNullPointers done at the end of updateBroadPhase
}
inline hkpPhantom::hkpPhantom( const hkpShape* shape )
: hkpWorldObject( shape, BROAD_PHASE_PHANTOM )
{
m_collidable.setOwner( this );
}
inline const hkArray<hkpPhantomListener*>& hkpPhantom::getPhantomListeners() const
{
return m_phantomListeners;
}
inline const hkArray<hkpPhantomOverlapListener*>& hkpPhantom::getPhantomOverlapListeners() const
{
return m_overlapListeners;
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
|
[
"[email protected]"
] |
[
[
[
1,
85
]
]
] |
09ac69fac72b0a63a53976d29e5a21ebb4f34c86
|
0a7a70f6d547867755f317e5569e63709672eba1
|
/src/ndssys/ndssys.h
|
5234f8f06feec60b50747e0072c075b66b0ac3c8
|
[] |
no_license
|
ballercat/ends
|
f787b03f90638ca3ad03735c65875f386456dad3
|
e3bb04481e289c272387d30ede8a7526226ba14d
|
refs/heads/master
| 2016-09-10T09:41:55.820693 | 2009-08-30T00:14:10 | 2009-08-30T00:14:10 | 35,772,611 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 684 |
h
|
#ifndef NDSSYS_H
#define NDSSYS_H
#include "../ndscpu/ndscpu.h"
#include "../ndsmem/ndsmem.h"
#ifndef NDS_DEBUG
#include "../ndsvideo/ndsvideo.h"
#include <SDL/SDL.h>
#endif
#include <cstdio>
class NDSSYSTEM
{
public:
NDSSYSTEM();
virtual ~NDSSYSTEM();
bool nds_loadfile(const char *fpath);
int parseinput();
int exec();
#ifndef NDS_DEBUG
protected:
SDL_Surface *screen;
NDSVIDEO *vid;
NDSMMU *mmu;
NDSCPU *cpu;
FILE *rom;
#else
NDSMMU *mmu;
NDSCPU *cpu;
protected:
FILE *rom;
#endif
};
#endif
|
[
"whinemore@5982b672-94f9-11de-9b71-cb34e3bcb0e2"
] |
[
[
[
1,
48
]
]
] |
527450971b7a8b77868f8c01843a7795990c1312
|
9426ad6e612863451ad7aac2ad8c8dd100a37a98
|
/ULLib/include/ULWaitCursor.h
|
af6c7e63b07fdec1d08d77800837fe14b3bcc9c0
|
[] |
no_license
|
piroxiljin/ullib
|
61f7bd176c6088d42fd5aa38a4ba5d4825becd35
|
7072af667b6d91a3afd2f64310c6e1f3f6a055b1
|
refs/heads/master
| 2020-12-28T19:46:57.920199 | 2010-02-17T01:43:44 | 2010-02-17T01:43:44 | 57,068,293 | 0 | 0 | null | 2016-04-25T19:05:41 | 2016-04-25T19:05:41 | null |
WINDOWS-1251
|
C++
| false | false | 675 |
h
|
///\file ULWaitCursor.h
///\brief фаил объявления класса курсора ожидания
#include <windows.h>
namespace ULOther
{
///\class CULWaitCursor
///\brief класса курсора ожидания
class CULWaitCursor
{
///\brief хендл курсора ожидания
HCURSOR m_hWaitCursor;
///\brief хендл предыдущего курсора
HCURSOR m_hCursor;
public:
///\brief конструктор
CULWaitCursor();
///\brief деструктор
~CULWaitCursor();
///\brief функция для востановления начального курсора
void Restore();
};
}
|
[
"UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f"
] |
[
[
[
1,
22
]
]
] |
af021bf66bcce9e353f91fd0dc64935aa8308903
|
ab582de0495f9b016e4602b578c3e9e2475bec44
|
/src/game/shared/weapon_parse.h
|
18d319ec7d771f0c833eb1efbacb95e80a41a181
|
[] |
no_license
|
lion7/millerslake
|
bf9e36493b10d5ac4619a0d59f4cfb0983bf0470
|
186ec556b5066c306c5735ab7efe136f1ce03019
|
refs/heads/master
| 2021-04-09T17:14:25.666942 | 2010-12-04T02:13:54 | 2010-12-04T02:13:54 | 32,201,552 | 0 | 0 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 6,227 |
h
|
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Weapon data file parsing, shared by game & client dlls.
//
// $NoKeywords: $
//=============================================================================//
#ifndef WEAPON_PARSE_H
#define WEAPON_PARSE_H
#ifdef _WIN32
#pragma once
#endif
#include "shareddefs.h"
class IFileSystem;
typedef unsigned short WEAPON_FILE_INFO_HANDLE;
// -----------------------------------------------------------
// Weapon sound types
// Used to play sounds defined in the weapon's classname.txt file
// This needs to match pWeaponSoundCategories in weapon_parse.cpp
// ------------------------------------------------------------
typedef enum {
EMPTY,
SINGLE,
SINGLE_NPC,
WPN_DOUBLE, // Can't be "DOUBLE" because windows.h uses it.
DOUBLE_NPC,
BURST,
RELOAD,
RELOAD_NPC,
MELEE_MISS,
MELEE_HIT,
MELEE_HIT_WORLD,
SPECIAL1,
SPECIAL2,
SPECIAL3,
TAUNT,
// Add new shoot sound types here
NUM_SHOOT_SOUND_TYPES,
} WeaponSound_t;
int GetWeaponSoundFromString( const char *pszString );
#define MAX_SHOOT_SOUNDS 16 // Maximum number of shoot sounds per shoot type
#define MAX_WEAPON_STRING 80
#define MAX_WEAPON_PREFIX 16
#define MAX_WEAPON_AMMO_NAME 32
#define WEAPON_PRINTNAME_MISSING "!!! Missing printname on weapon"
class CHudTexture;
class KeyValues;
//-----------------------------------------------------------------------------
// Purpose: Contains the data read from the weapon's script file.
// It's cached so we only read each weapon's script file once.
// Each game provides a CreateWeaponInfo function so it can have game-specific
// data (like CS move speeds) in the weapon script.
//-----------------------------------------------------------------------------
class FileWeaponInfo_t
{
public:
FileWeaponInfo_t();
// Each game can override this to get whatever values it wants from the script.
virtual void Parse( KeyValues *pKeyValuesData, const char *szWeaponName );
public:
bool bParsedScript;
bool bLoadedHudElements;
Vector vecIronsightPosOffset;// Millers Lake - Problems - 26-08-2010: Ironsights Offset position.
QAngle angIronsightAngOffset;// Millers Lake - Problems - 26-08-2010: Ironsights Offset angle.
float flIronsightFOVOffset; // Millers Lake - Problems - 26-08-2010: Ironsights Field of View Offest.
// SHARED
char szClassName[MAX_WEAPON_STRING];
char szPrintName[MAX_WEAPON_STRING]; // Name for showing in HUD, etc.
char szViewModel[MAX_WEAPON_STRING]; // View model of this weapon
char szWorldModel[MAX_WEAPON_STRING]; // Model of this weapon seen carried by the player
char szAnimationPrefix[MAX_WEAPON_PREFIX]; // Prefix of the animations that should be used by the player carrying this weapon
int iSlot; // inventory slot.
int iPosition; // position in the inventory slot.
int iMaxClip1; // max primary clip size (-1 if no clip)
int iMaxClip2; // max secondary clip size (-1 if no clip)
int iDefaultClip1; // amount of primary ammo in the gun when it's created
int iDefaultClip2; // amount of secondary ammo in the gun when it's created
int iWeight; // this value used to determine this weapon's importance in autoselection.
int iRumbleEffect; // Which rumble effect to use when fired? (xbox)
bool bAutoSwitchTo; // whether this weapon should be considered for autoswitching to
bool bAutoSwitchFrom; // whether this weapon can be autoswitched away from when picking up another weapon or ammo
int iFlags; // miscellaneous weapon flags
char szAmmo1[MAX_WEAPON_AMMO_NAME]; // "primary" ammo type
char szAmmo2[MAX_WEAPON_AMMO_NAME]; // "secondary" ammo type
// Sound blocks
char aShootSounds[NUM_SHOOT_SOUND_TYPES][MAX_WEAPON_STRING];
int iAmmoType;
int iAmmo2Type;
bool m_bMeleeWeapon; // Melee weapons can always "fire" regardless of ammo.
// This tells if the weapon was built right-handed (defaults to true).
// This helps cl_righthand make the decision about whether to flip the model or not.
bool m_bBuiltRightHanded;
bool m_bAllowFlipping; // False to disallow flipping the model, regardless of whether
// it is built left or right handed.
// CLIENT DLL
// Sprite data, read from the data file
int iSpriteCount;
CHudTexture *iconActive;
CHudTexture *iconInactive;
CHudTexture *iconAmmo;
CHudTexture *iconAmmo2;
CHudTexture *iconCrosshair;
CHudTexture *iconAutoaim;
CHudTexture *iconZoomedCrosshair;
CHudTexture *iconZoomedAutoaim;
CHudTexture *iconSmall;
// TF2 specific
bool bShowUsageHint; // if true, then when you receive the weapon, show a hint about it
// SERVER DLL
};
// The weapon parse function
bool ReadWeaponDataFromFileForSlot( IFileSystem* filesystem, const char *szWeaponName,
WEAPON_FILE_INFO_HANDLE *phandle, const unsigned char *pICEKey = NULL );
// If weapon info has been loaded for the specified class name, this returns it.
WEAPON_FILE_INFO_HANDLE LookupWeaponInfoSlot( const char *name );
FileWeaponInfo_t *GetFileWeaponInfoFromHandle( WEAPON_FILE_INFO_HANDLE handle );
WEAPON_FILE_INFO_HANDLE GetInvalidWeaponInfoHandle( void );
void PrecacheFileWeaponInfoDatabase( IFileSystem *filesystem, const unsigned char *pICEKey );
//
// Read a possibly-encrypted KeyValues file in.
// If pICEKey is NULL, then it appends .txt to the filename and loads it as an unencrypted file.
// If pICEKey is non-NULL, then it appends .ctx to the filename and loads it as an encrypted file.
//
// (This should be moved into a more appropriate place).
//
KeyValues* ReadEncryptedKVFile( IFileSystem *filesystem, const char *szFilenameWithoutExtension, const unsigned char *pICEKey );
// Each game implements this. It can return a derived class and override Parse() if it wants.
extern FileWeaponInfo_t* CreateWeaponInfo();
#endif // WEAPON_PARSE_H
|
[
"[email protected]@1b4041a7-fb09-ea03-7d66-d8ed986ac175",
"[email protected]@1b4041a7-fb09-ea03-7d66-d8ed986ac175"
] |
[
[
[
1,
79
],
[
82,
82
],
[
84,
164
]
],
[
[
80,
81
],
[
83,
83
]
]
] |
7606121f7a80179599bfbddff763201c5b4bd62a
|
205069c97095da8f15e45cede1525f384ba6efd2
|
/Casino/Code/Server/ShareModule/CommonModule/ExceptionHandle.cpp
|
7130c386a861676b0c5fff437c1fcc91ec748121
|
[] |
no_license
|
m0o0m/01technology
|
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
|
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
|
refs/heads/master
| 2021-01-17T22:12:26.467196 | 2010-01-05T06:39:11 | 2010-01-05T06:39:11 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,363 |
cpp
|
#include "stdafx.h"
#include "ExceptionHandle.h"
#include "se_translator.h"
#include "exception_trap.h"
#include "unhandled_report.h"
#include "sym_engine.h"
#include "debug_stream.h"
#include "exception2.h"
#include <fstream>
#include <iosfwd>
bool GT_DumpToStream(std::ostream& os,const TCHAR* szType,const TCHAR *pszFileName, int nLineNo, LPTSTR pszMsg)
{
os << TEXT("[Type]") << szType << std::endl;
SYSTEMTIME sysTm;
::GetLocalTime(&sysTm);
os << TEXT("[Time]") << sysTm.wMonth << TEXT("-") << sysTm.wDay << TEXT(" ")
<< sysTm.wHour << TEXT(":") << sysTm.wMinute << TEXT(":") << sysTm.wSecond <<std::endl;
TCHAR szModule[256] = "";
GetModuleFileName(NULL,szModule,256);
os << TEXT("[Module]") << szModule << TEXT(" [File]") << pszFileName << TEXT(" [Line]") << nLineNo << std::endl;
os << TEXT("[ThreadID]") << GetCurrentThreadId() << std::endl;
os << TEXT("[Message]") << pszMsg << std::endl;
return true;
}
bool GT_DumpToFile(const TCHAR* szType,const TCHAR *pszFileName, int nLineNo, LPTSTR pszMsg)
{
std::ofstream ofs;
ofs.open(EXCEPTOINHANDLE_FILEPATH,std::ios::app);
if(ofs.is_open())
{
ofs << TEXT("**********************************************************************") <<std::endl;
GT_DumpToStream(ofs,szType, pszFileName,nLineNo,pszMsg);
ofs << TEXT("[Trace]") << std::endl;
sym_engine::stack_trace(ofs);
ofs << TEXT("**********************************************************************") <<std::endl;
ofs.close();
}
return true;
}
bool GT_DumpSimple(const TCHAR* szType,const TCHAR *pszFileName, int nLineNo, LPTSTR szMsg)
{
GT_DumpToFile(szType, pszFileName,nLineNo,szMsg);
return true;
}
bool GT_DumpDetail(const TCHAR* szType,const TCHAR *pszFileName, int nLineNo, LPTSTR szFormat,...)
{
TCHAR szBuffer[2048]={0};
const size_t NUMCHARS = sizeof(szBuffer) / sizeof(szBuffer[0]);
const int LASTCHAR = NUMCHARS - 1;
va_list pArgs;
va_start(pArgs, szFormat);
_vsntprintf(szBuffer, NUMCHARS - 1, szFormat, pArgs);
va_end(pArgs);
szBuffer[LASTCHAR] = TEXT('\0');
GT_DumpToFile(szType, pszFileName,nLineNo,szBuffer);
return true;
}
bool GT_Dump_Access_violation(const TCHAR *pszFileName, int nLineNo, se_translator::access_violation& ex)
{
std::ofstream ofs;
ofs.open(EXCEPTOINHANDLE_FILEPATH,std::ios::app);
if(ofs.is_open())
{
ofs << TEXT("**********************************************************************") <<std::endl;
GT_DumpToStream(ofs,"Error", pszFileName,nLineNo,"");
ofs << TEXT("[Trace]") << std::endl;
ofs << ex.name() << " at 0x" << std::hex << ex.address()
<< ", thread attempts to " << (ex.is_read_op() ? "read" : "write")
<< " at 0x" << std::right << ex.inaccessible_address() << std::endl
<< "stack trace : " << std::endl;
sym_engine::stack_trace(ofs, ex.info()->ContextRecord);
ofs << TEXT("**********************************************************************") <<std::endl;
ofs.close();
}
return true;
}
bool GT_Dump_Se_translator(const TCHAR *pszFileName, int nLineNo, se_translator::no_memory& ex)
{
std::ofstream ofs;
ofs.open(EXCEPTOINHANDLE_FILEPATH,std::ios::app);
if(ofs.is_open())
{
ofs << TEXT("**********************************************************************") <<std::endl;
GT_DumpToStream(ofs,"Error", pszFileName,nLineNo,"");
ofs << ex.name() << " at 0x" << std::hex << ex.address()
<< ", unable to allocate " << std::dec << ex.mem_size() << " bytes" << std::endl
<< "stack trace : " << std::endl;
sym_engine::stack_trace(ofs, ex.info()->ContextRecord);
ofs << TEXT("**********************************************************************") <<std::endl;
ofs.close();
}
return true;
}
bool GT_Dump_Exception2(const TCHAR *pszFileName, int nLineNo, exception2& ex)
{
std::ofstream ofs;
ofs.open(EXCEPTOINHANDLE_FILEPATH,std::ios::app);
if(ofs.is_open())
{
ofs << TEXT("**********************************************************************") <<std::endl;
GT_DumpToStream(ofs,"Error", pszFileName,nLineNo,"");
ofs << ex.what() << std::endl
<< "stack trace :" << std::endl
<< ex.stack_trace() << std::endl;
ofs << TEXT("**********************************************************************") <<std::endl;
ofs.close();
}
return true;
}
|
[
"[email protected]"
] |
[
[
[
1,
122
]
]
] |
91ac5044def703431c717e89cd4a31998228f353
|
5506729a4934330023f745c3c5497619bddbae1d
|
/vst2.x/P4P1Feed/source/UdpLog.h
|
ad4d8edf10aa238cbb718a9aecdd1eb884ca9506
|
[] |
no_license
|
berak/vst2.0
|
9e6d1d7246567f367d8ba36cf6f76422f010739e
|
9d8f51ad3233b9375f7768be528525c15a2ba7a1
|
refs/heads/master
| 2020-03-27T05:42:19.762167 | 2011-02-18T13:35:09 | 2011-02-18T13:35:09 | 1,918,997 | 4 | 3 | null | null | null | null |
UTF-8
|
C++
| false | false | 242 |
h
|
#ifndef __UdpLog_onboard__
#define __UdpLog_onboard__
namespace UdpLog
{
void setup( int port, const char * host );
void print( const char * msg );
void printf( const char * format, ... );
};
#endif // __UdpLog_onboard__
|
[
"[email protected]"
] |
[
[
[
1,
13
]
]
] |
88edb3d8293b494b2f1555c293a0b1ee38d60413
|
6dac9369d44799e368d866638433fbd17873dcf7
|
/a.i.wars/src/branches/version-0.4/src/UserInterface.cpp
|
c6d1d2f1d6ab80f5835f5a87f77a7c66ad48ce4d
|
[] |
no_license
|
christhomas/fusionengine
|
286b33f2c6a7df785398ffbe7eea1c367e512b8d
|
95422685027bb19986ba64c612049faa5899690e
|
refs/heads/master
| 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,797 |
cpp
|
#include <aiwars.h>
SceneGraph *LoadScene; // Loading scenegraph
SceneGraph *TitleScene; // Titlescreen scenegraph
SceneGraph *GameScene; // In game scenegraph
UserInterface *LoadUI; // Loading interface
UserInterface *GameUI; // Game interface
IFont *font; // Font to render text
void UI_Loading(void)
{
LoadScene = fusion->Scene->AddScene();
fusion->Scene->ActivateScene(LoadScene);
// Activate Loading scene and Interface + Create a window for components
LoadUI = fusion->Interface->AddUI(LoadScene);
LoadUI->SetActive(true);
Window *w = LoadUI->AddWindow(fusion->Input);
// Load up a new font
font = fusion->Font->AddFont("Lucida.txf",TEXTUREFONT);
Textbox *Loading;
Textbox *Section;
Textbox *PoweredBy;
// Create all the Loading screen textboxes
Loading = reinterpret_cast<Textbox *>(w->AddComponent(new TextBoxSetup(20,SCREENHEIGHT-80,1,font,"Loading...")));
Section = reinterpret_cast<Textbox *>(w->AddComponent(new TextBoxSetup(20,SCREENHEIGHT-60,1,font,"For What its worth")));
PoweredBy = reinterpret_cast<Textbox *>(w->AddComponent(new TextBoxSetup(SCREENWIDTH-550,SCREENHEIGHT-570,1,font,"Powered By:")));
// Scale down the text accordingly
Loading->SetScale(0.5,0.5);
Section->SetScale(0.5,0.5);
PoweredBy->SetScale(0.5,0.5);
ITexture *t;
Overlay *o;
Entity *e;
// Create a texture, apply it to a new overlay
t = fusion->Graphics->CreateTexture("file://sprites/Fusion.tga");
o = fusion->Mesh->CreateOverlay(t);
// add a new animation frame
o->AddFrame();
// create an entity and use the overlay as the mesh
e = fusion->Mesh->CreateEntity(o);
// Scale the entity and set it's animation function
e->SetTranslate(TRANSLATE_ABS,SCREENWIDTH-550,SCREENHEIGHT-550,1);
e->SetScale(500,500,1);
LoadScene->AddEntity(e);
}
void UI_Titlescreen(void)
{
TitleScene = fusion->Scene->AddScene();
ITexture *t;
Overlay *o;
Entity *e;
t = fusion->Graphics->CreateTexture("file://sprites/title.tga");
o = fusion->Mesh->CreateOverlay(t);
o->AddFrame();
e = fusion->Mesh->CreateEntity(o);
e->SetTranslate(TRANSLATE_ABS,100,50,1);
e->SetScale(800,150,1);
TitleScene->AddEntity(e);
}
void UI_Game(void)
{
GameUI = fusion->Interface->AddUI(GameScene);
GameUI->SetActive(true);
Window *w = GameUI->AddWindow(fusion->Input);
for(unsigned int a=0;a<serverbot.size();a++){
Textbox *e = reinterpret_cast<Textbox *>(w->AddComponent(new TextBoxSetup(5,a*20,1,font,"#ERR")));
Textbox *n = reinterpret_cast<Textbox *>(w->AddComponent(new TextBoxSetup(20,a*20,1,font,"#ERR")));
e->SetScale(0.3f,0.3f);
e->SetColour(0,255,0,255);
n->SetScale(0.3f,0.3f);
n->SetColour(0,255,0,255);
serverbot[a]->SetDisplay(e,n);
}
}
|
[
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] |
[
[
[
1,
95
]
]
] |
8b2e0fec5971019a85bacfa31ea5cb0522e7e8a5
|
416087e3ebe80322737f53b3ca8ad5581967bb8d
|
/PCSuit/ECGProject/Filter.cpp
|
c9398501cb2f711e0e40895ea13c1c39bfa0bd48
|
[] |
no_license
|
caijilong/ecgsystem
|
a05c5796cbd86e5a4df1f4265ffa8c8252b126c0
|
fcc385ff759cb377a881af3c8fddca1224522e44
|
refs/heads/master
| 2021-01-21T22:26:41.957544 | 2009-07-28T16:27:17 | 2009-07-28T16:27:17 | 37,576,995 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,441 |
cpp
|
#include "stdafx.h"
#include "Filter.h"
#include "math.h"
CFilter::CFilter(int SamplingRate)
{
//LoadFilterCoeff();
sampling_rate = SamplingRate;
Filter_Buffer_40 = new float[BUFFER_SIZE];
Filter_Buffer_60 = new float[BUFFER_SIZE];
Filter_Buffer_0_05 = new float[BUFFER_SIZE];
for (int i=0;i<BUFFER_SIZE;i++) Filter_Buffer_40[i] = 0;
for (int i=0;i<BUFFER_SIZE;i++) Filter_Buffer_60[i] = 0;
for (int i=0;i<BUFFER_SIZE;i++) Filter_Buffer_0_05[i] = 0;
}
CFilter::~CFilter(void)
{
if (Filter_Buffer_40 != 0){
delete Filter_Buffer_40;
delete Filter_Buffer_60;
delete Filter_Buffer_0_05;
}
}
float CFilter::FixFilter(int samp)
{
double coeff[251] = {0.019573,-0.000485,0.000190,0.000529,-0.000401,0.002838,-0.000750,-0.000550,0.001138,0.000070,0.002687,-0.001686,-0.001029,
0.002653,0.000193,0.001208,-0.002447,-0.000144,0.004206,-0.001384,-0.000856,-0.001354,0.001518,0.003792,-0.004342,-0.001247,0.001642,
0.001407,0.000896,-0.006011,0.001030,0.003825,-0.001943,-0.001853,-0.004201,0.003550,0.002454,-0.006492,-0.001253,-0.000543,0.002621,
-0.001372,-0.008187,0.002208,0.000765,-0.001923,-0.003409,-0.006166,0.004322,-0.001716,-0.006085,-0.001650,-0.004097,0.002596,-0.004621,
-0.007022,0.000940,-0.004993,-0.000400,-0.004768,-0.006991,0.001114,-0.006792,-0.001450,-0.004037,-0.009176,0.000752,-0.006173,-0.002577,
-0.005833,-0.011358,0.003552,-0.005518,-0.007979,-0.007502,-0.008616,0.006726,-0.010560,-0.014953,-0.002137,-0.003346,0.002106,-0.019414,
-0.014052,0.009436,-0.006298,-0.010899,-0.019996,-0.002926,0.014289,-0.022074,-0.018758,-0.004960,0.004636,0.002331,-0.037352,-0.008358,
0.013696,-0.007788,-0.015976,-0.032885,0.012349,0.014418,-0.035932,-0.016456,-0.009321,0.017617,-0.005887,-0.054363,0.009824,0.007516,
-0.006616,-0.021109,-0.046761,0.041946,-0.005078,-0.043679,0.000824,-0.035279,0.056060,-0.037059,-0.075572,0.095819,-0.133451,0.183610,
0.745942,0.183610,-0.133451,0.095819,-0.075572,-0.037059,0.056060,-0.035279,0.000824,-0.043679,-0.005078,0.041946,-0.046761,-0.021109,
-0.006616,0.007516,0.009824,-0.054363,-0.005887,0.017617,-0.009321,-0.016456,-0.035932,0.014418,0.012349,-0.032885,-0.015976,-0.007788,
0.013696,-0.008358,-0.037352,0.002331,0.004636,-0.004960,-0.018758,-0.022074,0.014289,-0.002926,-0.019996,-0.010899,-0.006298,0.009436,
-0.014052,-0.019414,0.002106,-0.003346,-0.002137,-0.014953,-0.010560,0.006726,-0.008616,-0.007502,-0.007979,-0.005518,0.003552,-0.011358,
-0.005833,-0.002577,-0.006173,0.000752,-0.009176,-0.004037,-0.001450,-0.006792,0.001114,-0.006991,-0.004768,-0.000400,-0.004993,0.000940,
-0.007022,-0.004621,0.002596,-0.004097,-0.001650,-0.006085,-0.001716,0.004322,-0.006166,-0.003409,-0.001923,0.000765,0.002208,-0.008187,
-0.001372,0.002621,-0.000543,-0.001253,-0.006492,0.002454,0.003550,-0.004201,-0.001853,-0.001943,0.003825,0.001030,-0.006011,0.000896,
0.001407,0.001642,-0.001247,-0.004342,0.003792,0.001518,-0.001354,-0.000856,-0.001384,0.004206,-0.000144,-0.002447,0.001208,0.000193,
0.002653,-0.001029,-0.001686,0.002687,0.000070,0.001138,-0.000550,-0.000750,0.002838,-0.000401,0.000529,0.000190,-0.000485,0.019573};
float ret;
for (int i=BUFFER_SIZE-1;i>0;i--) Filter_Buffer_40[i] = Filter_Buffer_40[i-1];
Filter_Buffer_40[0] = samp;
ret = RTConvolution(Filter_Buffer_40,(float *)coeff,251);
return ret;
}
void CFilter::LoadFilterCoeff(int sampling_rate)
{
Coeff_40_LP = new float[101];
Coeff_60Notch = new float[301];
Coeff_0_05_HP = new float[371];
CreatFIRCoeff(Coeff_40_LP,50,sampling_rate,101,LP);
CreatFIRCoeff(Coeff_60Notch,60,sampling_rate,301,NOTCH);
CreatFIRCoeff(Coeff_0_05_HP,1.0f,sampling_rate,371,HP);
}
float CFilter::Sinc(float FC,int n,int FilterLen)
{
float s;
if((n - FilterLen/2)==0)
s = 2*PI*FC;
else if(0 > (n-FilterLen/2) || 0 < (n-FilterLen/2))
s = sin(2*PI*FC*(n-FilterLen/2))/(n-FilterLen/2);
s = s*(0.54f-0.46f*cos(2*PI*n/FilterLen));
return s;
}
void CFilter::CreatFIRCoeff(float *Coeff,float CutFreq,int SamplingRate,int FilterLen,int FilterType)
{
int i;
float sum = 0,FC;
if (FilterType == NOTCH) FC = float(CutFreq-2) / SamplingRate;
else if (FilterType == HP) FC = float((SamplingRate / 2) - CutFreq) / SamplingRate;
else FC = float(CutFreq) / SamplingRate;
for(i=0;i<FilterLen;i++)
{
Coeff[i] = Sinc(FC,i,FilterLen);
}
//Calculate unity gain at dc
sum = 0;
for(i=0;i<FilterLen;i++)
{
sum = sum+Coeff[i];
}
//Normalize for unity gain
for(i=0;i<FilterLen;i++)
{
Coeff[i] = Coeff[i]/sum;
}
if (FilterType == HP){
for(i=1;i<FilterLen;i+=2)
{
Coeff[i] = -Coeff[i];
}
}else if (FilterType == NOTCH){
float *Coeff2;
Coeff2 = new float[FilterLen];
FC = float(CutFreq+2) / SamplingRate;
for(i=0;i<FilterLen;i++)
{
Coeff2[i] = Sinc(FC,i,FilterLen);
}
//Calculate unity gain at dc
sum = 0;
for(i=0;i<FilterLen;i++)
{
sum = sum+Coeff2[i];
}
//Normalize for unity gain
for(i=0;i<FilterLen;i++)
{
Coeff2[i] = Coeff2[i]/sum;
}
for(i=1;i<FilterLen;i+=2)
{
Coeff2[i] = -Coeff2[i];
}
//Calculate summ kernel
for(i=0;i<FilterLen;i++)
{
Coeff[i] = Coeff[i]+Coeff2[i];
}
delete Coeff2;
}
}
float CFilter::FIR_40_LP(float samp)
{
int i;
float ret;
for (i=BUFFER_SIZE-1;i>0;i--) Filter_Buffer_40[i] = Filter_Buffer_40[i-1];
Filter_Buffer_40[0] = samp;
ret = RTConvolution(Filter_Buffer_40,Coeff_40_LP,101);
return ret;
}
float CFilter::FIR_60Notch(float samp)
{
int i;
float ret;
for (i=BUFFER_SIZE-1;i>0;i--) Filter_Buffer_60[i] = Filter_Buffer_60[i-1];
Filter_Buffer_60[0] = samp;
ret = RTConvolution(Filter_Buffer_60,Coeff_60Notch,301);
return ret;
}
float CFilter::FIR_0_05_HP(float samp)
{
int i;
float ret;
for (i=BUFFER_SIZE-1;i>0;i--) Filter_Buffer_0_05[i] = Filter_Buffer_0_05[i-1];
Filter_Buffer_0_05[0] = samp;
ret = RTConvolution(Filter_Buffer_0_05,Coeff_0_05_HP,371);
return ret;
}
float CFilter::RTConvolution(float *xn,float *hn,int hn_len)
{
int i,j,k;
float y;
y = 0;
for(i=0;i<hn_len;i++){
y += (hn[i]*xn[i]);
}
return y;
}
void CFilter::Convolution(float *xn,float *yn,float *hn,int hn_len,int xn_len)
{
int i,j,k;
float y;
for(j=0;j<xn_len;j++){
y = 0;
for(i=0;i<hn_len;i++){
k = j-i;
if (k >= 0 && k < xn_len) y += (hn[i]*xn[k]);
}
yn[j] = y;
}
}
|
[
"hawk.hsieh@6a298216-7b91-11de-a1b3-85d0aeae5c5b"
] |
[
[
[
1,
192
]
]
] |
6135788c846cc2a649faddbdf6444062fc9a24aa
|
8fd82049c092a6b80f63f402aca243096eb7b3c8
|
/MFCMailServer/MFCMailServer/Smtp.cpp
|
81fe93706128e4da016f527f6ff15dd57f64b3aa
|
[] |
no_license
|
phucnh/laptrinhmang-k52
|
47965acb82750b600b543cc5c43d00f59ce5bc54
|
b27a8a02f9ec8bf953b617402dce37293413bb0f
|
refs/heads/master
| 2021-01-18T22:22:24.692192 | 2010-12-09T02:00:10 | 2010-12-09T02:00:10 | 32,262,504 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 759 |
cpp
|
// Smtp.cpp : implementation file
//
#include "stdafx.h"
#include "MFCMailServer.h"
#include "Smtp.h"
#include "smtpclient.h"
// CSmtp
CSmtp::CSmtp()
{
}
CSmtp::CSmtp( CMFCMailServerDlg* parrent )
{
this->parrentDlg = parrent;
}
CSmtp::~CSmtp()
{
}
// CSmtp member functions
void CSmtp::OnAccept(int nErrorCode)
{
CSMTPClient* socketClient = new CSMTPClient(parrentDlg);
if (Accept(*socketClient))
{
CString sMsg("+OK SMTP Mail server connected"); // TODO: Implement message in here
sMsg.ReleaseBuffer();
sMsg+="\r\n";
socketClient->Send(sMsg,sMsg.GetLength(),0);
//phuc add 20101121
this->parrentDlg->WriteLog(sMsg);
//end phuc add 20101121
}
CAsyncSocket::OnAccept(nErrorCode);
}
|
[
"nguyenhongphuc.hut@e1f3f65c-33eb-5b6a-8ef2-7789ca584060"
] |
[
[
[
1,
45
]
]
] |
0e46915e9046c7f798bde6196cc2b8eddbb0b211
|
e626f4235084b56fcc1d619b9fffc5216f5eec0c
|
/metaparser2/ComMetaParserService20/RuleNode.h
|
90b7f0438d1693bb743c4e10996bb333588728bf
|
[] |
no_license
|
Programming-Systems-Lab/archived-metaparser2
|
b6721d6a040eac85f38600f43cb83136fe936f2c
|
aa8401f295f601833f17f6b2dd098fef211ee49b
|
refs/heads/master
| 2020-07-09T05:15:55.067233 | 2002-05-13T22:43:16 | 2002-05-13T22:43:16 | 67,139,974 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,047 |
h
|
#ifndef _MP_RULENODE_H
#define _MP_RULENODE_H
#include "NodeValue.h"
#include <vector>
enum nodeType
{
VARIABLE,
CONDITION,
OPERATOR,
OR,
AND,
ACTION,
RULE,
RULESET,
NOSUCHTYPE
};
enum operatorType
{
EQ,
NE,
GT,
GTE,
LT,
LTE,
MATCH
};
nodeType GetType(_bstr_t &t);
class MPNode
{
public:
MPNode() { m_pVal = NULL; }
virtual ~MPNode();
virtual void AddChild(MPNode* child);
virtual void PrintNode(int indent);
virtual void SetValue(NodeValue *pVal) { m_pVal = pVal; }
virtual void SetNamespace(_bstr_t &ns) { m_Namespace = ns; }
virtual void SetParser(IXMLDOMDocument2Ptr pDoc) { m_pDoc = pDoc; }
virtual void SetOutputDoc(IXMLDOMDocument2Ptr pOutputDoc) { m_pOutputDoc = pOutputDoc; }
virtual _bstr_t GetNamespace() { return m_Namespace; }
virtual NodeValue* Eval() = 0;
nodeType m_Type;
protected:
NodeValue *m_pVal;
_bstr_t m_Namespace;
IXMLDOMDocument2Ptr m_pDoc;
IXMLDOMDocument2Ptr m_pOutputDoc;
typedef std::vector<MPNode*> MPNodeList;
MPNodeList m_Children;
};
class VariableNode : public MPNode
{
public:
VariableNode();
virtual ~VariableNode();
virtual void PrintNode(int indent);
virtual void SetValue(NodeValue *pVal);
virtual NodeValue* Eval();
};
class ConditionNode : public MPNode
{
public:
ConditionNode();
virtual ~ConditionNode() { }
virtual void PrintNode(int indent);
virtual NodeValue* Eval();
virtual void SetValue(NodeValue *pVal);
protected:
bool Lte(VariableNode *a, VariableNode *b);
bool Lt(VariableNode *a, VariableNode *b);
bool Gte(VariableNode *a, VariableNode *b);
bool Gt(VariableNode *a, VariableNode *b);
bool Ne(VariableNode *a, VariableNode *b);
bool Eq(VariableNode *a, VariableNode *b);
bool Match(VariableNode *a, VariableNode *b);
};
class OperatorNode : public MPNode
{
public:
OperatorNode();
virtual ~OperatorNode() { }
virtual void PrintNode(int indent);
virtual NodeValue* Eval();
virtual void SetValue(NodeValue *pVal);
};
class OrNode : public MPNode
{
public:
OrNode();
virtual ~OrNode() { }
virtual void PrintNode(int indent);
virtual NodeValue* Eval();
virtual void SetValue(NodeValue *pVal);
};
class AndNode : public MPNode
{
public:
AndNode();
virtual ~AndNode() { }
virtual void PrintNode(int indent);
virtual NodeValue* Eval();
virtual void SetValue(NodeValue *pVal);
};
class ActionNode : public MPNode
{
public:
ActionNode();
virtual ~ActionNode() { }
virtual void PrintNode(int indent);
virtual void SetValue(NodeValue *pVal);
virtual NodeValue* Eval();
};
class RuleNode : public MPNode
{
public:
RuleNode();
virtual ~RuleNode() { }
virtual void PrintNode(int indent);
virtual NodeValue* Eval();
virtual void SetValue(NodeValue *pVal);
};
class RuleSetNode : public MPNode
{
public:
RuleSetNode();
virtual ~RuleSetNode() { }
virtual void PrintNode(int indent);
virtual void SetValue(NodeValue *pVal);
virtual NodeValue* Eval();
};
#endif
|
[
"sw375"
] |
[
[
[
1,
146
]
]
] |
82e84afcf5184f097b7f412ca5f73e2f843306f1
|
519a3884c80f7a3926880b28df5755935ec7aa57
|
/DicomShell/stdafx.cpp
|
ba8bbe78adc30eb23713d3d8e09b6c0e7a0438bf
|
[] |
no_license
|
Jeffrey2008/dicomshell
|
71ef9844ed83c38c2529a246b6efffdd5645ed92
|
14c98fcd9238428e1541e50b7d0a67878cf8add4
|
refs/heads/master
| 2020-10-01T17:39:11.786479 | 2009-09-02T17:49:27 | 2009-09-02T17:49:27 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 206 |
cpp
|
// stdafx.cpp : source file that includes just the standard includes
// DicomShell.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
|
[
"andreas.grimme@715416e8-819e-11dd-8f04-175a6ebbc832"
] |
[
[
[
1,
5
]
]
] |
acfdc72809331c77025b46af0e23fa59a3d3a507
|
c1a2953285f2a6ac7d903059b7ea6480a7e2228e
|
/deitel/ch08/Fig08_31/fig08_31.cpp
|
3295092139f852a2440a505f475daa809b0aa4f2
|
[] |
no_license
|
tecmilenio/computacion2
|
728ac47299c1a4066b6140cebc9668bf1121053a
|
a1387e0f7f11c767574fcba608d94e5d61b7f36c
|
refs/heads/master
| 2016-09-06T19:17:29.842053 | 2008-09-28T04:27:56 | 2008-09-28T04:27:56 | 50,540 | 4 | 3 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,842 |
cpp
|
// Fig. 8.31: fig08_31.cpp
// Using strcpy and strncpy.
#include <iostream>
using std::cout;
using std::endl;
#include <cstring> // prototypes for strcpy and strncpy
using std::strcpy;
using std::strncpy;
int main()
{
char x[] = "Happy Birthday to You"; // string length 21
char y[ 25 ];
char z[ 15 ];
strcpy( y, x ); // copy contents of x into y
cout << "The string in array x is: " << x
<< "\nThe string in array y is: " << y << '\n';
// copy first 14 characters of x into z
strncpy( z, x, 14 ); // does not copy null character
z[ 14 ] = '\0'; // append '\0' to z's contents
cout << "The string in array z is: " << z << endl;
return 0; // indicates successful termination
} // end main
/**************************************************************************
* (C) Copyright 1992-2008 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
|
[
"[email protected]"
] |
[
[
[
1,
43
]
]
] |
63f7c4e13d7de95db70f9a3ba7ec638afddba6b2
|
b3b0c727bbafdb33619dedb0b61b6419692e03d3
|
/Source/Calculator/ICalculator/LWCalculator_i.h
|
f4dc1a7a3de6cec7cfb786b3d53afc6f93482ccc
|
[] |
no_license
|
testzzzz/hwccnet
|
5b8fb8be799a42ef84d261e74ee6f91ecba96b1d
|
4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113
|
refs/heads/master
| 2021-01-10T02:59:32.527961 | 2009-11-04T03:39:39 | 2009-11-04T03:39:39 | 45,688,112 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,529 |
h
|
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 7.00.0500 */
/* at Sun Sep 27 10:57:23 2009
*/
/* Compiler settings for .\LWCalculator.idl:
Oicf, W1, Zp8, env=Win32 (32b run)
protocol : dce , ms_ext, c_ext, robust
error checks: stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING( )
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/
#ifndef __LWCalculator_i_h__
#define __LWCalculator_i_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifndef __ICalculator_FWD_DEFINED__
#define __ICalculator_FWD_DEFINED__
typedef interface ICalculator ICalculator;
#endif /* __ICalculator_FWD_DEFINED__ */
#ifndef __Calculator_FWD_DEFINED__
#define __Calculator_FWD_DEFINED__
#ifdef __cplusplus
typedef class Calculator Calculator;
#else
typedef struct Calculator Calculator;
#endif /* __cplusplus */
#endif /* __Calculator_FWD_DEFINED__ */
/* header files for imported files */
#include "oaidl.h"
#include "ocidl.h"
#ifdef __cplusplus
extern "C"{
#endif
#ifndef __ICalculator_INTERFACE_DEFINED__
#define __ICalculator_INTERFACE_DEFINED__
/* interface ICalculator */
/* [unique][helpstring][uuid][object] */
EXTERN_C const IID IID_ICalculator;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("44248C0A-9517-4EC4-8A86-EF057DC03436")
ICalculator : public IUnknown
{
public:
virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE PutKey(
/* [in] */ LONG key) = 0;
virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE QueryResult(
/* [retval][out] */ LONG *RetVal) = 0;
};
#else /* C style interface */
typedef struct ICalculatorVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
ICalculator * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */
__RPC__deref_out void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
ICalculator * This);
ULONG ( STDMETHODCALLTYPE *Release )(
ICalculator * This);
/* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *PutKey )(
ICalculator * This,
/* [in] */ LONG key);
/* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *QueryResult )(
ICalculator * This,
/* [retval][out] */ LONG *RetVal);
END_INTERFACE
} ICalculatorVtbl;
interface ICalculator
{
CONST_VTBL struct ICalculatorVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ICalculator_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define ICalculator_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define ICalculator_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define ICalculator_PutKey(This,key) \
( (This)->lpVtbl -> PutKey(This,key) )
#define ICalculator_QueryResult(This,RetVal) \
( (This)->lpVtbl -> QueryResult(This,RetVal) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __ICalculator_INTERFACE_DEFINED__ */
#ifndef __LWCalculatorLib_LIBRARY_DEFINED__
#define __LWCalculatorLib_LIBRARY_DEFINED__
/* library LWCalculatorLib */
/* [helpstring][version][uuid] */
EXTERN_C const IID LIBID_LWCalculatorLib;
EXTERN_C const CLSID CLSID_Calculator;
#ifdef __cplusplus
class DECLSPEC_UUID("AA4D79FB-E795-45C9-AE30-100D1F27A780")
Calculator;
#endif
#endif /* __LWCalculatorLib_LIBRARY_DEFINED__ */
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
|
[
"[email protected]"
] |
[
[
[
1,
193
]
]
] |
5e379c40e80ff60cb48e6fb5776231dd00f254be
|
d94c6cce730a771c18a6d84c7991464129ed3556
|
/vp_plugins/vprn_demon/main.cpp
|
c2eb2b313e7443fb67327dcd408e23eaa29bc3d4
|
[] |
no_license
|
S1aNT/cupsfilter
|
09afbcedb4f011744e670fae74d71fce4cebdd25
|
26ecc1e76eefecde2b00173dff9f91ebd92fb349
|
refs/heads/master
| 2021-01-02T09:26:27.015991 | 2011-03-15T06:43:47 | 2011-03-15T06:43:47 | 32,496,994 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 637 |
cpp
|
/**
* The text in UTF-8 encoding!
*/
#include <QtCore/QTextCodec>
#include <QtCore/QCoreApplication>
#include "config.h"
#include "servercore.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(images);
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForTr(codec);
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForLocale(codec);
QCoreApplication a(argc, argv);
installLog("GateKeeper",QObject::trUtf8("Техносерв А/Г"));
ServerCore server;
if ( !server.isReady() ){
return -1;
}
return a.exec();
}
|
[
"[email protected]"
] |
[
[
[
1,
26
]
]
] |
275caee223bd71c8939736cb701d70c7a702b233
|
b8c3d2d67e983bd996b76825f174bae1ba5741f2
|
/RTMP/utils/gil_2/libs/gil/sdl/test.cpp
|
c9c3052ba17832c5673b24abc78572946d59a9ce
|
[] |
no_license
|
wangscript007/rtmp-cpp
|
02172f7a209790afec4c00b8855d7a66b7834f23
|
3ec35590675560ac4fa9557ca7a5917c617d9999
|
refs/heads/master
| 2021-05-30T04:43:19.321113 | 2008-12-24T20:16:15 | 2008-12-24T20:16:15 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,320 |
cpp
|
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "boost/gil/gil_all.hpp"
#include "boost/gil/extension/io/bmp_io.hpp"
#include "boost/gil/extension/sdl/sdl_wrapper.hpp"
#include "boost/gil/extension/toolbox/hsl.hpp"
#include "boost/gil/extension/toolbox/hsl_algorithms.hpp"
using namespace std;
using namespace boost;
using namespace gil;
using namespace sdl;
struct my_timer_event_handler
{
// Return true to trigger redraw.
bool time_elapsed()
{
std::cout << "time elapsed" << std::endl;
return false;
}
};
class my_keyboard_event_handler
{
public:
my_keyboard_event_handler() {}
bool key_up()
{
toolbox::shift_hue( view( _hsl_img ), 0.1f );
copy_pixels( color_converted_view<rgb8_pixel_t>( view( _hsl_img ))
, _view );
return true;
}
void set_img( rgb8_view_t v )
{
_view = v;
_hsl_img.recreate( _view.dimensions() );
copy_pixels( color_converted_view<hsl32f_pixel_t>( _view )
, view( _hsl_img ));
}
private:
rgb8_view_t _view;
hsl32f_image_t _hsl_img;
};
struct my_redraw_event_handler
{
my_redraw_event_handler( rgb8_view_t v )
: _view( v ) {}
void redraw( const bgra8_view_t& sdl_view )
{
copy_pixels( color_converted_view<bgra8_pixel_t>( _view )
, sdl_view );
}
private:
rgb8_view_t _view;
};
int main( int argc, char* argv[] )
{
sdl_service ss;
rgb8_image_t img;
bmp_read_image( "flower.bmp", img );
typedef sdl_window< my_keyboard_event_handler
, my_redraw_event_handler
, my_timer_event_handler
> window_t;
typedef shared_ptr< window_t > window_ptr_t;
typedef shared_ptr< my_redraw_event_handler > rh_ptr_t;
rh_ptr_t rh_ptr( new my_redraw_event_handler( view( img ) ));
window_ptr_t win( new window_t( view( img ).width()
, view( img ).height()
, rh_ptr ));
win->set_img( view( img ));
win->set_timer( 1000 );
ss.add_window( win );
ss.run();
return 0;
}
|
[
"fpelliccioni@71ea4c15-5055-0410-b3ce-cda77bae7b57"
] |
[
[
[
1,
107
]
]
] |
faf52a4d3991c5f5273e1d49858746c371a0a612
|
93eac58e092f4e2a34034b8f14dcf847496d8a94
|
/ncl30-cpp/ncl30-generator/src/CompoundActionGenerator.cpp
|
c90560e7e3eef2fbedee3eac48dcd4b84c5b6256
|
[] |
no_license
|
lince/ginga-srpp
|
f8154049c7e287573f10c472944315c1c7e9f378
|
5dce1f7cded43ef8486d2d1a71ab7878c8f120b4
|
refs/heads/master
| 2020-05-27T07:54:24.324156 | 2011-10-17T13:59:11 | 2011-10-17T13:59:11 | 2,576,332 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,392 |
cpp
|
/******************************************************************************
Este arquivo eh parte da implementacao do ambiente declarativo do middleware
Ginga (Ginga-NCL).
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob
os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free
Software Foundation.
Este programa eh distribuido na expectativa de que seja util, porem, SEM
NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU
ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do
GNU versao 2 para mais detalhes.
Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto
com este programa; se nao, escreva para a Free Software Foundation, Inc., no
endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
Para maiores informacoes:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
******************************************************************************
This file is part of the declarative environment of middleware Ginga (Ginga-NCL)
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
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 GNU General Public License version 2 for more
details.
You should have received a copy of the GNU General Public License version 2
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
For further information contact:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
*******************************************************************************/
/**
* @file CompoundActionGenerator.cpp
* @author Caio Viel
* @date 29-01-10
*/
#include "../include/generables/CompoundActionGenerator.h"
namespace br {
namespace ufscar {
namespace lince {
namespace ncl {
namespace generator {
string CompoundActionGenerator::generateCode() {
string ret = "<compoundAction operator=\"";
short op = this->getOperator();
if (op == OP_PAR) {
ret += "par\" ";
} else if (op == OP_SEQ) {
ret += "seq\" ";
} else if (op == OP_EXCL) {
ret += "excl\" ";
}
string delay = this->getDelay();
if (delay != "0") {
ret += "delay=\"" + delay + "\" ";
}
ret += ">\n";
vector<Action*>* actions = this->getActions();
vector<Action*>::iterator it;
it = actions->begin();
while (it != actions->end()) {
Action* action = *it;
if (action->instanceOf("SimpleAction")) {
ret+= static_cast<SimpleActionGenerator*>(action)->generateCode() + "\n";
} else if (action->instanceOf("CompoundAction")) {
ret+= static_cast<CompoundActionGenerator*>(action)->generateCode() + "\n";
}
it++;
}
ret += "</compoundAction>\n";
return ret;
}
}
}
}
}
}
|
[
"[email protected]"
] |
[
[
[
1,
103
]
]
] |
b7b621e649bef164e91cf8732109dd9d80b2945a
|
dcff0f39e83ecab2ddcd482f3952ba317ee98f6c
|
/class-c++/proj1/main.cpp
|
cff64fdad749741492f84e7486e7b6a5a6660221
|
[] |
no_license
|
omgmovieslol/Code
|
f64048bc173e56538bb5f6164cce5d447cd7bd64
|
d5083b416469507b685a81d07a78fec1868644b1
|
refs/heads/master
| 2021-01-01T18:49:25.480158 | 2010-03-08T09:25:01 | 2010-03-08T09:25:01 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,058 |
cpp
|
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#define input_read 20
using namespace std;
int main()
{
int n;
char file1[input_read];
cout<<"Enter the file name"<< endl;
cin>> file1;
char fileout[input_read];
cout<<"Enter the file name to save the output"<< endl;
cin>> fileout;
ifstream input1(file1);
if (input1.fail()){
cout<< "error: could not find file"<< endl;
system("PAUSE");
exit(1);
}
ofstream output(fileout, ofstream::out);
if (output.fail()){
cout<< "error: could not output file"<< endl;
system("PAUSE");
exit(1);
}
int filecontents[20];
for(int i=0; i<20; i++){
while(!input1.eof()){
input1>> filecontents[i];
cout<< filecontents [i] << " ";
output<< filecontents [i] << " ";
}
}
cout<< endl;
output<< endl;
system("PAUSE");
return EXIT_SUCCESS;
}
|
[
"[email protected]"
] |
[
[
[
1,
50
]
]
] |
37df14034369ee24e966b88631ca7e26a6ea96b3
|
e419dcb4a688d0c7b743c52c2d3c4c2edffc3ab8
|
/Raytrace/raytrace/Randomizer.h
|
29e029a691f5e0e0c8a60ea8bd07ae54d6a6b7d0
|
[] |
no_license
|
Jazzinghen/DTU-Rendering
|
d7f833c01836fadb4401133d8a5c17523e04bf49
|
b03692ce19d0ea765d61e88e19cd8113da99b7fe
|
refs/heads/master
| 2021-01-01T15:29:49.250365 | 2011-12-20T00:49:32 | 2011-12-20T00:49:32 | 2,505,173 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,188 |
h
|
// 02576 Rendering Framework
// Written by Jeppe Revall Frisvad, 2010
// Copyright (c) DTU Informatics 2010
#ifndef RANDOMIZER_H
#define RANDOMIZER_H
#include <valarray>
class Randomizer
{
public:
Randomizer(unsigned long seed = 5489UL);
/* generates a random number on [0,0xffffffff]-interval */
unsigned long mt_random_int32();
/* generates a random number on [0,1]-real-interval */
double mt_random();
/* generates a random number on [0,1)-real-interval */
double mt_random_half_open();
/* generates a random number on (0,1)-real-interval */
double mt_random_open();
// Randomizer.cpp defines a global instance, this potentially
// leads to problems if used with constructors for other global
// variables. The safe_mt_random function checks if initalization
// is needed before computing the random number.
double safe_mt_random() { if(mt.size() == 0) init(); return mt_random(); }
private:
void init(unsigned long seed = 5489UL);
static const int N;
static const int M;
/* the array for the state vector */
std::valarray<unsigned int> mt;
int mti;
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
44
]
]
] |
b5ed6e449ecd916d1c6494113d7f8c0ace9ed7ef
|
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
|
/MediaPlayers/MultiEngine.h
|
1d4c28b94edb1ac0b66283d25311e353f9bdab79
|
[] |
no_license
|
outcast1000/Jaangle
|
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
|
18feb537068f1f3be6ecaa8a4b663b917c429e3d
|
refs/heads/master
| 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,136 |
h
|
// /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * 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 2, 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
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
#ifndef _MultiEngine_h_
#define _MultiEngine_h_
#include "MediaPlayerEngine.h"
#include "EventTarget.h"
class MultiEngine:public MediaPlayerEngine, public EventTarget
{
public:
MultiEngine();
virtual ~MultiEngine();
virtual void SetConfig(MediaEngineConfigOption meco, INT value);
virtual INT GetConfig(MediaEngineConfigOption meco);
virtual BOOL Supports(MediaEngineConfigOption meco);
virtual void SetEventTarget(EventTarget* pEvTarg);
virtual EventTarget* GetEventTarget() {return m_pEvTarget;}
virtual BOOL Open(LPCTSTR str);
virtual void Close();
//Playback Commands
virtual BOOL Start();
virtual BOOL Pause();
virtual BOOL Stop();
virtual PlayState GetPlayState();
//Total Media Length in seconds
virtual INT GetMediaInfo(MediaEngineOptionalIntInfoEnum meoii);
virtual LPCTSTR GetLocation();
virtual DOUBLE GetMediaLength();
//Media Position is seconds
virtual DOUBLE GetMediaPos();
virtual void SetMediaPos(DOUBLE secs);
//Settings
//Should be between 0-100
virtual void SetVolume(INT volume);
virtual INT GetVolume();
virtual void SetMute(BOOL bMute);
virtual BOOL GetMute();
//Extra Interface
//MultiEngine gets the responsibility to clear it
void AddEngine(MediaPlayerEngine* mpe);
void RemoveAllEngines();
virtual INT OnEvent(INT ID, INT param = 0, void* sender = 0);
virtual BOOL CanPlay(LPCTSTR str);
virtual MediaEngineState GetEngineState();
virtual MediaEngineErrorEnum GetLastError();
virtual BOOL GetSoundData(MediaEngineSoundData mesd, void* buffer, UINT bufferLen);
//Visualization
virtual BOOL IsVideo();
virtual const TCHAR* GetEngineDescription();
virtual void SetVideoContainerHWND(HWND hwnd);
virtual HWND GetVideoContainerHWND() {return m_hwndVideo;}
virtual void SetVideoPosition(int x, int y, int cx, int cy);
private:
HWND m_hwndVideo;
void SetError(LPCTSTR msg);
void PlayStateChanged();
EventTarget* m_pEvTarget;
std::vector<MediaPlayerEngine*> m_pEngines;
MediaPlayerEngine* m_pActiveEngine;
//HWND m_hwndViewers;
TCHAR m_engDesc[100];
UINT m_volume;
BOOL m_bMute;
//INT m_ActiveEngine;
};
#endif
|
[
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
] |
[
[
[
1,
104
]
]
] |
faaecb3c3b21c9072016fd4f802dcded93b80fff
|
dda0d7bb4153bcd98ad5e32e4eac22dc974b8c9d
|
/reporting/crashsender/sender/http_request_sender.h
|
1669dc3e9549737c4656c14164d548b198b61de1
|
[
"BSD-3-Clause"
] |
permissive
|
systembugtj/crash-report
|
abd45ceedc08419a3465414ad9b3b6a5d6c6729a
|
205b087e79eb8ed7a9b6a7c9f4ac580707e9cb7e
|
refs/heads/master
| 2021-01-19T07:08:04.878028 | 2011-04-05T04:03:54 | 2011-04-05T04:03:54 | 35,228,814 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,248 |
h
|
/*************************************************************************************
This file is a part of CrashRpt library.
Copyright (c) 2003, Michael Carruth
All rights reserved.
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 author 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.
***************************************************************************************/
// File: httpsend.h
// Description: Sends error report over HTTP connection.
// Authors: zexspectrum
// Date: 2009
#ifndef HTTP_REQUEST_SENDER_H_
#define HTTP_REQUEST_SENDER_H_
#include "stdafx.h"
#include "reporting/crashsender/assync_notification.h"
struct CHttpRequestFile {
CString m_sSrcFileName; // Name of the file attachment.
CString m_sContentType; // Content type.
};
// HTTP request information
class CHttpRequest {
public:
CString m_sUrl; // Script URL
std::map<CString, std::string> m_aTextFields; // Array of text fields to include into POST data
std::map<CString, CHttpRequestFile> m_aIncludedFiles; // Array of binary files to include into POST data
};
// Sends HTTP request
// See also: RFC 1867 - Form-based File Upload in HTML (http://www.ietf.org/rfc/rfc1867.txt)
class CHttpRequestSender {
public:
CHttpRequestSender();
// Sends HTTP request assynchroniously
BOOL SendAssync(CHttpRequest& Request, AssyncNotification* an);
private:
// Worker thread procedure
static DWORD WINAPI WorkerThread(VOID* pParam);
BOOL InternalSend();
// Used to calculate summary size of the request
BOOL CalcRequestSize(LONGLONG& lSize);
BOOL FormatTextPartHeader(CString sName, CString& sText);
BOOL FormatTextPartFooter(CString sName, CString& sText);
BOOL FormatAttachmentPartHeader(CString sName, CString& sText);
BOOL FormatAttachmentPartFooter(CString sName, CString& sText);
BOOL FormatTrailingBoundary(CString& sBoundary);
BOOL CalcTextPartSize(CString sFileName, LONGLONG& lSize);
BOOL CalcAttachmentPartSize(CString sFileName, LONGLONG& lSize);
BOOL WriteTextPart(HINTERNET hRequest, CString sName);
BOOL WriteAttachmentPart(HINTERNET hRequest, CString sName);
BOOL WriteTrailingBoundary(HINTERNET hRequest);
void UploadProgress(DWORD dwBytesWritten);
// This helper function is used to split URL into several parts
void
ParseURL(LPCTSTR szURL, LPTSTR szProtocol, UINT cbProtocol,
LPTSTR szAddress, UINT cbAddress, DWORD &dwPort, LPTSTR szURI,
UINT cbURI);
CHttpRequest m_Request; // HTTP request being sent
AssyncNotification* m_Assync; // Used to communicate with the main thread
CString m_sFilePartHeaderFmt;
CString m_sFilePartFooterFmt;
CString m_sTextPartHeaderFmt;
CString m_sTextPartFooterFmt;
CString m_sBoundary;
DWORD m_dwPostSize;
DWORD m_dwUploaded;
};
#endif // HTTP_REQUEST_SENDER_H_
|
[
"[email protected]@9307afbf-8b4c-5d34-949b-c69a0924eb0b"
] |
[
[
[
1,
105
]
]
] |
b378e64dccaafbfe078a04da1495bb1330a807a3
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/date_time/test/posix_time/testdst_rules.cpp
|
2d101b0579c43c4519c2572c804c5a656fb94f16
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
willrebuild/flyffsf
|
e5911fb412221e00a20a6867fd00c55afca593c7
|
d38cc11790480d617b38bb5fc50729d676aef80d
|
refs/heads/master
| 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 23,816 |
cpp
|
/* Copyright (c) 2002,2003 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0)
* Author: Jeff Garland
*/
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/local_timezone_defs.hpp"
#include "boost/date_time/testfrmwk.hpp"
// Define dst rule for Paraguay which is transitions forward on Oct 1 and
// back Mar 1
struct paraguay_dst_traits {
typedef boost::gregorian::date date_type;
typedef boost::gregorian::date::day_type day_type;
typedef boost::gregorian::date::month_type month_type;
typedef boost::gregorian::date::year_type year_type;
typedef boost::date_time::partial_date<boost::gregorian::date> start_rule_functor;
typedef boost::date_time::partial_date<boost::gregorian::date> end_rule_functor;
static day_type start_day(year_type) {return 1;}
static month_type start_month(year_type) {return boost::date_time::Oct;}
static day_type end_day(year_type) {return 1;}
static month_type end_month(year_type) {return boost::date_time::Mar;}
static int dst_start_offset_minutes() { return 120;}
static int dst_end_offset_minutes() { return 120; }
static int dst_shift_length_minutes() { return 60; }
static date_type local_dst_start_day(year_type year)
{
start_rule_functor start(start_day(year),
start_month(year));
return start.get_date(year);
}
static date_type local_dst_end_day(year_type year)
{
end_rule_functor end(end_day(year),
end_month(year));
return end.get_date(year);
}
};
// see http://www.timeanddate.com/time/aboutdst.html for some info
// also
int
main()
{
using namespace boost::posix_time;
using namespace boost::gregorian;
date d(2002,Feb,1);
ptime t(d);
//The following defines the US dst boundaries, except that the
//start and end dates are hard coded.
typedef boost::date_time::us_dst_rules<date, time_duration, 120, 60> us_dst;
date dst_start(2002,Apr, 7);
date dst_end(2002,Oct, 27);
ptime t3a(dst_start, time_duration(2,0,0)); //invalid time label
ptime t3b(dst_start, time_duration(2,59,59)); //invalid time label
ptime t4(dst_start, time_duration(1,59,59)); //not ds
ptime t5(dst_start, time_duration(3,0,0)); //always dst
ptime t6(dst_end, time_duration(0,59,59)); //is dst
ptime t7(dst_end, time_duration(1,0,0)); //ambiguous
ptime t8(dst_end, time_duration(1,59,59)); //ambiguous
ptime t9(dst_end, time_duration(2,0,0)); //always not dst
check("dst start", us_dst::local_dst_start_day(2002) == dst_start);
check("dst end", us_dst::local_dst_end_day(2002) == dst_end);
check("dst boundary", us_dst::is_dst_boundary_day(dst_start));
check("dst boundary", us_dst::is_dst_boundary_day(dst_end));
check("check if time is dst -- not",
us_dst::local_is_dst(t.date(), t.time_of_day())==boost::date_time::is_not_in_dst);
check("label on dst boundary invalid",
us_dst::local_is_dst(t3a.date(),t3a.time_of_day())==boost::date_time::invalid_time_label);
check("label on dst boundary invalid",
us_dst::local_is_dst(t3b.date(),t3b.time_of_day())==boost::date_time::invalid_time_label);
check("check if time is dst -- not",
us_dst::local_is_dst(t4.date(),t4.time_of_day())==boost::date_time::is_not_in_dst);
check("check if time is dst -- yes",
us_dst::local_is_dst(t5.date(),t5.time_of_day())==boost::date_time::is_in_dst);
check("check if time is dst -- not",
us_dst::local_is_dst(t6.date(),t6.time_of_day())==boost::date_time::is_in_dst);
check("check if time is dst -- ambig",
us_dst::local_is_dst(t7.date(),t7.time_of_day())==boost::date_time::ambiguous);
check("check if time is dst -- ambig",
us_dst::local_is_dst(t8.date(),t8.time_of_day())==boost::date_time::ambiguous);
check("check if time is dst -- not",
us_dst::local_is_dst(t9.date(),t9.time_of_day())==boost::date_time::is_not_in_dst);
//Now try a local without dst
typedef boost::date_time::null_dst_rules<date, time_duration> no_dst_adj;
check("check null dst rules",
no_dst_adj::local_is_dst(t4.date(),t4.time_of_day())==boost::date_time::is_not_in_dst);
check("check null dst rules",
no_dst_adj::local_is_dst(t5.date(),t5.time_of_day())==boost::date_time::is_not_in_dst);
check("check null dst rules",
no_dst_adj::utc_is_dst(t4.date(),t4.time_of_day())==boost::date_time::is_not_in_dst);
check("check null dst rules",
no_dst_adj::utc_is_dst(t5.date(),t5.time_of_day())==boost::date_time::is_not_in_dst);
//Try a southern hemisphere adjustment calculation
//This is following the rules for South Australia as best I can
//decipher them. Basically conversion to DST is last Sunday in
//October 02:00:00 and conversion off of dst is last sunday in
//March 02:00:00.
//This stuff uses the dst calculator directly...
date dst_start2(2002,Oct,27); //last Sunday in Oct
date dst_end2(2002,Mar,31); //last Sunday in March
typedef boost::date_time::dst_calculator<date,time_duration> dstcalc;
//clearly not in dst
boost::date_time::time_is_dst_result a1 =
dstcalc::local_is_dst(date(2002,May,1),hours(3),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern not dst", a1==boost::date_time::is_not_in_dst);
boost::date_time::time_is_dst_result a2 =
dstcalc::local_is_dst(date(2002,Jan,1),hours(3),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern is dst", a2==boost::date_time::is_in_dst);
boost::date_time::time_is_dst_result a3 =
dstcalc::local_is_dst(date(2002,Oct,28),hours(3),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern is dst", a3==boost::date_time::is_in_dst);
boost::date_time::time_is_dst_result a4 =
dstcalc::local_is_dst(date(2002,Oct,27),time_duration(1,59,59),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern boundary-not dst", a4==boost::date_time::is_not_in_dst);
boost::date_time::time_is_dst_result a5 =
dstcalc::local_is_dst(date(2002,Oct,27),hours(3),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern boundary-is dst", a5==boost::date_time::is_in_dst);
boost::date_time::time_is_dst_result a6 =
dstcalc::local_is_dst(date(2002,Oct,27),hours(2),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern boundary-invalid time", a6==boost::date_time::invalid_time_label);
boost::date_time::time_is_dst_result a7 =
dstcalc::local_is_dst(date(2002,Mar,31),time_duration(1,59,59),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern boundary-is dst", a7==boost::date_time::is_in_dst);
boost::date_time::time_is_dst_result a8 =
dstcalc::local_is_dst(date(2002,Mar,31),time_duration(2,0,0),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern boundary-ambiguous", a8==boost::date_time::ambiguous);
boost::date_time::time_is_dst_result a9 =
dstcalc::local_is_dst(date(2002,Mar,31),time_duration(2,59,59),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern boundary-ambiguous", a9==boost::date_time::ambiguous);
boost::date_time::time_is_dst_result a10 =
dstcalc::local_is_dst(date(2002,Mar,31),time_duration(3,0,0),
dst_start2, 120,
dst_end2, 180,
60);
check("check southern boundary-not", a10==boost::date_time::is_not_in_dst);
/******************** post release 1 -- new dst calc engine ********/
typedef boost::date_time::us_dst_trait<date> us_dst_traits;
typedef boost::date_time::dst_calc_engine<date, time_duration, us_dst_traits>
us_dst_calc2;
{
// us_dst_calc2
check("dst start", us_dst_calc2::local_dst_start_day(2002) == dst_start);
check("dst end", us_dst_calc2::local_dst_end_day(2002) == dst_end);
// std::cout << us_dst_calc2::local_dst_end_day(2002) << std::endl;
check("dst boundary", us_dst_calc2::is_dst_boundary_day(dst_start));
check("dst boundary", us_dst_calc2::is_dst_boundary_day(dst_end));
check("check if time is dst -- not",
us_dst_calc2::local_is_dst(t.date(), t.time_of_day())==boost::date_time::is_not_in_dst);
check("label on dst boundary invalid",
us_dst_calc2::local_is_dst(t3a.date(),t3a.time_of_day())==boost::date_time::invalid_time_label);
check("label on dst boundary invalid",
us_dst_calc2::local_is_dst(t3b.date(),t3b.time_of_day())==boost::date_time::invalid_time_label);
check("check if time is dst -- not",
us_dst_calc2::local_is_dst(t4.date(),t4.time_of_day())==boost::date_time::is_not_in_dst);
check("check if time is dst -- yes",
us_dst_calc2::local_is_dst(t5.date(),t5.time_of_day())==boost::date_time::is_in_dst);
check("check if time is dst -- not",
us_dst_calc2::local_is_dst(t6.date(),t6.time_of_day())==boost::date_time::is_in_dst);
check("check if time is dst -- ambig",
us_dst_calc2::local_is_dst(t7.date(),t7.time_of_day())==boost::date_time::ambiguous);
check("check if time is dst -- ambig",
us_dst_calc2::local_is_dst(t8.date(),t8.time_of_day())==boost::date_time::ambiguous);
check("check if time is dst -- not",
us_dst_calc2::local_is_dst(t9.date(),t9.time_of_day())==boost::date_time::is_not_in_dst);
}
{
//some new checks for the new 2007 us dst rules
date dst_start07(2007,Mar, 11);
date dst_end07(2007,Nov, 4);
check("dst start07", us_dst_calc2::local_dst_start_day(2007) == dst_start07);
check("dst end07", us_dst_calc2::local_dst_end_day(2007) == dst_end07);
check("dst boundary07", us_dst_calc2::is_dst_boundary_day(dst_start07));
check("dst boundary07", us_dst_calc2::is_dst_boundary_day(dst_end07));
date dst_start08(2008,Mar, 9);
date dst_end08(2008,Nov, 2);
check("dst start08", us_dst_calc2::local_dst_start_day(2008) == dst_start08);
check("dst end08", us_dst_calc2::local_dst_end_day(2008) == dst_end08);
check("dst boundary08", us_dst_calc2::is_dst_boundary_day(dst_start08));
check("dst boundary08", us_dst_calc2::is_dst_boundary_day(dst_end08));
date dst_start09(2009,Mar, 8);
date dst_end09(2009,Nov, 1);
check("dst start09", us_dst_calc2::local_dst_start_day(2009) == dst_start09);
check("dst end09", us_dst_calc2::local_dst_end_day(2009) == dst_end09);
check("dst boundary09", us_dst_calc2::is_dst_boundary_day(dst_start09));
check("dst boundary09", us_dst_calc2::is_dst_boundary_day(dst_end09));
}
/******************** post release 1 -- new dst calc engine - eu dst ********/
typedef boost::date_time::eu_dst_trait<date> eu_dst_traits;
typedef boost::date_time::dst_calc_engine<date, time_duration, eu_dst_traits>
eu_dst_calc;
date eu_dst_start(2002,Mar, 31);
date eu_dst_end(2002,Oct, 27);
ptime eu_invalid1(eu_dst_start, time_duration(2,0,0)); //invalid time label
ptime eu_invalid2(eu_dst_start, time_duration(2,59,59)); //invalid time label
ptime eu_notdst1(eu_dst_start, time_duration(1,59,59)); //not ds
ptime eu_isdst1(eu_dst_start, time_duration(3,0,0)); //always dst
ptime eu_isdst2(eu_dst_end, time_duration(1,59,59)); //is dst
ptime eu_amgbig1(eu_dst_end, time_duration(2,0,0)); //ambiguous
ptime eu_amgbig2(eu_dst_end, time_duration(2,59,59)); //ambiguous
ptime eu_notdst2(eu_dst_end, time_duration(3,0,0)); //always not dst
check("eu dst start", eu_dst_calc::local_dst_start_day(2002) == eu_dst_start);
check("eu dst end", eu_dst_calc::local_dst_end_day(2002) == eu_dst_end);
check("eu dst boundary", eu_dst_calc::is_dst_boundary_day(eu_dst_start));
check("eu dst boundary", eu_dst_calc::is_dst_boundary_day(eu_dst_end));
// on forward shift boundaries
check("eu label on dst boundary invalid",
eu_dst_calc::local_is_dst(eu_invalid1.date(),eu_invalid1.time_of_day())==boost::date_time::invalid_time_label);
check("eu label on dst boundary invalid",
eu_dst_calc::local_is_dst(eu_invalid2.date(),eu_invalid2.time_of_day())==boost::date_time::invalid_time_label);
check("eu check if time is dst -- not",
eu_dst_calc::local_is_dst(eu_notdst1.date(),eu_notdst1.time_of_day())==boost::date_time::is_not_in_dst);
check("check if time is dst -- yes",
eu_dst_calc::local_is_dst(eu_isdst1.date(),eu_isdst1.time_of_day())==boost::date_time::is_in_dst);
//backward shift boundary
check("eu check if time is dst -- yes",
eu_dst_calc::local_is_dst(eu_isdst2.date(),eu_isdst2.time_of_day())==boost::date_time::is_in_dst);
check("eu check if time is dst -- ambig",
eu_dst_calc::local_is_dst(eu_amgbig1.date(),eu_amgbig1.time_of_day())==boost::date_time::ambiguous);
check("eu check if time is dst -- ambig",
eu_dst_calc::local_is_dst(eu_amgbig2.date(),eu_amgbig2.time_of_day())==boost::date_time::ambiguous);
check("eu check if time is dst -- not",
eu_dst_calc::local_is_dst(eu_notdst2.date(),eu_notdst2.time_of_day())==boost::date_time::is_not_in_dst);
/******************** post release 1 -- new dst calc engine - gb dst ********/
/* Several places in Great Britan use eu start and end rules for the
day, but different local conversion times (eg: forward change at 1:00
am local and backward change at 2:00 am dst instead of 2:00am
forward and 3:00am back for the EU).
*/
typedef boost::date_time::uk_dst_trait<date> uk_dst_traits;
typedef boost::date_time::dst_calc_engine<date, time_duration, uk_dst_traits> uk_dst_calc;
date uk_dst_start(2002,Mar, 31);
date uk_dst_end(2002,Oct, 27);
ptime uk_invalid1(uk_dst_start, time_duration(1,0,0)); //invalid time label
ptime uk_invalid2(uk_dst_start, time_duration(1,59,59)); //invalid time label
ptime uk_notdst1(uk_dst_start, time_duration(0,59,59)); //not ds
ptime uk_isdst1(uk_dst_start, time_duration(2,0,0)); //always dst
ptime uk_isdst2(uk_dst_end, time_duration(0,59,59)); //is dst
ptime uk_amgbig1(uk_dst_end, time_duration(1,0,0)); //ambiguous
ptime uk_amgbig2(uk_dst_end, time_duration(1,59,59)); //ambiguous
ptime uk_notdst2(uk_dst_end, time_duration(3,0,0)); //always not dst
check("uk dst start", uk_dst_calc::local_dst_start_day(2002) == uk_dst_start);
check("uk dst end", uk_dst_calc::local_dst_end_day(2002) == uk_dst_end);
check("uk dst boundary", uk_dst_calc::is_dst_boundary_day(uk_dst_start));
check("uk dst boundary", uk_dst_calc::is_dst_boundary_day(uk_dst_end));
// on forward shift boundaries
check("uk label on dst boundary invalid",
uk_dst_calc::local_is_dst(uk_invalid1.date(),uk_invalid1.time_of_day())==boost::date_time::invalid_time_label);
check("uk label on dst boundary invalid",
uk_dst_calc::local_is_dst(uk_invalid2.date(),uk_invalid2.time_of_day())==boost::date_time::invalid_time_label);
check("uk check if time is dst -- not",
uk_dst_calc::local_is_dst(uk_notdst1.date(),uk_notdst1.time_of_day())==boost::date_time::is_not_in_dst);
check("uk check if time is dst -- yes",
uk_dst_calc::local_is_dst(uk_isdst1.date(),uk_isdst1.time_of_day())==boost::date_time::is_in_dst);
//backward shift boundary
check("uk check if time is dst -- yes",
uk_dst_calc::local_is_dst(uk_isdst2.date(),uk_isdst2.time_of_day())==boost::date_time::is_in_dst);
check("uk check if time is dst -- ambig",
uk_dst_calc::local_is_dst(uk_amgbig1.date(),uk_amgbig1.time_of_day())==boost::date_time::ambiguous);
check("uk check if time is dst -- ambig",
uk_dst_calc::local_is_dst(uk_amgbig2.date(),uk_amgbig2.time_of_day())==boost::date_time::ambiguous);
check("uk check if time is dst -- not",
uk_dst_calc::local_is_dst(uk_notdst2.date(),uk_notdst2.time_of_day())==boost::date_time::is_not_in_dst);
// /******************** post release 1 -- new dst calc engine ********/
// //Define dst rule for Paraguay which is transitions forward on Oct 1 and back Mar 1
typedef boost::date_time::dst_calc_engine<date, time_duration,
paraguay_dst_traits> pg_dst_calc;
{
date pg_dst_start(2002,Oct, 1);
date pg_dst_end(2002,Mar, 1);
date pg_indst(2002,Dec, 1);
date pg_notdst(2002,Jul, 1);
ptime pg_invalid1(pg_dst_start, time_duration(2,0,0)); //invalid time label
ptime pg_invalid2(pg_dst_start, time_duration(2,59,59)); //invalid time label
ptime pg_notdst1(pg_dst_start, time_duration(1,59,59)); //not ds
ptime pg_isdst1(pg_dst_start, time_duration(3,0,0)); //always dst
ptime pg_isdst2(pg_dst_end, time_duration(0,59,59)); //is dst
ptime pg_amgbig1(pg_dst_end, time_duration(1,0,0)); //ambiguous
ptime pg_amgbig2(pg_dst_end, time_duration(1,59,59)); //ambiguous
ptime pg_notdst2(pg_dst_end, time_duration(2,0,0)); //always not dst
check("pg dst start", pg_dst_calc::local_dst_start_day(2002) == pg_dst_start);
check("pg dst end", pg_dst_calc::local_dst_end_day(2002) == pg_dst_end);
check("pg dst boundary", pg_dst_calc::is_dst_boundary_day(pg_dst_start));
check("pg dst boundary", pg_dst_calc::is_dst_boundary_day(pg_dst_end));
// on forward shift boundaries
check("pg label on dst boundary invalid",
pg_dst_calc::local_is_dst(pg_invalid1.date(),pg_invalid1.time_of_day())==boost::date_time::invalid_time_label);
check("pg label on dst boundary invalid",
pg_dst_calc::local_is_dst(pg_invalid2.date(),pg_invalid2.time_of_day())==boost::date_time::invalid_time_label);
check("pg check if time is dst -- not",
pg_dst_calc::local_is_dst(pg_notdst1.date(),pg_notdst1.time_of_day())==boost::date_time::is_not_in_dst);
check("check if time is dst -- yes",
pg_dst_calc::local_is_dst(pg_isdst1.date(),pg_isdst1.time_of_day())==boost::date_time::is_in_dst);
//backward shift boundary
check("pg check if time is dst -- yes",
pg_dst_calc::local_is_dst(pg_isdst2.date(),pg_isdst2.time_of_day())==boost::date_time::is_in_dst);
check("pg check if time is dst -- ambig",
pg_dst_calc::local_is_dst(pg_amgbig1.date(),pg_amgbig1.time_of_day())==boost::date_time::ambiguous);
check("pg check if time is dst -- ambig",
pg_dst_calc::local_is_dst(pg_amgbig2.date(),pg_amgbig2.time_of_day())==boost::date_time::ambiguous);
check("pg check if time is dst -- not",
pg_dst_calc::local_is_dst(pg_notdst2.date(),pg_notdst2.time_of_day())==boost::date_time::is_not_in_dst);
// a couple not on the boudnary
check("pg check if time is dst -- yes",
pg_dst_calc::local_is_dst(pg_indst,time_duration(0,0,0))==boost::date_time::is_in_dst);
check("pg check if time is dst -- not",
pg_dst_calc::local_is_dst(pg_notdst,time_duration(0,0,0))==boost::date_time::is_not_in_dst);
}
// /******************** post release 1 -- new dst calc engine ********/
// //Define dst rule for Adelaide australia
typedef boost::date_time::acst_dst_trait<date> acst_dst_traits;
typedef boost::date_time::dst_calc_engine<date, time_duration,
acst_dst_traits> acst_dst_calc;
{
date acst_dst_start(2002,Oct, 27);
date acst_dst_end(2002,Mar, 31);
date acst_indst(2002,Dec, 1);
date acst_notdst(2002,Jul, 1);
ptime acst_invalid1(acst_dst_start, time_duration(2,0,0)); //invalid time label
ptime acst_invalid2(acst_dst_start, time_duration(2,59,59)); //invalid time label
ptime acst_notdst1(acst_dst_start, time_duration(1,59,59)); //not ds
ptime acst_isdst1(acst_dst_start, time_duration(3,0,0)); //always dst
ptime acst_isdst2(acst_dst_end, time_duration(1,59,59)); //is dst
ptime acst_amgbig1(acst_dst_end, time_duration(2,0,0)); //ambiguous
ptime acst_amgbig2(acst_dst_end, time_duration(2,59,59)); //ambiguous
ptime acst_notdst2(acst_dst_end, time_duration(3,0,0)); //always not dst
// std::cout << "acst dst_start: " << acst_dst_calc::local_dst_start_day(2002)
// << std::endl;
check("acst dst start", acst_dst_calc::local_dst_start_day(2002) == acst_dst_start);
check("acst dst end", acst_dst_calc::local_dst_end_day(2002) == acst_dst_end);
check("acst dst boundary", acst_dst_calc::is_dst_boundary_day(acst_dst_start));
check("acst dst boundary", acst_dst_calc::is_dst_boundary_day(acst_dst_end));
// on forward shift boundaries
check("acst label on dst boundary invalid",
acst_dst_calc::local_is_dst(acst_invalid1.date(),acst_invalid1.time_of_day())==boost::date_time::invalid_time_label);
check("acst label on dst boundary invalid",
acst_dst_calc::local_is_dst(acst_invalid2.date(),acst_invalid2.time_of_day())==boost::date_time::invalid_time_label);
check("acst check if time is dst -- not",
acst_dst_calc::local_is_dst(acst_notdst1.date(),acst_notdst1.time_of_day())==boost::date_time::is_not_in_dst);
check("check if time is dst -- yes",
acst_dst_calc::local_is_dst(acst_isdst1.date(),acst_isdst1.time_of_day())==boost::date_time::is_in_dst);
//backward shift boundary
check("acst check if time is dst -- yes",
acst_dst_calc::local_is_dst(acst_isdst2.date(),acst_isdst2.time_of_day())==boost::date_time::is_in_dst);
check("acst check if time is dst -- ambig",
acst_dst_calc::local_is_dst(acst_amgbig1.date(),acst_amgbig1.time_of_day())==boost::date_time::ambiguous);
check("acst check if time is dst -- ambig",
acst_dst_calc::local_is_dst(acst_amgbig2.date(),acst_amgbig2.time_of_day())==boost::date_time::ambiguous);
check("acst check if time is dst -- not",
acst_dst_calc::local_is_dst(acst_notdst2.date(),acst_notdst2.time_of_day())==boost::date_time::is_not_in_dst);
// a couple not on the boudnary
check("acst check if time is dst -- yes",
acst_dst_calc::local_is_dst(acst_indst,time_duration(0,0,0))==boost::date_time::is_in_dst);
check("acst check if time is dst -- not",
acst_dst_calc::local_is_dst(acst_notdst,time_duration(0,0,0))==boost::date_time::is_not_in_dst);
// ptime utc_t = ptime(acst_dst_start, hours(2)) - time_duration(16,30,0);
// std::cout << "UTC date/time of Adelaide switch over: " << utc_t << std::endl;
}
return printTestStats();
}
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
451
]
]
] |
6f3c58478e9469789e3cc039d1d9f12e09cefbd4
|
150926210848ebc2773f4683180b2e53e67232f1
|
/UFOHunt/ImageConverterTest/ImageConverterTest.cpp
|
b5637e8d2c8b971c9c01f5d5759b14ebbe774942
|
[] |
no_license
|
wkx11/kuradevsandbox
|
429dccabf6b07847ed33ea07bb77a93d7c8004f0
|
21f09987fd7e22ba6bf2c4929ca4cbf872827b36
|
refs/heads/master
| 2021-01-02T09:33:52.967804 | 2010-12-12T04:06:19 | 2010-12-12T04:06:19 | 37,631,953 | 0 | 0 | null | null | null | null |
SHIFT_JIS
|
C++
| false | false | 539 |
cpp
|
// ImageConverterTest.cpp : メイン プロジェクト ファイルです。
#include "stdafx.h"
#include "Form1.h"
using namespace UFOHunt::Lib;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// コントロールが作成される前に、Windows XP ビジュアル効果を有効にします
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// メイン ウィンドウを作成して、実行します
Application::Run(gcnew Form1());
return 0;
}
|
[
"sasraing@cdde4f24-bdbc-632a-de5c-276029d4cb88"
] |
[
[
[
1,
18
]
]
] |
58a2ad04aad0cb2c6d774494ef7c479eaaff1093
|
f246dc2a816ccd5acd0776a48c2c24cdb1f4178f
|
/libsrc/PigletOpSys.cpp
|
a56f3c4d5ae48244e9baeebfd2dfd3c6c6bce09f
|
[] |
no_license
|
profcturner/pigletlib
|
3f2c4b1af000d73cf4a176a8463c16aaeefde99a
|
b2ccbb43270a5e8d3a0f8ae6bd3d3cb82a061fec
|
refs/heads/master
| 2021-07-24T07:23:10.577261 | 2007-08-26T22:36:47 | 2007-08-26T22:36:47 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,750 |
cpp
|
/**
** Piglet Productions
**
** FileName : PigletOpSys.cpp
**
** Implements : PigletOpSys
**
**
**
** Description
**
**
**
**
** Initial Coding : Colin Turner
**
** Date : 2/4/1999
**
**
** Copyright applies on this file, and distribution may be limited.
*/
/*
** Revision 1.00
**
*/
#include <PigletOpSys.h>
PigletOpSys::PigletOpSys()
{
DetectMultiTasker();
}
char * PigletOpSys::GetName()
{
return(OpSysName);
}
char * PigletOpSys::GetVersion()
{
return(OpSysVersion);
}
void PigletOpSys::DetectMultiTasker()
{
#if defined(__NT__)
OpSysCode = OS_Win32;
return;
#elif defined(__OS2__)
OpSysCode = OS_OS2;
return;
#else
unsigned short TrueDosVersion = 0;
union REGS regs;
// Get the True DOS Version
#if defined(__WATCOMC__) && defined(__386__)
regs.w.ax = 0x3306;
int386(0x21, ®s, ®s);
if (regs.h.bh < 100 && regs.h.bl >= 5) {
TrueDosVersion = regs.w.bx;
}
#else
regs.x.ax = 0x3306;
int86(0x21, ®s, ®s);
if (regs.h.bh < 100 && regs.h.bl >= 5 && regs.w.bx == 0x3205) {
TrueDosVersion = regs.w.bx;
}
#endif
// detect DESQview
#if defined(__WATCOMC__) && defined(__386__)
regs.w.ax = 0x2B01;
regs.w.cx = 0x4445;
regs.w.dx = 0x5351;
int386(0x21, ®s, ®s);
#else
regs.x.ax = 0x2B01;
regs.x.cx = 0x4445;
regs.x.dx = 0x5351;
int86(0x21, ®s, ®s);
#endif
if (regs.h.al != 0xFF) {
strcpy(OpSysName, "DESQview");
OpSysCode = OS_DESQview;
return;
}
// detect OS/2
regs.h.ah = 0x30;
#if defined(__WATCOMC__) && defined(__386__)
int386(0x21, ®s, ®s);
#else
int86(0x21, ®s, ®s);
#endif
if (regs.h.al >= 10) {
strcpy(OpSysName, "OS/2");
OpSysCode = OS_OS2;
return;
}
// detect Windows
#if defined(__WATCOMC__) && defined(__386__)
regs.w.ax = 0x160A;
int386(0x2F, ®s, ®s);
if (regs.w.ax == 0) {
strcpy(OpSysName, "Windows");
switch (regs.h.bh) {
case 0x04: // Windows 9x
strcat(OpSysName, " 9x");
OpSysCode = OS_Win32;
break;
default:
OpSysCode = OS_Win16;
break;
}
}
#else
regs.x.ax = 0x160A;
int86(0x2F, ®s, ®s);
if (regs.w.ax == 0) {
strcpy(OpSysName, "Windows");
switch (regs.h.bh) {
case 0x04: // Windows 9x
strcat(OpSysName, " 9x");
OpSysCode = OS_Win32;
break;
default:
OpSysCode = OS_Win16;
break;
}
}
#endif
// detect Windows NT
if (TrueDosVersion == 0x3205) {
strcpy(OpSysName, "Windows NT");
OpSysCode = OS_WinNT;
return;
}
// must be MS-DOS
strcpy(OpSysName, "No Multitasker");
OpSysCode = OS_DOS;
#endif
}
void PigletOpSys::TimeSlice(void)
{
union REGS regs;
switch (OpSysCode) {
case OS_OS2:
case OS_Win16:
case OS_Win32:
case OS_WinNT:
#if defined(__WATCOMC__) && defined(__386__)
regs.w.ax = 0x1680;
int386(0x2F, ®s, ®s);
#else
regs.x.ax = 0x1680;
int86(0x2F, ®s, ®s);
#endif
break;
case OS_DESQview:
#if defined(__WATCOMC__) && defined(__386__)
regs.w.ax = 0x1000;
int386(0x15, ®s, ®s);
#else
regs.x.ax = 0x1000;
int86(0x15, ®s, ®s);
#endif
break;
case OS_DoubleDOS:
#if defined(__WATCOMC__) && defined(__386__)
regs.w.ax = 0xEE01;
int386(0x21, ®s, ®s);
#else
regs.x.ax = 0xEE01;
int86(0x21, ®s, ®s);
#endif
break;
default:
break;
}
}
|
[
"[email protected]"
] |
[
[
[
1,
197
]
]
] |
a1880e06850e8fccf2875ee7a1cf72cb0711ce4a
|
216ae2fd7cba505c3690eaae33f62882102bd14a
|
/source/NavyGameUnit.cpp
|
1fcd019cd98cb15e23e9c0adace4a0357bd590ff
|
[] |
no_license
|
TimelineX/balyoz
|
c154d4de9129a8a366c1b8257169472dc02c5b19
|
5a0f2ee7402a827bbca210d7c7212a2eb698c109
|
refs/heads/master
| 2021-01-01T05:07:59.597755 | 2010-04-20T19:53:52 | 2010-04-20T19:53:52 | 56,454,260 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 116 |
cpp
|
#include "NavyGameUnit.h"
Balyoz::NavyGameUnit::NavyGameUnit(){
}
Balyoz::NavyGameUnit::~NavyGameUnit(){
}
|
[
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
] |
[
[
[
1,
8
]
]
] |
8c24e0350bc2551209a2a35f2ad1db9195f65bb1
|
5ac13fa1746046451f1989b5b8734f40d6445322
|
/minimangalore/Nebula2/code/contrib/nspatialdb/src/spatialdb/noccludedfrustumvisitor.cc
|
0bb0ab74194a62dc0a30879a522d8e63a490234e
|
[] |
no_license
|
moltenguy1/minimangalore
|
9f2edf7901e7392490cc22486a7cf13c1790008d
|
4d849672a6f25d8e441245d374b6bde4b59cbd48
|
refs/heads/master
| 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,933 |
cc
|
//--------------------------------------------------
// nOccludedFrustumVisitor.cc
// (C) 2004 Gary Haussmann
//--------------------------------------------------
#include "spatialdb/nOccludedFrustumVisitor.h"
#include "gfx2/ngfxserver2.h"
nOccludedFrustumVisitor::nOccludedFrustumVisitor(const nCamera2 &cameraprojection,
const matrix44 &cameratransform,
nOcclusionVisitor &occlusionvisitor)
: nVisibleFrustumVisitor(cameraprojection, cameratransform), m_occlusionvisitor(occlusionvisitor),
m_frustumvisitor(cameraprojection, cameratransform)
{
// If we don't provide some sort of clipping to the occlusion visitor, it will try to
// collect all the occluders it finds, instead of ignoring the occluders outside of the
// view frustum. So we provide a copy of our local view frustum clipper and thus restrict
// the region from which occluders can be gathered.
m_occlusionvisitor.SetRestrictingVisitor(&m_frustumvisitor);
}
nOccludedFrustumVisitor::~nOccludedFrustumVisitor()
{
}
void nOccludedFrustumVisitor::Reset()
{
nVisibleFrustumVisitor::Reset();
m_frustumvisitor.Reset();
}
void nOccludedFrustumVisitor::Reset(const nCamera2 &newcamera, const matrix44 &newxform)
{
nVisibleFrustumVisitor::Reset();
m_frustumvisitor.Reset(newcamera, newxform);
}
void nOccludedFrustumVisitor::StartVisualizeDebug(nGfxServer2 *gfx2)
{
nVisibilityVisitor::StartVisualizeDebug(gfx2);
m_viewfrustumstack.Back().VisualizeFrustum(gfx2, vector4(1.0,0.0,1.0,0.5));
m_occlusionvisitor.StartVisualizeDebug(gfx2);
}
void nOccludedFrustumVisitor::EndVisualizeDebug()
{
nVisibilityVisitor::EndVisualizeDebug();
m_occlusionvisitor.EndVisualizeDebug();
}
VisitorFlags nOccludedFrustumVisitor::VisibilityTest(const bbox3 &testbox, VisitorFlags flags)
{
return m_occlusionvisitor.VisibilityTest(testbox, flags);
}
VisitorFlags nOccludedFrustumVisitor::VisibilityTest(const sphere &testsphere, VisitorFlags flags)
{
return m_occlusionvisitor.VisibilityTest(testsphere, flags);
}
void nOccludedFrustumVisitor::EnterLocalSpace(matrix44 &warp)
{
// transform the camera and generate a new frustum for the local space
matrix44 newtransform = warp * GetCameraTransform();
m_viewertransformstack.PushBack(newtransform);
nFrustumClipper newfrustum(m_cameraprojection, newtransform);
m_viewfrustumstack.PushBack(newfrustum);
nVisibilityVisitor::EnterLocalSpace(warp);
m_occlusionvisitor.EnterLocalSpace(warp);
}
void nOccludedFrustumVisitor::LeaveLocalSpace()
{
m_viewertransformstack.Erase(m_viewertransformstack.End()-1);
m_viewfrustumstack.Erase(m_viewfrustumstack.End()-1);
nVisibilityVisitor::LeaveLocalSpace();
m_occlusionvisitor.LeaveLocalSpace();
}
|
[
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] |
[
[
[
1,
84
]
]
] |
11955288963d2a4251cb2434e7606694a67720f4
|
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
|
/trunk/nGENE Proj/TerrainTypes.h
|
910b411743e3b781c45bfb70a04251edd0f5853d
|
[] |
no_license
|
svn2github/ngene
|
b2cddacf7ec035aa681d5b8989feab3383dac012
|
61850134a354816161859fe86c2907c8e73dc113
|
refs/heads/master
| 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,847 |
h
|
/*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: TerrainTypes.h
Version: 0.04
Info: This file defines some terrain related types
which are used by renderer and physics modules.
---------------------------------------------------------------------------
*/
#pragma once
#ifndef __INC_TERRAINTYPES_H_
#define __INC_TERRAINTYPES_H_
#include "Prerequisities.h"
namespace nGENE
{
/** Structure describing patch of the terrain.
@remarks
Patch is a terrain part you create when creating
NodeTerrain object. Patches consists of tiles.
*/
typedef struct STerrainPatchDescription
{
uint columns; ///< Number of vertices per row
uint rows; ///< Number of vertices per column
uint tiles_x; ///< Number of tiles in the x direction
uint tiles_z; ///< Number of tiles in the z direction
float texScaleX; ///< Texture u-coordinate scaling factor
float texScaleY; ///< Texture v-coordinate scaling factor
float heightScale; ///< Height will be scaled by this value
float step; ///< Distance between two neighbouring vertices
float skirtSize; ///< Height of the skirt
float* heights; /**< Heights of all points. It could be of float type
but to make integration with current version
of PhysX easier, it was decided to use byte instead. */
vector <pair <uint, float> > LODs; ///< Level of Details
STerrainPatchDescription():
columns(0),
rows(0),
tiles_x(0),
tiles_z(0),
texScaleX(1.0f),
texScaleY(1.0f),
heightScale(1.0f),
step(1.0f),
skirtSize(0.1f),
heights(NULL)
{
}
} TERRAIN_DESC;
}
#endif
|
[
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] |
[
[
[
1,
66
]
]
] |
a90e5fb2868c4a3496b2197dbdaf5d884c955801
|
def1c36bf3ce2de2d644f88d2ce60c0d72ecb146
|
/libs/mpt/src/include/common.h
|
f1e463e8f2496b240d254d1f7615b59aeebd2567
|
[] |
no_license
|
kinpro/ofxMPT
|
3e0ca3d6d2aa82035bbcb8bc44ff7716f7ffe3b9
|
f8c9126b5ee9fad3408c6361f3718859c9cb9094
|
refs/heads/master
| 2020-07-13T05:27:20.110695 | 2011-10-10T12:45:18 | 2011-10-10T12:45:18 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,656 |
h
|
/*
* common.h
*
* Copyright (c) 2003 Machine Perception Laboratory
* University of California San Diego.
* Please read the disclaimer and notes about redistribution
* at the end of this file.
*
* Authors: Josh Susskind, Ian Fasel, Bret Fortenberry
*/
#ifndef __MPLABCOMMON_H__
#define __MPLABCOMMON_H__
#ifdef WIN32
#include <windows.h>
#else
#include <iostream>
#include <sys/time.h>
#include <pthread.h>
#include "errno.h"
#endif
#include <iostream>
#include <algorithm>
#ifndef BYTE
#define BYTE unsigned char
#endif
#ifndef PIXEL_TYPE
#define PIXEL_TYPE BYTE
#endif
#undef BOOL
typedef int BOOL;
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#undef PIXEL_TYPE
#define PIXEL_TYPE BYTE
typedef struct sMUTEX {
int activation;
#ifdef WIN32
HANDLE mutex;
#else
pthread_mutex_t mutex;
#endif
} MUTEX_TYPE;
// ================================================================
#ifdef WIN32
#define MUTEX_LOCK_RETURN_TYPE DWORD
#define THREAD_RETURN_TYPE void
#define THREAD_TYPE HANDLE
#define THREAD_COND HANDLE
#define TIMETYPE DWORD
#define IMAGE_FLIPPED true
// ================================================================
#else //if not WIN32
class nRGBTRIPLE{
public:
PIXEL_TYPE rgbtRed;
PIXEL_TYPE rgbtGreen;
PIXEL_TYPE rgbtBlue;
// Default & Copy Constructors and = operator
nRGBTRIPLE() : rgbtRed(0), rgbtGreen(0), rgbtBlue(0){};
nRGBTRIPLE(PIXEL_TYPE r, PIXEL_TYPE g, PIXEL_TYPE b) :
rgbtRed(r), rgbtGreen(g), rgbtBlue(b){};
template<class T>
inline nRGBTRIPLE(const T &v){
rgbtRed = static_cast<PIXEL_TYPE>(v);
rgbtGreen = static_cast<PIXEL_TYPE>(v);
rgbtBlue = static_cast<PIXEL_TYPE>(v);
}
nRGBTRIPLE(const nRGBTRIPLE &v){
rgbtRed = v.rgbtRed;
rgbtGreen = v.rgbtGreen;
rgbtBlue = v.rgbtBlue;
}
template<class T>
// inline nRGBTRIPLE& operator=(const T &v){
inline void operator=(const T &v){
rgbtRed = static_cast<PIXEL_TYPE>(v);
rgbtGreen = static_cast<PIXEL_TYPE>(v);
rgbtBlue = static_cast<PIXEL_TYPE>(v);
// return *this;
}
// inline nRGBTRIPLE& operator=(const nRGBTRIPLE &v){
inline void operator=(const nRGBTRIPLE &v){
rgbtRed = v.rgbtRed;
rgbtGreen = v.rgbtGreen;
rgbtBlue = v.rgbtBlue;
// return *this;
}
};
#define RGBTRIPLE nRGBTRIPLE
//#ifndef FREEIMAGE_H
typedef unsigned long DWORD;
typedef unsigned short WORD;
typedef long LONG;
typedef long LONGLONG;
//#endif
#define MUTEX_LOCK_RETURN_TYPE int
#define WAIT_OBJECT_0 0
#define WAIT_TIMEOUT EBUSY
#define WAIT_ABANDONED EDEADLK
#define WAIT_FAILED EINVAL
#define THREAD_RETURN_TYPE void *
#define THREAD_TYPE pthread_t
#define THREAD_COND pthread_cond_t
#define TIMETYPE struct timeval
#define IMAGE_FLIPPED false
typedef struct tagBITMAPFILEHEADER { // bmfh
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER;
#ifndef FREEIMAGE_H
typedef struct tagBITMAPINFOHEADER{ // bmih
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} BITMAPINFOHEADER;
#endif
#endif //not WIN32
///////////////////////////////////////////////////////////////////
inline MUTEX_LOCK_RETURN_TYPE LockMutex(MUTEX_TYPE pMutex){
if(pMutex.activation == 1) {
std::cout << "error - trying to lock previously locked mutex\n";
return 0;
}
pMutex.activation = 1;
#ifdef WIN32
return WaitForSingleObject( pMutex.mutex, INFINITE );
#else
return pthread_mutex_lock(&pMutex.mutex);
#endif
}
///////////////////////////////////////////////////////////////////
inline MUTEX_LOCK_RETURN_TYPE TryLockMutex(MUTEX_TYPE pMutex, DWORD msec = 16){
MUTEX_LOCK_RETURN_TYPE rtn;
#ifdef WIN32
rtn = WaitForSingleObject(pMutex.mutex, msec );
#else
rtn = pthread_mutex_trylock(&pMutex.mutex);
#endif
if (rtn == WAIT_OBJECT_0) pMutex.activation = 1;
return rtn;
}
inline void CreateMutex (MUTEX_TYPE &pMutex) {
pMutex.activation = 0;
#ifdef WIN32
pMutex.mutex = CreateMutex (NULL, FALSE, NULL);
#else
pthread_mutex_init(&pMutex.mutex,NULL);
#endif
}
inline int ReleaseMutex(MUTEX_TYPE pMutex) {
pMutex.activation = 0;
#ifdef WIN32
return ReleaseMutex(pMutex.mutex);
#else
return (pthread_mutex_unlock(&pMutex.mutex)==0);
#endif
}
inline void CreateMutexEvent(THREAD_COND &pCond) {
#ifdef WIN32
pCond = CreateEvent(NULL, TRUE, FALSE, NULL);
#else
pthread_cond_init(&pCond,NULL);
#endif
}
inline void MutexCondSignal(THREAD_COND pCond) {
#ifdef WIN32
PulseEvent(pCond);
#else
pthread_cond_signal(&pCond);
#endif
}
inline void MutexCondWait(THREAD_COND &pCond, MUTEX_TYPE &pMutex) {
#ifdef WIN32
WaitForSingleObject( pCond, INFINITE );
#else
pthread_cond_wait(&pCond,&pMutex.mutex);
#endif
}
///////////////////////////////////////////////////////////////////
#endif // __MPLABCOMMON_H__
/*
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*
*/
|
[
"[email protected]"
] |
[
[
[
1,
259
]
]
] |
2480e3c671d8f1ec421b2ba695ceed117f65f34c
|
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
|
/SlonEngine/src/Physics/Bullet/BulletRotationalMotor.cpp
|
cd076ff8385b9797005f272ed8034d2cc88fa7d3
|
[] |
no_license
|
BackupTheBerlios/slon
|
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
|
dc10b00c8499b5b3966492e3d2260fa658fee2f3
|
refs/heads/master
| 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,748 |
cpp
|
#include "stdafx.h"
#define _DEBUG_NEW_REDEFINE_NEW 0
#include "Physics/Bullet/BulletCommon.h"
#include "Physics/Bullet/BulletConstraint.h"
#include "Physics/Bullet/BulletDynamicsWorld.h"
#include "Physics/Bullet/BulletRotationalMotor.h"
namespace slon {
namespace physics {
BulletRotationalMotor::BulletRotationalMotor(BulletConstraint* constraint_,
int axis_)
: constraint(constraint_)
, axis(axis_)
, numSimulatedSteps(0)
{
assert(constraint && axis >= 0 && axis < 3);
motor = constraint->getBtConstraint().getRotationalLimitMotor(axis);
}
void BulletRotationalMotor::calculateAngleInfo() const
{
// check if we have to update info
size_t numWorldSimulatedSteps = constraint->dynamicsWorld->getNumSimulatedSteps();
if (numSimulatedSteps < numWorldSimulatedSteps || numSimulatedSteps == 0)
{
btGeneric6DofConstraint& bConstraint = constraint->getBtConstraint();
btRigidBody& rbA = bConstraint.getRigidBodyA();
btRigidBody& rbB = bConstraint.getRigidBodyB();
btTransform trans;
// get offset from rigid body CM to joint
rbA.getMotionState()->getWorldTransform(trans);
btVector3 rA = trans.getBasis() * bConstraint.getFrameOffsetA().getOrigin();
rbB.getMotionState()->getWorldTransform(trans);
btVector3 rB = trans.getBasis() * bConstraint.getFrameOffsetB().getOrigin();
// position
position = btAdjustAngleToLimits(bConstraint.getAngle(axis), motor->m_loLimit, motor->m_hiLimit);
// convert angular to linear
btVector3 ax = bConstraint.getAxis(axis);
btVector3 velA(0,0,0);// = rA.cross( rbA.getAngularVelocity() );
btVector3 velB(0,0,0);// = rB.cross( rbB.getAngularVelocity() );
// correct linear to angular
velocity = (velA + rbA.getLinearVelocity()).dot( ax.cross(rA) ) / rA.length2();
velocity += (velB + rbB.getLinearVelocity()).dot( ax.cross(rB) ) / rB.length2();
// force
force = ax.dot( rbA.getTotalTorque() - rbB.getTotalTorque() );
numSimulatedSteps = numWorldSimulatedSteps;
}
}
math::Vector3r BulletRotationalMotor::getAxis() const
{
return to_vec(constraint->getBtConstraint().getAxis(axis));
}
real BulletRotationalMotor::getLoLimit() const
{
return motor->m_loLimit;
}
real BulletRotationalMotor::getHiLimit() const
{
return motor->m_hiLimit;
}
real BulletRotationalMotor::getPosition() const
{
calculateAngleInfo();
return position;
}
real BulletRotationalMotor::getVelocity() const
{
calculateAngleInfo();
return velocity;
}
real BulletRotationalMotor::getForce() const
{
calculateAngleInfo();
return force;
}
} // namespace physics
} // namespace slon
|
[
"devnull@localhost"
] |
[
[
[
1,
93
]
]
] |
229a788d2cbe4586a231bfd334cf386af13072b1
|
c0e409a05077ef54cf356044686d6858e302e303
|
/Assignments/2DDrawing/2DDrawing.cpp
|
ce7ffc2b1c9b5dd551f1b5e33833132038f9fe5e
|
[] |
no_license
|
mcd8604/cg1
|
e4bc4c9e00f05ff773837fbddf4615956dc6f203
|
e4bb436d3dc737b9f968388164c5bbfc2198d02a
|
refs/heads/master
| 2018-12-28T02:06:04.157991 | 2008-11-06T18:05:09 | 2008-11-06T18:05:09 | 40,638,417 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,131 |
cpp
|
// 2DDrawing.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include "GL/glut.h"
using namespace std;
#define RES_WIDTH 800.0
#define RES_HEIGHT 600.0
#define NEXT_SCREEN -1
#define PREV_SCREEN -2
//Polygon stipple pattern
const GLubyte pattern[] = {
0xFF, 0x00, 0x00, 0x77, 0x77, 0x00, 0x00, 0xFF,
0xFF, 0x00, 0x00, 0x77, 0x77, 0x00, 0x00, 0xFF,
0x00, 0xFF, 0x00, 0x77, 0x77, 0x00, 0xFF, 0x00,
0x00, 0xFF, 0x00, 0x77, 0x77, 0x00, 0xFF, 0x00,
0x00, 0x00, 0xFF, 0x77, 0x77, 0xFF, 0x00, 0x00,
0x00, 0x00, 0xFF, 0x77, 0x77, 0xFF, 0x00, 0x00,
0x00, 0x00, 0xAA, 0xFF, 0xFF, 0xAA, 0x00, 0x00,
0xAA, 0xAA, 0xAA, 0xFF, 0xFF, 0xAA, 0xAA, 0xAA,
0xAA, 0xAA, 0xAA, 0xFF, 0xFF, 0xAA, 0xAA, 0xAA,
0x00, 0x00, 0xAA, 0xFF, 0xFF, 0xAA, 0x00, 0x00,
0x00, 0x00, 0xFF, 0x77, 0x77, 0xFF, 0x00, 0x00,
0x00, 0x00, 0xFF, 0x77, 0x77, 0xFF, 0x00, 0x00,
0x00, 0xFF, 0x00, 0x77, 0x77, 0x00, 0xFF, 0x00,
0x00, 0xFF, 0x00, 0x77, 0x77, 0x00, 0xFF, 0x00,
0xFF, 0x00, 0x00, 0x77, 0x77, 0x00, 0x00, 0xFF,
0xFF, 0x00, 0x00, 0x77, 0x77, 0x00, 0x00, 0xFF
};
int mode;
struct Point {
int x;
int y;
};
struct PointList {
vector<Point> points;
};
struct Screen {
vector<PointList> pointLists;
};
vector<Screen> screens;
unsigned int curScreen;
void createNewPointList() {
screens[curScreen].pointLists.push_back(*new PointList());
}
void createNewScreen() {
Screen *screen = new Screen();
screens.push_back(*screen);
delete screen;
createNewPointList();
}
Point* mousePos;
int mouseLeftState;
void nextScreen() {
++curScreen;
if(curScreen >= screens.size()) {
createNewScreen();
}
}
void prevScreen() {
if(curScreen > 0) {
--curScreen;
}
}
void MenuHandler(int value) {
if(value == NEXT_SCREEN) {
nextScreen();
} else if(value == PREV_SCREEN) {
prevScreen();
} else {
mode = value;
if(screens[curScreen].pointLists.back().points.size() > 0) {
createNewPointList();
}
}
}
void Initialize(void) {
//Init GL
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, RES_WIDTH, 0.0, RES_HEIGHT);
//Init menu
glutCreateMenu(MenuHandler);
glutAddMenuEntry("Line", GL_LINES);
glutAddMenuEntry("Line Strip", GL_LINE_STRIP);
glutAddMenuEntry("Line Loop", GL_LINE_LOOP);
glutAddMenuEntry("Triangle", GL_TRIANGLES);
glutAddMenuEntry("Triangle Strip", GL_TRIANGLE_STRIP);
glutAddMenuEntry("Triangle Fan", GL_TRIANGLE_FAN);
glutAddMenuEntry("Quad", GL_QUADS);
glutAddMenuEntry("Quad Strip", GL_QUAD_STRIP);
glutAddMenuEntry("Polygon", GL_POLYGON);
glutAddMenuEntry("Next Screen", NEXT_SCREEN);
glutAddMenuEntry("Previous Screen", PREV_SCREEN);
glutAttachMenu(GLUT_RIGHT_BUTTON);
//Init mode and screen
mode = GL_LINES;
createNewScreen();
mousePos = new Point();
mousePos -> x = 0;
mousePos -> y = 0;
}
void Unload() {
delete mousePos;
}
void KeyUpdate(unsigned char key, int x, int y) {
}
void MouseUpdate(int button, int state, int x, int y) {
//detect left mouse click and push a new point
if(button == GLUT_LEFT_BUTTON) {
mouseLeftState = state;
Point* pt = new Point();
pt -> x = x;
pt -> y = RES_HEIGHT - y;
if(state == GLUT_DOWN) {
screens[curScreen].pointLists.back().points.push_back(*pt);
}
delete pt;
glutPostRedisplay();
}
}
void MotionUpdate(int x, int y)
{
mousePos -> x = x;
mousePos -> y = RES_HEIGHT - y;
glutPostRedisplay();
}
void PassiveMotionUpdate(int x, int y)
{
mousePos -> x = x;
mousePos -> y = RES_HEIGHT - y;
glutPostRedisplay();
}
void Draw(void)
{
glClear(GL_COLOR_BUFFER_BIT);
for(unsigned int i = 0; i < screens[curScreen].pointLists.size(); ++i) {
if( i % 2 == 0 ) {
glEnable( GL_LINE_STIPPLE );
glLineStipple( 4, 0xCCCC );
} else {
glEnable( GL_POLYGON_STIPPLE );
glPolygonStipple( pattern );
}
glColor3f((1.0 / screens[curScreen].pointLists.size()) * i, 1 - (1.0 / screens[curScreen].pointLists.size()) * i, 0.0);
glLineWidth(i * 1.0);
glBegin(mode);
for(unsigned int k = 0; k < screens[curScreen].pointLists[i].points.size(); ++k) {
glVertex2i(screens[curScreen].pointLists[i].points[k].x, screens[curScreen].pointLists[i].points[k].y);
}
if(i == screens[curScreen].pointLists.size() - 1) {
glVertex2i(mousePos -> x, mousePos -> y);
}
glEnd();
if( i % 2 == 0 ) {
glDisable( GL_LINE_STIPPLE );
} else {
glDisable( GL_POLYGON_STIPPLE );
}
}
glFlush();
glutSwapBuffers();
}
int _tmain(int argc, char** argv)
{
glEnable(GL_DOUBLEBUFFER);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(10, 10);
glutInitWindowSize(RES_WIDTH,RES_HEIGHT);
glutCreateWindow("2D Drawing");
Initialize();
glutDisplayFunc(Draw);
glutMouseFunc(MouseUpdate);
glutMotionFunc(MotionUpdate);
glutPassiveMotionFunc(PassiveMotionUpdate);
glutMainLoop();
Unload();
return 0;
}
|
[
"[email protected]"
] |
[
[
[
1,
232
]
]
] |
5cfbe4488160c4c803728b3fb7a3ef96371e0633
|
e8b8c5d9510b267e41c496024f7f439d1aff1618
|
/Pieces/ZPiece.h
|
5e03b0aaa8864d085cfb37a378e9ed3d52277927
|
[] |
no_license
|
Archetype/milkblocks
|
b80250cb5820188a16df73d528f80e3523d129b0
|
28ee5a44e5afc2440b77feec77202b310f395361
|
refs/heads/master
| 2021-01-19T21:29:05.453990 | 2011-07-12T02:44:59 | 2011-07-12T02:44:59 | 1,030,899 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 273 |
h
|
#ifndef _ZPIECE_H_
#define _ZPIECE_H_
#ifndef _PIECE_H_
#include "piece.h"
#endif
class ZPiece : public Piece
{
protected:
char* RotationGrid();
int States();
int Size();
public:
ZPiece( Grid* grid ) : Piece( grid ) { Initialize(); }
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
18
]
]
] |
f59aa1c51c4ab9ccd7cc8bd5eb7f16448d0319cd
|
105cc69f4207a288be06fd7af7633787c3f3efb5
|
/HovercraftUniverse/CoreEngine/GameStateManager.cpp
|
04c74b626a8dabfe3a988778fd8a6463cfe6dde5
|
[] |
no_license
|
allenjacksonmaxplayio/uhasseltaacgua
|
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
|
ad54e9aa3ad841b8fc30682bd281c790a997478d
|
refs/heads/master
| 2020-12-24T21:21:28.075897 | 2010-06-09T18:05:23 | 2010-06-09T18:05:23 | 56,725,792 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,902 |
cpp
|
#include "GameStateManager.h"
#include "BasicGameState.h"
namespace HovUni {
GameStateManager::GameStateManager(InputManager * inputMgr, GameState initialState, BasicGameState* gameState)
: mInputManager(inputMgr), mCurrentState(initialState), mCurrentGameState(gameState) {
//Make sure all game states are initialised to null
mGameStates[MAIN_MENU] = 0;
mGameStates[LOBBY] = 0;
mGameStates[IN_GAME] = 0;
//Register ourselves to the input manager
mInputManager->addKeyListener(this, "GameStateManager");
mInputManager->addMouseListener(this, "GameStateManager");
//Store the initial state
addGameState(initialState, gameState);
//Activate it
gameState->activate();
}
void GameStateManager::addGameState(GameState state, BasicGameState* gameState) {
//Old states CAN be replaced!
if (mGameStates[state] != 0) {
if (mCurrentState == state) {
//Set the new game state as active
mCurrentGameState = gameState;
}
//Delete the old state
delete mGameStates[state];
mGameStates[state] = 0;
}
mGameStates[state] = gameState;
// Register ourselfs to the gamestate
gameState->setManager(this);
}
void GameStateManager::switchState(GameState state) {
//Notify the previous one of deactivation
BasicGameState* currState = mGameStates[mCurrentState];
if (currState != 0) {
currState->disable();
} else {
//Maybe notify?
}
//Set the new state as active
mCurrentState = state;
mCurrentGameState = mGameStates[mCurrentState];
if (mCurrentGameState != 0) {
mCurrentGameState->activate();
} else {
//TODO: Maybe notify?
}
}
bool GameStateManager::frameStarted(const Ogre::FrameEvent & evt) {
//Update the input manager
mInputManager->capture();
if (mCurrentGameState) {
return mCurrentGameState->frameStarted(evt);
}
return true; //Default return
}
bool GameStateManager::mouseMoved(const OIS::MouseEvent & e) {
if (mCurrentGameState) {
return mCurrentGameState->mouseMoved(e);
}
return true; //Default return
}
bool GameStateManager::mousePressed(const OIS::MouseEvent & e, OIS::MouseButtonID id) {
if (mCurrentGameState) {
return mCurrentGameState->mousePressed(e, id);
}
return true; //Default return
}
bool GameStateManager::mouseReleased(const OIS::MouseEvent & e, OIS::MouseButtonID id) {
if (mCurrentGameState) {
return mCurrentGameState->mouseReleased(e, id);
}
return true; //Default return
}
bool GameStateManager::keyPressed(const OIS::KeyEvent & e) {
if (mCurrentGameState) {
return mCurrentGameState->keyPressed(e);
}
return true; //Default return
}
bool GameStateManager::keyReleased(const OIS::KeyEvent & e) {
if (mCurrentGameState) {
return mCurrentGameState->keyReleased(e);
}
return true; //Default return
}
}
|
[
"nick.defrangh@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
] |
[
[
[
1,
106
]
]
] |
2a21b5f11e8fb6499429cc0c6d55b64d22b9d64e
|
ea12fed4c32e9c7992956419eb3e2bace91f063a
|
/zombie/code/zombie/zombieentity/src/zombieentity/ncsuperentity_cmds.cc
|
374e4b7c32dbbd6af37dda0559701afe7a4764fe
|
[] |
no_license
|
ugozapad/TheZombieEngine
|
832492930df28c28cd349673f79f3609b1fe7190
|
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
|
refs/heads/master
| 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 762 |
cc
|
#include "precompiled/pchgameplay.h"
//------------------------------------------------------------------------------
// ncsuperentity_cmds.cc
// (C) 2006 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "zombieentity/ncsuperentity.h"
#include "ndebug/nceditor.h"
#include "entity/nobjectmagicinstancer.h"
//------------------------------------------------------------------------------
/**
SaveCmds
*/
bool
ncSuperEntity::SaveCmds (nPersistServer* ps)
{
if ( nComponentObject::SaveCmds(ps) )
{
// -- relativePos
ps->Put (this->entityObject, 'ISRP', this->relativePos.x, this->relativePos.y, this->relativePos.z);
}
return true;
}
|
[
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] |
[
[
[
1,
26
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.