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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8fcf1b64df1a02f661d4f49387cf7be235cf0808 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/teststdio/src/tstdio_auto.cpp | c2a3edf4c02812bfd206cd50ff59df7a0a6e7434 | [] | 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 | MacCentralEurope | C++ | false | false | 80,840 | cpp | /*
* 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 : tstdio_auto.cpp
* Part of : teststdio
*
* Description : ?Description
* Version: 0.5
*
*/
#include "tstdio.h"
#define MAX_LEN 20
// ============================ MEMBER FUNCTIONS ===============================
/*--------------------- FILE-RELATED OPERATIONS -----------------------------*/
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::remove1
API Tested : remove
TestCase Description: The test case tries to remove an existing file which is
not opened by any process
-------------------------------------------------------------------------------
*/
TInt CTestStdio::remove1()
{
INFO_PRINTF1(_L("fscanf returned:\n%d"));
//Same as for unlink or rmdir. See stdlib test cases.
char name[50] = "C:\\Logs\\remove1.txt";
FILE *fp = NULL;
int retval = 0;
fp = fopen(name, "w");
if(fp == NULL)
{
INFO_PRINTF1(_L("Error : File open"));
return -1;
}
fclose(fp);
retval = remove(name);
if (retval<0)
{
INFO_PRINTF2(_L("remove failed - error %d"), errno);
}
return retval;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::remove2
API Tested : remove
TestCase Description: Create one file, try to remove the opened file and then
close it. It should be removed after the close.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::remove2()
{
INFO_PRINTF1(_L("remove2"));
char name[16] = "c:\\remove2.txt";
FILE *fp = NULL;
int retval = 0;
fp = fopen (name, "w");
if (fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
retval = remove(name);
if (retval<0)
{
INFO_PRINTF2(_L("remove failed - error %d"), errno);
fclose(fp);
remove(name);
retval = 0;
return retval;
}
fclose (fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::rename1
API Tested : rename
TestCase Description: create one file and move it to new file using rename()
-------------------------------------------------------------------------------
*/
TInt CTestStdio::rename1()
{
INFO_PRINTF1(_L("rename1"));
char oldpath[14] = "c:\\path1.txt";
char newpath[14] = "c:\\path2.txt";
FILE *fp = NULL;
int retval = 0;
fp = fopen (oldpath, "w");
if (fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
fclose (fp);
retval = rename(oldpath, newpath);
if (retval<0)
{
INFO_PRINTF1(_L("rename failed - error "));
unlink(oldpath);
}
unlink(newpath);
return retval;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::tempnam1
API Tested : tempnam
TestCase Description: This function creates a unique temporary file name in user
specified directory.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::tempnam1()
{
INFO_PRINTF1(_L("tempnam1"));
TInt res = KErrNone;
FILE *stream = NULL;
char* name = "c:\\tmp";
char* file;
if (mkdir(name, 0666) == -1)
{
if (errno != EEXIST)
{
res = KErrGeneral;
return res;
}
}
for (int i = 1; i <= 10; i++)
{
if ((file = tempnam(name,"wow.")) == NULL)
{
INFO_PRINTF1(_L("tempnam() failed\n"));
res = KErrGeneral;
}
else
{
INFO_PRINTF2(_L("Creating tempfile %d"),i);
if ((stream = fopen(file,"wb+")) == NULL)
{
INFO_PRINTF1(_L("Could not open temporary file\n"));
res = KErrGeneral;
}
else
{
int bytes = fprintf(stream, "tempnam1");
fflush(stream);
if(bytes != 8) // 8 bytes is string length of 'tempnam1'
{
INFO_PRINTF1(_L("Error in fprintf"));
res = KErrGeneral;
}
else
{
char buf[10];
fseek(stream, -8, SEEK_CUR); //reset file position indicator
bytes = fscanf(stream, "%s", buf);
if(strlen(buf) != 8)
{
INFO_PRINTF1(_L("Error in fscanf, Test case failed"));
fclose(stream);
unlink(file);
free(file);
return KErrGeneral;
}
if(strcmp(buf, "tempnam1"))
{
INFO_PRINTF1(_L("String read from file does not match the string - tempnam1"));
res = KErrGeneral;
}
}
fclose(stream);
}
unlink(file);
}
free(file);
}
return res;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::tempnam2
API Tested : tempnam
TestCase Description: This function creates a unique temporary file name in
implementation specified directory. If dir = NULL P_tmpdir
(C:\\Private\\UID3)which is implementation defined shall
be used and if pfx = NULL file name generated shall be
prefixed as tmp.xxxxxx
-------------------------------------------------------------------------------
*/
TInt CTestStdio::tempnam2()
{
INFO_PRINTF1(_L("tempnam2"));
TInt res = KErrNone;
FILE *stream = NULL;
char* file;
for (int i = 1; i <= 10; i++)
{
if ((file = tempnam(NULL,NULL)) == NULL)
{
INFO_PRINTF1(_L("tempnam() failed\n"));
res = KErrGeneral;
}
else
{
INFO_PRINTF2(_L("Creating tempfile %d"),i);
if ((stream = fopen(file,"wb+")) == NULL)
{
INFO_PRINTF1(_L("Could not open temporary file\n"));
res = KErrGeneral;
}
else
{
int bytes = fprintf(stream, "tempnam2");
fflush(stream);
if(bytes != 8) // 8 bytes is string length of 'tempnam1'
{
INFO_PRINTF1(_L("Error in fprintf"));
res = KErrGeneral;
}
else
{
char buf[10];
fseek(stream, -8, SEEK_CUR); //reset file position indicator
bytes = fscanf(stream, "%s", buf);
if(strlen(buf) != 8)
{
INFO_PRINTF1(_L("Error in fscanf, Test case failed"));
fclose(stream);
unlink(file);
free(file);
return KErrGeneral;
}
if(strcmp(buf, "tempnam2"))
{
INFO_PRINTF1(_L("String read from file does not match the string - tempnam1"));
res = KErrGeneral;
}
}
fclose(stream);
}
unlink(file);
}
free(file);
}
return res;
}
/*--------------- END OF FILE-RELATED OPERATIONS -----------------------------*/
/*--------------------- STREAM-RELATED OPERATIONS ---------------------------*/
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fclose1
API Tested : fclose
TestCase Description: Just open a file and close it
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fclose1()
{
INFO_PRINTF1(_L("fclose1"));
FILE *fp;
fp = fopen("c:\\input.txt", "w");
if(fp == NULL)
{
INFO_PRINTF1(_L("Error : File open"));
return -1;
}
fprintf(fp, "This is the first line\n");
INFO_PRINTF1(_L("Wrote to file\n"));
//do something here
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fflush1
API Tested : fflush
TestCase Description: Create a file, put the mode to full buffering then call
fflush
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fflush1()
{
INFO_PRINTF1(_L("fflush1"));
FILE *fp;
int retval = 0;
char name[20] = "c:\\fflush1.txt";
fp = fopen(name, "w");
if(fp == NULL)
{
INFO_PRINTF1(_L("Error : File open"));
return -1;
}
setvbuf(fp, NULL, _IOFBF, 100); // set to full buffering with NULL buffer
fprintf(fp, "we are trying to buffer 100 characters at once with NULL buffer. ");
retval = fflush(fp);
if (retval)
{
INFO_PRINTF1(_L("fflush failed"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "Again.. we are trying to buffer 100 characters at once with NULL buffer. ");
retval = fflush(fp);
if (retval)
{
INFO_PRINTF1(_L("fflush failed"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "Once Again.. we are trying to buffer 100 characters at once with NULL buffer\n");
retval = fflush(fp);
if (retval)
{
INFO_PRINTF1(_L("fflush failed"));
fclose(fp);
unlink(name);
return -1;
}
fclose(fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fopen1
API Tested : fopen
TestCase Description: Create a file using fopen() using absolute path and write
something in to it. Then close it. Open the same file
again in append mode and write something in to it
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fopen1()
{
INFO_PRINTF1(_L("fopen1"));
FILE *fp;
char name[20] = "c:\\fopen1.txt";
if ((fp = fopen (name, "w")) == NULL)
{
INFO_PRINTF1(_L("Error creating file"));
return -1;
}
INFO_PRINTF1(_L("Opened file c:\\fopen1.txt\n"));
fprintf(fp, "This is the first line\n");
INFO_PRINTF1(_L("Wrote to file\n"));
fclose (fp);
INFO_PRINTF1(_L("Closed file\n"));
if ((fp = fopen (name, "a")) == NULL)
{
INFO_PRINTF1(_L("Error creating file"));
return -1;
}
INFO_PRINTF1(_L("Opened file c:\\fopen1.txt for appending\n"));
fprintf(fp, "This is the second line\n");
fclose (fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fopen2
API Tested : fopen
TestCase Description: Create a file using fopen() using relative path and write
something in to it. Then close it. Open the same file
again in append mode and write something in to it
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fopen2()
{
INFO_PRINTF1(_L("fopen2"));
FILE *fp;
RFs fs;
fs.Connect();
TBuf<30> buf(_L("C:\\System"));
TBuf<30> buf2;
fs.SetSessionPath(buf);
fs.SessionPath(buf2);
if ((fp = fopen ("..\\input.txt", "w")) == NULL) //relative path
{
INFO_PRINTF1(_L("Error creating file"));
return -1;
}
INFO_PRINTF1(_L("Opened file c:\\input.txt\n"));
fprintf(fp, "This is the first line\n");
INFO_PRINTF1(_L("Wrote to file\n"));
fclose (fp);
INFO_PRINTF1(_L("Closed file\n"));
fs.Close();
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fopen3
API Tested : fopen
TestCase Description: Open a file in read-only mode and try to write something
into it
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fopen3()
{
INFO_PRINTF1(_L("fopen3"));
FILE *fp;
int retval = 0;
if ((fp = fopen ("C:\\input.txt", "w")) == NULL)
{
INFO_PRINTF1(_L("Error opening file"));
return -1;
}
fclose(fp);
if ((fp = fopen ("C:\\input.txt", "r")) == NULL)
{
INFO_PRINTF1(_L("Error opening file"));
return -1;
}
retval = fputc('c', fp);
if (retval == EOF)
{
retval = KErrNone; //Negative test case, So Success
}
else
{
retval = -1;
}
fclose(fp);
return retval;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::setbuf1
API Tested : setbuf
TestCase Description: Test setbuf in full buffering mode
-------------------------------------------------------------------------------
*/
TInt CTestStdio::setbuf1()
{
INFO_PRINTF1(_L("setbuf1"));
FILE *fp;
char FullBuf[bufSize];
char name[20] = "c:\\setbuf1.txt";
fp = fopen(name, "w");
if (fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
setbuf(fp, FullBuf); // Fully buffered
if (ferror(fp))
{
INFO_PRINTF1(_L("setbuf failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "we are trying to buffer 20 characters at once. ");
fprintf(fp, "Again.. we are trying to buffer 20 characters at once. ");
fprintf(fp, "Once Again.. we are trying to buffer 20 characters at once\n");
fclose(fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::setbuf2
API Tested : setbuf
TestCase Description: Test setbuf in unbuffered mode
-------------------------------------------------------------------------------
*/
TInt CTestStdio::setbuf2()
{
INFO_PRINTF1(_L("setbuf2"));
FILE *fp;
char name[20] = "c:\\setbuf2.txt";
fp = fopen(name, "w");
if (fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
setbuf(fp, NULL); // unbuffered
if (ferror(fp))
{
INFO_PRINTF1(_L("setbuf failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "write to a file with no buffering");
fprintf(fp, "Again.. write to a file with no buffering\n");
fclose(fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::setvbuf1
API Tested : setvbuf
TestCase Description: Test setvbuf in line buffering mode with and without
buffer (NULL buffer)
-------------------------------------------------------------------------------
*/
TInt CTestStdio::setvbuf1()
{
INFO_PRINTF1(_L("setvbuf1"));
FILE *fp;
char lineBuf[bufSize];
int retval = 0;
char name[20] = "c:\\setvbuf1.txt";
fp = fopen(name, "w");
if (fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
retval = setvbuf(fp, lineBuf, _IOLBF, 1024); // set to line buffering
if (retval)
{
INFO_PRINTF1(_L("setvbuf failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "1st line without eol\t");
fprintf(fp, "2nd line with eol\n");
retval = setvbuf(fp, NULL, _IOLBF, 1024); // set to line buffering with NULL buffer
if (retval)
{
INFO_PRINTF1(_L("setvbuf failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "3rd line without eol\t");
fprintf(fp, "4th line with eol\n");
fclose(fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::setvbuf2
API Tested : setvbuf
TestCase Description: Test setvbuf in full buffering mode with and without
buffer (NULL buffer)
-------------------------------------------------------------------------------
*/
TInt CTestStdio::setvbuf2()
{
INFO_PRINTF1(_L("setvbuf2"));
FILE *fp;
char FullBuf[bufSize];
int retval = 0;
char name[20] = "c:\\setvbuf2.txt";
fp = fopen(name, "w");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
retval = setvbuf(fp, FullBuf, _IOFBF, 20); // set to full buffering
if (retval)
{
INFO_PRINTF1(_L("setvbuf failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "we are trying to buffer 20 characters at once. ");
fprintf(fp, "Again.. we are trying to buffer 20 characters at once. ");
fprintf(fp, "Once Again.. we are trying to buffer 20 characters at once\n");
retval = setvbuf(fp, NULL, _IOFBF, 20); // set to full buffering with NULL buffer
if (retval)
{
INFO_PRINTF1(_L("setvbuf failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "we are trying to buffer 20 characters at once with NULL buffer. ");
fprintf(fp, "Again.. we are trying to buffer 20 characters at once with NULL buffer. ");
fprintf(fp, "Once Again.. we are trying to buffer 20 characters at once with NULL buffer\n");
fclose(fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::setvbuf3
API Tested : setvbuf
TestCase Description: Test setvbuf in unbuffered mode with and without
buffer (NULL buffer)
-------------------------------------------------------------------------------
*/
TInt CTestStdio::setvbuf3()
{
INFO_PRINTF1(_L("setvbuf3"));
FILE *fp;
char NoBuf[bufSize];
int retval = 0;
char name[20] = "c:\\setvbuf3.txt";
fp = fopen(name, "w");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
retval = setvbuf(fp, NoBuf, _IONBF, 10); // set to No buffering
if (retval)
{
INFO_PRINTF1(_L("setvbuf failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "write to a file with no buffering");
fprintf(fp, "Again.. write to a file with no buffering\n");
retval = setvbuf(fp, NULL, _IONBF, 10); // set to No buffering with NULL buffer. Same as above
if (retval)
{
INFO_PRINTF1(_L("setvbuf failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fprintf(fp, "write to a file with no buffering and NULL buffer. ");
fprintf(fp, "Again.. write to a file with no buffering and NULL buffer\n");
fclose(fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::clearerr1
API Tested : clearerr
TestCase Description: Read single character at a time, stopping on EOF or
error. Then call clearerr(). It should clear the EOF and
error flags.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::clearerr1()
{
INFO_PRINTF1(_L("clearerr1"));
char a;
FILE *fp;
fp = fopen("c:\\input.txt", "r");
if (fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
// read single chars at a time, stopping on EOF or error:
while(fread(&a, sizeof(char), 1, fp), !feof(fp) && !ferror(fp))
{
INFO_PRINTF2(_L("I read %c\t"), a);
}
if (feof(fp))
{
INFO_PRINTF1(_L("End of file was reached.\n"));
}
if (ferror(fp))
{
INFO_PRINTF1(_L("An error occurred.\n"));
}
clearerr(fp);
if (!feof(fp) && !ferror(fp))
{
INFO_PRINTF1(_L("clearerr sucessful\n"));
}
else
{
fclose(fp);
return -1;
}
fclose(fp);
return KErrNone;
}
TInt CTestStdio::feof1()
{
INFO_PRINTF1(_L("feof1"));
char a;
FILE *fp;
fp = fopen("c:\\input.txt", "r");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
// read single chars at a time, stopping on EOF or error:
while(fread(&a, sizeof(char), 1, fp), !feof(fp) && !ferror(fp))
{
INFO_PRINTF2(_L("I read %c\t"), a);
}
if (feof(fp))
{
INFO_PRINTF1(_L("End of file was reached.\n"));
}
if (ferror(fp))
{
INFO_PRINTF1(_L("An error occurred.\n"));
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::ferror1
API Tested : ferror
TestCase Description: This test case tries to write something in to a file in
read-only mode so the ferror() will give some error.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::ferror1()
{
INFO_PRINTF1(_L("ferror1"));
FILE * fp;
char a;
fp=fopen("c:\\input.txt","r");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
else
{
fwrite(&a, sizeof(char), 1, fp);
if (ferror (fp))
{
INFO_PRINTF1(_L("ferror successful\n"));
}
else
{
fclose(fp);
return -1;
}
clearerr(fp);
if (!ferror(fp))
{
INFO_PRINTF1(_L("ferror successful after clearerr\n"));
}
fclose (fp);
}
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fread1
API Tested : fread
TestCase Description: read single char at a time, stopping on EOF or error
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fread1()
{
INFO_PRINTF1(_L("fread1"));
char a;
FILE *fp;
fp = fopen("c:\\input.txt", "r");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
// read single chars at a time, stopping on EOF or error:
while (fread(&a, sizeof(char), 1, fp), !feof(fp) && !ferror(fp))
{
INFO_PRINTF2(_L("I read %c\t"), a);
}
if (ferror(fp)) //Some error occured
{
fclose(fp);
return -1;
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fread2
API Tested : fread
TestCase Description: Testing for the return value of the fread() API for the
different input values
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fread2()
{
INFO_PRINTF1(_L("fread2"));
char a[20] ;//= "\0";
FILE *fp;
fp = fopen("c:\\input.txt", "r");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
if ((fread(&a, sizeof(a), 1, fp)) != 1 )
{
INFO_PRINTF1(_L("Fread()::Error"));
fclose(fp);
return -1;
}
int retval = fseek(fp, 0, SEEK_SET); // seek to the beginning of the file
if((fread(&a, sizeof(char), 10, fp)) != 10 )
{
fclose(fp);
INFO_PRINTF1(_L("Fread()::Error"));
return -1;
}
else
{
a[10] = '\0';
TBuf<MAX_LEN> buf;
TInt len = strlen(a);
for (TInt j =0; j<len;j++)
{
buf.Append(a[j]);
}
INFO_PRINTF2(_L("Read string - %S\n"), &buf);
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fread3
API Tested : fread
TestCase Description: Testing the fread() API for the different values of input
"nitem"
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fread3()
{
INFO_PRINTF1(_L("fread3"));
char a[20] = "\0";
FILE *fp;
fp = fopen("c:\\input.txt", "r");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
if(fread(&a, sizeof(a), 0, fp) != 0 )
{
fclose(fp);
INFO_PRINTF1(_L("fread not returning Zero when nitem = 0"));
return -1;
}
if(fread(&a, 0, 0, fp) != 0 )
{
fclose(fp);
INFO_PRINTF1(_L("fread not returning Zero when nitem = 0 and size = 0"));
return -1;
}
INFO_PRINTF2(_L("original NULL string - %s\n"),a);
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fwrite1
API Tested : fwrite
TestCase Description: Write some random characters in to a file
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fwrite1()
{
INFO_PRINTF1(_L("fwrite1"));
int i;
int r[10];
FILE *fp;
// populate the array with random numbers:
for(i = 0; i < 10; i++)
{
r[i] = rand();
}
// save the random numbers (10 ints) to the file
fp = fopen("c:\\fwrite1.txt", "wb");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
fwrite(r, sizeof(int), 10, fp); // write 10 ints
if (ferror(fp))
{
fclose(fp);
return -1;
}
fclose(fp);
unlink("c:\\fwrite1.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fwrite2
API Tested : fwrite
TestCase Description: Testing for the return value of the fwrite() API for the
different input values
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fwrite2()
{
INFO_PRINTF1(_L("fwrite2"));
char a[20] = "f;dl`24|N0";
FILE *fp;
fp = fopen("c:\\fwrite2.txt", "wb");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
if(fwrite(&a, sizeof(a), 1, fp) != 1 )
{
INFO_PRINTF1(_L("fwrite failed\n"));
return -1;
}
if(fwrite(&a, sizeof(char), 10, fp) != 10 )
{
INFO_PRINTF1(_L("fwrite failed\n"));
return -1;
}
fclose(fp);
unlink("c:\\fwrite2.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fwrite3
API Tested : fwrite
TestCase Description: Testing the fwrite() API for the different values of
input "nitem". Also test whether fwrite returns 0 incase
of nitem or size i/p is zero.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fwrite3()
{
INFO_PRINTF1(_L("fwrite3"));
char a[20] = "\f;dl`24|N0";
FILE *fp;
fp = fopen("c:\\fwrite3.txt", "wb");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
if(fwrite(&a, sizeof(a), 0, fp) != 0 )
{
INFO_PRINTF1(_L("fwrite not returning Zero when nitem = 0"));
return -1;
}
if(fwrite(&a, 0, 0, fp) != 0 )
{
INFO_PRINTF1(_L("fwrite not returning Zero when nitem = 0 and size = 0"));
return -1;
}
fclose(fp);
unlink("c:\\fwrite3.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fgetpos1
API Tested : fgetpos
TestCase Description: This test case reads a line from the file, saves the
position, reads another line from the file. Then restores
the position to where we saved and again reads one more
line from that position.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fgetpos1()
{
INFO_PRINTF1(_L("fgetpos1"));
char s[20];
fpos_t pos;
char *buf = "This is the test.\n";
FILE *fp;
int retval;
fp = fopen("C:\\input.txt","w");
fputs(buf , fp);
fputs(buf , fp);
fclose(fp);
fp = fopen("C:\\input.txt","r");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
fgets(s, sizeof(s), fp); // read a line from the file
retval = fgetpos(fp, &pos); // save the position
if (retval)
{
INFO_PRINTF1(_L ("fgetpos failed\n"));
return -1;
}
fgets(s, sizeof(s), fp); // read another line from the file
retval = fsetpos(fp, &pos); // now restore the position to where we saved
if (retval)
{
INFO_PRINTF1(_L ("fgetpos failed\n"));
return -1;
}
fgets(s, sizeof(s), fp); // read the second line from the file again
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fseek1
API Tested : fseek
TestCase Description: Test fseek() to set the file pointer to different
positions in a file.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fseek1()
{
INFO_PRINTF1(_L("fseek1"));
FILE *fp;
int retval;
fp = fopen("c:\\input.txt", "a");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
fprintf(fp, "This is the first line\n");
fprintf(fp, "This is the first line\n");
INFO_PRINTF1(_L("Wrote to file\n"));
retval = fseek(fp, 30, SEEK_SET); // seek to the 20th byte of the file
if (retval)
{
INFO_PRINTF1(_L ("fseek failed\n"));
return -1;
}
retval = fseek(fp, -10, SEEK_CUR); // seek backward 30 bytes from the current pos
if (retval)
{
INFO_PRINTF1(_L ("fseek failed\n"));
return -1;
}
retval = fseek(fp, -10, SEEK_END); // seek to the 10th byte before the end of file
if (retval)
{
INFO_PRINTF1(_L ("fseek failed\n"));
return -1;
}
retval = fseek(fp, 0, SEEK_SET); // seek to the beginning of the file
if (retval)
{
INFO_PRINTF1(_L ("fseek failed\n"));
return -1;
}
long pos = ftell(fp);
if (pos ==0)
{
INFO_PRINTF1(_L("fseek successful\n"));
retval = KErrNone;
}
fclose(fp);
return retval;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fseek2
API Tested : fseek
TestCase Description: 1. Create an empty file
2. fseek beyond the EOF
3. Verify the size of the file
Return value : Fstat fills up stat file size with zero
Testcase returns KerrNone
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fseek2()
{
INFO_PRINTF1(_L("fseek2"));
int retval;
FILE *fp;
struct stat st;
fp = fopen("c:\\fseek.txt", "a+");
retval = fseek(fp, 100, SEEK_SET); // seeking to the 100th byte in the empty file
if(retval != 0)
INFO_PRINTF1(_L("fseek failed"));
else
{
INFO_PRINTF2(_L("ftell returns %d\n"), ftell(fp));
fstat(fileno(fp), &st);
if(st.st_size != 0)
{
INFO_PRINTF2(_L("size of file = %d"),st.st_size);
INFO_PRINTF1(_L("Size of the file should have been 0 bytes"));
return KErrGeneral;
}
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fsetpos1
API Tested : fsetpos
TestCase Description: This test case reads a line from the file, saves the
position, reads another line from the file. Then restores
the position to where we saved and again reads one more
line from that position.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fsetpos1()
{
INFO_PRINTF1(_L("fsetpos1"));
char s[20];
char s1[20];
char s2[20];
fpos_t pos;
char *buf = "This is the test";
FILE *fp;
int retval;
fp = fopen("C:\\input.txt","w");
fputs(buf , fp);
fputs(buf, fp);
fclose(fp);
fp = fopen("C:\\input.txt","r");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
fgets(s, sizeof(s), fp); // read a line from the file
retval = fgetpos(fp, &pos); // save the position
if (retval)
{
INFO_PRINTF1(_L ("fgetpos failed\n"));
return -1;
}
fgets(s1, sizeof(s1), fp); // read another line from the file
fsetpos(fp, &pos); // now restore the position to where we saved
fgets(s2, sizeof(s2), fp); // read the second line from the file again
if(strcmp(s1,s2))
{
INFO_PRINTF1(_L("Fsetpos():: failed .."));
fclose(fp);
return -1;
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fsetpos2
API Tested : fsetpos
TestCase Description: Test that, call to ungetc() will affect the functionality
of fsetpos() API
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fsetpos2()
{
INFO_PRINTF1(_L("fsetpos2"));
char s[20];
char s1[20];
char s2[20];
fpos_t pos;
char *buf = "This is the test";
FILE *fp;
fp = fopen("C:\\input.txt","w");
fputs(buf, fp);
fputs(buf, fp);
fclose(fp);
fp = fopen("C:\\input.txt","r");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
fgets(s, sizeof(s), fp); // read a line from the file
// As we tested fsetpos() working accordingly...
fgetpos(fp, &pos); // save the position
fgets(s1, sizeof(s1), fp); // read another line from the file
ungetc('f',fp); //Must undo any effects of ungetc() on the same stream
fsetpos(fp, &pos); // now restore the position to where we saved
fgets(s2, sizeof(s2), fp); // read the second line from the file again
if(strcmp(s1,s2))
{
INFO_PRINTF1(_L("Fsetpos():: failed .."));
fclose(fp);
return -1;
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::ftell1
API Tested : ftell
TestCase Description: Test basic functionality of ftell()
-------------------------------------------------------------------------------
*/
TInt CTestStdio::ftell1()
{
INFO_PRINTF1(_L("ftell1"));
long pos;
FILE *fp;
fp = fopen("c:\\ftell1.txt", "w");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
fwrite("Initially, Write something in to ftell1.txt", sizeof(char), 32, fp);
// store the current position in variable "pos":
pos = ftell(fp);
if (pos < 0)
{
INFO_PRINTF1(_L ("ftell failed\n"));
return -1;
}
// seek ahead 10 bytes:
fseek(fp, 10, SEEK_CUR);
// do some mysterious writes to the file
fwrite("Again, Write something in to ftell1.txt", sizeof(char), 28, fp);
// and return to the starting position, stored in "pos":
fseek(fp, pos, SEEK_SET);
fwrite("Overwriting", sizeof(char), 11, fp);
fclose(fp);
unlink("c:\\ftell1.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::rewind1
API Tested : rewind
TestCase Description: Test the basic functionality of rewind
-------------------------------------------------------------------------------
*/
TInt CTestStdio::rewind1()
{
INFO_PRINTF1(_L("rewind1"));
FILE *fp;
fp = fopen("c:\\input.txt", "r");
if (fp == NULL)
{
INFO_PRINTF1(_L ("fopen failed\n"));
return -1;
}
fseek(fp, 100, SEEK_SET); // seek to the 100th byte of the file
fseek(fp, -30, SEEK_CUR); // seek backward 30 bytes from the current pos
fseek(fp, -10, SEEK_END); // seek to the 10th byte before the end of file
rewind(fp); // seek to the beginning of the file
if (ferror(fp))
{
return -1;
}
long pos = ftell(fp);
if (pos ==0)
{
INFO_PRINTF1(_L("rewind successful\n"));
}
fclose(fp);
return KErrNone;
}
/*--------------- END OF STREAM-RELATED OPERATIONS --------------------------*/
/*--------------------- INPUT/OUTPUT OPERATIONS -----------------------------*/
/*
-------------------------------------------------------------------------------
Function Name : CTStdio::fgetc1
API Tested : fgetc
TestCase Description: The test function opens a file which has characters.
It reads all the characters in the file one by one till
EOF and writes the characters in the log file.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fgetc1()
{
INFO_PRINTF1(_L("fgetc1"));
FILE *fp;
fp = fopen("C:\\input.txt","w");
fclose(fp);
fp = fopen("C:\\input.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
int n = fgetc(fp);
INFO_PRINTF1(_L("fgetc done"));
while (n != -1)
{
n = fgetc(fp);
}
if (n == EOF)
{
INFO_PRINTF1(_L("End of file reached!"));
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fgets1
API Tested : fgets
TestCase Description: The test case function will open a file with characters.
It reads all the characters from the file as one string.
It writes the read string into log file. Then it does
another string read from the stream where the EOF is
already reached. This read will return NULL.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fgets1()
{
INFO_PRINTF1(_L("fgets1"));
FILE *fp;
char buf[20];
fp = fopen("C:\\input.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
if(fgets(buf,18,fp) != NULL)
{
INFO_PRINTF2(_L("%s\n"), buf);
}
else
{
INFO_PRINTF1(_L("Buffer is empty\n"));
}
buf[0] = '\0';
if(fgets(buf,2,fp) != NULL)
{
INFO_PRINTF2(_L("%s\n"), buf);
}
else
{
INFO_PRINTF1(_L("Buffer is empty\n"));
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fgets2
API Tested : fgets
TestCase Description: The test case will open a file which has characters. The
function reads 3 strings where the size of the string to
be read is less than, equal to and greater than the number
of characters in the file. The file position indicator is
rewinded after each time fgets function is called.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fgets2()
{
INFO_PRINTF1(_L("fgets2"));
FILE *fp;
char buf[30];
fp = fopen("C:\\input.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
if(fgets(buf,5,fp) != NULL)
{
INFO_PRINTF2(_L("%s\n"), buf);
}
else
{
INFO_PRINTF1(_L("Buffer is empty\n"));
}
rewind(fp);
if(fgets(buf,18,fp) != NULL)
{
INFO_PRINTF2(_L("%s\n"), buf);
}
else
{
INFO_PRINTF1(_L("Buffer is empty\n"));
}
rewind(fp);
if(fgets(buf,20,fp) != NULL)
{
INFO_PRINTF2(_L("%s\n"), buf);
}
else
{
INFO_PRINTF1(_L("Buffer is empty\n"));
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fgets3
API Tested : fgets
TestCase Description: This test case open a file with characters. The function
will read a string which has a new line charater within
the specified length of the string to be read.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fgets3()
{
INFO_PRINTF1(_L("fgets3"));
FILE *fp;
char buf[20];
fp = fopen("C:\\input.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
if(fgets(buf,10,fp) != NULL)
{
INFO_PRINTF2(_L("%s\n"), buf);
}
else
{
INFO_PRINTF1(_L("Buffer is empty\n"));
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fputc1
API Tested : fputc
TestCase Description: The testcase function writes one character on to a file
and closes the file. The same file is again opened and a
character is read from the file.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fputc1()
{
INFO_PRINTF1(_L("fputc1"));
FILE *fp;
int rretval,wretval;
char name[20] = "c:\\fputc1.txt";
fp = fopen(name,"w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = fputc('a',fp); //fputc(char(0x0905),fp);
if(wretval == EOF)
{
INFO_PRINTF1(_L("fputc failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fclose(fp);
fp = fopen("C:\\fputc1.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
fclose(fp);
unlink(name);
return -1;
}
rretval = fgetc(fp);
if(wretval != rretval)
{
INFO_PRINTF1(_L("fputc failed\n"));
}
else
{
INFO_PRINTF1(_L("fputc passed\n"));
}
fclose(fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fputc2
API Tested : fputc
TestCase Description: The testcase function writes a set characters on to a
file and closes the file. The same file is again opened
and characters areread from the file.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fputc2()
{
INFO_PRINTF1(_L("fputc2"));
FILE *fp;
int wretval[10],rretval;
int alphabets[10] = {0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a};
int i;
char name[20] = "c:\\fputc2.txt";
fp = fopen(name,"w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
for(i=0;i<10;i++)
{
wretval[i] = fputc((char) alphabets[i],fp);
if(wretval[i] == EOF)
{
INFO_PRINTF1(_L("fputc failed\n"));
fclose(fp);
unlink(name);
return -1;
}
}
fclose(fp);
fp = fopen("C:\\fputc2.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
for(i=0;i<10;i++)
{
rretval = fgetc(fp);
if(rretval != wretval[i])
{
INFO_PRINTF1(_L("fputc failed\n"));
fclose(fp);
unlink(name);
return -1;
}
}
INFO_PRINTF1(_L("fputc passed\n"));
fclose(fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fputc3
API Tested : fputc
TestCase Description: The testcase function writes a new line character on to a
file and closes the file. The same file is again opened
and the content is read from the file.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fputc3()
{
INFO_PRINTF1(_L("fputc3"));
FILE *fp;
int rretval, wretval;
char name[20] = "c:\\fputc3.txt";
fp = fopen(name, "w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = fputc('\n',fp);
if(wretval == EOF)
{
INFO_PRINTF1(_L("fputc failed\n"));
fclose(fp);
unlink(name);
return -1;
}
fclose(fp);
fp = fopen("C:\\fputc3.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
rretval = fgetc(fp);
if(wretval != rretval)
{
INFO_PRINTF1(_L("fputc failed\n"));
}
else
{
INFO_PRINTF1(_L("fputc passed\n"));
}
fclose(fp);
unlink(name);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fputc4
API Tested : fputc
TestCase Description: The testcase function tries writing a character on to a
file which is opened for reading only.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fputc4()
{
INFO_PRINTF1(_L("fputc4"));
FILE *fp;
int wretval = 0;
char name[20] = "c:\\input.txt";
fp = fopen(name,"w");
fclose(fp);
fp = fopen(name,"r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = fputc('c',fp);
if(wretval == EOF)
{
fclose(fp);
return KErrNone; //Negative test case, So success
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fputs1
API Tested : fputs
TestCase Description: The testcase funtion will write a fixed lenth string to a
file, then the file is closed. The same file again opened
and the string that was written using fputws is read back
using fgets and the 2 strings are compared to determine
the result of the test case.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fputs1()
{
INFO_PRINTF1(_L("fputs1"));
FILE *fp;
int wretval;
char rs1[10],rs2[10];
char *buf = "This is a test";
char *rptr;
int retval;
fp = fopen("C:\\input.txt","w");
fputs(buf,fp);
fclose(fp);
fp = fopen("C:\\input.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
rptr = fgets(rs1,10,fp);
if(rptr == NULL)
{
INFO_PRINTF1(_L("fgets failed\n"));
fclose(fp);
return -1;
}
fclose(fp);
fp = fopen("c:\\fputs1.txt","w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = fputs(rs1,fp);
if(wretval == EOF)
{
INFO_PRINTF1(_L("fputs failed\n"));
fclose(fp);
return -1;
}
fclose(fp);
fp = fopen("C:\\fputs1.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
rptr = fgets(rs2,10,fp);
if(rptr == NULL)
{
INFO_PRINTF1(_L("fgets failed\n"));
fclose(fp);
return -1;
}
retval = strcmp(rs1,rs2);
if(retval == 0)
{
INFO_PRINTF1(_L("fputs passed\n"));
}
else
{
INFO_PRINTF1(_L("fputs failed\n"));
}
fclose(fp);
unlink("C:\\fputs1.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fputs2
API Tested : fputs
TestCase Description: The testcase function will write a string which has a new
line character in the middle and the file is closed. The
same file is opened and the string is read back by fgets API.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fputs2()
{
INFO_PRINTF1(_L("fputs2"));
FILE *fp;
int wretval;
char rs1[10] = "abcd\nefg";
char *rptr,rs2[10];
int retval;
fp = fopen("c:\\fputs2.txt","w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = fputs(rs1,fp);
if(wretval == EOF)
{
INFO_PRINTF1(_L("fputs failed\n"));
fclose(fp);
return -1;
}
fclose(fp);
fp = fopen("C:\\fputs2.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
rptr = fgets(rs2,10,fp);
if(rptr == NULL)
{
INFO_PRINTF1(_L("fgets failed\n"));
fclose(fp);
return -1;
}
retval = strcmp(rs1,rs2);
if(retval == 0)
{
INFO_PRINTF1(_L("fputs failed\n"));
}
else
{
INFO_PRINTF1(_L("fputs passed\n"));
}
fclose(fp);
unlink("C:\\fputs2.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fputs3
API Tested : fputs
TestCase Description: The testcase will open a file in read-only mode and try
to write a string.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fputs3()
{
INFO_PRINTF1(_L("fputs3"));
FILE *fp;
int wretval;
char rs1[10] = "abcd\nefg";
fp = fopen("C:\\input.txt","w");
fclose(fp);
fp = fopen("C:\\input.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = fputs(rs1,fp);
if(wretval == EOF)
{
INFO_PRINTF1(_L("fputs passed\n"));
fclose(fp);
return KErrNone;
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fputs4
API Tested : fputs
TestCase Description: The testcase function will write a string to a file which
has a null terminator in the middle of the string, the
file is closed after writing. Then the same file is
opened and the content is read out and compared.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fputs4()
{
INFO_PRINTF1(_L("fputs4"));
FILE *fp;
int wretval;
char rs1[10] = "abcd\0efg";
char *rptr, rs2[10];
int retval;
fp = fopen("c:\\fputs4.txt","w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = fputs(rs1,fp);
if(wretval == EOF)
{
INFO_PRINTF1(_L("fputs failed\n"));
fclose(fp);
return -1;
}
fclose(fp);
fp = fopen("C:\\fputs4.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
rptr = fgets(rs2,10,fp);
if(rptr == NULL)
{
INFO_PRINTF1(_L("fputs failed\n"));
}
retval = strcmp(rs1,rs2);
if(retval == 0)
{
INFO_PRINTF1(_L("fputs passed\n"));
}
else
{
INFO_PRINTF1(_L("fputs failed\n"));
}
fclose(fp);
unlink("C:\\fputs4.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::getc1
API Tested : getc
TestCase Description: The test function opens a file which has characters. It
reads all the characters in the file one by one till EOF
and writes the characters into log file.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::getc1()
{
INFO_PRINTF1(_L("getc1"));
FILE *fp;
int retval;
fp = fopen("C:\\input.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
retval = getc(fp);
while((int)(retval = getc(fp) )!= EOF)
{
INFO_PRINTF3(_L("%c\t%x\n"), retval, retval);
}
fclose(fp);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::putc1
API Tested : putc
TestCase Description: The testcase function writes one character on to a file
and closes the file. The same file is again opened and
a character is read from the file.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::putc1()
{
INFO_PRINTF1(_L("putc1"));
FILE *fp;
int rretval, wretval;
fp = fopen("c:\\putc1.txt","w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = putc('a',fp); //putc(char(0x0905), fp);
if(wretval == EOF)
{
INFO_PRINTF1(_L("putc failed\n"));
fclose(fp);
return -1;
}
fclose(fp);
fp = fopen("C:\\putc1.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
rretval = fgetc(fp);
if(wretval != rretval)
{
INFO_PRINTF1(_L("putc failed\n"));
}
else
{
INFO_PRINTF1(_L("putc passed\n"));
}
fclose(fp);
unlink("c:\\putc1.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::putc2
API Tested : putc
TestCase Description: The testcase function writes a set of characters on to a
file and closes the file. The same file is again opened
and characters are read from the file.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::putc2()
{
INFO_PRINTF1(_L("putc2"));
FILE *fp;
int wretval[10], rretval;
int alphabets[10] = {0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a};
int i;
fp = fopen("c:\\putc2.txt","w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
for(i=0;i<10;i++)
{
wretval[i] = putc((char) alphabets[i],fp);
if(wretval[i] == EOF)
{
INFO_PRINTF1(_L("putc failed\n"));
fclose(fp);
return -1;
}
}
fclose(fp);
fp = fopen("C:\\putc2.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
for(i=0;i<10;i++)
{
rretval = fgetc(fp);
if(rretval != wretval[i])
{
INFO_PRINTF1(_L("putc failed\n"));
fclose(fp);
return -1;
}
}
INFO_PRINTF1(_L("putc passed\n"));
fclose(fp);
unlink("c:\\putc2.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::putc3
API Tested : putc
TestCase Description: The testcase function writes a new line character on to a
file and closes the file. The same file is again opened
and the content is read from the file.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::putc3()
{
INFO_PRINTF1(_L("putc3"));
FILE *fp;
int rretval,wretval;
fp = fopen("c:\\putc3.txt","w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = putc('\n',fp);
if(wretval == EOF)
{
INFO_PRINTF1(_L("putc failed\n"));
fclose(fp);
return -1;
}
fclose(fp);
fp = fopen("C:\\putc3.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
rretval = fgetc(fp);
if(wretval != rretval)
{
INFO_PRINTF1(_L("putc failed\n"));
}
else
{
INFO_PRINTF1(_L("putc passed\n"));
}
fclose(fp);
unlink("c:\\putc3.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::putc4
API Tested : putc
TestCase Description: The testcase function tries writing a character on to a
file which is opened for reading only.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::putc4()
{
INFO_PRINTF1(_L("putc4"));
FILE *fp;
int wretval;
fp = fopen("C:\\input.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
wretval = putc('\n', fp);
if(wretval == EOF)
{
INFO_PRINTF1(_L("putc passed\n"));
fclose(fp);
return KErrNone;
}
INFO_PRINTF1(_L("putc failed\n"));
fclose(fp);
unlink("input.txt");
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::ungetc1
API Tested : ungetc
TestCase Description: The testcase function opens a file and writes few
characters into the file. Then the file is closed. Once
again the same file is opened and ungetc and getc API's
are called. The test case is verified by comparing the
characters written by ungetc and read by getc.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::ungetc1()
{
INFO_PRINTF1(_L("ungetc1"));
FILE *fp;
int err = -1;
int c;
fp = fopen("c:\\ungetc1.txt","w");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
fputs ("bla", fp);
INFO_PRINTF1(_L("fputs done\n"));
fclose (fp);
fp = fopen("c:\\ungetc1.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
if(ungetc ('z', fp) != 'z')
{
err = 1;
}
INFO_PRINTF2(_L("%d"), err);
INFO_PRINTF1(_L("ungetc done"));
if(getc (fp) != 'z')
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
if(getc (fp) != 'b')
err = 1;
INFO_PRINTF2(_L("%d"),err);
if(getc (fp) != 'l')
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
if(ungetc ('m', fp) != 'm')
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
INFO_PRINTF1(_L("ungetc done"));
if(getc (fp) != 'm')
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
if((c = getc (fp)) != 'a')
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
if(getc (fp) != EOF)
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
if(ungetc (c, fp) != c)
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
INFO_PRINTF1(_L("ungetc done"));
if(feof (fp) != 0)
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
if(getc (fp) != c)
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
if(getc (fp) != EOF)
{
err = 1;
}
INFO_PRINTF2(_L("%d"),err);
fclose (fp);
unlink("c:\\ungetc1.txt");
if(err == 1)
{
INFO_PRINTF1(_L("ungetc failed\n"));
}
else
{
INFO_PRINTF1(_L("ungetc passed\n"));
}
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fileno1
API Tested : fileno
TestCase Description: The function fileno examines the argument stream and returns its
integer descriptor.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fileno1()
{
INFO_PRINTF1(_L("fileno1"));
FILE *fp;
char *buf="C:\\fileno.txt";
int i;
fp = fopen(buf,"w");
i = fileno(fp);
if( i == -1)
{
INFO_PRINTF1(_L("fileno1 failed\n"));
}
else
{
INFO_PRINTF1(_L("fileno1 passed\n"));
}
fclose(fp);
unlink(buf);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::fileno2
API Tested : fileno
TestCase Description: Negative testcase. This testcase tries to call fileno on a
file stream which has been closed using a call to fclose()
-------------------------------------------------------------------------------
*/
TInt CTestStdio::fileno2()
{
INFO_PRINTF1(_L("fileno2"));
FILE *fp;
char *buf="C:\\fileno.txt";
int i;
fp = fopen(buf,"w");
fclose(fp);
i = fileno(fp);
if( i == -1 && errno == EBADF)
{
INFO_PRINTF1(_L("fileno2:closed stream Passed\n"));
}
else
{
INFO_PRINTF1(_L("fileno2:closed stream failed\n"));
}
fp = NULL;
i = fileno(fp);
if( i == -1 && errno == EBADF)
{
INFO_PRINTF1(_L("fileno2: Null stream Passed\n"));
}
else
{
INFO_PRINTF1(_L("fileno2: Null stream failed\n"));
}
unlink(buf);
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::getw1
API Tested : getw
TestCase Description: The test function opens a file write word and read it back
and compare it with written value.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::getw1()
{
INFO_PRINTF1(_L("getw"));
INFO_PRINTF1(_L("putw"));
FILE *fp;
int rretval;
int word = 94;
char name[20] = "c:\\fgetw1.txt";
fp = fopen(name,"wb");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
putw(word,fp);
if (ferror(fp))
{
INFO_PRINTF1(_L("Error writing to file\n"));
}
else
{
INFO_PRINTF1(_L("Successful write\n"));
}
fclose(fp);
/* reopen the file */
fp = fopen(name, "rb");
if (fp == NULL)
{
INFO_PRINTF2(_L("Error opening file %s\n"), name);
return -1;
}
/* extract the word */
rretval = getw(fp);
if (ferror(fp))
{
INFO_PRINTF1(_L("Error reading file\n"));
}
else
{
INFO_PRINTF2(_L("Successful read: word = %d\n"), word);
}
/* Clean up */
fclose(fp);
unlink(name);
if(rretval != word)
{
return -1;
}
else
{
return KErrNone;
}
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::putw1
API Tested : fgetc
TestCase Description: The test function opens a file write word and read it back
and compare it with written value.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::putw1()
{
INFO_PRINTF1(_L("putw"));
FILE *fp;
int rretval;
int word = 94;
char name[20] = "c:\\fputw1.txt";
fp = fopen(name,"wb");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
putw(word,fp);
if (ferror(fp))
{
INFO_PRINTF1(_L("Error writing to file\n"));
}
else
{
INFO_PRINTF1(_L("Successful write\n"));
}
fclose(fp);
/* reopen the file */
fp = fopen(name, "rb");
if (fp == NULL)
{
INFO_PRINTF2(_L("Error opening file %s\n"), name);
return -1;
}
/* extract the word */
rretval = getw(fp);
if (ferror(fp))
{
INFO_PRINTF1(_L("Error reading file\n"));
}
else
{
INFO_PRINTF2(_L("Successful read: word = %d\n"), word);
}
/* Clean up */
fclose(fp);
unlink(name);
if(rretval != word)
{
return -1;
}
else
{
return KErrNone;
}
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::getdirentries1
API Tested : getdirentries
TestCase Description: The function fileno examines the argument stream and returns its
integer descriptor.
-------------------------------------------------------------------------------
*/
TInt CTestStdio::getdirentries1()
{
INFO_PRINTF1(_L("getdirentries1"));
char buf[4096];
long dbase = (off_t) 0;
struct dirent *d1;
struct dirent *d2;
char * name1 = "dummy.txt";
char * name2 = "junk.txt";
int fd;
int len_getdir;
TInt len=0;
TPtrC string;
GetStringFromConfig(ConfigSection(),_L("parameter1"), string);
TBuf8<100> buf1;
buf1.Copy(string);
char* path1 = (char*) buf1.Ptr();
len=buf1.Length();
path1[len]='\0';
TFileName dirName(string);
RFs iTestSession;
iTestSession.Connect();
if(iTestSession.MkDir(dirName) != KErrNone)
{
INFO_PRINTF1(_L("create dir failed, directory may be already present\n"));
return -1;
}
INFO_PRINTF1(_L("create dir successfully\n"));
iTestSession.Close();
strcat(path1,"dummy.txt");
TInt fd1,fd2;
fd1=open(path1,O_WRONLY|O_CREAT|O_TRUNC);
if( fd1 == - 1)
{
INFO_PRINTF1(_L("open file 1 failed\n"));
return -1;
}
else
{
INFO_PRINTF1(_L("opened file 1\n"));
path1[len]='\0';
strcat(path1,"junk.txt");
fd2=open(path1,O_WRONLY|O_CREAT|O_TRUNC);
if( fd2 == -1 )
{
INFO_PRINTF1(_L("open file 2 failed\n"));
return -1;
}
close(fd1);
close(fd2);
path1[len-1]='\0';
INFO_PRINTF1(_L("both files opened successfully\n"));
}
fd = open(path1,O_RDONLY);
if(fd == -1)
{
INFO_PRINTF1(_L("open dir failed\n"));
return -1;
}
INFO_PRINTF1(_L("open dir successfully\n"));
len_getdir = getdirentries (fd, buf,(unsigned int)sizeof (buf),&dbase);
if(len_getdir == -1)
{
INFO_PRINTF1(_L("getdirentries call failed\n"));
return -1;
}
d1=(struct dirent *)buf;
d2 = (struct dirent *)(buf + d1->d_reclen);
if(strcmp(d1->d_name,name1) || strcmp(d2->d_name,name2))
{
close(fd);
path1[len -1] = '\\';
path1[len] = '\0';
strcat(path1,"junk.txt");
remove(path1);
path1[len] = '\0';
strcat(path1,"dummy.txt");
remove(path1);
path1[len] = '\0';
remove(path1);
INFO_PRINTF1(_L("Remove dir successful\n"));
INFO_PRINTF1(_L("strcmp failed on files\n"));
close(fd);
return -1;
}
close(fd);
path1[len -1] = '\\';
path1[len] = '\0';
strcat(path1,"junk.txt");
remove(path1);
path1[len] = '\0';
strcat(path1,"dummy.txt");
remove(path1);
path1[len] = '\0';
remove(path1);
INFO_PRINTF1(_L("Remove dir successful\n"));
INFO_PRINTF1(_L("getdirentries call successful\n"));
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Function Name : CTestStdio::getdirentries2
API Tested : getdirentries
TestCase Description: The function examines whether the file name(d_name) returned is null terminated or not
-------------------------------------------------------------------------------
*/
TInt CTestStdio::getdirentries2()
{
int retval;
long basep=(off_t) 0;
char buf[1024];
struct dirent * d;
char * dname="C:\\emp";
char * fname1="C:\\emp\\abc1.txt";
char * fname="C:\\emp\\def.txt";
int fd,fd1, fd2;
retval = mkdir(dname,0666);
if(retval)
{
INFO_PRINTF2(_L("failed to create directory and errno returned is %d"),errno);
return KErrGeneral;
}
fd2=open(fname1,O_WRONLY|O_CREAT);
fd1=open(fname,O_WRONLY|O_CREAT);
if(fd1==-1)
{
INFO_PRINTF2(_L("file creation failed and errno is %d\n"),errno);
return KErrGeneral;
}
fd=open(dname,O_RDONLY);
if(fd==-1)
{
INFO_PRINTF2(_L("directory opening failed and errno returned is %d\n"),errno);
return KErrGeneral;
}
retval = getdirentries (fd, buf,(unsigned int)sizeof (buf),&basep);
if(retval == -1)
{
INFO_PRINTF2(_L("getdirentries call failed and errno returned is %d\n"),errno);
return KErrGeneral;
}
INFO_PRINTF1(_L("getdirentries is success\n"));
d=(struct dirent *)buf;
TBuf<MAX_LEN> buffer;
TInt len = strlen(d->d_name);
for (TInt j =0; j<len;j++)
{
buffer.Append(d->d_name[j]);
}
INFO_PRINTF2(_L("first file name - %S\n"),&buffer);
retval = strcmp(d->d_name, "abc1.txt");
INFO_PRINTF2(_L("the length of the first record is %d\n"),d->d_reclen);
if(d->d_reclen!=20)
{
INFO_PRINTF1(_L("The length of the record is misleading\n"));
return KErrGeneral;
}
if(retval)
{
INFO_PRINTF1(_L("file name is not matching might be not null terminated\n"));
return KErrGeneral;
}
struct dirent* d2 = (struct dirent *)(buf + d->d_reclen);
INFO_PRINTF2(_L("the length of the second record is %d\n"),d2->d_reclen);
if(d2->d_reclen!=16)
{
INFO_PRINTF1(_L("The length of the record is misleading\n"));
return KErrGeneral;
}
buffer.Zero();
len = strlen(d2->d_name);
for (TInt j =0; j<len;j++)
{
buffer.Append(d2->d_name[j]);
}
INFO_PRINTF2(_L("second file name - %S\n"),&buffer);
retval = strcmp(d2->d_name, "def.txt");
if(retval)
{
INFO_PRINTF1(_L("file name is not matching might be not null terminated\n"));
return KErrGeneral;
}
INFO_PRINTF1(_L("file name is null terminated\n"));
close(fd2);
close(fd1);
close(fd);
retval = remove(fname1);
retval =remove(fname);
retval = rmdir(dname);
if(retval)
{
INFO_PRINTF2(_L("File or directory removal failed %d\n"), retval);
return KErrGeneral;
}
return KErrNone;
}
//-------------------------------------------------------------------------------
//Function Name : CTestStdio::freopen1
//API Tested : freopen
//Description : This api checks if stdout contents are redirected to the file
//-------------------------------------------------------------------------------
TInt CTestStdio::freopen1()
{
char filename[20] = "c:\\myfile.txt";
char string[] = "This redirects to a file\n";
char string1[30];
FILE *fp = freopen (filename,"w",stdout);
if(fp == NULL)
{
INFO_PRINTF1(_L("freopen failed\n"));
return -1;
}
int retval = printf ("%s", string);// sentence is redirected to a file.\n");
fclose (stdout);
FILE *fp1 = fopen(filename,"r");
if(fp1 == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
else
{
fgets(string1, retval+1, fp1);//fgets reads bytes from stream upto n-1 bytes or \n
}
fclose (fp1);
if(strcmp(string1, string)==0)
{
INFO_PRINTF1(_L("freopen successful\n"));
return KErrNone;
}
else
{
INFO_PRINTF1(_L("freopen failed\n"));
return KErrGeneral;
}
}
//-------------------------------------------------------------------------------
//Function Name : Testbinopen
//API Tested : open()
//Description : Given a path for a file, returns a file descriptor. Testing
// against defect number Team Track id : 111519
//--------------------------------------------------------------------------------
TInt CTestStdio::binaryopen()
{
int fd = -1;
int ret = 0;
fd = open("c:\\binaryfile.bd", O_RDWR|O_CREAT|O_BINARY);
if(fd != -1)
{
INFO_PRINTF1(_L("open() failed\n"));
return KErrGeneral;
}
ret = close(fd);
if(ret == -1)
{
INFO_PRINTF1(_L("close() failed\n"));
remove("c:\\binaryfile.bd");
return KErrGeneral;
}
//cleanup
remove("c:\\binaryfile.bd");
return KErrNone;
}
//---------------------------------------------------------------------------------
//Function Name : Testbinfopen
//API Tested : fopen(), fclose()
//Description : Given a path for a file, returns a file stream. Testing
// against defect number Team Track Id:111519
//---------------------------------------------------------------------------------
TInt CTestStdio::binaryfopen()
{
FILE *fs = NULL;
int ret = 0;
fs = fopen("c:\\binaryfile1.bd","wb+");
if(NULL == fs)
{
INFO_PRINTF1(_L("fopen() failed\n"));
return KErrGeneral;
}
ret = fclose(fs);
if(0 != ret)
{
INFO_PRINTF1(_L("fopen() failed\n"));
remove("c:\\binaryfile1.bd");
return KErrGeneral;
}
//Clean up
remove("c:\\binaryfile1.bd");
return KErrNone;
}
//---------------------------------------------------------------------------------
//Function Name : Testsprintf1
//API Tested : sprintf1
//Description : Its a manual test.Follow the steps given below to change the epoc environment
// 1) Goto control panel -> International
// 2) Select Tab " No " and change the decimal seperator to ','
// and run the test by uncommenting the TestStep in script file,
// against defect number Team Track Id:DEF111624
//---------------------------------------------------------------------------------
TInt CTestStdio::Testsprintf1()
{
float value = 0.100000f;
float value1 = 1234567.123000;
float value2 = 123.123000;
float value3 = 4.0;
char result[32];
char result1[32];
char result2[32];
char result3[32];
sprintf (result, "%f",value);
sprintf (result1, "%10.1f",value1);
sprintf (result2, "%f",value2);
sprintf (result3, "%10.1f",value3);
if(!(strcmp(result,"0.10000")))
{
INFO_PRINTF1(_L("sprintf failed\n"));
return KErrGeneral;
}
if(!(strcmp(result,"1234567.1")))
{
INFO_PRINTF1(_L("sprintf failed\n"));
return KErrGeneral;
}
if(!(strcmp(result,"123.123000")))
{
INFO_PRINTF1(_L("sprintf failed\n"));
return KErrGeneral;
}
if(!(strcmp(result," 4.0")))
{
INFO_PRINTF1(_L("sprintf failed\n"));
return KErrGeneral;
}
return KErrNone;
}
int getFirstMissingDrive(char& aChar)
{
RFs fs;
fs.Connect();
//obtain list of available drives
char ch = 'A';
TDriveList driveList8;
fs.DriveList(driveList8);
fs.Close();
for (TInt i = 0; i < KMaxDrives; ++i)
{
if (driveList8[i]==0)
{
aChar=ch;
return 0;
}
++ch;
}
return -1;
}
TInt CTestStdio::InvalidDriveTests29()
{
char file[12+1]; //rqd max is 12
char drive;
int ret;
SetTestStepResult(EPass);
if(getFirstMissingDrive(drive)==0)
{
struct stat sbuf;
struct utimbuf times;
int fd;
FILE* fptr;
sprintf(file, "%c:\\file.txt", drive);
fptr=fopen(file, "a");
if(fptr!=NULL || errno!=ENOENT)
{
INFO_PRINTF2(_L("fopen() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file\\", drive);
ret=mkdir(file, 0x777);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("mkdir() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file\\", drive);
ret=rmdir(file);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("rmdir() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=stat(file, &sbuf);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("stat() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file\\", drive);
ret=chdir(file);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("chdir() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=chmod(file, S_IRUSR|S_IRGRP|S_IROTH);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("chmod() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=utime(file, ×);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("utime() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
fd=open("c:\\invdr.txt", O_CREAT|O_WRONLY);
close(fd);
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=rename(file, "c:\\invdr.txt");
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("rename() -1 error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
ret=rename("c:\\invdr.txt", file);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("rename() -2 error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
ret=rename(file, file);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("rename() -3 error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file", drive);
ret=mkfifo(file, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("mkfifo() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=link("c:\\invdr.txt", file);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("link() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=unlink(file);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("unlink() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=creat(file, O_CREAT|O_WRONLY);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("creat() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
fptr=freopen(file, "a+", stdout);
if(fptr!=NULL || errno!=ENOENT)
{
INFO_PRINTF2(_L("freopen() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=access(file, F_OK);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("access() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=symlink("c:\\invdr.txt", file);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("symlink() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
memset(file, 0, 13);
sprintf(file, "%c:\\file.txt", drive);
ret=truncate(file, 128);
if(ret!=-1 || errno!=ENOENT)
{
INFO_PRINTF2(_L("truncate() error- Error no. %d..."), errno);
SetTestStepResult(EFail);
}
unlink("c:\\invdr.txt");
}
return TestStepResult();
}
//-------------------------------------------------------------------------------
//Function Name : Testgetchar
//API Tested : seteof
//Description : This api checks if End Of File has been reached
//-------------------------------------------------------------------------------
/*TInt CTestStdio::Testgetchar()
{
FILE *fp;
int retval;
fp = fopen("C:\\input.txt","r");
if(fp == NULL)
{
INFO_PRINTF1(_L("fopen failed\n"));
return -1;
}
retval = getchar();
while((int)(retval = getc(fp) )!= EOF)
{
INFO_PRINTF3(_L("%c\t%x\n"), retval, retval);
}
fclose(fp);
return 0;
}*/
//-------------------------------------------------------------------------------
//Function Name : Testferror
//API Tested : ferror
//Description: Tests if a error has occurred in the last file operation like
// reading and writing with the given stream
//-------------------------------------------------------------------------------
/*--------------------- END OF INPUT/OUTPUT OPERATIONS ----------------------*/
/**
*Testcase Name:wopenTest
*API Name :wopen()
*Description :It possibly create a file or device
* successful, wopen returns a non-negative integer, termed a file descriptor.
* It returns -1 on failure
*/
TInt CTestStdio::wopenTest()
{
int fd = wopen(L"c:\\wopen.txt" ,O_CREAT, 0666) ;
if(fd == -1 )
{
INFO_PRINTF1(_L("Failed to create and open file in current working directory \n") );
return KErrGeneral;
}
INFO_PRINTF1(_L("File created and opened in current working directory \n" ) );
return KErrNone;
}
/**
*TestCase Name :posix_spawnattr_destroyTest()
*API :posix_spawnattr_destroy
*Description :It destroy's a spawn attributes object.
*which can be reinitialized using posix_spawnattr_init();
*Upon successful completion it returns zero
*/
TInt CTestStdio::posix_spawnattr_destroyTest()
{
posix_spawnattr_t* attrp;
TInt err=posix_spawnattr_init(attrp=0);
if(err!=0)
{
INFO_PRINTF1(_L("posix_spawnattr_init failed..."));
}
err =posix_spawnattr_destroy(attrp);
if(err!= 0)
{
return KErrGeneral;
}
return KErrNone;
}
/**
*Testcase Name :setgroupsTest
*API :setgroups()
*Description :Sets the supplementary group IDs for the process.
*On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
*/
TInt CTestStdio::setgroupsTest()
{
TInt ret=setgroups(1,0);
if(ret<0)
{
return KErrGeneral;
}
return KErrNone;
}
/**
*Testcase Name :sigactionTest
*API :sigaction()
*Description : The sigaction system call is used to change the action for
* a signal.It returns return 0 on success and -1 on error.
*/
TInt CTestStdio::sigactionTest()
{
TInt ret = sigaction(SIGINT,NULL,NULL);
if(ret == -1)
{
return KErrGeneral;
}
else
{
return KErrNone;
}
}
/**
*Testcase Name:getpwentTest
*API :getpwent()
*Description :It return a valid pointer to a passwd structure on success or NULL
if the entry is not found or if an error occurs
*/
TInt CTestStdio::getpwentTest()
{
struct passwd* pw_ent=NULL;
setpwent();
pw_ent = getpwent();
if(pw_ent == NULL)
{
return KErrGeneral;
}
free(pw_ent->pw_dir);
free(pw_ent);
endpwent();
return KErrNone;
}
/**
*Test case Name :brkTest()
*API :brk()
*Description :The brk function is used to change the amount of memory allocated in a processís data segment
*Upon successful completion, brk() returns 0. Otherwise, it returns -1 and sets errno to indicate the error.
*/
TInt CTestStdio::brkTest()
{
TInt ret=brk(0);
if(ret == -1)
{
return KErrGeneral;
}
else
{
return KErrNone;
}
}
// End of File
| [
"none@none"
] | [
[
[
1,
3468
]
]
] |
0c27296dac582f6b1fc369680d0b4528061d3bfd | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/wave/cpplexer/convert_trigraphs.hpp | ba6a3fcc1a3cdd78687ce7cb28aee26fda010587 | [
"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 | 4,409 | hpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
Grammar for universal character validation (see C++ standard: Annex E)
http://www.boost.org/
Copyright (c) 2001-2007 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)
=============================================================================*/
#if !defined(CONVERT_TRIGRAPHS_HK050403_INCLUDED)
#define CONVERT_TRIGRAPHS_HK050403_INCLUDED
#include <boost/wave/wave_config.hpp>
#include <boost/wave/cpplexer/cpplexer_exceptions.hpp>
// this must occur after all of the includes and before any code appears
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_PREFIX
#endif
///////////////////////////////////////////////////////////////////////////////
namespace boost {
namespace wave {
namespace cpplexer {
namespace impl {
///////////////////////////////////////////////////////////////////////////////
//
// Test, whether the given string represents a valid trigraph sequence
//
///////////////////////////////////////////////////////////////////////////////
template <typename StringT>
inline bool
is_trigraph(StringT const& trigraph)
{
if (trigraph.size() < 3 || '?' != trigraph[0] || '?' != trigraph[1])
return false;
switch (trigraph[2]) {
case '\'': case '=': case '/': case '(':
case ')': case '<': case '>': case '!':
case '-':
break;
default:
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
// convert_trigraph
//
// The function convert_trigraph() converts a single trigraph character
// sequence into the corresponding character.
//
// If the given character sequence doesn't form a valid trigraph sequence
// no conversion is performed.
//
///////////////////////////////////////////////////////////////////////////////
template <typename StringT>
inline StringT
convert_trigraph(StringT const &trigraph)
{
StringT result (trigraph);
if (is_trigraph(trigraph)) {
switch (trigraph[2]) {
case '\'': result = "^"; break;
case '=': result = "#"; break;
case '/': result = "\\"; break;
case '(': result = "["; break;
case ')': result = "]"; break;
case '<': result = "{"; break;
case '>': result = "}"; break;
case '!': result = "|"; break;
case '-': result = "~"; break;
}
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
//
// convert_trigraphs
//
// The function convert_trigraph() converts all trigraphs in the given
// string into the corresponding characters.
//
// If one of the given character sequences doesn't form a valid trigraph
// sequence no conversion is performed.
//
///////////////////////////////////////////////////////////////////////////////
template <typename StringT>
inline StringT
convert_trigraphs(StringT const &value)
{
StringT result;
typename StringT::size_type pos = 0;
typename StringT::size_type pos1 = value.find_first_of ("?", 0);
if (StringT::npos != pos1) {
do {
result += value.substr(pos, pos1-pos);
StringT trigraph (value.substr(pos1));
if (is_trigraph(trigraph)) {
result += convert_trigraph(trigraph);
pos1 = value.find_first_of ("?", pos = pos1+3);
}
else {
result += value[pos1];
pos1 = value.find_first_of ("?", pos = pos1+1);
}
} while (StringT::npos != pos1);
result += value.substr(pos);
}
else {
result = value;
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
} // namespace impl
} // namespace cpplexer
} // namespace wave
} // namespace boost
// the suffix header occurs after all of the code
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_SUFFIX
#endif
#endif // !defined(CONVERT_TRIGRAPHS_HK050403_INCLUDED)
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
139
]
]
] |
78fec4cd3f610f157d2a958755c53bbceb7a0e4b | 188058ec6dbe8b1a74bf584ecfa7843be560d2e5 | /FLVCodec/MP4XPCIV3_config_helper.cpp | 53e1d086dc75f3ad72471e5ab39c2fd71384e4c2 | [] | no_license | mason105/red5cpp | 636e82c660942e2b39c4bfebc63175c8539f7df0 | fcf1152cb0a31560af397f24a46b8402e854536e | refs/heads/master | 2021-01-10T07:21:31.412996 | 2007-08-23T06:29:17 | 2007-08-23T06:29:17 | 36,223,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,994 | cpp | /******************************************************************************
*
* Copyright WIS Technologies (c) (2003)
* All Rights Reserved
*
*******************************************************************************
*
* FILE:
* config_helper.c
*
* DESCRIPTION:
*
*
*
* AUTHOR:
*
*
* <SOURCE CONTROL TAGS TBD>
*
******************************************************************************/
#include "stdafx.h"
#include "wisproxypci.h"
#include "MP4XPCIV3_config_error.h"
#include "MP4XPCIV3_config_helper.h"
///////////////////////////////////////////////////////////////////////////////
// confiuration helper
///////////////////////////////////////////////////////////////////////////////
unsigned char IsFlagsSet(unsigned long test_flags, unsigned long mandetory_flags)
{
if ( test_flags == 0 ) return 1; // we treat 0 as 0xFFFFFFFF
return ( ( (~(test_flags)) & (mandetory_flags) ) == 0 ) ? 1 : 0;
}
unsigned char IsCompatibleWithCurrentTVStandard(TV_STANDARD tv_standard, unsigned long standards_mask)
{
if ( tv_standard == TVStandard_None )
return standards_mask == TVStandard_None;
if ( standards_mask == TVStandard_None )
return tv_standard == TVStandard_None;
return IsFlagsSet(standards_mask, tv_standard);
}
long FindStreamConfiguration(_VIDEO_CAPABILITIES* caps, TCFGSTREAM* stream)
{
unsigned long index;
for ( index = 0 ; index < caps->_num_of_stream_configs ; index ++ )
{
TCFGSTREAM* stream_caps = caps->_stream_configs + index;
// compress mode must be same
if ( stream->compress_mode != stream_caps->compress_mode ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_MPEG4_MODE ) )
if ( stream->mpeg4_mode != stream_caps->mpeg4_mode ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_DVD_COMPLIANT ) )
if ( stream->DVD_compliant != stream_caps->DVD_compliant ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_SEQUENCE_MODE ) )
if ( stream->sequence != stream_caps->sequence ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_GOP_MODE ) )
if ( stream->gop_mode != stream_caps->gop_mode ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_GOP_SIZE ) )
if ( stream->gop_size != stream_caps->gop_size ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_DEINTERLACE_MODE ) )
if ( stream->deinterlace_mode != stream_caps->deinterlace_mode ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_SEARCH_RANGE ) )
if ( stream->search_range != stream_caps->search_range ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_GOPHEAD_ENABLE ) )
if ( stream->gop_head_enable != stream_caps->gop_head_enable ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_SEQHEAD_ENABLE ) )
if ( stream->seq_head_enable != stream_caps->seq_head_enable ) continue;
if ( IsFlagsSet( stream_caps->header.flags, FLAGS_STREAM_ASPECT_RATIO ) )
if ( stream->aspect_ratio != stream_caps->aspect_ratio ) continue;
// memcpy(stream->header.name, stream_caps->header.name, sizeof(stream->header.name));
// memcpy(stream->header.desc, stream_caps->header.desc, sizeof(stream->header.desc));
return index;
}
return -1;
}
long FindFrameRateConfiguration(_VIDEO_CAPABILITIES* caps, TCFGFRAMERATE* framerate)
{
unsigned long index;
for ( index = 0 ; index < caps->_num_of_framerate_configs ; index ++ )
{
TCFGFRAMERATE* framerate_caps = caps->_framerate_configs + index;
// frame rate and tv standard must be same
if ( framerate->frame_rate != framerate_caps->frame_rate ) continue;
if ( ! IsCompatibleWithCurrentTVStandard(framerate->tv_standard, framerate_caps->tv_standard) ) continue;
if ( IsFlagsSet( framerate_caps->header.flags, FLAGS_FRAMERATE_DROP_FRAME ) )
if ( framerate->drop_frame != framerate_caps->drop_frame ) continue;
if ( IsFlagsSet( framerate_caps->header.flags, FLAGS_FRAMERATE_IVTC_ENABLE ) )
if ( framerate->ivtc_enable != framerate_caps->ivtc_enable ) continue;
// memcpy(framerate->header.name, framerate_caps->header.name, sizeof(framerate->header.name));
// memcpy(framerate->header.desc, framerate_caps->header.desc, sizeof(framerate->header.desc));
return index;
}
return -1;
}
long FindResolutionConfiguration(_VIDEO_CAPABILITIES* caps, TCFGRESOLUTION* resolution)
{
unsigned long index;
for ( index = 0 ; index < caps->_num_of_resolution_configs ; index ++ )
{
TCFGRESOLUTION* resolution_caps = caps->_resolution_configs + index;
// width, height and tv standard must be same
if ( resolution->width != resolution_caps->width ) continue;
if ( resolution->height != resolution_caps->height ) continue;
if ( ! IsCompatibleWithCurrentTVStandard(resolution->tv_standard, resolution_caps->tv_standard) ) continue;
if ( IsFlagsSet( resolution_caps->header.flags, FLAGS_RESOLUTION_SCALE_OFFSET ) )
{
if ( resolution->h_sub_offset != resolution_caps->h_sub_offset ) continue;
if ( resolution->v_sub_offset != resolution_caps->v_sub_offset ) continue;
if ( resolution->h_scale_enb != resolution_caps->h_scale_enb ) continue;
if ( resolution->v_scale_enb != resolution_caps->v_scale_enb ) continue;
}
// memcpy(resolution->header.name, resolution_caps->header.name, sizeof(resolution->header.name));
// memcpy(resolution->header.desc, resolution_caps->header.desc, sizeof(resolution->header.desc));
resolution->max_bitrate = resolution_caps->max_bitrate;
resolution->min_bitrate = resolution_caps->min_bitrate;
return index;
}
return -1;
}
/*
long FindBitRateConfiguration(_VIDEO_CAPABILITIES* caps, TCFGBRCTRL* bitrate)
{
unsigned long index;
#define FLAGS_BITRATE_VBV_BUFFER 0x00000010
#define FLAGS_BITRATE_CONVERGE_SPEED 0x00000020
#define FLAGS_BITRATE_LAMBDA 0x00000040
#define FLAGS_BITRATE_IPBQ 0x00000100
for ( index = 0 ; index < caps->_num_of_bitrate_configs ; index ++ )
{
TCFGBRCTRL* bitrate_caps = caps->_bitrate_configs + index;
// target bitrate and Q must be same
if ( bitrate->target_bitrate != bitrate_caps->target_bitrate ) continue;
if ( bitrate->Q != bitrate_caps->Q ) continue;
if ( IsFlagsSet( bitrate_caps->header.flags, FLAGS_BITRATE_PEAK ) )
if ( bitrate->peak_bitrate != bitrate_caps->peak_bitrate ) continue;
if ( IsFlagsSet( bitrate_caps->header.flags, FLAGS_BITRATE_VBV_BUFFER ) )
if ( bitrate->vbv_buffer != bitrate_caps->vbv_buffer ) continue;
if ( IsFlagsSet( bitrate_caps->header.flags, FLAGS_BITRATE_CONVERGE_SPEED ) )
if ( bitrate->converge_speed != bitrate_caps->converge_speed ) continue;
if ( IsFlagsSet( bitrate_caps->header.flags, FLAGS_BITRATE_LAMBDA ) )
if ( bitrate->lambda != bitrate_caps->lambda ) continue;
if ( IsFlagsSet( bitrate_caps->header.flags, FLAGS_BITRATE_IPBQ ) )
{
if ( bitrate->IQ != bitrate_caps->IQ ) continue;
if ( bitrate->PQ != bitrate_caps->PQ ) continue;
if ( bitrate->BQ != bitrate_caps->BQ ) continue;
}
memcpy(bitrate->header.name, bitrate_caps->header.name, sizeof(bitrate->header.name));
memcpy(bitrate->header.desc, bitrate_caps->header.desc, sizeof(bitrate->header.desc));
return index;
}
return -1;
}
*/
enum CONFIG_ERROR Config_IsAllowedByAssociations(
_VIDEO_CAPABILITIES* caps,
TCFGASSOCIATION* assc)
{
unsigned long index;
for ( index = 0 ; index < caps->_num_of_associations ; index ++ )
{
TCFGASSOCIATION* association = caps->_associations + index;
if ( association->_master_type != assc->_master_type ) continue;
if ( association->_slave_type != assc->_slave_type ) continue;
if ( association->_master_id != assc->_master_id && association->_master_id != ASSOCIATION_ALL ) continue;
if ( association->_slave_id != assc->_slave_id && association->_slave_id != ASSOCIATION_ALL ) continue;
return ( association->_associate_type == ASSOCIATION_TYPE_ALLOW ) ? ERROR_NONE : ERROR_OTHERS;
}
///////////////////////////////////////////////////////////////////////////////////////
// by default we allow this association
///////////////////////////////////////////////////////////////////////////////////////
return ERROR_NONE;
}
/*
enum CONFIG_ERROR Config_EnumVideoConfigurations(_VIDEO_CAPABILITIES* caps, unsigned long system, unsigned long stream)
{
unsigned long res_index, fps_index;
TCFGASSOCIATION association;
caps->_num_of_configurations = 0;
if ( caps->_configurations != NULL ) FREE_MEM(caps->_configurations);
caps->_configurations = ALLOC_MEM( caps->_num_of_bitrate_configs * caps->_num_of_framerate_configs * caps->_num_of_resolution_configs * sizeof(TVCFG_ENTRY) );
if ( caps->_configurations == NULL ) return ERROR_OUT_OF_MEMORY;
///////////////////////////////////////////////////////////////////////////////////////
// for each possible configuration combinations, prescreen invalid configurations:
// 1 check the associations to check sanity
// 2 check the tv standards to prevent incompatible framerate and resolution configurations
// 3 check the bitrate range to prevent incompatible bitrate configurations
///////////////////////////////////////////////////////////////////////////////////////
for ( fps_index = 0 ; fps_index < caps->_num_of_framerate_configs ; fps_index ++ )
{
if ( caps->_framerate_configs[fps_index].tv_standard != caps->_system_configs[system].tv_standard ) continue;
for ( res_index = 0 ; res_index < caps->_num_of_resolution_configs ; res_index ++ )
{
if ( caps->_resolution_configs[res_index].tv_standard != caps->_system_configs[system].tv_standard ) continue;
///////////////////////////////////////////////////////////////////////////////////////
// is the combination allowed by our association? :
// system <-> stream <-> fps_index <-> res_index <-> brc_index
///////////////////////////////////////////////////////////////////////////////////////
association._master_type = TYPE_STREAM_CONFIG;
association._master_id = stream;
association._slave_type = TYPE_FRAMERATE_CONFIG;
association._slave_id = fps_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
association._master_type = TYPE_STREAM_CONFIG;
association._master_id = stream;
association._slave_type = TYPE_RESOLUTION_CONFIG;
association._slave_id = res_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
association._master_type = TYPE_FRAMERATE_CONFIG;
association._master_id = fps_index;
association._slave_type = TYPE_RESOLUTION_CONFIG;
association._slave_id = res_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
PrintMsg(DEBUG_CONFIGURATION|DEBUG_INFO_LEVEL, ("valid configuration: system %d, stream %d, framerate %d, resolution %d !!!",
system, stream, fps_index, res_index));
caps->_configurations[caps->_num_of_configurations].framerate_index = fps_index;
caps->_configurations[caps->_num_of_configurations].resolution_index = res_index;
caps->_configurations[caps->_num_of_configurations].bitrate_index = -1;
caps->_num_of_configurations ++;
}
}
if ( caps->_num_of_configurations <= 0 ) // there is no valid configurations
return ERROR_CONFIG_VIDEO_CAPABILITY;
PrintMsg(DEBUG_CONFIGURATION|DEBUG_INFO_LEVEL, ("total valid configuration: %d", caps->_num_of_configurations));
return ERROR_NONE;
}
enum CONFIG_ERROR Config_EnumVideoConfigurationsEx(_VIDEO_CAPABILITIES* caps, unsigned long system, unsigned long stream)
{
unsigned long brc_index, res_index, fps_index;
TCFGASSOCIATION association;
caps->_num_of_configurations = 0;
if ( caps->_configurations != NULL ) FREE_MEM(caps->_configurations);
caps->_configurations = ALLOC_MEM( caps->_num_of_bitrate_configs * caps->_num_of_framerate_configs * caps->_num_of_resolution_configs * sizeof(TVCFG_ENTRY) );
if ( caps->_configurations == NULL ) return ERROR_OUT_OF_MEMORY;
///////////////////////////////////////////////////////////////////////////////////////
// for each possible configuration combinations, prescreen invalid configurations:
// 1 check the associations to check sanity
// 2 check the tv standards to prevent incompatible framerate and resolution configurations
// 3 check the bitrate range to prevent incompatible bitrate configurations
///////////////////////////////////////////////////////////////////////////////////////
for ( fps_index = 0 ; fps_index < caps->_num_of_framerate_configs ; fps_index ++ )
{
if ( caps->_framerate_configs[fps_index].tv_standard != caps->_system_configs[system].tv_standard ) continue;
for ( res_index = 0 ; res_index < caps->_num_of_resolution_configs ; res_index ++ )
{
if ( caps->_resolution_configs[res_index].tv_standard != caps->_system_configs[system].tv_standard ) continue;
for ( brc_index = 0 ; brc_index < caps->_num_of_bitrate_configs ; brc_index ++ )
{
if ( ( caps->_bitrate_configs[brc_index].target_bitrate != 0 ) &&
( caps->_bitrate_configs[brc_index].target_bitrate > caps->_resolution_configs[res_index].max_bitrate
|| caps->_bitrate_configs[brc_index].target_bitrate < caps->_resolution_configs[res_index].min_bitrate ) )
continue;
///////////////////////////////////////////////////////////////////////////////////////
// is the combination allowed by our association? :
// system <-> stream <-> fps_index <-> res_index <-> brc_index
///////////////////////////////////////////////////////////////////////////////////////
association._master_type = TYPE_STREAM_CONFIG;
association._master_id = stream;
association._slave_type = TYPE_FRAMERATE_CONFIG;
association._slave_id = fps_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
association._master_type = TYPE_STREAM_CONFIG;
association._master_id = stream;
association._slave_type = TYPE_RESOLUTION_CONFIG;
association._slave_id = res_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
association._master_type = TYPE_STREAM_CONFIG;
association._master_id = stream;
association._slave_type = TYPE_BITRATE_CONFIG;
association._slave_id = brc_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
association._master_type = TYPE_FRAMERATE_CONFIG;
association._master_id = fps_index;
association._slave_type = TYPE_RESOLUTION_CONFIG;
association._slave_id = res_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
association._master_type = TYPE_FRAMERATE_CONFIG;
association._master_id = fps_index;
association._slave_type = TYPE_BITRATE_CONFIG;
association._slave_id = brc_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
association._master_type = TYPE_RESOLUTION_CONFIG;
association._master_id = res_index;
association._slave_type = TYPE_BITRATE_CONFIG;
association._slave_id = brc_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
PrintMsg(DEBUG_CONFIGURATION|DEBUG_INFO_LEVEL, ("valid configuration: system %d, stream %d, framerate %d, resolution %d, bitrate %d !!!",
system, stream, fps_index, res_index, brc_index));
caps->_configurations[caps->_num_of_configurations].framerate_index = fps_index;
caps->_configurations[caps->_num_of_configurations].resolution_index = res_index;
caps->_configurations[caps->_num_of_configurations].bitrate_index = brc_index;
caps->_num_of_configurations ++;
}
}
}
if ( caps->_num_of_configurations <= 0 ) // there is no valid configurations
return ERROR_CONFIG_VIDEO_CAPABILITY;
PrintMsg(DEBUG_CONFIGURATION|DEBUG_INFO_LEVEL, ("total valid configuration: %d", caps->_num_of_configurations));
return ERROR_NONE;
}
*/
enum CONFIG_ERROR Config_EnumVideoConfigurationsExx(_VIDEO_CAPABILITIES* caps, unsigned long system, TV_STANDARD current_tv_standard)
{
unsigned long str_index, res_index, fps_index;
TCFGASSOCIATION association;
caps->_num_of_configurations = 0;
if ( caps->_configurations != NULL ) FREE_MEM(caps->_configurations);
caps->_configurations = (TVCFG_ENTRY*)ALLOC_MEM( caps->_num_of_stream_configs *
caps->_num_of_framerate_configs *
caps->_num_of_resolution_configs *
sizeof(TVCFG_ENTRY) );
if ( caps->_configurations == NULL ) return ERROR_OUT_OF_MEMORY;
///////////////////////////////////////////////////////////////////////////////////////
// for each possible configuration combinations, prescreen invalid configurations:
// 1 check the associations to check sanity
// 2 check the tv standards to prevent incompatible framerate and resolution configurations
// 3 check the bitrate range to prevent incompatible bitrate configurations
///////////////////////////////////////////////////////////////////////////////////////
for ( str_index = 0 ; str_index < caps->_num_of_stream_configs ; str_index ++ )
{
for ( fps_index = 0 ; fps_index < caps->_num_of_framerate_configs ; fps_index ++ )
{
if ( IsCompatibleWithCurrentTVStandard(current_tv_standard, caps->_framerate_configs[fps_index].tv_standard) == 0 ) continue;
// if ( ( caps->_framerate_configs[fps_index].tv_standard & caps->_system_configs[system].tv_standard ) == 0 ) continue;
for ( res_index = 0 ; res_index < caps->_num_of_resolution_configs ; res_index ++ )
{
if ( IsCompatibleWithCurrentTVStandard(current_tv_standard, caps->_resolution_configs[res_index].tv_standard) == 0 ) continue;
// if ( ( caps->_resolution_configs[res_index].tv_standard & caps->_system_configs[system].tv_standard ) == 0 ) continue;
///////////////////////////////////////////////////////////////////////////////////////
// is the combination allowed by our association? :
// system <-> stream <-> fps_index <-> res_index <-> brc_index
///////////////////////////////////////////////////////////////////////////////////////
association._master_type = TYPE_STREAM_CONFIG;
association._master_id = str_index;
association._slave_type = TYPE_FRAMERATE_CONFIG;
association._slave_id = fps_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
association._master_type = TYPE_STREAM_CONFIG;
association._master_id = str_index;
association._slave_type = TYPE_RESOLUTION_CONFIG;
association._slave_id = res_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
association._master_type = TYPE_FRAMERATE_CONFIG;
association._master_id = fps_index;
association._slave_type = TYPE_RESOLUTION_CONFIG;
association._slave_id = res_index;
if ( Config_IsAllowedByAssociations(caps, &association ) != ERROR_NONE ) continue;
#ifdef DRIVER
// PrintMsg(DEBUG_CONFIGURATION|DEBUG_INFO_LEVEL, ("valid configuration ex: system %d, stream %d, framerate %d, resolution %d!!!",
// system, str_index, fps_index, res_index));
#endif
caps->_configurations[caps->_num_of_configurations].stream_index = str_index;
caps->_configurations[caps->_num_of_configurations].framerate_index = fps_index;
caps->_configurations[caps->_num_of_configurations].resolution_index = res_index;
caps->_num_of_configurations ++;
}
}
}
if ( caps->_num_of_configurations <= 0 ) // there is no valid configurations
return ERROR_CONFIG_VIDEO_CAPABILITY;
// PrintMsg(DEBUG_CONFIGURATION|DEBUG_INFO_LEVEL, ("total valid configuration: %d", caps->_num_of_configurations));
return ERROR_NONE;
}
int INVERSE32(int x)
{
UINT8 *code = (UINT8*)&x, r[4];
r[3] = code[0]; r[2] = code[1]; r[1] = code[2]; r[0] = code[3];
return *((int*)r);
}
unsigned long FormatGOStreamSEQHeader(TCFG_FORMAT_EXTENSION* extension,
char** ppSeqHeader)
{
#define MAX_GO_SEQ_HEADER_LEN 200
static char go_seqheader[MAX_GO_SEQ_HEADER_LEN];
unsigned long go_seqheader_length = 0;
*((unsigned long*)(go_seqheader + 0)) = 0xF1010000;
// char interlace; // 0 for progressive or 1 for interlace orignal input or 2 for interlace source and interlacing coding
*((char *)(go_seqheader + 4)) = 1;// (pcfg->syscfg.sensor_pformat == UYVYI ? (pcfg->strcfg.interlace_coding == 1 ? 2 : 1) : 0);
// char mode; // 'MultiMedia.H': EVideoFormat
*((char *)(go_seqheader + 5)) = extension->_stream.compress_mode;
// char seq; // see ESequenceMode
*((char *)(go_seqheader + 6)) = extension->_stream.sequence;
// int cols; // count of macroblocks in horizontal
*((int*)(go_seqheader + 7)) = INVERSE32(extension->_resolution.width >> 4);
// int rows; // count of macroblocks in vertical
*((int*)(go_seqheader + 11)) = INVERSE32(extension->_resolution.height >> 4);
// REAL64 fps; // frame rate of current stream
*((int*)(go_seqheader + 15)) = INVERSE32(extension->_bitrate.target_bitrate);
// char uvmode; // see EVideoFormat (for uv motion vectors)
*((char *)(go_seqheader + 19)) = extension->_stream.compress_mode - GO;
// char dqmode; // see EVideoFormat (for DCTQ mismatch control)
// GO (0x40) indicates no iQ-mismatch-control and use JDCT
*((char *)(go_seqheader + 20)) = GO;
// char fpmode; // see EFractionLevel
// by default we only use FLHALF
*((char *)(go_seqheader + 21)) = 1;
// char acpred; // If do AC prediction in intra macro-block
*((char *)(go_seqheader + 22)) = 0;
// char userq; // if use user customized quantization table(1: Yes, 0: No)
*((char *)(go_seqheader + 23)) = 0;
go_seqheader_length = 24;
*ppSeqHeader = go_seqheader;
return go_seqheader_length;
}
unsigned long FormatMPEG1StreamSEQHeader(TCFG_FORMAT_EXTENSION* extension,
char** ppSeqHeader)
{
#define MAX_MPEG1_SEQ_HEADER_LEN 200
static char mpeg1_seqheader[MAX_MPEG1_SEQ_HEADER_LEN];
static unsigned long ratetab[8] = { 24000, 24024, 25025, 30000, 30030, 50050, 60000, 60060 };
int j, frame_rate_code, aspect_ratio_code;
unsigned long mpeg1_seqheader_length = 12;
for ( j = 0 ; j < 8 ; j ++ )
if(ratetab[j] == extension->_framerate.frame_rate ) break;
frame_rate_code = ( j == 8 ) ? 4 : j + 1;
aspect_ratio_code = extension->_stream.DVD_compliant ? extension->_stream.aspect_ratio : 2;
mpeg1_seqheader[0] = 0;
mpeg1_seqheader[1] = 0;
mpeg1_seqheader[2] = 1;
mpeg1_seqheader[3] = (char)0xB3;
mpeg1_seqheader[4] = (char)( extension->_resolution.width >> 4);
mpeg1_seqheader[5] = (char)( ( ( extension->_resolution.width << 4 ) & 0xF0 ) + ( ( extension->_resolution.height >> 8 ) & 0x0F ) );
mpeg1_seqheader[6] = (char)( extension->_resolution.height & 0xFF);
mpeg1_seqheader[7] = (char)( (aspect_ratio_code << 4 ) + frame_rate_code);
mpeg1_seqheader[8] = (char)0xFF;
mpeg1_seqheader[9] = (char)0xFF;
mpeg1_seqheader[10] = (char)0xF2;
mpeg1_seqheader[11] = (char)0xA8;
*ppSeqHeader = mpeg1_seqheader;
return mpeg1_seqheader_length;
}
unsigned long FormatMPEG2StreamSEQHeader(TCFG_FORMAT_EXTENSION* extension,
char** ppSeqHeader)
{
#define MAX_MPEG2_SEQ_HEADER_LEN 200
static char mpeg2_seqheader[MAX_MPEG2_SEQ_HEADER_LEN];
static unsigned long ratetab[8] = { 24000, 24024, 25025, 30000, 30030, 50050, 60000, 60060 };
int j, frame_rate_code, aspect_ratio_code, interlace_coding;
unsigned long mpeg2_seqheader_length = 22;
for ( j = 0 ; j < 8 ; j ++ )
if(ratetab[j] == extension->_framerate.frame_rate) break;
frame_rate_code = ( j == 8 ) ? 4 : j + 1;
aspect_ratio_code = extension->_stream.DVD_compliant ? extension->_stream.aspect_ratio : 2;
interlace_coding = extension->_stream.deinterlace_mode == 2;
mpeg2_seqheader[0] = 0;
mpeg2_seqheader[1] = 0;
mpeg2_seqheader[2] = 1;
mpeg2_seqheader[3] = (char)0xB3;
mpeg2_seqheader[4] = (char)( extension->_resolution.width >> 4);
mpeg2_seqheader[5] = (char)( ( ( extension->_resolution.width << 4 ) & 0xF0 ) + ( ( extension->_resolution.height >> 8 ) & 0x0F ) );
mpeg2_seqheader[6] = (char)( extension->_resolution.height & 0xFF);
mpeg2_seqheader[7] = (char)( (aspect_ratio_code << 4 ) + frame_rate_code);
mpeg2_seqheader[8] = (char)0x17; // variable bit rate value (9.8MB/s) + 1 bit marker
mpeg2_seqheader[9] = (char)0xED;
mpeg2_seqheader[10] = (char)((1 << 5) + ((112 & 0x03E0) >> 5));
mpeg2_seqheader[11] = (char)(((112 & 0x1F) << 3) + // vbv_buffer_size_value 112
(0 << 2) + // constrained_parameters_flag
(0 << 1) + // load_intra_quantizer_matrix
0); // load_inter_quantizer_matrix;
mpeg2_seqheader[12] = (char)0x0;
mpeg2_seqheader[13] = (char)0x0;
mpeg2_seqheader[14] = (char)0x1;
mpeg2_seqheader[15] = (char)0xB5;
mpeg2_seqheader[16] = (char)0x14;
mpeg2_seqheader[17] = (UINT8) (8 << 4) + // level indication
(extension->_stream.DVD_compliant? 0:((UINT8) ((1 - interlace_coding) << 3))) + // progressive/interlace sequence
(UINT8) (1 << 1); // chroma_format
mpeg2_seqheader[18] = (char)0x0;
mpeg2_seqheader[19] = (char)0x1;
mpeg2_seqheader[20] = (char)0x0;
mpeg2_seqheader[21] = (char)0x0;
*ppSeqHeader = mpeg2_seqheader;
return mpeg2_seqheader_length;
}
unsigned long FormatMPEG4StreamSEQHeader(TCFG_FORMAT_EXTENSION* extension,
char** ppSeqHeader)
{
#define MAX_MPEG4_SEQ_HEADER_LEN 200
static char mpeg4_seqheader[MAX_MPEG4_SEQ_HEADER_LEN];
unsigned long mpeg4_seqheader_length = 18;
mpeg4_seqheader[0] = (char)0x0;
mpeg4_seqheader[1] = (char)0x0;
mpeg4_seqheader[2] = (char)0x1;
mpeg4_seqheader[3] = (char)0x0;
mpeg4_seqheader[4] = (char)0x0;
mpeg4_seqheader[5] = (char)0x0;
mpeg4_seqheader[6] = (char)0x1;
mpeg4_seqheader[7] = (char)0x20;
mpeg4_seqheader[8] = (char)0x0;
mpeg4_seqheader[9] = (char)0x84;
mpeg4_seqheader[10] = (char)0x5D;
mpeg4_seqheader[11] = (char)0x4C;
mpeg4_seqheader[12] = (char)(0x28 + ( ( extension->_resolution.width >> 10 ) & 0x7 ));
mpeg4_seqheader[13] = (char)(extension->_resolution.width >> 2);
mpeg4_seqheader[14] = (char)(0x20 + ( ( extension->_resolution.height >> 8 ) & 0x1F ));
mpeg4_seqheader[15] = (char)(extension->_resolution.height & 0xFF);
mpeg4_seqheader[16] = (char)0xA3;
mpeg4_seqheader[17] = (char)0x1F;
*ppSeqHeader = mpeg4_seqheader;
return mpeg4_seqheader_length;
}
/****************************** end of config_helper.c ***********************/
| [
"soaris@46205fef-a337-0410-8429-7db05d171fc8"
] | [
[
[
1,
637
]
]
] |
fe37df21f340f425b105a51f7f9415eea57bfb10 | 57574cc7192ea8564bd630dbc2a1f1c4806e4e69 | /Poker/Cliente/ImagenRecortada.cpp | e721ee0ce69fc837ad8b481a64a46b37babf8ac5 | [] | no_license | natlehmann/taller-2010-2c-poker | 3c6821faacccd5afa526b36026b2b153a2e471f9 | d07384873b3705d1cd37448a65b04b4105060f19 | refs/heads/master | 2016-09-05T23:43:54.272182 | 2010-11-17T11:48:00 | 2010-11-17T11:48:00 | 32,321,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,610 | cpp | #include "ImagenRecortada.h"
#include "ServiciosGraficos.h"
ImagenRecortada::ImagenRecortada(int ancho, int alto){
this->setAncho(ancho);
this->setAlto(alto);
this->colorMascara = NULL;
}
ImagenRecortada::~ImagenRecortada(void){
if (this->colorMascara != NULL) {
delete (this->colorMascara);
}
this->superficie = NULL;
}
Color* ImagenRecortada::getColorMascara() {
if (this->colorMascara == NULL) {
this->colorMascara = new Color(0,255,0);
}
return this->colorMascara;
}
void ImagenRecortada::setColorMascara(Uint8 red, Uint8 green, Uint8 blue){
this->getColorMascara()->setRed(red);
this->getColorMascara()->setGreen(green);
this->getColorMascara()->setBlue(blue);
this->hayCambios = true;
}
void ImagenRecortada::setColorMascara(Color colorMascara){
this->getColorMascara()->setRed(colorMascara.getRed());
this->getColorMascara()->setGreen(colorMascara.getGreen());
this->getColorMascara()->setBlue(colorMascara.getBlue());
this->hayCambios = true;
}
SDL_Surface* ImagenRecortada::getSuperficie(){
if (this->superficie == NULL) {
this->superficie = ServiciosGraficos::crearSuperficie(
this->getAncho(), this->getAlto());
SDL_FillRect(this->superficie, NULL,
this->getColorMascara()->toUint32(this->superficie));
}
return this->superficie;
}
void ImagenRecortada::dibujarSobreSup(SDL_Surface* superficie) {
if (this->superficie != NULL) {
ServiciosGraficos::merge(this->getSuperficie(), superficie, this->getOffsetRect(),
this->getColorMascara()->toUint32(this->getSuperficie()));
}
}
| [
"[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296"
] | [
[
[
1,
63
]
]
] |
61a68a77f16ecb1bb4f67a54aa602a68ddeac65d | f6a8ffe1612a9a39fc1daa4e7849cad56ec351f0 | /PaintingThreads/PaintingThreads/Form1.h | d100481374604ad9c9bdcafc4d5057f3e1fb0066 | [] | no_license | comebackfly/c-plusplus-programming | 03e097ec5b85a4bf1d8fdd47041a82d7b6ca0753 | d9b2fb3caa60459fe459cacc5347ccc533b4b1ec | refs/heads/master | 2021-01-01T18:12:09.667814 | 2011-07-18T22:30:31 | 2011-07-18T22:30:31 | 35,753,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,459 | h | #pragma once
#include "ImageObject.h"
#include "PaintThread.h"
#include "ImageLoader.h"
#include "HTWStringConverter.h"
//#include "graphlibHTW.h"
#include <windows.h>
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "User32.lib")
#include <WinDef.h>
#include <iostream>
#include <string>
namespace PaintingThreads {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Runtime::InteropServices;
using namespace System;
using namespace System::Threading;
/// <summary>
/// Summary for Form1
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
Thread^ paintingThr;
Thread^ pauseThr;
static int nameId = 0;
ImageObject* backgroundImage;
ImageObject* final;
PaintThread^ paintThread;
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::GroupBox^ grpCtrl;
protected:
private: System::Windows::Forms::Button^ btnStartPainting;
private: System::Windows::Forms::GroupBox^ grpPaintOptions;
private: System::Windows::Forms::TrackBar^ trbThreads;
private: System::Windows::Forms::TextBox^ txtLoops;
private: System::Windows::Forms::Label^ lblLoops;
private: System::Windows::Forms::TextBox^ txtThreads;
private: System::Windows::Forms::Label^ lblThreads;
private: System::Windows::Forms::TrackBar^ trbLoops;
private: System::Windows::Forms::Button^ btnLoadImage;
private: System::Windows::Forms::PictureBox^ pictureBox;
private: System::Windows::Forms::Button^ btnPause;
private: System::Windows::Forms::OpenFileDialog^ openFile1;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->grpCtrl = (gcnew System::Windows::Forms::GroupBox());
this->btnPause = (gcnew System::Windows::Forms::Button());
this->btnStartPainting = (gcnew System::Windows::Forms::Button());
this->grpPaintOptions = (gcnew System::Windows::Forms::GroupBox());
this->trbThreads = (gcnew System::Windows::Forms::TrackBar());
this->txtLoops = (gcnew System::Windows::Forms::TextBox());
this->lblLoops = (gcnew System::Windows::Forms::Label());
this->txtThreads = (gcnew System::Windows::Forms::TextBox());
this->lblThreads = (gcnew System::Windows::Forms::Label());
this->trbLoops = (gcnew System::Windows::Forms::TrackBar());
this->btnLoadImage = (gcnew System::Windows::Forms::Button());
this->pictureBox = (gcnew System::Windows::Forms::PictureBox());
this->openFile1 = (gcnew System::Windows::Forms::OpenFileDialog());
this->grpCtrl->SuspendLayout();
this->grpPaintOptions->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trbThreads))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trbLoops))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox))->BeginInit();
this->SuspendLayout();
//
// grpCtrl
//
this->grpCtrl->BackColor = System::Drawing::Color::Transparent;
this->grpCtrl->Controls->Add(this->btnStartPainting);
this->grpCtrl->Controls->Add(this->grpPaintOptions);
this->grpCtrl->Controls->Add(this->btnLoadImage);
this->grpCtrl->Location = System::Drawing::Point(12, 12);
this->grpCtrl->Name = L"grpCtrl";
this->grpCtrl->Size = System::Drawing::Size(144, 265);
this->grpCtrl->TabIndex = 0;
this->grpCtrl->TabStop = false;
this->grpCtrl->Text = L"control";
//
// btnPause
//
this->btnPause->Enabled = false;
this->btnPause->Location = System::Drawing::Point(52, 283);
this->btnPause->Name = L"btnPause";
this->btnPause->Size = System::Drawing::Size(63, 23);
this->btnPause->TabIndex = 9;
this->btnPause->Text = L"snapShot";
this->btnPause->UseVisualStyleBackColor = true;
this->btnPause->Click += gcnew System::EventHandler(this, &Form1::btnPause_Click);
//
// btnStartPainting
//
this->btnStartPainting->Enabled = false;
this->btnStartPainting->Location = System::Drawing::Point(31, 231);
this->btnStartPainting->Name = L"btnStartPainting";
this->btnStartPainting->Size = System::Drawing::Size(81, 23);
this->btnStartPainting->TabIndex = 8;
this->btnStartPainting->Text = L"start painting";
this->btnStartPainting->UseVisualStyleBackColor = true;
this->btnStartPainting->Click += gcnew System::EventHandler(this, &Form1::btnStartPainting_Click);
//
// grpPaintOptions
//
this->grpPaintOptions->Controls->Add(this->trbThreads);
this->grpPaintOptions->Controls->Add(this->txtLoops);
this->grpPaintOptions->Controls->Add(this->lblLoops);
this->grpPaintOptions->Controls->Add(this->txtThreads);
this->grpPaintOptions->Controls->Add(this->lblThreads);
this->grpPaintOptions->Controls->Add(this->trbLoops);
this->grpPaintOptions->Location = System::Drawing::Point(6, 70);
this->grpPaintOptions->Name = L"grpPaintOptions";
this->grpPaintOptions->Size = System::Drawing::Size(132, 155);
this->grpPaintOptions->TabIndex = 7;
this->grpPaintOptions->TabStop = false;
this->grpPaintOptions->Text = L"Paint options";
//
// trbThreads
//
this->trbThreads->Location = System::Drawing::Point(10, 40);
this->trbThreads->Maximum = 100;
this->trbThreads->Minimum = 1;
this->trbThreads->Name = L"trbThreads";
this->trbThreads->Size = System::Drawing::Size(75, 45);
this->trbThreads->TabIndex = 1;
this->trbThreads->Value = 1;
this->trbThreads->Scroll += gcnew System::EventHandler(this, &Form1::trbThreads_Scroll);
//
// txtLoops
//
this->txtLoops->Location = System::Drawing::Point(91, 104);
this->txtLoops->MaxLength = 4;
this->txtLoops->Name = L"txtLoops";
this->txtLoops->Size = System::Drawing::Size(34, 20);
this->txtLoops->TabIndex = 4;
this->txtLoops->Text = L"100";
this->txtLoops->TextChanged += gcnew System::EventHandler(this, &Form1::txtLoops_TextChanged);
//
// lblLoops
//
this->lblLoops->AutoSize = true;
this->lblLoops->Location = System::Drawing::Point(12, 88);
this->lblLoops->Name = L"lblLoops";
this->lblLoops->Size = System::Drawing::Size(39, 13);
this->lblLoops->TabIndex = 6;
this->lblLoops->Text = L"Loops:";
//
// txtThreads
//
this->txtThreads->Location = System::Drawing::Point(91, 40);
this->txtThreads->MaxLength = 2;
this->txtThreads->Name = L"txtThreads";
this->txtThreads->Size = System::Drawing::Size(34, 20);
this->txtThreads->TabIndex = 3;
this->txtThreads->Text = L"1";
this->txtThreads->TextChanged += gcnew System::EventHandler(this, &Form1::txtThreads_TextChanged);
//
// lblThreads
//
this->lblThreads->AutoSize = true;
this->lblThreads->Location = System::Drawing::Point(7, 27);
this->lblThreads->Name = L"lblThreads";
this->lblThreads->Size = System::Drawing::Size(49, 13);
this->lblThreads->TabIndex = 5;
this->lblThreads->Text = L"Threads:";
//
// trbLoops
//
this->trbLoops->Location = System::Drawing::Point(10, 104);
this->trbLoops->Maximum = 1000;
this->trbLoops->Minimum = 1;
this->trbLoops->Name = L"trbLoops";
this->trbLoops->Size = System::Drawing::Size(75, 45);
this->trbLoops->TabIndex = 2;
this->trbLoops->Value = 100;
this->trbLoops->Scroll += gcnew System::EventHandler(this, &Form1::trbLoops_Scroll);
//
// btnLoadImage
//
this->btnLoadImage->Location = System::Drawing::Point(21, 29);
this->btnLoadImage->Name = L"btnLoadImage";
this->btnLoadImage->Size = System::Drawing::Size(75, 23);
this->btnLoadImage->TabIndex = 0;
this->btnLoadImage->Text = L"load image";
this->btnLoadImage->UseVisualStyleBackColor = true;
this->btnLoadImage->Click += gcnew System::EventHandler(this, &Form1::btnLoadImage_Click);
//
// pictureBox
//
this->pictureBox->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
this->pictureBox->Location = System::Drawing::Point(167, 12);
this->pictureBox->Name = L"pictureBox";
this->pictureBox->Size = System::Drawing::Size(640, 480);
this->pictureBox->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
this->pictureBox->TabIndex = 1;
this->pictureBox->TabStop = false;
//
// openFile1
//
this->openFile1->FileName = L"file";
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(818, 503);
this->Controls->Add(this->btnPause);
this->Controls->Add(this->pictureBox);
this->Controls->Add(this->grpCtrl);
this->Name = L"Form1";
this->Text = L"PaintingThreads";
this->FormClosing += gcnew System::Windows::Forms::FormClosingEventHandler(this, &Form1::Form1_FormClosing);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->grpCtrl->ResumeLayout(false);
this->grpPaintOptions->ResumeLayout(false);
this->grpPaintOptions->PerformLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trbThreads))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trbLoops))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox))->EndInit();
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
}
// load image button
private: System::Void btnLoadImage_Click(System::Object^ sender, System::EventArgs^ e) {
// file dialog zum laden des bildes
if(openFile1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
System::IO::StreamReader ^ sr = gcnew
System::IO::StreamReader(openFile1->FileName);
sr->Close();
pictureBox->Enabled = "True";
// load image into picture box
pictureBox->Image = Image::FromFile(openFile1->FileName);
backgroundImage = ImageLoader::loadImage(Image::FromFile(openFile1->FileName)->Width,Image::FromFile(openFile1->FileName)->Height,3,HTWStringConverter::Sys2Std(openFile1->FileName));
btnStartPainting->Enabled = true;
}
}
// text slider threads
private: System::Void txtThreads_TextChanged(System::Object^ sender, System::EventArgs^ e) {
int threadSlider;
// pruefen ob Wert eine Zahl ist
if(!Int32::TryParse(txtThreads->Text, threadSlider)) {
// keine Zahl
System::Windows::Forms::MessageBox::Show("Wert zwischen 1 und 10");
//default wert
txtThreads->Text = "1";
}
else {
// pruefen ob > 100 oder <0
if(System::Convert::ToInt32(txtThreads->Text)>100) {
System::Windows::Forms::MessageBox::Show("Wert zwischen 1 und 100");
txtThreads->Text= "100";
} else if(System::Convert::ToInt32(txtThreads->Text)<1) {
System::Windows::Forms::MessageBox::Show("Wert zwischen 1 und 100");
txtThreads->Text= "1";
} else {
trbThreads->Value = System::Convert::ToInt32(txtThreads->Text);
}
}
}
// slider threads
private: System::Void trbThreads_Scroll(System::Object^ sender, System::EventArgs^ e) {
txtThreads->Text = System::Convert::ToString(trbThreads->Value);
}
// slider loops
private: System::Void trbLoops_Scroll(System::Object^ sender, System::EventArgs^ e) {
txtLoops->Text = System::Convert::ToString(trbLoops->Value);
}
// text slider loops
private: System::Void txtLoops_TextChanged(System::Object^ sender, System::EventArgs^ e) {
int loopsSlider;
// pruefen ob Wert eine Zahl ist
if(!Int32::TryParse(txtLoops->Text, loopsSlider)) {
// keine Zahl
System::Windows::Forms::MessageBox::Show("Wert zwischen 1 und 5000");
//default wert
txtThreads->Text = "100";
}
else {
// pruefen ob > 5000 oder <0
if(System::Convert::ToInt32(txtLoops->Text)>5000) {
System::Windows::Forms::MessageBox::Show("Wert zwischen 1 und 5000");
txtLoops->Text= "5000";
} else if(System::Convert::ToInt32(txtLoops->Text)<1) {
System::Windows::Forms::MessageBox::Show("Wert zwischen 1 und 5000");
txtLoops->Text= "1";
} else {
trbLoops->Value = System::Convert::ToInt32(txtLoops->Text);
}
}
}
// button startPainting
private: System::Void btnStartPainting_Click(System::Object^ sender, System::EventArgs^ e) {
//startPaintingOk = 1;
btnPause->Enabled = true;
paintingThr = gcnew System::Threading::Thread(gcnew ThreadStart(this,&Form1::paintThreadStart));
paintingThr->Start();
}
public: System::Void paintThreadStart() {
// PaintThread Objekt erzeugen
paintThread = gcnew PaintThread(backgroundImage, System::Convert::ToInt32(txtLoops->Text));
// gewuenschte Anzahl an Threads aus dem Object paintThreads erzeugen
for(int i=0; i<System::Convert::ToInt32(txtThreads->Text); i++){
// code zum starten der painting funktion
paintThread->startThread(i);
}
}
// pause button to get a result picture
private: System::Void btnPause_Click(System::Object^ sender, System::EventArgs^ e) {
pauseThr = gcnew System::Threading::Thread(gcnew ThreadStart(this,&Form1::pauseThreadStart));
pauseThr->Start();
}
public: System::Void pauseThreadStart() {
nameId++;
System::String^ fileName = ("C:\\Windows\\Temp\\temp" + nameId + ".jpg");
const char* charName = (char*) Marshal::StringToHGlobalAnsi(fileName ).ToPointer();
final = paintThread->getImageObject();
if(htwSaveImage(charName,final->getImageContent(),final->getWidth(), final->getHeight(),final->getBytesPerPixel())) {
delete pictureBox->Image;
pictureBox->Image = Image::FromFile(fileName);
} else System::Windows::Forms::MessageBox::Show("Fehler beim Speichern");
}
// alle temp-Bilder loeschen
private: System::Void Form1_FormClosing(System::Object^ sender, System::Windows::Forms::FormClosingEventArgs^ e) {
delete pictureBox->Image;
for(int i=1;i<=nameId;i++) {
System::String^ fileName = ("C:\\Windows\\Temp\\temp" + i + ".jpg");
if(System::IO::File::Exists(fileName)) {
System::IO::File::Delete(fileName);
}
}
if (paintingThr) {
if (paintingThr->IsAlive) paintingThr->Abort();
}
if (pauseThr) {
if (pauseThr->IsAlive) pauseThr->Abort();
}
}
};
} | [
"[email protected]@5f9f56c3-fb77-04ef-e3c5-e71eb3e36737",
"[email protected]@5f9f56c3-fb77-04ef-e3c5-e71eb3e36737"
] | [
[
[
1,
5
],
[
15,
23
],
[
25,
33
],
[
40,
40
],
[
42,
61
],
[
79,
92
],
[
111,
112
],
[
247,
250
],
[
255,
255
],
[
258,
258
],
[
265,
265
],
[
267,
271
],
[
273,
282
],
[
284,
285
],
[
287,
287
],
[
289,
297
],
[
302,
302
],
[
304,
309
],
[
311,
311
],
[
313,
314
],
[
316,
316
],
[
318,
319
],
[
321,
321
],
[
323,
343
],
[
345,
345
],
[
347,
351
],
[
360,
360
],
[
362,
362
],
[
364,
365
],
[
367,
369
],
[
386,
400
]
],
[
[
6,
14
],
[
24,
24
],
[
34,
39
],
[
41,
41
],
[
62,
78
],
[
93,
110
],
[
113,
246
],
[
251,
254
],
[
256,
257
],
[
259,
264
],
[
266,
266
],
[
272,
272
],
[
283,
283
],
[
286,
286
],
[
288,
288
],
[
298,
301
],
[
303,
303
],
[
310,
310
],
[
312,
312
],
[
315,
315
],
[
317,
317
],
[
320,
320
],
[
322,
322
],
[
344,
344
],
[
346,
346
],
[
352,
359
],
[
361,
361
],
[
363,
363
],
[
366,
366
],
[
370,
385
]
]
] |
510f99f299d7e4c321a26d7affda9ce3a81579a6 | 3187b0dd0d7a7b83b33c62357efa0092b3943110 | /src/dlib/sockets/sockets_kernel_1.cpp | 648b22b37f9facabf7d1332775a50676aadcc908 | [
"BSL-1.0"
] | permissive | exi/gravisim | 8a4dad954f68960d42f1d7da14ff1ca7a20e92f2 | 361e70e40f58c9f5e2c2f574c9e7446751629807 | refs/heads/master | 2021-01-19T17:45:04.106839 | 2010-10-22T09:11:24 | 2010-10-22T09:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,911 | cpp | // Copyright (C) 2003 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_SOCKETS_KERNEL_1_CPp_
#define DLIB_SOCKETS_KERNEL_1_CPp_
#include "../platform.h"
#ifdef WIN32
#ifndef _WINSOCKAPI_
#define _WINSOCKAPI_ /* Prevent inclusion of winsock.h in windows.h */
#endif
#include "../windows_magic.h"
#include "sockets_kernel_1.h"
#include <windows.h>
#include <Winsock2.h>
#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#endif
// tell visual studio to link to the libraries we need if we are
// in fact using visual studio
#ifdef _MSC_VER
#pragma comment (lib, "ws2_32.lib")
#endif
#include "../assert.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
class SOCKET_container
{
/*!
This object is just a wrapper around the SOCKET type. It exists
so that we can #include the windows.h and Winsock2.h header files
in this cpp file and not at all in the header file.
!*/
public:
SOCKET_container (
SOCKET s = INVALID_SOCKET
) : val(s) {}
SOCKET val;
operator SOCKET&() { return val; }
SOCKET_container& operator= (
const SOCKET& s
) { val = s; return *this; }
bool operator== (
const SOCKET& s
) const { return s == val; }
};
// ----------------------------------------------------------------------------------------
// stuff to ensure that WSAStartup() is always called before any sockets stuff is needed
namespace sockets_kernel_1_mutex
{
mutex startup_lock;
}
class sockets_startupdown
{
public:
sockets_startupdown();
~sockets_startupdown() { WSACleanup( ); }
};
sockets_startupdown::sockets_startupdown (
)
{
WSADATA wsaData;
WSAStartup (MAKEWORD(2,0), &wsaData);
}
void sockets_startup()
{
// mutex crap to make this function thread-safe
sockets_kernel_1_mutex::startup_lock.lock();
static sockets_startupdown a;
sockets_kernel_1_mutex::startup_lock.unlock();
}
// ----------------------------------------------------------------------------------------
// lookup functions
int
get_local_hostname (
std::string& hostname
)
{
// ensure that WSAStartup has been called and WSACleanup will eventually
// be called when program ends
sockets_startup();
try
{
char temp[NI_MAXHOST];
if (gethostname(temp,NI_MAXHOST) == SOCKET_ERROR )
{
return OTHER_ERROR;
}
hostname = temp;
}
catch (...)
{
return OTHER_ERROR;
}
return 0;
}
// -----------------
int
hostname_to_ip (
const std::string& hostname,
std::string& ip,
int n
)
{
// ensure that WSAStartup has been called and WSACleanup will eventually
// be called when program ends
sockets_startup();
try
{
// if no hostname was given then return error
if ( hostname.empty())
return OTHER_ERROR;
hostent* address;
address = gethostbyname(hostname.c_str());
if (address == 0)
{
return OTHER_ERROR;
}
// find the nth address
in_addr* addr = reinterpret_cast<in_addr*>(address->h_addr_list[0]);
for (int i = 1; i <= n; ++i)
{
addr = reinterpret_cast<in_addr*>(address->h_addr_list[i]);
// if there is no nth address then return error
if (addr == 0)
return OTHER_ERROR;
}
char* resolved_ip = inet_ntoa(*addr);
// check if inet_ntoa returned an error
if (resolved_ip == NULL)
{
return OTHER_ERROR;
}
ip.assign(resolved_ip);
}
catch(...)
{
return OTHER_ERROR;
}
return 0;
}
// -----------------
int
ip_to_hostname (
const std::string& ip,
std::string& hostname
)
{
// ensure that WSAStartup has been called and WSACleanup will eventually
// be called when program ends
sockets_startup();
try
{
// if no ip was given then return error
if (ip.empty())
return OTHER_ERROR;
hostent* address;
unsigned long ipnum = inet_addr(ip.c_str());
// if inet_addr coudln't convert ip then return an error
if (ipnum == INADDR_NONE)
{
return OTHER_ERROR;
}
address = gethostbyaddr(reinterpret_cast<char*>(&ipnum),4,AF_INET);
// check if gethostbyaddr returned an error
if (address == 0)
{
return OTHER_ERROR;
}
hostname.assign(address->h_name);
}
catch (...)
{
return OTHER_ERROR;
}
return 0;
}
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// connection object
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
connection::
connection(
SOCKET_container sock,
unsigned short foreign_port,
const std::string& foreign_ip,
unsigned short local_port,
const std::string& local_ip
) :
user_data(0),
connection_socket(*(new SOCKET_container())),
connection_foreign_port(foreign_port),
connection_foreign_ip(foreign_ip),
connection_local_port(local_port),
connection_local_ip(local_ip),
sd(false),
sdo(false),
sdr(0)
{
connection_socket = sock;
}
// ----------------------------------------------------------------------------------------
connection::
~connection (
)
{
if (connection_socket != INVALID_SOCKET)
closesocket(connection_socket);
delete &connection_socket;
}
// ----------------------------------------------------------------------------------------
long connection::
write (
const char* buf,
long num
)
{
const long old_num = num;
long status;
while (num > 0)
{
if ( (status = send(connection_socket,buf,num,0)) == SOCKET_ERROR)
{
if (sdo_called())
return SHUTDOWN;
else
return OTHER_ERROR;
}
num -= status;
buf += status;
}
return old_num;
}
// ----------------------------------------------------------------------------------------
long connection::
read (
char* buf,
long num
)
{
long status = recv(connection_socket,buf,num,0);
if (status == SOCKET_ERROR)
{
// if this error is the result of a shutdown call then return SHUTDOWN
if (sd_called())
return SHUTDOWN;
else
return OTHER_ERROR;
}
else if (status == 0 && sd_called())
{
return SHUTDOWN;
}
return status;
}
// ----------------------------------------------------------------------------------------
int connection::
shutdown_outgoing (
)
{
sd_mutex.lock();
if (sdo || sd)
{
sd_mutex.unlock();
return sdr;
}
sdo = true;
sdr = ::shutdown(connection_socket,SD_SEND);
// convert -1 error code into the OTHER_ERROR error code
if (sdr == -1)
sdr = OTHER_ERROR;
int temp = sdr;
sd_mutex.unlock();
return temp;
}
// ----------------------------------------------------------------------------------------
int connection::
shutdown (
)
{
sd_mutex.lock();
if (sd)
{
sd_mutex.unlock();
return sdr;
}
sd = true;
SOCKET stemp = connection_socket;
connection_socket = INVALID_SOCKET;
sdr = closesocket(stemp);
// convert SOCKET_ERROR error code into the OTHER_ERROR error code
if (sdr == SOCKET_ERROR)
sdr = OTHER_ERROR;
int temp = sdr;
sd_mutex.unlock();
return temp;
}
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// listener object
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
listener::
listener(
SOCKET_container sock,
unsigned short port,
const std::string& ip
) :
listening_socket(*(new SOCKET_container)),
listening_port(port),
listening_ip(ip),
inaddr_any(listening_ip.empty())
{
listening_socket = sock;
}
// ----------------------------------------------------------------------------------------
listener::
~listener (
)
{
closesocket(listening_socket);
delete &listening_socket;
}
// ----------------------------------------------------------------------------------------
int listener::
accept (
connection*& new_connection,
unsigned long timeout
)
{
SOCKET incoming;
sockaddr_in incomingAddr;
int length = sizeof(sockaddr_in);
// implement timeout with select if timeout is > 0
if (timeout > 0)
{
fd_set read_set;
// initialize read_set
FD_ZERO(&read_set);
// add the listening socket to read_set
FD_SET(listening_socket, &read_set);
// setup a timeval structure
timeval time_to_wait;
time_to_wait.tv_sec = static_cast<long>(timeout/1000);
time_to_wait.tv_usec = static_cast<long>((timeout%1000)*1000);
// wait on select
int status = select(0,&read_set,0,0,&time_to_wait);
// if select timed out
if (status == 0)
return TIMEOUT;
// if select returned an error
if (status == SOCKET_ERROR)
return OTHER_ERROR;
}
// call accept to get a new connection
incoming=::accept(listening_socket,reinterpret_cast<sockaddr*>(&incomingAddr),&length);
// if there was an error return OTHER_ERROR
if ( incoming == INVALID_SOCKET )
return OTHER_ERROR;
// get the port of the foreign host into foreign_port
int foreign_port = ntohs(incomingAddr.sin_port);
// get the IP of the foreign host into foreign_ip
std::string foreign_ip;
{
char* foreign_ip_temp = inet_ntoa(incomingAddr.sin_addr);
// check if inet_ntoa() returned an error
if (foreign_ip_temp == NULL)
{
closesocket(incoming);
return OTHER_ERROR;
}
foreign_ip.assign(foreign_ip_temp);
}
// get the local ip
std::string local_ip;
if (inaddr_any == true)
{
sockaddr_in local_info;
length = sizeof(sockaddr_in);
// get the local sockaddr_in structure associated with this new connection
if ( getsockname (
incoming,
reinterpret_cast<sockaddr*>(&local_info),
&length
) == SOCKET_ERROR
)
{ // an error occurred
closesocket(incoming);
return OTHER_ERROR;
}
char* temp = inet_ntoa(local_info.sin_addr);
// check if inet_ntoa() returned an error
if (temp == NULL)
{
closesocket(incoming);
return OTHER_ERROR;
}
local_ip.assign(temp);
}
else
{
local_ip = listening_ip;
}
// set the SO_OOBINLINE option
int flag_value = 1;
if (setsockopt(incoming,SOL_SOCKET,SO_OOBINLINE,reinterpret_cast<const char*>(&flag_value),sizeof(int)) == SOCKET_ERROR )
{
closesocket(incoming);
return OTHER_ERROR;
}
// make a new connection object for this new connection
try
{
new_connection = new connection (
incoming,
foreign_port,
foreign_ip,
listening_port,
local_ip
);
}
catch (...) { closesocket(incoming); return OTHER_ERROR; }
return 0;
}
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// socket creation functions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
int
create_listener (
listener*& new_listener,
unsigned short port,
const std::string& ip
)
{
// ensure that WSAStartup has been called and WSACleanup will eventually
// be called when program ends
sockets_startup();
sockaddr_in sa; // local socket structure
ZeroMemory(&sa,sizeof(sockaddr_in)); // initialize sa
SOCKET sock = socket (AF_INET, SOCK_STREAM, 0); // get a new socket
// if socket() returned an error then return OTHER_ERROR
if (sock == INVALID_SOCKET )
{
return OTHER_ERROR;
}
// set the local socket structure
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
if (ip.empty())
{
// if the listener should listen on any IP
sa.sin_addr.S_un.S_addr = htons(INADDR_ANY);
}
else
{
// if there is a specific ip to listen on
sa.sin_addr.S_un.S_addr = inet_addr(ip.c_str());
// if inet_addr cound't convert the ip then return an error
if ( sa.sin_addr.S_un.S_addr == INADDR_NONE )
{
closesocket(sock);
return OTHER_ERROR;
}
}
// set the SO_REUSEADDR option
int flag_value = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,reinterpret_cast<const char*>(&flag_value),sizeof(int));
// bind the new socket to the requested port and ip
if (bind(sock,reinterpret_cast<sockaddr*>(&sa),sizeof(sockaddr_in))==SOCKET_ERROR)
{ // if there was an error
closesocket(sock);
// if the port is already bound then return PORTINUSE
if (WSAGetLastError() == WSAEADDRINUSE)
return PORTINUSE;
else
return OTHER_ERROR;
}
// tell the new socket to listen
if ( listen(sock,SOMAXCONN) == SOCKET_ERROR)
{
// if there was an error return OTHER_ERROR
closesocket(sock);
// if the port is already bound then return PORTINUSE
if (WSAGetLastError() == WSAEADDRINUSE)
return PORTINUSE;
else
return OTHER_ERROR;
}
// determine the port used if necessary
if (port == 0)
{
sockaddr_in local_info;
int length = sizeof(sockaddr_in);
if ( getsockname (
sock,
reinterpret_cast<sockaddr*>(&local_info),
&length
) == SOCKET_ERROR
)
{
closesocket(sock);
return OTHER_ERROR;
}
port = ntohs(local_info.sin_port);
}
// initialize a listener object on the heap with the new socket
try { new_listener = new listener(sock,port,ip); }
catch(...) { closesocket(sock); return OTHER_ERROR; }
return 0;
}
// ----------------------------------------------------------------------------------------
int
create_connection (
connection*& new_connection,
unsigned short foreign_port,
const std::string& foreign_ip,
unsigned short local_port,
const std::string& local_ip
)
{
// ensure that WSAStartup has been called and WSACleanup
// will eventually be called when program ends
sockets_startup();
sockaddr_in local_sa; // local socket structure
sockaddr_in foreign_sa; // foreign socket structure
ZeroMemory(&local_sa,sizeof(sockaddr_in)); // initialize local_sa
ZeroMemory(&foreign_sa,sizeof(sockaddr_in)); // initialize foreign_sa
int length;
SOCKET sock = socket (AF_INET, SOCK_STREAM, 0); // get a new socket
// if socket() returned an error then return OTHER_ERROR
if (sock == INVALID_SOCKET )
{
return OTHER_ERROR;
}
// set the foreign socket structure
foreign_sa.sin_family = AF_INET;
foreign_sa.sin_port = htons(foreign_port);
foreign_sa.sin_addr.S_un.S_addr = inet_addr(foreign_ip.c_str());
// if inet_addr cound't convert the ip then return an error
if ( foreign_sa.sin_addr.S_un.S_addr == INADDR_NONE )
{
closesocket(sock);
return OTHER_ERROR;
}
// set up the local socket structure
local_sa.sin_family = AF_INET;
// set the local ip
if (local_ip.empty())
{
// if the listener should listen on any IP
local_sa.sin_addr.S_un.S_addr = htons(INADDR_ANY);
}
else
{
// if there is a specific ip to listen on
local_sa.sin_addr.S_un.S_addr = inet_addr(local_ip.c_str());
// if inet_addr couldn't convert the ip then return an error
if (local_sa.sin_addr.S_un.S_addr == INADDR_NONE)
{
closesocket(sock);
return OTHER_ERROR;
}
}
// set the local port
local_sa.sin_port = htons(local_port);
// bind the new socket to the requested local port and local ip
if ( bind (
sock,
reinterpret_cast<sockaddr*>(&local_sa),
sizeof(sockaddr_in)
) == SOCKET_ERROR
)
{ // if there was an error
closesocket(sock);
// if the port is already bound then return PORTINUSE
if (WSAGetLastError() == WSAEADDRINUSE)
return PORTINUSE;
else
return OTHER_ERROR;
}
// connect the socket
if (connect (
sock,
reinterpret_cast<sockaddr*>(&foreign_sa),
sizeof(sockaddr_in)
) == SOCKET_ERROR
)
{
closesocket(sock);
// if the port is already bound then return PORTINUSE
if (WSAGetLastError() == WSAEADDRINUSE)
return PORTINUSE;
else
return OTHER_ERROR;
}
// determine the local port and IP and store them in used_local_ip
// and used_local_port
int used_local_port;
std::string used_local_ip;
sockaddr_in local_info;
if (local_port == 0)
{
length = sizeof(sockaddr_in);
if (getsockname (
sock,
reinterpret_cast<sockaddr*>(&local_info),
&length
) == SOCKET_ERROR
)
{
closesocket(sock);
return OTHER_ERROR;
}
used_local_port = ntohs(local_info.sin_port);
}
else
{
used_local_port = local_port;
}
// determine real local ip
if (local_ip.empty())
{
// if local_port is not 0 then we must fill the local_info structure
if (local_port != 0)
{
length = sizeof(sockaddr_in);
if ( getsockname (
sock,
reinterpret_cast<sockaddr*>(&local_info),
&length
) == SOCKET_ERROR
)
{
closesocket(sock);
return OTHER_ERROR;
}
}
char* temp = inet_ntoa(local_info.sin_addr);
// check if inet_ntoa returned an error
if (temp == NULL)
{
closesocket(sock);
return OTHER_ERROR;
}
used_local_ip.assign(temp);
}
else
{
used_local_ip = local_ip;
}
// set the SO_OOBINLINE option
int flag_value = 1;
if (setsockopt(sock,SOL_SOCKET,SO_OOBINLINE,reinterpret_cast<const char*>(&flag_value),sizeof(int)) == SOCKET_ERROR )
{
closesocket(sock);
return OTHER_ERROR;
}
// initialize a connection object on the heap with the new socket
try
{
new_connection = new connection (
sock,
foreign_port,
foreign_ip,
used_local_port,
used_local_ip
);
}
catch(...) {closesocket(sock); return OTHER_ERROR; }
return 0;
}
// ----------------------------------------------------------------------------------------
}
#endif // WIN32
#endif // DLIB_SOCKETS_KERNEL_1_CPp_
| [
"[email protected]"
] | [
[
[
1,
822
]
]
] |
5428aa240b101aa8aca46f54ababe598feba965c | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Toolset/frmErrorList.h | d2f173f5aa37a1b1f6ea738376a1b64b6cf4c53a | [] | 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 | 12,873 | h | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: frmErrorList.h
Version: 0.03
---------------------------------------------------------------------------
*/
#pragma once
#ifndef __INC_FRMERRORLIST_H_
#define __INC_FRMERRORLIST_H_
#include "Logger.h"
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace WeifenLuo::WinFormsUI::Docking;
using System::String;
namespace nGENEToolset
{
/// <summary>
/// Summary for frmErrorList
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public ref class frmErrorList : public WeifenLuo::WinFormsUI::Docking::DockContent
{
private:
ToolsetLogManaged^ logger;
int m_nErrors;
int m_nWarnings;
int m_nMessages;
public:
frmErrorList(void)
{
InitializeComponent();
logger = gcnew ToolsetLogManaged();
logger->log += gcnew LogEventHandler(this, &frmErrorList::frmErrorList_Log);
m_nErrors = 0;
m_nWarnings = 0;
m_nMessages = 0;
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~frmErrorList()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::DataGridViewTextBoxColumn^ ID;
protected:
private: System::Windows::Forms::DataGridView^ dgvLog;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ TypeID;
private: System::Windows::Forms::DataGridViewImageColumn^ Type;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ Description;
private: System::Windows::Forms::ToolStripButton^ btnMessages;
private: System::Windows::Forms::ToolStripSeparator^ toolStripSeparator2;
private: System::Windows::Forms::ToolStrip^ tstMsgType;
private: System::Windows::Forms::ToolStripButton^ btnErrors;
private: System::Windows::Forms::ToolStripSeparator^ toolStripSeparator1;
private: System::Windows::Forms::ToolStripButton^ btnWarnings;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(frmErrorList::typeid));
this->ID = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn());
this->dgvLog = (gcnew System::Windows::Forms::DataGridView());
this->TypeID = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn());
this->Type = (gcnew System::Windows::Forms::DataGridViewImageColumn());
this->Description = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn());
this->btnMessages = (gcnew System::Windows::Forms::ToolStripButton());
this->toolStripSeparator2 = (gcnew System::Windows::Forms::ToolStripSeparator());
this->tstMsgType = (gcnew System::Windows::Forms::ToolStrip());
this->btnErrors = (gcnew System::Windows::Forms::ToolStripButton());
this->toolStripSeparator1 = (gcnew System::Windows::Forms::ToolStripSeparator());
this->btnWarnings = (gcnew System::Windows::Forms::ToolStripButton());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dgvLog))->BeginInit();
this->tstMsgType->SuspendLayout();
this->SuspendLayout();
//
// ID
//
this->ID->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::AllCells;
this->ID->HeaderText = L"ID";
this->ID->Name = L"ID";
this->ID->ReadOnly = true;
this->ID->Resizable = System::Windows::Forms::DataGridViewTriState::False;
this->ID->Width = 43;
//
// dgvLog
//
this->dgvLog->AllowUserToAddRows = false;
this->dgvLog->AllowUserToDeleteRows = false;
this->dgvLog->AllowUserToResizeColumns = false;
this->dgvLog->AllowUserToResizeRows = false;
this->dgvLog->BackgroundColor = System::Drawing::SystemColors::ControlLightLight;
this->dgvLog->ColumnHeadersBorderStyle = System::Windows::Forms::DataGridViewHeaderBorderStyle::Single;
this->dgvLog->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize;
this->dgvLog->Columns->AddRange(gcnew cli::array< System::Windows::Forms::DataGridViewColumn^ >(4) {this->ID, this->TypeID,
this->Type, this->Description});
this->dgvLog->Dock = System::Windows::Forms::DockStyle::Fill;
this->dgvLog->GridColor = System::Drawing::Color::Gainsboro;
this->dgvLog->Location = System::Drawing::Point(0, 23);
this->dgvLog->MultiSelect = false;
this->dgvLog->Name = L"dgvLog";
this->dgvLog->ReadOnly = true;
this->dgvLog->RowHeadersVisible = false;
this->dgvLog->ScrollBars = System::Windows::Forms::ScrollBars::Vertical;
this->dgvLog->SelectionMode = System::Windows::Forms::DataGridViewSelectionMode::FullRowSelect;
this->dgvLog->Size = System::Drawing::Size(698, 187);
this->dgvLog->TabIndex = 6;
//
// TypeID
//
this->TypeID->HeaderText = L"TypeID";
this->TypeID->Name = L"TypeID";
this->TypeID->ReadOnly = true;
this->TypeID->Visible = false;
//
// Type
//
this->Type->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::AllCells;
this->Type->HeaderText = L"Type";
this->Type->Name = L"Type";
this->Type->ReadOnly = true;
this->Type->Resizable = System::Windows::Forms::DataGridViewTriState::False;
this->Type->Width = 37;
//
// Description
//
this->Description->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::Fill;
this->Description->HeaderText = L"Description";
this->Description->Name = L"Description";
this->Description->ReadOnly = true;
this->Description->SortMode = System::Windows::Forms::DataGridViewColumnSortMode::NotSortable;
//
// btnMessages
//
this->btnMessages->Checked = true;
this->btnMessages->CheckOnClick = true;
this->btnMessages->CheckState = System::Windows::Forms::CheckState::Checked;
this->btnMessages->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"btnMessages.Image")));
this->btnMessages->ImageTransparentColor = System::Drawing::Color::Magenta;
this->btnMessages->Name = L"btnMessages";
this->btnMessages->Size = System::Drawing::Size(78, 20);
this->btnMessages->Text = L"0 Messages";
this->btnMessages->Click += gcnew System::EventHandler(this, &frmErrorList::btnMessages_Click);
//
// toolStripSeparator2
//
this->toolStripSeparator2->Name = L"toolStripSeparator2";
this->toolStripSeparator2->Size = System::Drawing::Size(6, 23);
//
// tstMsgType
//
this->tstMsgType->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(5) {this->btnErrors, this->toolStripSeparator1,
this->btnWarnings, this->toolStripSeparator2, this->btnMessages});
this->tstMsgType->LayoutStyle = System::Windows::Forms::ToolStripLayoutStyle::Flow;
this->tstMsgType->Location = System::Drawing::Point(0, 0);
this->tstMsgType->Name = L"tstMsgType";
this->tstMsgType->Size = System::Drawing::Size(698, 23);
this->tstMsgType->TabIndex = 5;
this->tstMsgType->Text = L"toolStrip1";
//
// btnErrors
//
this->btnErrors->Checked = true;
this->btnErrors->CheckOnClick = true;
this->btnErrors->CheckState = System::Windows::Forms::CheckState::Checked;
this->btnErrors->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"btnErrors.Image")));
this->btnErrors->ImageTransparentColor = System::Drawing::Color::Magenta;
this->btnErrors->Name = L"btnErrors";
this->btnErrors->Size = System::Drawing::Size(57, 20);
this->btnErrors->Text = L"0 Errors";
this->btnErrors->Click += gcnew System::EventHandler(this, &frmErrorList::btnErrors_Click);
//
// toolStripSeparator1
//
this->toolStripSeparator1->Name = L"toolStripSeparator1";
this->toolStripSeparator1->Size = System::Drawing::Size(6, 23);
//
// btnWarnings
//
this->btnWarnings->Checked = true;
this->btnWarnings->CheckOnClick = true;
this->btnWarnings->CheckState = System::Windows::Forms::CheckState::Checked;
this->btnWarnings->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"btnWarnings.Image")));
this->btnWarnings->ImageTransparentColor = System::Drawing::Color::Magenta;
this->btnWarnings->Name = L"btnWarnings";
this->btnWarnings->Size = System::Drawing::Size(77, 20);
this->btnWarnings->Text = L"0 Warnings";
this->btnWarnings->Click += gcnew System::EventHandler(this, &frmErrorList::btnWarnings_Click);
//
// frmErrorList
//
this->AllowEndUserDocking = true;
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(698, 210);
this->Controls->Add(this->dgvLog);
this->Controls->Add(this->tstMsgType);
this->DockAreas = static_cast<WeifenLuo::WinFormsUI::Docking::DockAreas>((((WeifenLuo::WinFormsUI::Docking::DockAreas::Float
| WeifenLuo::WinFormsUI::Docking::DockAreas::DockTop)
| WeifenLuo::WinFormsUI::Docking::DockAreas::DockBottom)
| WeifenLuo::WinFormsUI::Docking::DockAreas::Document));
this->Name = L"frmErrorList";
this->ShowHint = WeifenLuo::WinFormsUI::Docking::DockState::DockBottom;
this->Text = L"Error List";
this->TabText = L"Error List";
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dgvLog))->EndInit();
this->tstMsgType->ResumeLayout(false);
this->tstMsgType->PerformLayout();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
public:
System::Void frmErrorList_Log(String^ str, int type)
{
bool visible = true;
cli::array<Object^>^ values = gcnew cli::array<Object^>(4);
static int msgID;
++msgID;
values[0] = msgID;
values[1] = type;
switch(type)
{
case 0: values[2] = btnErrors->Image;
visible = btnErrors->Checked;
++m_nErrors;
btnErrors->Text = m_nErrors + " Errors";
break;
case 1: values[2] = btnWarnings->Image;
visible = btnWarnings->Checked;
++m_nWarnings;
btnWarnings->Text = m_nWarnings + " Warnings";
break;
case 2: values[2] = btnMessages->Image;
visible = btnMessages->Checked;
++m_nMessages;
btnMessages->Text = m_nMessages + " Messages";
break;
}
values[3] = str;
try
{
this->dgvLog->Rows->Add(values);
this->dgvLog->Rows[dgvLog->Rows->Count - 1]->Visible = visible;
}
catch(Exception^ e)
{
System::Console::WriteLine(e->Message);
}
}
private: System::Void btnErrors_Click(System::Object^ sender, System::EventArgs^ e)
{
bool visible = btnErrors->Checked;
int size = dgvLog->Rows->Count;
dgvLog->SuspendLayout();
for(int i = 0; i < size; ++i)
{
if(dgvLog->Rows[i]->Cells[1]->Value->ToString()->CompareTo("0") == 0)
dgvLog->Rows[i]->Visible = visible;
}
dgvLog->ResumeLayout();
}
private: System::Void btnWarnings_Click(System::Object^ sender, System::EventArgs^ e)
{
bool visible = btnWarnings->Checked;
int size = dgvLog->Rows->Count;
dgvLog->SuspendLayout();
for(int i = 0; i < size; ++i)
{
if(dgvLog->Rows[i]->Cells[1]->Value->ToString()->CompareTo("1") == 0)
dgvLog->Rows[i]->Visible = visible;
}
dgvLog->ResumeLayout();
}
private: System::Void btnMessages_Click(System::Object^ sender, System::EventArgs^ e)
{
bool visible = btnMessages->Checked;
int size = dgvLog->Rows->Count;
dgvLog->SuspendLayout();
for(int i = 0; i < size; ++i)
{
if(dgvLog->Rows[i]->Cells[1]->Value->ToString()->CompareTo("2") == 0)
dgvLog->Rows[i]->Visible = visible;
}
dgvLog->ResumeLayout();
}
};
}
#endif | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
351
]
]
] |
4c1ff9265af752c35c162f0830c3fe682f5efb51 | b08e948c33317a0a67487e497a9afbaf17b0fc4c | /Display/FontBMF.h | a0f8e8ea0c4c470fad270cb6b46f61a06ad6019e | [] | no_license | 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 | 10,285 | h | #ifndef __FONTBMF_H__
#define __FONTBMF_H__
#include "../Display/Font.h"
#include "../Core/File.h"
#include "../Core/Pool.h"
namespace ElixirEngine
{
namespace BitmapFont
{
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayFont;
typedef DisplayFont* DisplayFontPtr;
typedef DisplayFont& DisplayFontRef;
class DisplayFontText;
typedef DisplayFontText* DisplayFontTextPtr;
typedef DisplayFontText& DisplayFontTextRef;
class DisplayFontLoader;
typedef DisplayFontLoader* DisplayFontLoaderPtr;
typedef DisplayFontLoader& DisplayFontLoaderRef;
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
// see Bitmap Font binary format documentation.
struct BlockInfo
{
enum EBitField
{
EBitField_SMOOTH = 0x01 << 0,
EBitField_UNICODE = 0x01 << 1,
EBitField_ITALIC = 0x01 << 2,
EBitField_BOLD = 0x01 << 3,
EBitField_FIXEDHEIGHT = 0x01 << 4,
EBitField_RESERVED5 = 0x01 << 5,
EBitField_RESERVED6 = 0x01 << 6,
EBitField_RESERVED7 = 0x01 << 7,
};
short m_sFontSize;
Byte m_uBitField;
Byte m_uCharSet;
Word m_uStretchH;
Byte m_uAA;
Byte m_uPaddingUp;
Byte m_uPaddingRight;
Byte m_uPaddingDown;
Byte m_uPaddingLeft;
Byte m_uSpacingHoriz;
Byte m_uSpacingVert;
Byte m_uOutline;
string m_strFontName;
};
struct BlockCommon
{
enum EBitField
{
EBitField_RESERVED0 = 0x01 << 0,
EBitField_RESERVED1 = 0x01 << 1,
EBitField_RESERVED2 = 0x01 << 2,
EBitField_RESERVED3 = 0x01 << 3,
EBitField_RESERVED4 = 0x01 << 4,
EBitField_RESERVED5 = 0x01 << 5,
EBitField_RESERVED6 = 0x01 << 6,
EBitField_PACKED = 0x01 << 7,
};
Word m_uLineHeight;
Word m_uBase;
Word m_uScaleW;
Word m_uScaleH;
Word m_uPages;
Byte m_uBitField;
Byte m_uAlphaChannel;
Byte m_uRedChannel;
Byte m_uGreenChannel;
Byte m_uBlueChannel;
};
struct BlockPages
{
StringVec m_vPageNames;
};
struct BlockChar
{
UInt m_uID;
Word m_uX;
Word m_uY;
Word m_uWidth;
Word m_uHeight;
short m_sXOffset;
short m_sYOffset;
short m_sXAdvance;
Byte m_uPage;
Byte m_uChannel;
// Followings are not part of BMF binary format.
// They have been added to ease vertex initialization.
float m_fX;
float m_fY;
float m_fWidth;
float m_fHeight;
};
typedef BlockChar* BlockCharPtr;
typedef BlockChar& BlockCharRef;
typedef vector<BlockChar> BlockCharVec;
typedef map<UInt, BlockChar> BlockCharMap;
struct BlockKerning
{
UInt m_uFirst;
UInt m_uSecond;
short m_sAmount;
};
typedef BlockKerning* BlockKerningPtr;
typedef BlockKerning& BlockKerningRef;
typedef vector<BlockKerning> BlockKerningVec;
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
struct VertexFont
{
Vector3 m_f3Pos; // xyz
Vector3 m_f2UV; // u, v, texture index
static VertexElement s_VertexElement[3];
};
typedef VertexFont* VertexFontPtr;
typedef VertexFont& VertexFontRef;
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
typedef Pool<VertexFont> VertexFontPool;
typedef VertexFontPool* VertexFontPoolPtr;
typedef VertexFontPool& VertexFontPoolRef;
template<typename T>
class FontObjectBuffer : public CoreObject
{
public:
typedef T* TPtr;
typedef T& TRef;
typedef Pool<T> TPool;
typedef TPool* TPoolPtr;
typedef TPool& TPoolRef;
public:
FontObjectBuffer()
: CoreObject(),
m_pPool(NULL),
m_uMax(0)
{
}
virtual ~FontObjectBuffer()
{
}
virtual bool Create(const boost::any& _rConfig)
{
return Reserve(boost::any_cast<const UInt>(_rConfig));
}
virtual void Update()
{
}
virtual void Release()
{
if (NULL != m_pPool)
{
delete m_pPool;
m_pPool = NULL;
m_uMax = 0;
}
}
TPtr Alloc(const UInt _uSize = 1)
{
return m_pPool->Alloc(_uSize);
}
void Free(TPtr _pT)
{
m_pPool->Free(_pT);
}
protected:
bool Reserve(UInt _uSize)
{
if ((NULL != m_pPool) && (m_uMax != _uSize))
{
delete m_pPool;
m_pPool = NULL;
}
m_uMax = _uSize;
if (0 < m_uMax)
{
m_pPool = new TPool(m_uMax);
}
return ((0 < m_uMax) && (m_uMax == m_pPool->Capacity()));
}
protected:
TPoolPtr m_pPool;
UInt m_uMax;
};
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
typedef FontObjectBuffer<VertexFont> VertexPool;
typedef VertexPool* VertexPoolPtr;
typedef VertexPool& VertexPoolRef;
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayFontText : public ElixirEngine::DisplayFontText
{
public:
struct CreateInfo
{
DisplayPtr m_pDisplay;
DisplayFontPtr m_pFont;
};
typedef CreateInfo* CreateInfoPtr;
typedef CreateInfo& CreateInfoRef;
public:
DisplayFontText();
virtual ~DisplayFontText();
virtual bool Create(const boost::any& _rConfig);
virtual void Release();
virtual void RenderBegin();
virtual void Render();
virtual void RenderEnd();
virtual void SetText(const wstring& _wstrText);
virtual void SetColor(const Vector4& _f4Color);
protected:
void BuildText(const bool _bTextChanged, const bool _bSizeChanged, const bool _bRebuildText);
protected:
wstring m_wstrText;
Vector4 m_f4Color;
DisplayFontPtr m_pFont;
VertexFontPtr m_pVertex;
ElixirEngine::VertexBufferPtr m_pPreviousVertexBuffer;
Key m_uPreviousVertexDecl;
unsigned int m_uPreviousVBOffset;
unsigned int m_uPreviousVBStride;
UInt m_uVertexCount;
bool m_bTextChanged;
bool m_bSizeChanged;
bool m_bRebuildText;
};
typedef FontObjectBuffer<DisplayFontText> TextPool;
typedef TextPool* TextPoolPtr;
typedef TextPool& TextPoolRef;
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayFont : public ElixirEngine::DisplayFont
{
friend class DisplayFontText;
public:
DisplayFont(DisplayFontManagerRef _rFontManager, DisplayFontLoaderRef _rFontLoader);
virtual ~DisplayFont();
virtual bool Create(const boost::any& _rConfig);
virtual void Update();
virtual void Release();
virtual ElixirEngine::DisplayFontTextPtr CreateText();
virtual void ReleaseText(ElixirEngine::DisplayFontTextPtr _pText);
virtual DisplayRef GetDisplay();
DisplayFontLoaderRef GetLoader();
protected:
bool CheckHeader(FilePtr _pFile, Byte& _uVersion);
bool ReadBlockInfo(FilePtr _pFile, UInt& _uBlockSise);
bool ReadBlockCommon(FilePtr _pFile, UInt& _uBlockSise);
bool ReadBlockPages(FilePtr _pFile, UInt& _uBlockSise);
bool ReadBlockChars(FilePtr _pFile, UInt& _uBlockSise);
bool ReadBlockKerning(FilePtr _pFile, UInt& _uBlockSise);
bool LoadTextures(const string& _strPath);
short GetKerning(const wchar_t _wcFirst, const wchar_t _wcSecond);
protected:
BlockInfo m_oBlockInfo;
BlockCommon m_oBlockCommon;
BlockPages m_oBlockPages;
BlockCharMap m_mBlockChars;
BlockKerningVec m_vBlockKernings;
DisplayTexturePtrMap m_mTextures;
DisplayFontLoaderRef m_rFontLoader;
};
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayFontLoader : public ElixirEngine::DisplayFontLoader
{
public:
struct CreateInfo
{
UInt m_uVertexCount;
UInt m_uTextCount;
};
typedef CreateInfo* CreateInfoPtr;
typedef CreateInfo& CreateInfoRef;
public:
DisplayFontLoader(DisplayFontManagerRef _rFontManager);
virtual ~DisplayFontLoader();
virtual bool Create(const boost::any& _rConfig);
virtual void Release();
virtual ElixirEngine::DisplayFontPtr Load(const string& _strFileName);
virtual void Unload(ElixirEngine::DisplayFontPtr _pFont);
VertexPoolRef GetVertexPool();
TextPoolRef GetTextPool();
Key GetVertexDecl();
protected:
VertexPoolPtr m_pVertexPool;
TextPoolPtr m_pTextPool;
Key m_uVertexDecl;
};
}
}
#endif
| [
"voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329"
] | [
[
[
1,
364
]
]
] |
98e1bc18c4673d39192687fd9e9f045d3d38c2c0 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Shared/include/MapMovingInterface.h | bc4a85415df0b0a0ab98fe9b649ce91b2fcdf957 | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,950 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MAPMOVINGINTERFACE_H
#define MAPMOVINGINTERFACE_H
#include "config.h"
class MC2Coordinate;
class MC2Point;
class TileMapInfoCallback;
class UserDefinedFeature;
/**
* Class containing information about a clicked poi / feature.
*/
class ClickInfo {
public:
/// Virtual destructor.
virtual ~ClickInfo() {}
/// Returns the name of the feature. Must not return NULL.
virtual const char* getName() const = 0;
/// Returns true if the highlight should be turned on (change cursor).
virtual bool shouldHighlight() const = 0;
/**
* Get the server string.
*/
virtual const char* getServerString() const { return NULL; }
/**
* Get the clicked user feature.
*/
virtual UserDefinedFeature* getClickedUserFeature() const { return NULL; }
/**
* Get the outline feature.
*/
virtual UserDefinedFeature* getOutlineFeature() const { return NULL; }
/**
* Get the distance to feature.
*/
virtual int32 getDistance() const { return 0; }
};
/**
* Inteface to components that have a moving map.
*/
class MapMovingInterface {
public:
/**
* Virtual destructor.
*/
virtual ~MapMovingInterface() {}
/**
* Called by the keyhandler when it is moving
* the map because of a key being held pressed.
* Will be called with the value false when
* movement ends. <br />
* Can be used to draw the map quicker and uglier
* when moving and then drawing a nice one when it
* stops.
* @param moving True if moving, false if not.
*/
virtual void setMovementMode( bool moving ) = 0;
/**
* Returns a reference to info for the feature at the specified
* position on the screen.
* @param point The point on the screen where
* the info should be found.
* @param onlyPois True if only poi info should be returned.
*/
virtual const ClickInfo&
getInfoForFeatureAt( const MC2Point& point,
bool onlyPois,
TileMapInfoCallback* infoCallback = NULL ) = 0;
/**
* Returns a reference to the center coordinate.
*/
virtual const MC2Coordinate& getCenter() const = 0;
/**
* Transforms a world coordinate to a screen coordinate.
*/
virtual void transform( MC2Point& point,
const MC2Coordinate& coord ) const = 0;
/**
* Transforms the point on the screen to a world
* coordinate.
*/
virtual void inverseTransform( MC2Coordinate& coord,
const MC2Point& point ) const = 0;
/**
* Sets the center coordinate to newCenter.
*/
virtual void setCenter(const MC2Coordinate& newCenter) = 0;
/**
* Sets the specified point on the screen to the
* specified coordinate.
* @param newCoord The new coordinate to move the specified
* point to.
* @param screenPoint The point on the screen to set to the
* specified coordinate.
*/
virtual void setPoint(const MC2Coordinate& newCoord,
const MC2Point& screenPoint ) = 0;
/**
* Sets the specified point on the screen to the
* specified coordinate and rotate around that point.
*
* This method call result in the same thing as below,
* but more efficiently implemented:
*
* setPoint( newCoord, screenPoint );
* setAngle( angleDegrees, screenPoint );
*
*
* @param newCoord The new coordinate to move the specified
* point to.
* @param screenPoint The point on the screen to set to the
* specified coordinate.
* @param angle The angle in degrees to rotate around
* the screenPoint.
*/
virtual void setPoint(const MC2Coordinate& newCoord,
const MC2Point& screenPoint,
double angleDegrees ) = 0;
/**
* Moves the screen. Unit pixels.
*/
virtual void move(int deltaX, int deltaY) = 0;
/**
* Sets the angle to the number of degrees in the
* parameter. Rotates around the center.
*/
virtual void setAngle(double angleDegrees) = 0;
/**
* Sets the angle to the number of degrees in the
* parameter.
* @param angleDegrees Angle in degrees.
* @param rotationPoint Point to rotate around.
*/
virtual void setAngle( double angleDegrees,
const MC2Point& rotationPoint ) = 0;
/**
* Rotates the display the supplied number of degrees ccw.
*/
virtual void rotateLeftDeg( int nbrDeg ) = 0;
/**
* Returns the current angle in degrees.
*/
virtual double getAngle() const = 0;
/**
* Sets scale in meters per pixel.
* @param scale New scale.
* @return The scale set.
*/
virtual double setScale(double scale) = 0;
/**
* Returns the current scale in meters per pixel.
*/
virtual double getScale() const = 0;
/**
* Zooms the display. Value larger than one means zoom in.
* Corresponds to setScale( factor * getScale() )
*/
virtual double zoom(double factor) = 0;
/**
* Zooms in so that a specific point at the screen is located at a
* a certain coordinate.
*
* @param factor The factor to zoom in.
* Value larger than one means zoom in.
* @param zoomCoord The coordinate to zoom in to.
* @param zoomPoint The point on the screen where the zoomCoord
* should be located.
*/
virtual double zoom( double factor,
const MC2Coordinate& zoomCoord,
const MC2Point& zoomPoint ) = 0;
/**
* Zooms the display to the supplied corners.
*/
virtual void setPixelBox( const MC2Point& oneCorner,
const MC2Point& otherCorner ) = 0;
/**
* Zooms the display to the supplied world box.
*/
virtual void setWorldBox( const MC2Coordinate& oneCorner,
const MC2Coordinate& otherCorner ) = 0;
/**
* Get the next point that contains a feature that could be
* highlighted.
* @param point [IN] The point to be set to the next highlightable
* feature.
* @return True if a highlightable feature was found and thus
* if the point was updated. False otherwise.
*/
virtual bool getNextHighlightPoint( MC2Point& point ) = 0;
/**
* Shows highlight for last info point if visible is true.
*/
virtual void setHighlight( bool visible ) = 0;
/**
* If the screen can be handled as a bitmap. I.e.
* if the methods moveBitmap, setPointBitmap, setBitmapDragPoint
* zoomBitmapAtPoint and zoomBitmapAtCenter are properly
* implemented.
*/
virtual bool canHandleScreenAsBitmap() const { return false; }
/**
* Move the map as a bitmap. The deltas corresponds to in which
* direction the map should be moved, i.e. it should be the
* same values as used when calling the move() method.
*/
virtual void moveBitmap(int deltaX, int deltaY) {}
/**
* Set the point when moving the screen as a bitmap.
* setBitmapDragPoint must have first been called to know
* which point on the bitmap that should be moved.
*/
virtual void setPointBitmap(const MC2Point& screenPoint ) {}
/**
* Set the bitmap drag point. This must be set before the
* setPointBitmap can be called.
*/
virtual void setBitmapDragPoint( const MC2Point& dragPoint ) {}
/**
* Zoom the map as a bitmap at a specific point.
*/
virtual void zoomBitmapAtPoint( double factor,
const MC2Point& screenPoint ) {}
/**
* Zoom the map as a bitmap at the center.
*/
virtual void zoomBitmapAtCenter( double factor ) {}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
276
]
]
] |
85d0b58442ea840556baeb80a863f5d535d0ebdd | f7d8a85f9d0c1956d64efbe96d056e338b0e0641 | /Src/FileDownloader.cpp | c23fd0ad0eab66bb86e9df5f785e5a7862cfaeeb | [] | no_license | thennequin/dlfm | 6183dfeb485f860396573eda125fd61dcd497660 | 0b122e7042ec3b48660722e2b41ef0a0551a70a9 | refs/heads/master | 2020-04-11T03:53:12.856319 | 2008-07-06T10:17:29 | 2008-07-06T10:17:29 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 8,620 | cpp | #include "FileDownloader.h"
#include "DLManager.h"
FileDownloader::FileDownloader(FileDownloader& copy)
: wxThread(wxTHREAD_JOINABLE)
{
pLink = copy.pLink;
pFileName = copy.pFileName;
//pMutex = new wxMutex(); // copy.pMutex;
//pMutex=copy.pMutex;
pStatePage.pParent = this;
pStateHeader.pParent = this;
pStateData.pParent = this;
pStateNone.pParent = this;
iFileSize=copy.iFileSize;
iDataPos=copy.iDataPos;
iTime=GetTickCount();
Status = copy.Status;
bAlreadyRun=false;
bStartDL=copy.bStartDL;
RetryCount=copy.RetryCount;
Error=ERROR_NONE;
pOutput=NULL;
pCurl=NULL;
fMoySpeed=0;
fSpeed=0;
Manager = copy.Manager;
return;
if ( Create() != wxTHREAD_NO_ERROR )
{
wxLogError(wxT("Can't create thread!"));
Status=FFD_ERROR;
ErrorTime=GetTickCount();
Error=ERROR_THREAD_NOT_CREATE;
Manager->UpdateScreen(true);
return;
}
}
FileDownloader::FileDownloader(wxString link,wxString filename,DLManager *manager)
: wxThread(wxTHREAD_JOINABLE)
{
iTime = GetTickCount();
/*pLinkPageRef=NULL;
pHeader=NULL;
pOutput=NULL;
pCurl=NULL;
pFinalLink=NULL;
pLink=NULL;
pFileName=NULL;*/
//wxLogMessage("Init FileDownloader\n");
//if (link==NULL || filename==NULL || mutex==NULL)
//return;
/*pLink = (char*)malloc(strlen(link));
if (pLink)
{
strcpy(pLink,link);
pLink[strlen(link)]='\0';
}
pFileName=(char*)malloc(strlen(filename));
if (pFileName)
{
strcpy(pFileName,filename);
pFileName[strlen(filename)]='\0';
}*/
pLink = link;
pFileName = filename;
//pMutex = new wxMutex();
//wxLogDebug("Filename : %s",pFileName);
//Status=FFD_STOP;
pStatePage.pParent = this;
pStateHeader.pParent = this;
pStateData.pParent = this;
pStateNone.pParent = this;
iFileSize=-2;
iDataPos=0;
iTime=GetTickCount();
Status = FFD_STOP;
bAlreadyRun=false;
fMoySpeed=0;
fSpeed=0;
pOutput=NULL;
pCurl=NULL;
Manager = manager;
bStartDL=false;
Error=ERROR_NONE;
RetryCount=0;
if ( Create() != wxTHREAD_NO_ERROR )
{
wxLogError(wxT("Can't create thread!"));
Status=FFD_ERROR;
Error=ERROR_THREAD_NOT_CREATE;
return;
}
}
FileDownloader::~FileDownloader(void)
{
//delete pMutex;
}
void *FileDownloader::Entry()
{
wxLogMessage("Init Download : %s\n",pLink);
pCurl = curl_easy_init();
if (pCurl)
{
/*pMutex->Lock();*/
CURLcode Res;
wxLogMessage("Ouverture fichier\n");
//pOutput = fopen("downloads/"+pFileName,"ab");
pOutput = fopen(Manager->mConfig->ReadStringValue("DownloadPath","Downloads")+"/"+pFileName,"ab");
/*pMutex->Unlock();*/
if (!pOutput)
return 0;
//LockFile(pFilename);
//wxLogMessage("Debut de téléchargement du fichier\n");
//fseek (pOutput, 0, SEEK_END);
//iDataPos = ftell(pOutput);
//wxLogMessage("Pos : %d\n",iDataPos);
/*pMutex->Lock();*/
char Range[64];
Range[0]='\0';
sprintf_s(Range,64,"%d-",iDataPos);
wxLogMessage("Commencement dl\n");
//Début de téléchargement du fichier
curl_easy_reset(pCurl);
curl_easy_setopt(pCurl, CURLOPT_URL, pLink);
//curl_easy_setopt(pCurl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(pCurl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13");
//curl_easy_setopt(pCurl, CURLOPT_REFERER, pLink);
curl_easy_setopt(pCurl, CURLOPT_RANGE,Range); // "38920-"
curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, &pStateData);
curl_easy_setopt(pCurl, CURLOPT_WRITEHEADER, &pStateHeader);
curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, WriteData);
/*pMutex->Unlock();*/
//bStartDL=false;
Res = curl_easy_perform(pCurl);
if (Res != CURLE_OK) {
wxLogError("Erreur de DL");
if (Status!=FFD_STOP)
{
fprintf(stderr, "Curl perform failed: %s\n", curl_easy_strerror(Res));
if (RetryCount<Manager->MaxRetry)
Status=FFD_RETRY;
else
Status=FFD_ERROR;
ErrorTime=GetTickCount();
Error=ERROR_HOST_NOT_FOUND;
return 0;
}
}
if (Status==FFD_START)
Status=FFD_FINISH;
Manager->UpdateScreen(true);
}
/*if (RetryCount>=Manager->MaxRetry)
Status=FFD_ERROR;
else*/
Status=FFD_RETRY;
ErrorTime=GetTickCount();
Error=ERROR_CONNECTION_FAILED;
return 0;
}
void FileDownloader::OnExit()
{
//if (Status != FFD_FINISH)
//Status = FFD_STOP;
Manager->UpdateScreen(true);
wxLogMessage("Exit\n");
wxLogMessage("Fermeture fichier\n");
if (pOutput)
fclose(pOutput);
pOutput=NULL;
wxLogMessage("Fermeture connection\n");
if (pCurl)
curl_easy_cleanup(pCurl);
pCurl=NULL;
fMoySpeed=0;
fSpeed=0;
}
void FileDownloader::StartDownload()
{
if (Status==FFD_START)
return;
Status=FFD_START;
Manager->UpdateScreen(true);
if ( Create() != wxTHREAD_NO_ERROR )
{
wxLogError(wxT("Can't create thread!"));
Status=FFD_ERROR;
ErrorTime=GetTickCount();
Error=ERROR_THREAD_NOT_CREATE;
Manager->UpdateScreen(true);
return;
}
int error = Run();
bAlreadyRun=true;
if ( error == wxTHREAD_RUNNING )
{
wxLogError(wxT("wxTHREAD_RUNNING"));
if (RetryCount<Manager->MaxRetry)
Status=FFD_RETRY;
else
Status=FFD_ERROR;
ErrorTime=GetTickCount();
Error=ERROR_THREAD_NOT_CREATE;
}
}
void FileDownloader::StopDownload()
{
Status = FFD_STOP;
}
size_t FileDownloader::WriteData(void *buffer, size_t size, size_t nmemb, void *userp)
{
StateData *pDT = (StateData*)userp;
if (!pDT)
//return -1;
return size*nmemb;
FileDownloader *pFFD = pDT->pParent;
if (!pFFD)
//return -1;
return size*nmemb;
if (pFFD->Status!=FFD_START)
return 0;
switch (pDT->Type)
{
case StateData::DT_NONE:
return size*nmemb;
break;
case StateData::DT_PAGE:
pFFD->pLinkPageRef.append((char*)buffer,size*nmemb);
return size*nmemb;
break;
case StateData::DT_HEADER:
pFFD->pHeader.append((char*)buffer,size*nmemb);
return size*nmemb;
break;
case StateData::DT_FILE_DATA:
//if (pFFD->iFileSize==-2)
if (pFFD->bStartDL==false)
{
pFFD->bStartDL=true;
// On récupére la taille du fichier finale
curl_off_t Size = Parser::GetFileSizeHTTP(pFFD->pHeader);
/*double size2;
double size3;
curl_easy_getinfo(pFFD->pCurl, CURLINFO_SIZE_DOWNLOAD, &size2);
curl_easy_getinfo(pFFD->pCurl, CURLINFO_REQUEST_SIZE, &size2);
curl_easy_getinfo(pFFD->pCurl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size3);
wxLogMessage("Size: %d Size2: %f",size,size2+size3);*/
//CURLINFO_REQUEST_SIZE
//wxLogMessage("Size: %d",size);
if (pFFD->iDataPos>0)
if (Size!=pFFD->iFileSize)
{
if (pFFD->RetryCount<pFFD->Manager->MaxRetry)
pFFD->Status=FFD_RETRY;
else
pFFD->Status=FFD_ERROR;
pFFD->ErrorTime=GetTickCount();
pFFD->Error=ERROR_DIFFERENT_FILESIZE;
return 0;
}
pFFD->iTime=GetTickCount();
if (Size<=0)
pFFD->iFileSize=-1;
else
pFFD->iFileSize=Size/*+pFFD->iDataPos*/;
}
fseek(pFFD->pOutput,pFFD->iDataPos,SEEK_SET);
int len = fwrite(buffer,size,nmemb,pFFD->pOutput);
//fwrite(&pFFD->iFileSize,sizeof(long),1,pFFD->pOutput);
//fwrite(&pFFD->iDataPos,sizeof(long),1,pFFD->pOutput);
//fwrite(&HeaderSize,sizeof(int),1,pFFD->pOutput);
//End of write header
//float Speed = len*1000/((float)GetTickCount()-pFFD->iTime);
long tick = GetTickCount();
if (tick!=pFFD->iTime)
{
pFFD->iByteDL+=size*nmemb;
if (tick-pFFD->iTime>=1000)
{
pFFD->fSpeed=pFFD->iByteDL*1000.0/(tick-pFFD->iTime);
//long speed=pFFD->fSpeed/1000;
//wxLogMessage("Speed ; %d %d %d %d",speed,size*nmemb,GetTickCount(),pFFD->iTime);
if (pFFD->fMoySpeed==0)
pFFD->fMoySpeed=pFFD->fSpeed;
else
pFFD->fMoySpeed=(pFFD->fMoySpeed+pFFD->fSpeed)/2;
//curl_easy_getinfo(pFFD->pCurl, CURLINFO_SPEED_DOWNLOAD, &(pFFD->fMoySpeed));
pFFD->iTime=GetTickCount();
pFFD->iByteDL=0;
}
}
pFFD->iDataPos+=len;
//pFFD->Manager->UpdateBlocks(pFFD);
if (pFFD->iDataPos==pFFD->iFileSize)
pFFD->Status=FFD_FINISH;
if (len!=size*nmemb)
{
if (pFFD->RetryCount<pFFD->Manager->MaxRetry)
pFFD->Status=FFD_RETRY;
else
pFFD->Status=FFD_ERROR;
pFFD->ErrorTime=GetTickCount();
pFFD->Error=ERROR_FILE_WRITE_ERROR;
pFFD->Manager->UpdateScreen(true);
}
return len;
break;
}
return size*nmemb;
} | [
"CameleonTH@0c2b0ced-2a4c-0410-b056-e1a948518b24"
] | [
[
[
1,
373
]
]
] |
94b7547d97a9d86322ecbf83958224c7bedc5f78 | ed1a161411b6850d6113b640b5b8c776e7cb0f2c | /BIN/Selene.h | ee64cf10bb5dedc69806609221d0d61074824129 | [] | no_license | weimingtom/tiglics | 643d19a616dcae3e474471e3dea868f6631463ba | 450346a441ee6c538e39968311ab60eb9e572746 | refs/heads/master | 2021-01-10T01:36:31.607727 | 2008-08-13T03:35:45 | 2008-08-13T03:35:45 | 48,733,131 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 530,088 | h | #pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
#include <windows.h>
//-----------------------------------------------------------------------------------
// WARNING
//-----------------------------------------------------------------------------------
#pragma inline_depth ( 255 )
#pragma inline_recursion ( on )
#pragma warning ( disable: 4100 )
#pragma warning ( disable: 4819 )
#pragma warning ( disable: 4201 )
#pragma warning ( disable: 4239 )
#pragma warning ( disable: 4995 )
#pragma warning ( disable: 4996 )
#pragma warning ( disable: 4324 )
//-----------------------------------------------------------------------------------
// LIBRARY
//-----------------------------------------------------------------------------------
#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "gdi32.lib" )
#pragma comment( lib, "user32.lib" )
#pragma comment( lib, "comdlg32.lib" )
#pragma comment( lib, "advapi32.lib" )
//-----------------------------------------------------------------------------------
// TYPEDEF
//-----------------------------------------------------------------------------------
typedef char Sint8; ///< signed char 型の別定義
typedef short Sint16; ///< signed short 型の別定義
typedef long Sint32; ///< signed long 型の別定義
typedef long long Sint64; ///< signed long 型の別定義
typedef unsigned char Uint8; ///< unsigned char 型の別定義
typedef unsigned short Uint16; ///< unsigned short 型の別定義
typedef unsigned long Uint32; ///< unsigned long 型の別定義
typedef unsigned long long Uint64; ///< unsigned long long 型の別定義
typedef float Float; ///< float 型の別定義
typedef double Double; ///< double 型の別定義
typedef long Bool; ///< bool 型の別定義
//-----------------------------------------------------------------------------------
// DEFINE
//-----------------------------------------------------------------------------------
#define ef else if ///< else if 簡略用マクロ
#define PI (3.141592653589793238462643383279f) ///< π
#define PI2 (6.283185307179586476925286766559f) ///< 2π
#define REV(val) (1.0f/toF(val)) ///< 逆数算出マクロ
#define AXIS_RANGE_MAX (4096) ///< ジョイスティックの軸の最大値
#define toF(val) ((Float)(val)) ///< floatへのキャスト
#define toI(val) ((Sint32)(val)) ///< intへのキャスト
#define MIN(N1,N2) ((N1 < N2) ? (N1) : (N2)) ///< 最小値取得マクロ
#define MAX(N1,N2) ((N1 > N2) ? (N1) : (N2)) ///< 最大値取得マクロ
#define SWAP(N1,N2) { N1 = N2 - N1; N2 -= N1; N1 += N2; } ///< 値交換マクロ
#define SAFE_ADDREF(val) if ( (val) != NULL ) { (val)->AddRef(); } ///< COM安全AddRefマクロ
#define SAFE_RELEASE(val) if ( (val) != NULL ) { (val)->Release(); (val) = NULL; } ///< COM安全Releaseマクロ
#define SAFE_DELETE(val) if ( (val) != NULL ) { delete (val); (val) = NULL; } ///< newメモリ安全解放
#define SAFE_DELETE_ARRAY(val) if ( (val) != NULL ) { delete [] (val); (val) = NULL; } ///< new[]メモリ安全解放
#define ANGLE_TABLE_BIT (16) ///< サインテーブルのビット数
#define ANGLE_MAX (1 << ANGLE_TABLE_BIT) ///< サインテーブルのサイズ
#define ANGLE_TABLE_MASK (ANGLE_MAX - 1) ///< サインテーブルのアクセス用マスク
#define NORMALIZE_ANGLE(val) ((val) & ANGLE_TABLE_MASK) ///< 角度の正規化
#define DEG_TO_ANGLE(val) toI(toF(val) * toF(ANGLE_MAX) / 360.0f) ///< 度数法から専用角度
#define ANGLE_TO_DEG(val) ((val) * 360 / ANGLE_MAX) ///< 度数法から専用角度
#define PI_TO_ANGLE(val) toI(toF(val) * toF(ANGLE_MAX) / PI2) ///< 弧度法から専用角度
#define ANGLE_TO_PI(val) (toF(val) * PI2 / toF(ANGLE_MAX)) ///< 専用角度から弧度法
#define MemoryClear(PD,S) ::FillMemory((PD),(S),0x00) ///< メモリクリア
#define MemoryFill(PD,PS,S) ::FillMemory((PD),(S),(PS)) ///< メモリ塗りつぶし
#define MemoryMove(PD,PS,S) ::MoveMemory((PD),(PS),(S)) ///< メモリ移動
#define MemoryCopy(PD,PS,S) ::CopyMemory((PD),(PS),(S)) ///< メモリコピー
//-----------------------------------------------------------------------------------
// DEFINE
//-----------------------------------------------------------------------------------
#ifdef LIB_SELENE
# define SELENE_DLL_API
#else // LIB_SELENE
# ifdef DLL_SELENE
# define SELENE_DLL_API __declspec(dllexport)
# else // DLL_SELENE
# define SELENE_DLL_API __declspec(dllimport)
# endif // DLL_SELENE
#endif // LIB_SELENE
//-----------------------------------------------------------------------------------
// ENUM
//-----------------------------------------------------------------------------------
/**
@brief ライブラリ名前空間
*/
namespace Selene
{
/**
@brief 頂点定義
@author 葉迩倭
頂点定義クラスの作成時に指定するフラグです。<BR>
なお VERTEX_ELEMENT_PRIMITIVE、VERTEX_ELEMENT_SPRITE、VERTEX_ELEMENT_3DBASE は<BR>
独立しており排他です。
*/
enum eVertexElement
{
VERTEX_ELEMENT_PRIMITIVE = 1 << 0, ///< 位置と色だけを含む最も単純な2D用頂点
VERTEX_ELEMENT_SPRITE = 1 << 1, ///< 位置と色とテクスチャUVを含む2D用頂点
VERTEX_ELEMENT_3DBASE = 1 << 2, ///< 位置と色を含むもっとも単純な3D頂点
VERTEX_ELEMENT_3DTEXTURE = 1 << 3, ///< テクスチャUVを含む基本的な3D用頂点
VERTEX_ELEMENT_3DLIGHT = 1 << 4, ///< ライティングに関する法線を含む3D頂点
VERTEX_ELEMENT_3DBUMP = 1 << 5, ///< バンプマップに関する接線を含む3D頂点
VERTEX_ELEMENT_3DANIMATION = 1 << 6, ///< スキニングに関するボーンのインデックス&ウェイトを含む3D頂点
};
/**
@brief IParticle用タイプ
@author 葉迩倭
*/
enum eParticleType
{
PARTICLE_TYPE_NORMAL, ///< 通常パーティクル
PARTICLE_TYPE_VOLUME, ///< 疑似ボリュームパーティクル
};
/**
@brief フレームレート定義
@author 葉迩倭
*/
enum eFrameRate
{
FRAME_RATE_60, ///< 1フレーム1/60秒
FRAME_RATE_30, ///< 1フレーム1/30秒
FRAME_RATE_20, ///< 1フレーム1/20秒
FRAME_RATE_15, ///< 1フレーム1/15秒
};
/**
@brief アダプタータイプ
@author 葉迩倭
*/
enum eGraphicCardNo
{
GRAPHIC_CARD_NO1, ///< 1番目に接続されたビデオカード
GRAPHIC_CARD_NO2, ///< 2番目に接続されたビデオカード
GRAPHIC_CARD_DEFAULT_NO = GRAPHIC_CARD_NO1, ///< デフォルトのビデオカード
GRAPHIC_CARD_NV_PERF_HUD = 0xFFFFFFFF, ///< NVPerfHUD専用のビデオカード
};
/**
@brief サーフェイスフォーマット定義
@author 葉迩倭
*/
enum eSurfaceFormat
{
FORMAT_INVALID, ///< 無効
FORMAT_TEXTURE_32BIT, ///< 32Bitテクスチャフォーマットに準拠
FORMAT_TEXTURE_16BIT, ///< 16Bitテクスチャフォーマットに準拠
FORMAT_TEXTURE_DXT, ///< DXT圧縮フォーマットテクスチャ
FORMAT_TARGET_UCHAR4, ///< unsnged char x4 レンダリングターゲット
FORMAT_TARGET_FLOAT1, ///< float x1 レンダリングターゲット
FORMAT_TARGET_FLOAT2, ///< float x2 レンダリングターゲット
FORMAT_TARGET_FLOAT4, ///< float x4 レンダリングターゲット
FORMAT_TARGET_FLOAT4_ALPHA, ///< float x4 アルファ可能レンダリングターゲット
FORMAT_DEPTHBUFFER_SURFACE, ///< 深度バッファ
FORMAT_DEPTHBUFFER_TEXTURE, ///< 深度バッファ
FORMAT_MAX,
FORMAT_TARGET_32BIT = FORMAT_TARGET_UCHAR4,
FORMAT_TARGET_HDR = FORMAT_TARGET_FLOAT4_ALPHA,
};
/**
@brief テクスチャステージ定義
@author 葉迩倭
テクスチャステージに関しての定義です。<BR>
3Dオブジェクトに関しては基本的にシェーダー内で<BR>
UVを計算するようになっているので、<BR>
頂点データとして保持するUVはカラーマップとライトマップだけです。
*/
enum eTextureStage
{
TEXTURE_STAGE_COLOR = 0, ///< カラーマップ
TEXTURE_STAGE_LIGHT, ///< ライトマップ
TEXTURE_STAGE_ENVIRONMENT, ///< キューブ環境
TEXTURE_STAGE_SPECULAR, ///< スペキュラマップ
TEXTURE_STAGE_NORMAL, ///< バンプor視差マップ用法線マップ
TEXTURE_STAGE_SHADOW, ///< シャドウマップ
TEXTURE_STAGE_DEPTH, ///< 深度マップ
TEXTURE_STAGE_TOON, ///< トゥーン用特殊マップ
TEXTURE_STAGE_MAX, ///< テクスチャステージ数
MATERIAL_TEXTURE_MAX = TEXTURE_STAGE_NORMAL + 1,
};
/**
@brief 描画タイプ定義
@author 葉迩倭
各種描画タイプに関しての定義です。
*/
enum eDrawType
{
DRAW_TYPE_NORMAL, ///< 通常描画
DRAW_TYPE_BLEND, ///< 半透明描画
DRAW_TYPE_ADD, ///< 加算描画
DRAW_TYPE_ADD_NOALPHA, ///< 加算描画(アルファ値無効)
DRAW_TYPE_SUB, ///< 減算描画
DRAW_TYPE_SUB_NOALPHA, ///< 減算描画(アルファ値無効)
DRAW_TYPE_MULTIPLE, ///< 乗算描画
};
/**
@brief カリングタイプ定義
@author 葉迩倭
ポリゴンの表裏に描画に関しての定義です。
*/
enum eCullType
{
CULL_FRONT, ///< 表の場合のみ描画
CULL_BACK, ///< 裏の場合のみ描画
CULL_NONE, ///< 裏表両面描画
};
/**
@brief テクスチャフィルタタイプ定義
@author 葉迩倭
ポリゴンの表裏に描画に関しての定義です。
*/
enum eTextureFilterType
{
TEXTURE_FILTER_DISABLE, ///< フィルタリング無し
TEXTURE_FILTER_2D, ///< バイリニアフィルタリング
TEXTURE_FILTER_3D_LOW, ///< バイリニアフィルタリング
TEXTURE_FILTER_3D_MIDDLE, ///< 異方性フィルタリング/低画質
TEXTURE_FILTER_3D_HIGH, ///< 異方性フィルタリング/高画質
};
/**
@brief ファイルシーク定義
@author 葉迩倭
*/
enum eSeekFlag
{
SEEK_FILE_CURRENT, ///< カレント位置
SEEK_FILE_START, ///< 先頭位置
SEEK_FILE_END, ///< 終端位置
};
/**
@brief 頂点変換タイプ
@author 葉迩倭
*/
enum eTransformType
{
TRANSFORM_TYPE_MODEL, ///< モデル用頂点変換
TRANSFORM_TYPE_BILLBOARD, ///< ビルボード用頂点変換
};
/**
@brief バンプタイプ
@author 葉迩倭
*/
enum eBumpType
{
BUMP_TYPE_NONE, ///< バンプ処理なし
BUMP_TYPE_ENABLE, ///< バンプ処理あり
};
/**
@brief スペキュラタイプ
@author 葉迩倭
*/
enum eSpecularType
{
SPECULAR_TYPE_NONE, ///< スペキュラ処理なし
SPECULAR_TYPE_ENABLE, ///< スペキュラ処理あり
};
/**
@brief モーションブラーレベル
@author 葉迩倭
*/
enum eSceneMotionBlurQuarity
{
MOTION_BLUR_LIGHT, ///< モデル引き延ばしを行わない軽量なブラー
MOTION_BLUR_FULL, ///< モデル引き延ばしを行うブラー
MOTION_BLUR_MAX
};
/**
@brief 被写界深度タイプ
@author 葉迩倭
*/
enum eSceneDepthOfFieldType
{
DOF_TYPE_DISABLE, ///< 被写界深度なし
DOF_TYPE_ENABLE, ///< 被写界深度あり
};
/**
@brief フォグタイプ
@author 葉迩倭
*/
enum eSceneFogType
{
FOG_TYPE_DISABLE, ///< フォグなし
FOG_TYPE_ENABLE, ///< フォグあり
};
/**
@brief アンチエイリアスタイプ
@author 葉迩倭
*/
enum eSceneAntiAliasType
{
AA_TYPE_DISABLE, ///< アンチエイリアスなし
AA_TYPE_ENABLE, ///< アンチエイリアスあり
};
/**
@brief フォグエフェクト
@author 葉迩倭
*/
enum eSceneFogEffect
{
FOG_EFFECT_LINEAR, ///< 線形フォグ
// FOG_EFFECT_SCATTERING, ///< スキャッタリング
};
/**
@brief シェーディングタイプ
@author 葉迩倭
*/
enum eSceneShadingType
{
SHADING_TYPE_NORMAL, ///< 通常のシェーディング
SHADING_TYPE_TOON, ///< トゥーン風シェーディング
SHADING_TYPE_HATCHING, ///< ハッチング風シェーディング
};
/**
@brief シーン用モーションブラータイプ
@author 葉迩倭
*/
enum eSceneMotionBlurType
{
MOTION_BLUR_TYPE_DISABLE, ///< なし
MOTION_BLUR_TYPE_LOW, ///< クオリティ低:4サンプリング
MOTION_BLUR_TYPE_HIGH, ///< クオリティ高:8サンプリング
};
/**
@brief シーン用シャドウマップタイプ
@author 葉迩倭
*/
enum eSceneShadowType
{
SHADOW_TYPE_DISABLE, ///< 影なし
SHADOW_TYPE_PROJECTION, ///< プロジェクションシャドウ
SHADOW_TYPE_SHADOWMAP, ///< シャドウマッピング
};
/**
@brief シーン用シャドウクオリティタイプ
@author 葉迩倭
*/
enum eSceneShadowQuarity
{
SHADOW_QUARITY_LOW, ///< 低解像度(512x512)
SHADOW_QUARITY_MIDDLE, ///< 低解像度(1024x1024)
SHADOW_QUARITY_HIGH, ///< 低解像度(2048x2048)
SHADOW_QUARITY_BEST, ///< 低解像度(4096x4096)
};
/**
@brief HDR処理
@author 葉迩倭
*/
enum eSceneHighDynamicRangeType
{
HDR_TYPE_DISABLE, ///< HDR処理なし
HDR_TYPE_ENABLE, ///< HDR処理あり
};
/**
@brief HDRエフェクト
@author 葉迩倭
*/
enum eSceneHighDynamicRangeEffect
{
HDR_EFFECT_BLOOM, ///< ブルーム処理
HDR_EFFECT_CROSS, ///< クロスフィルタ
};
/**
@brief 投影シャドウ用種類
@author 葉迩倭
*/
enum eProjectionShadowType
{
PROJECTION_SHADOW_DISABLE, ///< 影を落とさず、影の影響もない
PROJECTION_SHADOW_DROP_SIMPLE, ///< 丸影を落とし、影の影響は受けない
PROJECTION_SHADOW_DROP_SHAPE, ///< モデルの形状の影を落とし、影の影響は受けない
};
/**
@brief 投影シャドウ用プライオリティ
@author 葉迩倭
*/
enum eProjectionShadowPriority
{
PROJECTION_SHADOW_PRIORITY_0, ///< 影を落とさない
PROJECTION_SHADOW_PRIORITY_1, ///< PROJECTION_SHADOW_PRIORITY_0以下に影を落とす
PROJECTION_SHADOW_PRIORITY_2, ///< PROJECTION_SHADOW_PRIORITY_1以下に影を落とす
PROJECTION_SHADOW_PRIORITY_3, ///< PROJECTION_SHADOW_PRIORITY_2以下に影を落とす
PROJECTION_SHADOW_PRIORITY_4, ///< PROJECTION_SHADOW_PRIORITY_3以下に影を落とす
PROJECTION_SHADOW_PRIORITY_MAX,
};
/**
@brief ボタン状態
@author 葉迩倭
*/
enum eInputButtonState
{
BUTTON_STATE_FREE, ///< 押していない状態取得用
BUTTON_STATE_HOLD, ///< 押し続けている状態取得用
BUTTON_STATE_PUSH, ///< 押した瞬間取得用
BUTTON_STATE_PULL, ///< 離した瞬間取得用
BUTTON_STATE_MAX,
};
/**
@brief 軸定義
@author 葉迩倭
*/
enum eInputAxisType
{
AXIS_TYPE_01, ///< 1番目の軸
AXIS_TYPE_02, ///< 2番目の軸
AXIS_TYPE_03, ///< 3番目の軸
AXIS_TYPE_04, ///< 4番目の軸
AXIS_TYPE_MAX,
};
/**
@brief ボタン種類
@author 葉迩倭
*/
enum eInputButtonType
{
BUTTON_AXIS1_UP, ///< 上方向指定
BUTTON_AXIS1_DOWN, ///< 下方向指定
BUTTON_AXIS1_LEFT, ///< 左方向指定
BUTTON_AXIS1_RIGHT, ///< 右方向指定
BUTTON_AXIS2_UP, ///< 上方向指定
BUTTON_AXIS2_DOWN, ///< 下方向指定
BUTTON_AXIS2_LEFT, ///< 左方向指定
BUTTON_AXIS2_RIGHT, ///< 右方向指定
BUTTON_AXIS3_UP, ///< 上方向指定
BUTTON_AXIS3_DOWN, ///< 下方向指定
BUTTON_AXIS3_LEFT, ///< 左方向指定
BUTTON_AXIS3_RIGHT, ///< 右方向指定
BUTTON_AXIS4_UP, ///< 上方向指定
BUTTON_AXIS4_DOWN, ///< 下方向指定
BUTTON_AXIS4_LEFT, ///< 左方向指定
BUTTON_AXIS4_RIGHT, ///< 右方向指定
BUTTON_01, ///< ボタン1指定
BUTTON_02, ///< ボタン2指定
BUTTON_03, ///< ボタン3指定
BUTTON_04, ///< ボタン4指定
BUTTON_05, ///< ボタン5指定
BUTTON_06, ///< ボタン6指定
BUTTON_07, ///< ボタン7指定
BUTTON_08, ///< ボタン8指定
BUTTON_09, ///< ボタン9指定
BUTTON_10, ///< ボタン10指定
BUTTON_11, ///< ボタン11指定
BUTTON_12, ///< ボタン12指定
BUTTON_13, ///< ボタン13指定
BUTTON_14, ///< ボタン14指定
BUTTON_15, ///< ボタン15指定
BUTTON_16, ///< ボタン16指定
BUTTON_AXIS_MAX,
BUTTON_MAX = BUTTON_16 - BUTTON_01,
AXIS_MAX = BUTTON_AXIS4_RIGHT - BUTTON_AXIS1_UP,
BUTTON_DISABLE, ///< 無効
};
/**
@brief ジョイスティック軸方向定義
@author 葉迩倭
*/
enum ePadAxisDirection
{
PAD_AXIS_X, ///< X軸
PAD_AXIS_Y, ///< Y軸
PAD_AXIS_Z, ///< Z軸
PAD_AXIS_DIRECTION_MAX,
};
/**
@brief ジョイスティック軸種類定義
@author 葉迩倭
*/
enum ePadAxisType
{
PAD_AXIS_POSITION,
PAD_AXIS_POSITION_ROTATE,
PAD_AXIS_VELOCITY,
PAD_AXIS_VELOCITY_ROTATE,
PAD_AXIS_ACCEL,
PAD_AXIS_ACCEL_ROTATE,
PAD_AXIS_FORCE,
PAD_AXIS_FORCE_ROTATE,
PAD_AXIS_POV,
PAD_AXIS_MAX,
};
/**
@brief ジョイスティックスライダー定義
@author 葉迩倭
*/
enum ePadSliderType
{
PAD_SLIDER_0, ///< 1番目のスライダー
PAD_SLIDER_1, ///< 2番目のスライダー
PAD_SLIDER_2, ///< 3番目のスライダー
PAD_SLIDER_3, ///< 4番目のスライダー
PAD_SLIDER_MAX,
};
/**
@brief ジョイスティックボタン定義
@author 葉迩倭
*/
enum ePadButtonType
{
PAD_BUTTON_01,
PAD_BUTTON_02,
PAD_BUTTON_03,
PAD_BUTTON_04,
PAD_BUTTON_05,
PAD_BUTTON_06,
PAD_BUTTON_07,
PAD_BUTTON_08,
PAD_BUTTON_09,
PAD_BUTTON_10,
PAD_BUTTON_11,
PAD_BUTTON_12,
PAD_BUTTON_13,
PAD_BUTTON_14,
PAD_BUTTON_15,
PAD_BUTTON_16,
PAD_BUTTON_MAX,
};
/**
@brief 仮想キーコード
@author 葉迩倭
*/
enum eVirtualKeyCode
{
SELENE_VK_ESCAPE = 0x01,
SELENE_VK_1 = 0x02,
SELENE_VK_2 = 0x03,
SELENE_VK_3 = 0x04,
SELENE_VK_4 = 0x05,
SELENE_VK_5 = 0x06,
SELENE_VK_6 = 0x07,
SELENE_VK_7 = 0x08,
SELENE_VK_8 = 0x09,
SELENE_VK_9 = 0x0A,
SELENE_VK_0 = 0x0B,
SELENE_VK_MINUS = 0x0C,
SELENE_VK_EQUALS = 0x0D,
SELENE_VK_BACK = 0x0E,
SELENE_VK_TAB = 0x0F,
SELENE_VK_Q = 0x10,
SELENE_VK_W = 0x11,
SELENE_VK_E = 0x12,
SELENE_VK_R = 0x13,
SELENE_VK_T = 0x14,
SELENE_VK_Y = 0x15,
SELENE_VK_U = 0x16,
SELENE_VK_I = 0x17,
SELENE_VK_O = 0x18,
SELENE_VK_P = 0x19,
SELENE_VK_LBRACKET = 0x1A,
SELENE_VK_RBRACKET = 0x1B,
SELENE_VK_RETURN = 0x1C,
SELENE_VK_LCONTROL = 0x1D,
SELENE_VK_A = 0x1E,
SELENE_VK_S = 0x1F,
SELENE_VK_D = 0x20,
SELENE_VK_F = 0x21,
SELENE_VK_G = 0x22,
SELENE_VK_H = 0x23,
SELENE_VK_J = 0x24,
SELENE_VK_K = 0x25,
SELENE_VK_L = 0x26,
SELENE_VK_SEMICOLON = 0x27,
SELENE_VK_APOSTROPHE = 0x28,
SELENE_VK_GRAVE = 0x29,
SELENE_VK_LSHIFT = 0x2A,
SELENE_VK_BACKSLASH = 0x2B,
SELENE_VK_Z = 0x2C,
SELENE_VK_X = 0x2D,
SELENE_VK_C = 0x2E,
SELENE_VK_V = 0x2F,
SELENE_VK_B = 0x30,
SELENE_VK_N = 0x31,
SELENE_VK_M = 0x32,
SELENE_VK_COMMA = 0x33,
SELENE_VK_PERIOD = 0x34,
SELENE_VK_SLASH = 0x35,
SELENE_VK_RSHIFT = 0x36,
SELENE_VK_MULTIPLY = 0x37,
SELENE_VK_LMENU = 0x38,
SELENE_VK_SPACE = 0x39,
SELENE_VK_CAPITAL = 0x3A,
SELENE_VK_F1 = 0x3B,
SELENE_VK_F2 = 0x3C,
SELENE_VK_F3 = 0x3D,
SELENE_VK_F4 = 0x3E,
SELENE_VK_F5 = 0x3F,
SELENE_VK_F6 = 0x40,
SELENE_VK_F7 = 0x41,
SELENE_VK_F8 = 0x42,
SELENE_VK_F9 = 0x43,
SELENE_VK_F10 = 0x44,
SELENE_VK_NUMLOCK = 0x45,
SELENE_VK_SCROLL = 0x46,
SELENE_VK_NUMPAD7 = 0x47,
SELENE_VK_NUMPAD8 = 0x48,
SELENE_VK_NUMPAD9 = 0x49,
SELENE_VK_SUBTRACT = 0x4A,
SELENE_VK_NUMPAD4 = 0x4B,
SELENE_VK_NUMPAD5 = 0x4C,
SELENE_VK_NUMPAD6 = 0x4D,
SELENE_VK_ADD = 0x4E,
SELENE_VK_NUMPAD1 = 0x4F,
SELENE_VK_NUMPAD2 = 0x50,
SELENE_VK_NUMPAD3 = 0x51,
SELENE_VK_NUMPAD0 = 0x52,
SELENE_VK_DECIMAL = 0x53,
SELENE_VK_OEM_102 = 0x56,
SELENE_VK_F11 = 0x57,
SELENE_VK_F12 = 0x58,
SELENE_VK_KANA = 0x70,
SELENE_VK_ABNT_C1 = 0x73,
SELENE_VK_CONVERT = 0x79,
SELENE_VK_NOCONVERT = 0x7B,
SELENE_VK_YEN = 0x7D,
SELENE_VK_ABNT_C2 = 0x7E,
SELENE_VK_NUMPADEQUALS = 0x8D,
SELENE_VK_PREVTRACK = 0x90,
SELENE_VK_NUMPADENTER = 0x9C,
SELENE_VK_RCONTROL = 0x9D,
SELENE_VK_NUMPADCOMMA = 0xB3,
SELENE_VK_DIVIDE = 0xB5,
SELENE_VK_SYSRQ = 0xB7,
SELENE_VK_RMENU = 0xB8,
SELENE_VK_PAUSE = 0xC5,
SELENE_VK_HOME = 0xC7,
SELENE_VK_UP = 0xC8,
SELENE_VK_PRIOR = 0xC9,
SELENE_VK_LEFT = 0xCB,
SELENE_VK_RIGHT = 0xCD,
SELENE_VK_END = 0xCF,
SELENE_VK_DOWN = 0xD0,
SELENE_VK_NEXT = 0xD1,
SELENE_VK_INSERT = 0xD2,
SELENE_VK_DELETE = 0xD3,
SELENE_VK_LWIN = 0xDB,
SELENE_VK_RWIN = 0xDC,
SELENE_VK_DISABLE = 0x00
};
/**
@brief マウスボタン状態定義
@author 葉迩倭
*/
enum eMouseState
{
MOUSE_FREE, ///< マウスボタンは押されていない
MOUSE_PULL, ///< マウスボタンは離された
MOUSE_PUSH, ///< マウスボタンは押された
MOUSE_HOLD, ///< マウスボタンは押されつづけている
};
/**
@brief 物理シミュレーション用接触点定義
@author 葉迩倭
*/
enum eContactMode
{
ContactMu2 = 0x001,
ContactFDir1 = 0x002,
ContactBounce = 0x004,
ContactSoftERP = 0x008,
ContactSoftCFM = 0x010,
ContactMotion1 = 0x020,
ContactMotion2 = 0x040,
ContactSlip1 = 0x080,
ContactSlip2 = 0x100,
ContactApprox0 = 0x0000,
ContactApprox1_1 = 0x1000,
ContactApprox1_2 = 0x2000,
ContactApprox1 = 0x3000,
};
/**
@brief 描画系
*/
namespace Renderer
{
/**
@brief シェーダー系
*/
namespace Shader
{
}
/**
@brief 描画オブジェクト系
*/
namespace Object
{
}
}
/**
@brief ファイル系
*/
namespace File
{
}
namespace Scene
{
}
/**
@brief 入力デバイス系
*/
namespace Peripheral
{
}
/**
@brief サウンド系
*/
namespace Sound
{
}
/**
@brief システム系
*/
namespace System
{
}
/**
@brief 算術演算系
*/
namespace Math
{
}
/**
@brief 数値補間系
*/
namespace Interpolation
{
}
/**
@brief コリジョン系
*/
namespace Collision
{
}
/**
@brief 物理シミュレーション系
*/
namespace Dynamics
{
class IRigidModel;
class IRigidBody;
class IContactPoint;
class ISimulationWorld;
}
/**
@brief スレッド系
*/
namespace Thread
{
}
/**
@brief シーン系
*/
namespace Scene
{
}
/**
@brief ファイル系
*/
namespace File
{
}
/**
@brief ファイバー系
*/
namespace Fiber
{
}
/**
@brief ネットワーク系
*/
namespace Network
{
class INetworkManager;
class ISocketTCP;
class IServerTCP;
class IServerClientTCP;
}
}
//-----------------------------------------------------------------------------------
// INTERFACE
//-----------------------------------------------------------------------------------
namespace Selene
{
class ICore;
class IGraphicCard;
namespace Renderer
{
class IRender;
class ITexture;
class ITexture;
namespace Shader
{
class IShader;
}
namespace Object
{
class IPoint2D;
class ILine2D;
class IPrimitive2D;
class ISprite2D;
class IFontSprite2D;
class IPoint3D;
class ILine3D;
class IPrimitive3D;
class ISprite3D;
class IFontSprite3D;
class IParticle;
class IModel;
class IMapModel;
}
}
namespace Fiber
{
class IFiber;
class IFiberController;
};
namespace Peripheral
{
class IMouse;
class IKeyboard;
class IJoystick;
class IInputController;
}
namespace File
{
class IFileManager;
class IResourceFile;
}
namespace Sound
{
class ISound;
class IStreamSound;
}
namespace Scene
{
class IPrimitiveActor;
class ISpriteActor;
class IParticleActor;
class IModelActor;
class IMapActor;
class ICamera;
class ISceneManager;
class ICustomizedSceneManager;
class ICustomizedSceneRenderMaterial;
class ICustomizedSceneRenderObject;
}
namespace Dynamics
{
class ISimulationWorld;
class IRigidBody;
class IRigidModel;
class IContactPoint;
}
namespace Math
{
class Vector2D;
class Vector3D;
class Vector4D;
class Quaternion;
class Matrix;
class Style;
}
}
//-----------------------------------------------------------------------------------
// INLINE
//-----------------------------------------------------------------------------------
namespace Selene
{
inline void Float2Int( Sint32 &iVal, Float fVal )
{
*((Uint32*)&iVal) = *((Uint32*)&fVal);
}
inline void Int2Float( Float &fVal, Sint32 iVal )
{
*((Uint32*)&fVal) = *((Uint32*)&iVal);
}
inline Float FastSqrt( Float fVal )
{
Float fRetVal;
Sint32 iVal;
Float2Int( iVal, fVal );
iVal &= 0x7FFFFFFF;
iVal -= 0x3F800000;
iVal >>= 1;
iVal += 0x3F800000;
Int2Float( fRetVal, iVal );
return fRetVal;
}
inline float InvSqrt( float fVal )
{
Sint32 iVal;
Float fValHalf = fVal * 0.5f;
Float2Int( iVal, fVal );
iVal = 0x5F375A86 - (iVal >> 1);
Int2Float( fVal, iVal );
return fVal * (1.5f - fValHalf * fVal * fVal);
}
inline Float Abs( Float fVal )
{
Sint32 iVal;
Float2Int( iVal, fVal );
iVal &= 0x7FFFFFFF;
Int2Float( fVal, iVal );
return fVal;
}
inline Sint32 Abs( Sint32 iVal )
{
return iVal & 0x7FFFFFFF;
}
inline Bool Is2ByteChara( char Src )
{
unsigned char Code = *((unsigned char*)&Src);
if ( Code <= 0x80 ) return false; // 制御コード&文字
if ( Code <= 0x9F ) return true;
if ( Code <= 0xDF ) return false; // 半角カナ
if ( Code <= 0xFE ) return true;
return false;
}
}
#pragma once
/**
@file
@brief 色表現用クラス
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
/**
@brief 色情報管理クラス
@author 葉迩倭
@note
各種データの色を定義するためのクラスです。<BR>
ライブラリ内で色を指定する場合はすべてこのクラスを使います。
*/
class CColor
{
public:
union {
struct {
Uint8 b; ///< 色の青成分
Uint8 g; ///< 色の緑成分
Uint8 r; ///< 色の赤成分
Uint8 a; ///< 色の透明度成分
};
Sint32 Color; ///< 色の32Bit整数表記
};
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CColor()
{
}
/**
@brief コンストラクタ
@author 葉迩倭
@param r [in] 赤成分(0〜255)
@param g [in] 緑成分(0〜255)
@param b [in] 青成分(0〜255)
@param a [in] アルファ成分(0〜255)
*/
CColor( Sint32 r, Sint32 g, Sint32 b, Sint32 a = 255 )
{
this->a = (Uint8)a;
this->r = (Uint8)r;
this->g = (Uint8)g;
this->b = (Uint8)b;
}
/**
@brief コンストラクタ
@author 葉迩倭
@param Color [in] 色成分
*/
CColor( Sint32 Color )
{
this->Color = Color;
}
/**
@brief 色ブレンド
@author 葉迩倭
@param SrcA [in] 色成分
@param SrcB [in] 色成分
@param fRate [in] ブレンド率
@note
2つの色をブレンドします。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Selene::CColor ColorA( 255, 255, 255, 255 );
Selene::CColor ColorB( 128, 128, 128, 128 );
// ColorAとColorBを50%でブレンド
Selene::CColor Ret;
Ret.Blend( ColorA, ColorB, 0.5f );
return 0;
}
@endcode
*/
CColor &Blend( const CColor &SrcA, const CColor &SrcB, Float fRate )
{
if ( fRate < 0.0f ) fRate = 0.0f;
if ( fRate > 1.0f ) fRate = 1.0f;
r = (Uint8)(toF(SrcA.r) + (toF(SrcB.r - SrcA.r) * fRate));
g = (Uint8)(toF(SrcA.g) + (toF(SrcB.g - SrcA.g) * fRate));
b = (Uint8)(toF(SrcA.b) + (toF(SrcB.b - SrcA.b) * fRate));
a = (Uint8)(toF(SrcA.a) + (toF(SrcB.a - SrcA.a) * fRate));
return *this;
}
/**
@brief オペレーター=演算子
@author 葉迩倭
*/
CColor operator = ( const CColor &Color )
{
this->a = Color.a;
this->r = Color.r;
this->g = Color.g;
this->b = Color.b;
return *this;
}
/**
@brief オペレーター=演算子
@author 葉迩倭
*/
CColor operator = ( Sint32 Color )
{
this->Color = Color;
return *this;
}
/**
@brief 型変換
@author 葉迩倭
*/
operator Sint32 () const
{
return Color;
}
public:
/**
@brief 色取得
@author 葉迩倭
@note
RGBAカラー取得
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Selene::CColor Color = Selene::CColor::RGBA( 255, 255, 255, 255 );
return 0;
}
@endcode
*/
static CColor RGBA( Sint32 r, Sint32 g, Sint32 b, Sint32 a )
{
return CColor( r, g, b, a );
}
/**
@brief 色取得
@author 葉迩倭
@note
BGRAカラー取得
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Selene::CColor Color = Selene::CColor::BGRA( 255, 255, 255, 255 );
return 0;
}
@endcode
*/
static CColor BGRA( Sint32 b, Sint32 g, Sint32 r, Sint32 a )
{
return CColor( r, g, b, a );
}
/**
@brief 色取得
@author 葉迩倭
@note
ARGBカラー取得
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Selene::CColor Color = Selene::CColor::ARGB( 255, 255, 255, 255 );
return 0;
}
@endcode
*/
static CColor ARGB( Sint32 a, Sint32 r, Sint32 g, Sint32 b )
{
return CColor( r, g, b, a );
}
/**
@brief 色取得
@author 葉迩倭
@note
XRGBカラー取得
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Selene::CColor Color = Selene::CColor::XRGB( 255, 255, 255 );
return 0;
}
@endcode
*/
static CColor XRGB( Sint32 r, Sint32 g, Sint32 b )
{
return CColor( r, g, b, 255 );
}
};
}
#pragma once
/**
@file
@brief システム系関数群
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace System
{
/**
@brief システム初期化
@author 葉迩倭
@param IsSetExePath [in] カレントディレクトリを実行ファイルの場所に強制的に変更するかの有無
@param IsCreateLogFile [in] ログファイルを生成するかどうか
@param IsSSE [in] SSEの使用有無
@retval true 成功
@retval false 失敗
@note
Seleneシステムの初期化を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// システムの起動
if ( System::Initialize() )
{
}
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Initialize( Bool IsSetExePath = true, Bool IsCreateLogFile = true, Bool IsSSE = true );
/**
@brief システム終了
@author 葉迩倭
@note
Seleneシステムの終了をします。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// システムの起動
if ( System::Initialize() )
{
}
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
SELENE_DLL_API void Finalize( void );
/**
@brief 多重起動ブロック
@author 葉迩倭
@param pApplicationName [in] アプリケーション名
@retval false 既に同名のアプリケーションが起動している
@retval true 同名のアプリケーションは存在しない
@note
返り値false時にアプリケーションを終了させることで<BR>
多重起動を防止することができます。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// システムの起動
if ( System::Initialize() )
{
// 多重起動チェック
if ( System::BlockDualBoot( "Application Name" ) )
{
}
}
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
SELENE_DLL_API Bool BlockDualBoot( const char *pApplicationName );
/**
@brief カレントディレクトリリセット
@author 葉迩倭
@note
カレントディレクトリをアプリケーションの実行フォルダに設定します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// システムの起動
if ( System::Initialize() )
{
// カレントディレクトリを実行ファイルのフォルダにする
System::ResetCurrentDirectory();
}
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
SELENE_DLL_API void ResetCurrentDirectory( void );
/**
@brief ディレクトリ生成
@author 葉迩倭
@param pPath [in] フォルダパス
@note
指定パスへディレクトリを生成します。<BR>
途中のフォルダが存在しない場合、全ての階層に対してフォルダを作成していきます。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// システムの起動
if ( System::Initialize() )
{
// カレントディレクトリを実行ファイルのフォルダにする
System::ResetCurrentDirectory();
// カレントディレクトリの場所以下にフォルダ生成
// ※実行ファイルの場所にフォルダを掘る
System::DirectoryCreate( "Save\\Config" );
}
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
SELENE_DLL_API void DirectoryCreate( const char *pPath );
/**
@brief Coreの取得
@author 葉迩倭
@return ICoreインターフェイス
@note
ウィンドウを管理するICoreクラスを生成/取得します。<BR>
現在、1つのICoreしか生成できません。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
// システムの起動
if ( System::Initialize() )
{
// ICoreの生成
ICore *pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
SELENE_DLL_API ICore *CreateCore( void );
/**
@brief SSEのサポートの有無
@author 葉迩倭
@return SSEのサポートの有無
@note
使用しているCPUがSSEをサポートしているかを調べます。<BR>
この関数はInitialize()のIsSSEにfalseを指定するとかならずfalseを返します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// システムの起動
if ( System::Initialize() )
{
// SSEサポートしてる?
if ( System::IsSupportSSE() )
{
// SSEでSIMD演算
}
else
{
// FPUで普通に演算
}
}
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
SELENE_DLL_API Bool IsSupportSSE( void );
/**
@brief 使用するCPU番号を設定
@author 葉迩倭
@param No [in] CPU番号
@note
現在のスレッドで使用するCPUの番号を設定します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// システムの起動
if ( System::Initialize() )
{
// 現在のスレッドをCPU1で動かす
System::SetThreadCPUNo( 1 );
}
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
SELENE_DLL_API void SetThreadCPUNo( Sint32 No );
}
}
#pragma once
/**
@file
@brief システム系関数群
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Dynamics
{
/**
@brief ダイナミクス用ワールド生成
@author 葉迩倭
@return ワールドのインターフェイス
@note
Dynamics(ODE)のワールドの生成を行います。
@code
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// ワールドの生成
ISimulationWorld *pWorld = CreateWorld();
// 略
…
// ワールドの解放
SAFE_RELEASE( pWorld );
return 0;
}
@endcode
*/
SELENE_DLL_API ISimulationWorld *CreateWorld( Scene::ISceneManager *pScene = NULL );
}
}
#pragma once
/**
@file
@brief システム系関数群
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Network
{
/**
@brief ネットワークマネージャーインターフェイス生成
@author 葉迩倭
@return ネットワークマネージャーインターフェイス
@note
新規のネットワークマネージャーインターフェイスを生成します。<BR>
ネットワークのパスなどの設定は全てINetworkManagerを経由して行います。
取得したネットワークマネージャーインターフェイスは使用終了後には必ずRelease()して下さい。。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
Network::INetworkManager *pNetworkMgr = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
SELENE_DLL_API INetworkManager *CreateManager( void );
}
}
#pragma once
/**
@file
@brief クリティカルセクション操作
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Thread
{
/**
@brief クリティカルセクション管理クラス
@author 葉迩倭
*/
class SELENE_DLL_API CCriticalSection
{
private:
CRITICAL_SECTION m_CriticalSection; ///< クリティカルセクション
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CCriticalSection();
/**
@brief デストラクタ
@author 葉迩倭
*/
virtual ~CCriticalSection();
/**
@brief クリティカルセクションに入る
@author 葉迩倭
@note
クリティカルセクションに入ります。
@code
using namespace Selene;
CriticalSection cs;
Sint32 g_Result = 0;
void CThreadProc( void *pData )
{
// 変数にアクセス前にロック
cs.Enter();
// 適当
for ( Sint32 i = 0; i < 100000; )
{
g_Result += i * i;
}
// 変数使い終わったのでアクセスロック解除
cs.Leave();
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// 適当に待ってる
Sleep( 1000 );
// 変数にアクセス前にロック
cs.Enter();
// 結果をゲット
Sint32 ret = g_Result;
// 変数使い終わったのでアクセスロック解除
cs.Leave();
// スレッド終わってる?
while ( !CThread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
void Enter( void ) const;
/**
@brief クリティカルセクションから抜ける
@author 葉迩倭
@note
クリティカルセクションから抜けます。
@code
using namespace Selene;
CriticalSection cs;
Sint32 g_Result = 0;
void CThreadProc( void *pData )
{
// 変数にアクセス前にロック
cs.Enter();
// 適当
for ( Sint32 i = 0; i < 100000; )
{
g_Result += i * i;
}
// 変数使い終わったのでアクセスロック解除
cs.Leave();
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// 適当に待ってる
Sleep( 1000 );
// 変数にアクセス前にロック
cs.Enter();
// 結果をゲット
Sint32 ret = g_Result;
// 変数使い終わったのでアクセスロック解除
cs.Leave();
// スレッド終わってる?
while ( !CThread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
void Leave( void ) const;
};
/**
@brief 自動クリティカルセクション管理クラス
@author 葉迩倭
*/
class CAutoLock
{
private:
const CCriticalSection &m_cs; ///< 使用するクリティカルセクション
private:
/**
@brief = オペレーター
@author 葉迩倭
@param Lock [in] 入力
@return 入力と同じもの
コンパイルを通すためのダミー用。
*/
CAutoLock & operator = ( CAutoLock &Lock ) {
return Lock;
}
public:
/**
@brief コンストラクタ
@author 葉迩倭
@param cs [in] クリティカルセクション
@note
コンストラクタ内で自動的にクリティカルセクションに入ります。
@code
using namespace Selene;
CriticalSection cs;
Sint32 g_Result = 0;
void CThreadProc( void *pData )
{
// Lockのコンストラクタ内で
// csがクリティカルセクションに入る
CAutoLock Lock( cs );
// 適当
for ( Sint32 i = 0; i < 100000; )
{
g_Result += i * i;
}
// スコープから抜けるときにLockのデストラクタがコールされ
// csがクリティカルセクションから抜ける
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// 適当に待ってる
Sleep( 1000 );
// 変数にアクセス前にロック
cs.Enter();
// 結果をゲット
Sint32 ret = g_Result;
// 変数使い終わったのでアクセスロック解除
cs.Leave();
// スレッド終わってる?
while ( !CThread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
CAutoLock( const CCriticalSection &cs )
: m_cs ( cs )
{
m_cs.Enter();
}
/**
@brief コンストラクタ
@author 葉迩倭
@param cs [in] クリティカルセクション
@note
コンストラクタ内で自動的にクリティカルセクションに入ります。
@code
using namespace Selene;
CriticalSection cs;
Sint32 g_Result = 0;
void CThreadProc( void *pData )
{
// Lockのコンストラクタ内で
// csがクリティカルセクションに入る
CAutoLock Lock( &cs );
// 適当
for ( Sint32 i = 0; i < 100000; )
{
g_Result += i * i;
}
// スコープから抜けるときにLockのデストラクタがコールされ
// csがクリティカルセクションから抜ける
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// 適当に待ってる
Sleep( 1000 );
// 変数にアクセス前にロック
cs.Enter();
// 結果をゲット
Sint32 ret = g_Result;
// 変数使い終わったのでアクセスロック解除
cs.Leave();
// スレッド終わってる?
while ( !CThread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
CAutoLock( const CCriticalSection *cs )
: m_cs ( *cs )
{
m_cs.Enter();
}
/**
@brief デストラクタ
@author 葉迩倭
@note
デストラクタが呼ばれる時に自動的にクリティカルセクションから出ます。
@code
using namespace Selene;
CriticalSection cs;
Sint32 g_Result = 0;
void CThreadProc( void *pData )
{
// Lockのコンストラクタ内で
// csがクリティカルセクションに入る
CAutoLock Lock( &cs );
// 適当
for ( Sint32 i = 0; i < 100000; )
{
g_Result += i * i;
}
// スコープから抜けるときにLockのデストラクタがコールされ
// csがクリティカルセクションから抜ける
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// 適当に待ってる
Sleep( 1000 );
// 変数にアクセス前にロック
cs.Enter();
// 結果をゲット
Sint32 ret = g_Result;
// 変数使い終わったのでアクセスロック解除
cs.Leave();
// スレッド終わってる?
while ( !CThread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
~CAutoLock()
{
m_cs.Leave();
}
};
}
}
#pragma once
/**
@file
@brief イベント操作
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Thread
{
/**
@brief スレッド用イベントオブジェクト
@author 葉迩倭
*/
class SELENE_DLL_API CEvent
{
private:
HANDLE m_EventHandle[MAXIMUM_WAIT_OBJECTS]; ///< イベントハンドル
Sint32 m_HandleCount; ///< イベント数
public:
/**
@brief コンストラクタ
@author 葉迩倭
@param IsSignal [in] シグナル状態で初期化する場合はtrue
@param Count [in] イベントのカウント(MAXIMUM_WAIT_OBJECTS以下)
*/
CEvent( Bool IsSignal = false, Sint32 Count = 1 );
/**
@brief デストラクタ
@author 葉迩倭
*/
virtual ~CEvent();
/**
@brief 指定されたイベントをシグナル状態に設定
@author 葉迩倭
@param No [in] シグナル状態するイベントの番号
@note
指定した番号のイベントをシグナル状態に設定します。
@code
using namespace Selene;
// 5個のイベント生成
Event Event( false, 5 );
void ThreadProc( void *pData )
{
// No=3のイベントがシグナル?
while ( !Event.IsSignal( 3 ) )
{
// しばし待つ
Sleep( 1000 );
}
// No=3のイベントを非シグナルにする
Event.Reset( 3 );
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Thread Thread;
// スレッド生成
Thread.Create( ThreadProc, NULL );
// 適当に待ってるふり
Sleep( 1000 );
// No=3のイベントをシグナルにする
Event.Set( 3 );
// スレッド終わってる?
while ( !Thread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
virtual void Set( Sint32 No = 0 );
/**
@brief 指定されたイベントを非シグナル状態に設定
@author 葉迩倭
@param No [in] 非シグナル状態するイベントの番号
@note
指定した番号のイベンとぉ非シグナル状態に設定します。
@code
using namespace Selene;
// 5個のイベント生成
Event Event( false, 5 );
void ThreadProc( void *pData )
{
// No=3のイベントがシグナル?
while ( !Event.IsSignal( 3 ) )
{
// しばし待つ
Sleep( 1000 );
}
// No=3のイベントを非シグナルにする
Event.Reset( 3 );
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Thread Thread;
// スレッド生成
Thread.Create( ThreadProc, NULL );
// 適当に待ってるふり
Sleep( 1000 );
// No=3のイベントをシグナルにする
Event.Set( 3 );
// スレッド終わってる?
while ( !Thread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
virtual void Reset( Sint32 No = 0 );
/**
@brief 指定したイベントがシグナル状態かチェック
@author 葉迩倭
@param No [in] チェックするイベントの番号
@retval false 非シグナル状態
@retval true シグナル状態
@note
指定したイベントがシグナル状態になっているかをチェックします。
@code
using namespace Selene;
// 5個のイベント生成
Event Event( false, 5 );
void ThreadProc( void *pData )
{
// No=3のイベントがシグナル?
while ( !Event.IsSignal( 3 ) )
{
// しばし待つ
Sleep( 1000 );
}
// No=3のイベントを非シグナルにする
Event.Reset( 3 );
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Thread Thread;
// スレッド生成
Thread.Create( ThreadProc, NULL );
// 適当に待ってるふり
Sleep( 1000 );
// No=3のイベントをシグナルにする
Event.Set( 3 );
// スレッド終わってる?
while ( !Thread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
virtual Bool IsSignal( Sint32 No = 0 );
/**
@brief 全てのイベントがシグナル状態かチェック
@author 葉迩倭
@retval false 非シグナル状態
@retval true シグナル状態
@note
全てのイベントがシグナル状態になっているかをチェックします。
@code
using namespace Selene;
// 3個のイベント生成
Event Event( false, 3 );
void ThreadProc( void *pData )
{
// 全部シグナルになるまで待つ
while ( !Event.IsSignalAll() )
{
// まだなのでしばし待つ
Sleep( 1000 );
}
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Thread Thread;
// スレッド生成
Thread.Create( ThreadProc, NULL );
// 適当に待ってるふり
Sleep( 1000 );
// イベントをシグナルにする
Event.Set( 0 );
Event.Set( 1 );
Event.Set( 2 );
// スレッド終わってる?
while ( !Thread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
virtual Bool IsSignalAll( void );
/**
@brief シグナル状態になったイベントを取得
@author 葉迩倭
@param TimeOut [in] タイムアウトms時間(-1で無限)
@retval -1 タイムアウト
@retval 0以上 シグナル状態になったイベント番号
@note
指定時間待機し1つでもシグナル状態になったらその瞬間にそのイベントの番号を返します。<BR>
指定時間経過してもシグナル状態になったイベントがなければ-1を返します。
@code
using namespace Selene;
// 3個のイベント生成
Event Event( false, 3 );
void ThreadProc( void *pData )
{
// 何かがシグナルになるまで1秒ほど待つ
Sint32 No = Event.Wait( 1000 );
switch ( No )
{
case 0:
case 1:
case 2:
break;
default:
break;
}
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Thread Thread;
// スレッド生成
Thread.Create( ThreadProc, NULL );
// 適当に待ってるふり
Sleep( 1000 );
// イベントをシグナルにする
Event.Set( 1 );
// スレッド終わってる?
while ( !Thread.WaitForExit() )
{
Sleep( 1000 );
}
return 0;
}
@endcode
*/
virtual Sint32 Wait( Sint32 TimeOut = -1 );
/**
@brief シグナル状態になったイベントを取得
@author 葉迩倭
@param No [in] ハンドル番号
@return ハンドル
@note
指定番号のハンドルを取得します。
*/
virtual HANDLE GetHandle( Sint32 No );
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Thread
{
/**
@brief スレッド実行優先度
@author 葉迩倭
*/
enum eCThreadPriority
{
THREAD_PRIORITY_LOW = -2, /// 低い
THREAD_PRIORITY_MIDDLE = -1, /// やや低い
THREAD_PRIORITY_DEFAULT = 0, /// 通常
THREAD_PRIORITY_HIGH = +1, /// 高い
};
/**
@brief スレッド管理操作クラス
@author 葉迩倭
*/
class SELENE_DLL_API CThread
{
private:
/**
@brief スレッド用関数
@author 葉迩倭
@param pArguments [in] CThreadのポインタ
@note
クラスの関数を直接は指定できないので<BR>
staticな関数を経由して呼び出す。
*/
static Uint32 __stdcall CThreadFunc( void* pArguments );
private:
HANDLE m_hThread; ///< スレッドハンドル
Uint32 m_ThreadId; ///< スレッドID
void *m_pData; ///< スレッドデータ伝達用ポインタ
void (*m_pMainProc)( void* ); ///< スレッド関数
CCriticalSection m_cs; ///< クリティカルセクション
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CThread();
/**
@brief デストラクタ
@author 葉迩倭
*/
virtual ~CThread();
public:
/**
@brief スレッド生成
@author 葉迩倭
@param pCThreadFunc [in] スレッド関数
@param pData [in] スレッドに引き渡すデータポインタ
@retval false 生成失敗or既にスレッドが生成されている
@retval true 生成完了
@note
スレッドの生成を行います。
@code
using namespace Selene;
void CThreadProc( void *pData )
{
// 10秒待機
Sleep( 10 * 1000 );
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// スレッド終わるまで待つ
while ( !CThread.WaitForExit() )
{
// 適当
Sleep( 100 );
}
return 0;
}
@endcode
*/
virtual Bool Create( void (*pCThreadFunc)( void* ), void *pData );
/**
@brief スレッド終了待ち
@author 葉迩倭
@retval false スレッドは終了していない
@retval true スレッドは終了した
@note
スレッドが終了するのを待ちます
@code
void CThreadProc( void *pData )
{
// 10秒待機
Sleep( 10 * 1000 );
}
void hogehoge( void )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// スレッド終わるまで待つ
while ( !CThread.WaitForExit() )
{
// 適当
Sleep( 100 );
}
}
@endcode
*/
virtual Bool WaitForExit( void );
/**
@brief スレッドの優先度変更
@author 葉迩倭
@param Priority [in] スレッド処理の優先度
@note
スレッドの優先度を変更します。<BR>
デフォルトの優先度はTHREAD_PRIORITY_DEFAULTです。
@code
using namespace Selene;
void CThreadProc( void *pData )
{
// 10秒待機
Sleep( 10 * 1000 );
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// スレッドの優先度を1ランク下げる
CThread.SetPriority( THREAD_PRIORITY_MIDDLE );
// スレッド終わるまで待つ
while ( !CThread.WaitForExit() )
{
// 適当
Sleep( 100 );
}
return 0;
}
@endcode
*/
virtual Bool SetPriority( Sint32 Priority );
/**
@brief スレッドの中断を解除
@author 葉迩倭
@note
スレッドのサスペンドカウントが 1 減ります。<BR>
カウントが 0 になった時点でスレッドの中断が解除されます。
@code
using namespace Selene;
void CThreadProc( void *pData )
{
// 10秒待機
Sleep( 10 * 1000 );
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// スレッド一時停止
CThread.Suspend();
// 適当に待ってるふり
Sleep( 1000 );
// スレッド再開
CThread.Resume();
// スレッド終わるまで待つ
while ( !CThread.WaitForExit() )
{
// 適当
Sleep( 100 );
}
return 0;
}
@endcode
*/
virtual void Resume( void );
/**
@brief スレッドの実行を中断
@author 葉迩倭
@note
指定されたスレッドの実行が中断され、<BR>
そのスレッドのサスペンドカウントが 1 増えます。
@code
void CThreadProc( void *pData )
{
}
void hogehoge( void )
{
Selene::CThread CThread;
// スレッド生成
CThread.Create( CThreadProc );
// スレッド一時停止
CThread.Suspend();
// 略
…
// スレッド再開
CThread.Resume();
// 略
…
}
@endcode
*/
virtual void Suspend( void );
/**
@brief スレッドの実行を終了
@author 葉迩倭
@note
指定されたスレッドの実行を強制終了します。<BR>
この関数で終了させる場合はスタックの解放などが行われないので<BR>
通常は使用しないでください。<BR>
強制終了を行わざるを得ない状況でのみ使用して下さい。
@code
using namespace Selene;
void CThreadProc( void *pData )
{
// 10秒待機
Sleep( 10 * 1000 );
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
CThread CThread;
// スレッド生成
CThread.Create( CThreadProc, NULL );
// 適当に待ってるふり
Sleep( 1000 );
// スレッド終わってる?
if ( !CThread.WaitForExit() )
{
// 強制終了
CThread.Terminate();
}
return 0;
}
@endcode
*/
virtual void Terminate( void );
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
/**
@brief ファイルオープンモード
@author 葉迩倭
*/
enum eFileOpenType
{
FILE_OPEN_TYPE_WRITE, ///< 書き込み専用
FILE_OPEN_TYPE_READ, ///< 読み込み専用
FILE_OPEN_TYPE_READ_WRITE, ///< 読み書き用
FILE_OPEN_TYPE_INVALID, ///< 無効
};
namespace File
{
/**
@brief ファイル操作
@author 葉迩倭
*/
class SELENE_DLL_API CFile
{
private:
HANDLE m_hFile; ///< ファイルハンドル
eFileOpenType m_Type; ///< ファイルオープンモード
FILETIME m_TimeCreate; ///< ファイル作成時間
FILETIME m_TimeAccess; ///< ファイルアクセス時間
FILETIME m_TimeLastWrite; ///< ファイル書き込み時間
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CFile( const char *pFileName, eFileOpenType Type );
/**
@brief デストラクタ
@author 葉迩倭
*/
virtual ~CFile();
/**
@brief ファイルオープンチェック
@author 葉迩倭
@retval false ファイルは開かれていない
@retval true ファイルは開かれている
*/
virtual Bool IsOpened( void );
/**
@brief ファイル書き込み
@author 葉迩倭
@param pData [in] 書き込みデータ
@param Size [in] データサイズ
@return 実際の書き込みサイズ
*/
virtual Sint32 Write( const void *pData, Sint32 Size );
/**
@brief ファイル読み込み
@author 葉迩倭
@param pData [in] 読み込みデータ
@param Size [in] データサイズ
@return 実際の読み込みサイズ
*/
virtual Sint32 Read( void *pData, Sint32 Size );
/**
@brief ファイルサイズ取得
@author 葉迩倭
*/
virtual Sint32 GetFileSize( void );
/**
@brief ファイル位置取得
@author 葉迩倭
preturn ファイル位置
*/
virtual Sint32 GetFilePosition( void );
/**
@brief 先頭からシーク
@author 葉迩倭
@param Offset [in] 先頭からのオフセット
@param ファイル位置
*/
virtual Sint32 SeekStart( Sint32 Offset );
/**
@brief 終端からシーク
@author 葉迩倭
@param Offset [in] 終端からのオフセット
@param ファイル位置
*/
virtual Sint32 SeekEnd( Sint32 Offset );
/**
@brief シーク
@author 葉迩倭
@param Offset [in] 現在位置からのオフセット
@param ファイル位置
*/
virtual Sint32 Seek( Sint32 Offset );
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace File
{
/**
@brief HTMLログ用ファイル操作
@author 葉迩倭
*/
class SELENE_DLL_API CFileHtmlLog : public CFile
{
private:
Thread::CCriticalSection m_CS;
public:
CFileHtmlLog( const char *pFileName, const char *pTitle );
virtual ~CFileHtmlLog();
virtual Sint32 Print( Sint32 Color, const char *pStr,... );
virtual Sint32 PrintStrong( Sint32 Color, const char *pStr,... );
virtual Sint32 PrintLine( Sint32 Color, const char *pStr,... );
virtual Sint32 PrintStrongLine( Sint32 Color, const char *pStr,... );
virtual Sint32 TableBegin( void );
virtual Sint32 TableEnd( void );
virtual Sint32 TableLine( Sint32 Bold );
virtual Sint32 CellBegin( Sint32 Width );
virtual Sint32 CellEnd( void );
};
}
}
#pragma once
/**
@file
@brief 2次元ベクトル
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Math
{
/**
@brief 2次元ベクトル演算クラス
*/
class SELENE_DLL_API Vector2D
{
public:
Float x;
Float y;
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
Vector2D();
/**
@brief コンストラクタ
@author 葉迩倭
@param v [in] 入力
*/
Vector2D( const Vector2D &v );
/**
@brief コンストラクタ
@author 葉迩倭
@param fPx [in] x初期値
@param fPy [in] y初期値
*/
Vector2D( Float fPx, Float fPy );
/**
@brief 加算
@author 葉迩倭
@param In1 [in] 加算用入力ベクトル
@param In2 [in] 加算用入力ベクトル
@return 計算結果後の*this
@note
this = In + In2
*/
Vector2D& Add( const Vector2D &In1, const Vector2D &In2 );
/**
@brief 減算
@author 葉迩倭
@param In1 [in] 加算用入力ベクトル
@param In2 [in] 加算用入力ベクトル
@return 計算結果後の*this
@note
this = In - In2
*/
Vector2D& Sub( const Vector2D &In1, const Vector2D &In2 );
/**
@brief 値設定
@author 葉迩倭
@param fPx [in] x設定値
@param fPy [in] y設定値
@return 計算結果後の*this
*/
Vector2D& Set( Float fPx, Float fPy );
/**
@brief 長さの二乗取得
@author 葉迩倭
@return 長さの二乗
*/
Float LengthSq( void ) const;
/**
@brief 長さ取得
@author 葉迩倭
@return 長さ
*/
Float Length( void ) const;
/**
@brief 長さ取得
@author 葉迩倭
@return 長さ
*/
Float LengthFast( void ) const;
/**
@brief 内積
@author 葉迩倭
@param In [in] 内積算出用入力ベクトル
@return 内積
*/
Float Dot( const Vector2D &In ) const;
/**
@brief 正規化
@author 葉迩倭
@return 計算結果後の*this
@note
長さを1.0に正規化します。
*/
Vector2D& Normalize( void );
/**
@brief 正規化
@author 葉迩倭
@return 計算結果後の*this
@note
長さを1.0に正規化します。
*/
Vector2D& NormalizeFast( void );
/**
@brief 反射ベクトルの取得
@author 葉迩倭
@param In1 [in] 反射対象の法線
@param In2 [in] 入射ベクトル
@return 計算結果後の*this
*/
Vector2D& Reflect( const Vector2D &In1, const Vector2D &In2 );
/**
@brief 正規化
@author 葉迩倭
@param In [in] 正規化元のベクトル
@return 計算結果後の*this
*/
Vector2D& Normalize( const Vector2D &In );
/**
@brief 正規化
@author 葉迩倭
@param In [in] 正規化元のベクトル
@return 計算結果後の*this
*/
Vector2D& NormalizeFast( const Vector2D &In );
/**
@brief 外積
@author 葉迩倭
@param In [in] 外積用のベクトル
@return z=0.0として計算したベクトルの外積
*/
Float Cross( const Vector2D &In ) const;
/**
@brief 反射
@author 葉迩倭
@param In [in] 反射用法線
@return 計算結果後の*this
*/
Vector2D& Reflect( const Vector2D &In );
/**
@brief Z軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 計算結果後の*this
*/
Vector2D& RotationZ( Sint32 Angle );
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator + () const
{
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator - () const
{
return Vector2D(-x, -y);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Bool operator == ( const Vector2D &v )
{
return (x == v.x) && (y == v.y);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Bool operator != ( const Vector2D &v )
{
return (x != v.x) || (y != v.y);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D& operator += ( Float f )
{
x += f;
y += f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D& operator -= ( Float f )
{
x -= f;
y -= f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D& operator *= ( Float f )
{
x *= f;
y *= f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D& operator /= ( Float f )
{
x /= f;
y /= f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D& operator += ( const Vector2D &v )
{
x += v.x;
y += v.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D& operator -= ( const Vector2D &v )
{
x -= v.x;
y -= v.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D& operator *= ( const Vector2D &v )
{
x *= v.x;
y *= v.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D& operator /= ( const Vector2D &v )
{
x /= v.x;
y /= v.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator + ( Float f ) const
{
return Vector2D(x + f, y + f);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator - ( Float f ) const
{
f = 1.0f / f;
return Vector2D(x - f, y - f);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator * ( Float f ) const
{
return Vector2D(x * f, y * f);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator / ( Float f ) const
{
return Vector2D(x / f, y / f);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator + ( const Vector2D &v ) const
{
return Vector2D(x + v.x, y + v.y);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator - ( const Vector2D &v ) const
{
return Vector2D(x - v.x, y - v.y);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator * ( const Vector2D &v ) const
{
return Vector2D(x * v.x, y * v.y);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector2D operator / ( const Vector2D &v ) const
{
return Vector2D(x / v.x, y / v.y);
}
};
}
}
#pragma once
/**
@file
@brief 3次元ベクトル
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Math
{
/**
@brief 3次元ベクトル演算クラス
*/
class SELENE_DLL_API Vector3D
{
public:
Float x;
Float y;
Float z;
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
Vector3D();
/**
@brief コンストラクタ
@author 葉迩倭
@param v [in] 入力
*/
Vector3D( const Vector3D &v );
/**
@brief コンストラクタ
@author 葉迩倭
@param fPx [in] x初期値
@param fPy [in] y初期値
@param fPz [in] z初期値
*/
Vector3D( Float fPx, Float fPy, Float fPz );
/**
@brief 加算
@author 葉迩倭
@param In1 [in] 加算用入力ベクトル
@param In2 [in] 加算用入力ベクトル
@return 計算結果後の*this
@note
this = In + In2
*/
Vector3D& Add( const Vector3D &In1, const Vector3D &In2 );
/**
@brief 減算
@author 葉迩倭
@param In1 [in] 加算用入力ベクトル
@param In2 [in] 加算用入力ベクトル
@return 計算結果後の*this
@note
this = In - In2
*/
Vector3D& Sub( const Vector3D &In1, const Vector3D &In2 );
/**
@brief 値設定
@author 葉迩倭
@param fPx [in] x設定値
@param fPy [in] y設定値
@param fPz [in] z設定値
@return 計算結果後の*this
*/
Vector3D& Set( Float fPx, Float fPy, Float fPz );
/**
@brief 長さの二乗取得
@author 葉迩倭
@return 長さの二乗
*/
Float LengthSq( void ) const;
/**
@brief 長さ取得
@author 葉迩倭
@return 長さ
*/
Float Length( void ) const;
/**
@brief 長さ取得
@author 葉迩倭
@return 長さ
*/
Float LengthFast( void ) const;
/**
@brief 内積
@author 葉迩倭
@param In [in] 内積算出用入力ベクトル
@return 内積
*/
Float Dot( const Vector3D &In ) const;
/**
@brief 正規化
@author 葉迩倭
@return 計算結果後の*this
@note
長さを1.0に正規化します。
*/
Vector3D &Normalize( void );
/**
@brief 正規化
@author 葉迩倭
@return 計算結果後の*this
@note
長さを1.0に正規化します。
*/
Vector3D &NormalizeFast( void );
/**
@brief 外積
@author 葉迩倭
@param In1 [in] 外積算出用入力ベクトル
@param In2 [in] 外積算出用入力ベクトル
@return 計算結果後の*this
*/
Vector3D& Cross( const Vector3D &In1, const Vector3D &In2 );
/**
@brief 反射ベクトルの取得
@author 葉迩倭
@param In1 [in] 反射対象の法線
@param In2 [in] 入射ベクトル
@return 計算結果後の*this
*/
Vector3D& Reflect( const Vector3D &In1, const Vector3D &In2 );
/**
@brief 拡大縮小+回転変換
@author 葉迩倭
@param In1 [in] 変換元ベクトル
@param In2 [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector3D& TransformNormal( const Vector3D &In1, const Matrix &In2 );
/**
@brief 拡大縮小+回転+移動変換
@author 葉迩倭
@param In1 [in] 変換元ベクトル
@param In2 [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector3D& TransformCoord( const Vector3D &In1, const Matrix &In2 );
/**
@brief 透視変換
@author 葉迩倭
@param In1 [in] 変換元ベクトル
@param In2 [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector3D& TransformProjection( const Vector3D &In1, const Matrix &In2 );
/**
@brief 正規化
@author 葉迩倭
@param In [in] 正規化元のベクトル
@return 計算結果後の*this
*/
Vector3D &Normalize( const Vector3D &In );
/**
@brief 正規化
@author 葉迩倭
@param In [in] 正規化元のベクトル
@return 計算結果後の*this
*/
Vector3D &NormalizeFast( const Vector3D &In );
/**
@brief 外積
@author 葉迩倭
@param In [in] 外積用のベクトル
@return 計算結果後の*this
*/
Vector3D& Cross( const Vector3D &In );
/**
@brief 反射
@author 葉迩倭
@param In [in] 反射用法線
@return 計算結果後の*this
*/
Vector3D& Reflect( const Vector3D &In );
/**
@brief 拡大縮小+回転変換
@author 葉迩倭
@param In [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector3D& TransformNormal( const Matrix &In );
/**
@brief 拡大縮小+回転+移動変換
@author 葉迩倭
@param In [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector3D& TransformCoord( const Matrix &In );
/**
@brief 透視変換
@author 葉迩倭
@param In [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector3D& TransformProjection( const Matrix &In );
/**
@brief X軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 計算結果後の*this
*/
Vector3D& RotationX( Sint32 Angle );
/**
@brief Y軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 計算結果後の*this
*/
Vector3D& RotationY( Sint32 Angle );
/**
@brief Z軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 計算結果後の*this
*/
Vector3D& RotationZ( Sint32 Angle );
/**
@brief ベクトルを軸に回転
@author 葉迩倭
@param Angle [in] 回転角度
@param Axis [in] 回転軸
@return 計算結果後の*this
*/
Vector3D& RotationAxis( Sint32 Angle, const Vector3D &Axis );
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator + () const
{
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator - () const
{
return Vector3D(-x, -y, -z);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Bool operator == ( const Vector3D &v )
{
return (x == v.x) && (y == v.y) && (z == v.z);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Bool operator != ( const Vector3D &v )
{
return (x != v.x) || (y != v.y) || (z != v.z);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D& operator += ( Float f )
{
x += f;
y += f;
z += f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D& operator -= ( Float f )
{
x -= f;
y -= f;
z -= f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D& operator *= ( Float f )
{
x *= f;
y *= f;
z *= f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D& operator /= ( Float f )
{
x /= f;
y /= f;
z /= f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D& operator += ( const Vector3D &v )
{
x += v.x;
y += v.y;
z += v.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D& operator -= ( const Vector3D &v )
{
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D& operator *= ( const Vector3D &v )
{
x *= v.x;
y *= v.y;
z *= v.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D& operator /= ( const Vector3D &v )
{
x /= v.x;
y /= v.y;
z /= v.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator + ( Float f ) const
{
return Vector3D(x + f, y + f, z + f);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator - ( Float f ) const
{
return Vector3D(x - f, y - f, z - f);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator * ( Float f ) const
{
return Vector3D(x * f, y * f, z * f);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator / ( Float f ) const
{
return Vector3D(x / f, y / f, z / f);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator + ( const Vector3D &v ) const
{
return Vector3D(x + v.x, y + v.y, z + v.z);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator - ( const Vector3D &v ) const
{
return Vector3D(x - v.x, y - v.y, z - v.z);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator * ( const Vector3D &v ) const
{
return Vector3D(x * v.x, y * v.y, z * v.z);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector3D operator / ( const Vector3D &v ) const
{
return Vector3D(x - v.x, y - v.y, z - v.z);
}
};
}
}
#pragma once
/**
@file
@brief 4次元ベクトル
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Math
{
/**
@brief 4次元ベクトル演算クラス
*/
class SELENE_DLL_API Vector4D
{
public:
Float x;
Float y;
Float z;
Float w;
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
Vector4D();
/**
@brief コンストラクタ
@author 葉迩倭
@param v [in] 入力(x, y, 0, 1)に展開
*/
Vector4D( const Vector2D &v );
/**
@brief コンストラクタ
@author 葉迩倭
@param v [in] 入力(x, y, z, 1)に展開
*/
Vector4D( const Vector3D &v );
/**
@brief コンストラクタ
@author 葉迩倭
@param v [in] 入力
*/
Vector4D( const Vector4D &v );
/**
@brief コンストラクタ
@author 葉迩倭
@param fPx [in] x初期値
@param fPy [in] y初期値
@param fPz [in] z初期値
@param fPw [in] w初期値
*/
Vector4D( Float fPx, Float fPy = 0.0f, Float fPz = 0.0f, Float fPw = 1.0f );
/**
@brief 加算
@author 葉迩倭
@param In1 [in] 加算用入力ベクトル
@param In2 [in] 加算用入力ベクトル
@return 計算結果後の*this
@note
this = In + In2
*/
Vector4D& Add( const Vector4D &In1, const Vector4D &In2 );
/**
@brief 減算
@author 葉迩倭
@param In1 [in] 加算用入力ベクトル
@param In2 [in] 加算用入力ベクトル
@return 計算結果後の*this
@note
this = In - In2
*/
Vector4D& Sub( const Vector4D &In1, const Vector4D &In2 );
/**
@brief 値設定
@author 葉迩倭
@param fPx [in] x設定値
@param fPy [in] y設定値
@param fPz [in] z設定値
@param fPw [in] w設定値
@return 計算結果後の*this
*/
Vector4D& Set( Float fPx, Float fPy, Float fPz, Float fPw = 1.0f );
/**
@brief 長さの二乗取得
@author 葉迩倭
@return 長さの二乗
*/
Float LengthSq( void ) const;
/**
@brief 長さ取得
@author 葉迩倭
@return 長さ
*/
Float Length( void ) const;
/**
@brief 長さ取得
@author 葉迩倭
@return 長さ
*/
Float LengthFast( void ) const;
/**
@brief 内積
@author 葉迩倭
@param In [in] 内積算出用入力ベクトル
@return 内積
*/
Float Dot( const Vector4D &In ) const;
/**
@brief 正規化
@author 葉迩倭
@return 計算結果後の*this
@note
長さを1.0に正規化します。
*/
Vector4D& Normalize( void );
/**
@brief 正規化
@author 葉迩倭
@return 計算結果後の*this
@note
長さを1.0に正規化します。
*/
Vector4D& NormalizeFast( void );
/**
@brief 外積
@author 葉迩倭
@param In1 [in] 外積算出用入力ベクトル
@param In2 [in] 外積算出用入力ベクトル
@return 計算結果後の*this
*/
Vector4D& Cross( const Vector4D &In1, const Vector4D &In2 );
/**
@brief 反射ベクトルの取得
@author 葉迩倭
@param In1 [in] 反射対象の法線
@param In2 [in] 入射ベクトル
@return 計算結果後の*this
*/
Vector4D& Reflect( const Vector4D &In1, const Vector4D &In2 );
/**
@brief 拡大縮小+回転変換
@author 葉迩倭
@param In1 [in] 変換元ベクトル
@param In2 [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector4D& TransformNormal( const Vector4D &In1, const Matrix &In2 );
/**
@brief 拡大縮小+回転+移動変換
@author 葉迩倭
@param In1 [in] 変換元ベクトル
@param In2 [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector4D& TransformCoord( const Vector4D &In1, const Matrix &In2 );
/**
@brief 透視変換
@author 葉迩倭
@param In1 [in] 変換元ベクトル
@param In2 [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector4D& TransformProjection( const Vector4D &In1, const Matrix &In2 );
/**
@brief 正規化
@author 葉迩倭
@param In [in] 正規化元のベクトル
@return 計算結果後の*this
*/
Vector4D& Normalize( const Vector4D &In );
/**
@brief 正規化
@author 葉迩倭
@param In [in] 正規化元のベクトル
@return 計算結果後の*this
*/
Vector4D& NormalizeFast( const Vector4D &In );
/**
@brief 外積
@author 葉迩倭
@param In [in] 外積用のベクトル
@return 計算結果後の*this
*/
Vector4D& Cross( const Vector4D &In );
/**
@brief 反射
@author 葉迩倭
@param In [in] 反射用法線
@return 計算結果後の*this
*/
Vector4D& Reflect( const Vector4D &In );
/**
@brief 拡大縮小+回転変換
@author 葉迩倭
@param In [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector4D& TransformNormal( const Matrix &In );
/**
@brief 拡大縮小+回転+移動変換
@author 葉迩倭
@param In [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector4D& TransformCoord( const Matrix &In );
/**
@brief 透視変換
@author 葉迩倭
@param In [in] 変換用マトリックス
@return 計算結果後の*this
*/
Vector4D& TransformProjection( const Matrix &In );
/**
@brief X軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 計算結果後の*this
*/
Vector4D& RotationX( Sint32 Angle );
/**
@brief Y軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 計算結果後の*this
*/
Vector4D& RotationY( Sint32 Angle );
/**
@brief Z軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 計算結果後の*this
*/
Vector4D& RotationZ( Sint32 Angle );
/**
@brief ベクトルを軸に回転
@author 葉迩倭
@param Angle [in] 回転角度
@param Axis [in] 回転軸
@return 計算結果後の*this
*/
Vector4D& RotationAxis( Sint32 Angle, const Vector3D &Axis );
/**
@brief オペレーター
@author 葉迩倭
*/
Bool operator == ( const Vector4D &v )
{
return (x == v.x) && (y == v.y) && (z == v.z) && (w == v.w);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Bool operator != ( const Vector4D &v )
{
return (x != v.x) || (y != v.y) || (z != v.z) || (w != v.w);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator + () const
{
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator - () const
{
return Vector4D(-x, -y, -z, 1.0);
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator += ( const Vector2D &v )
{
x += v.x;
y += v.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator -= ( const Vector2D &v )
{
x -= v.x;
y -= v.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator *= ( const Vector2D &v )
{
x *= v.x;
y *= v.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator /= ( const Vector2D &v )
{
x /= v.x;
y /= v.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator += ( const Vector3D &v )
{
x += v.x;
y += v.y;
z += v.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator -= ( const Vector3D &v )
{
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator *= ( const Vector3D &v )
{
x *= v.x;
y *= v.y;
z *= v.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator /= ( const Vector3D &v )
{
x /= v.x;
y /= v.y;
z /= v.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator += ( Float f )
{
x += f;
y += f;
z += f;
w += f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator -= ( Float f )
{
x -= f;
y -= f;
z -= f;
w -= f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator *= ( Float f )
{
x *= f;
y *= f;
z *= f;
w *= f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator /= ( Float f )
{
x /= f;
y /= f;
z /= f;
w /= f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator += ( const Vector4D &v )
{
x += v.x;
y += v.y;
z += v.z;
w += v.w;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator -= ( const Vector4D &v )
{
x -= v.x;
y -= v.y;
z -= v.z;
w -= v.w;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator *= ( const Vector4D &v )
{
x *= v.x;
y *= v.y;
z *= v.z;
w *= v.w;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator /= ( const Vector4D &v )
{
x /= v.x;
y /= v.y;
z /= v.z;
w /= v.w;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D& operator *= ( Matrix &m )
{
return TransformCoord( m );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator + ( Float f ) const
{
return Vector4D(x + f, y + f, z + f, w + f );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator - ( Float f ) const
{
return Vector4D(x - f, y - f, z - f, w - f );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator * ( Float f ) const
{
return Vector4D(x * f, y * f, z * f, w * f );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator / ( Float f ) const
{
return Vector4D(x / f, y / f, z / f, w / f );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator + ( const Vector2D &v ) const
{
return Vector4D(x + v.x, y + v.y, z, w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator - ( const Vector2D &v ) const
{
return Vector4D(x - v.x, y - v.y, z, w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator * ( const Vector2D &v ) const
{
return Vector4D(x * v.x, y * v.y, z, w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator / ( const Vector2D &v ) const
{
return Vector4D(x / v.x, y / v.y, z, w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator + ( const Vector3D &v ) const
{
return Vector4D(x + v.x, y + v.y, z + v.z, w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator - ( const Vector3D &v ) const
{
return Vector4D(x - v.x, y - v.y, z - v.z, w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator * ( const Vector3D &v ) const
{
return Vector4D(x * v.x, y * v.y, z * v.z, w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator / ( const Vector3D &v ) const
{
return Vector4D(x / v.x, y / v.y, z / v.z, w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator + ( const Vector4D &v ) const
{
return Vector4D(x + v.x, y + v.y, z + v.z, w + v.w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator - ( const Vector4D &v ) const
{
return Vector4D(x - v.x, y - v.y, z - v.z, w - v.w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator * ( const Vector4D &v ) const
{
return Vector4D(x * v.x, y * v.y, z * v.z, w * v.w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator / ( const Vector4D &v ) const
{
return Vector4D(x / v.x, y / v.y, z / v.z, w / v.w );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Vector4D operator * ( Matrix &m ) const
{
Vector4D vTemp;
return vTemp.TransformCoord( *this, m );
}
};
}
}
#pragma once
/**
@file
@brief 四元数管理
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Math
{
/**
@brief 四元数クラス
*/
class SELENE_DLL_API Quaternion
{
public:
Float x;
Float y;
Float z;
Float w;
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
Quaternion();
/**
@brief コンストラクタ
@author 葉迩倭
@param x [in] X要素
@param y [in] Y要素
@param z [in] Z要素
@param w [in] W要素
*/
Quaternion( Float x, Float y, Float z, Float w );
/**
@brief コンストラクタ
@author 葉迩倭
@param In [in] クォータニオン
*/
Quaternion( const Quaternion &In );
/**
@brief コンストラクタ
@author 葉迩倭
@param mIn [in] マトリックス
*/
Quaternion( const Matrix &mIn );
/**
@brief 加算
@author 葉迩倭
@param In1 [in] 入力クォータニオン1
@param In2 [in] 入力クォータニオン2
@return 計算結果後の*this
@note
二つのクォータニオンを加算します。
*/
Quaternion& Add( const Quaternion &In1, const Quaternion &In2 );
/**
@brief 減算
@author 葉迩倭
@param In1 [in] 入力クォータニオン1
@param In2 [in] 入力クォータニオン2
@return 計算結果後の*this
@note
二つのクォータニオンを減算します。
*/
Quaternion& Sub( const Quaternion &In1, const Quaternion &In2 );
/**
@brief 乗算
@author 葉迩倭
@param In1 [in] 入力クォータニオン1
@param In2 [in] 入力クォータニオン2
@return 計算結果後の*this
@note
二つのクォータニオンを乗算します。
*/
Quaternion& Mul( const Quaternion &In1, const Quaternion &In2 );
/**
@brief 線形補間
@author 葉迩倭
@param In0 [in] 入力クォータニオン1
@param In1 [in] 入力クォータニオン2
@param fRate [in] ブレンド率(0.0〜1.0f)
@return 計算結果後の*this
@note
二つのクォータニオンを線形補間します
*/
Quaternion& Lerp( const Quaternion &In0, const Quaternion &In1, Float fRate );
/**
@brief 球面線形補間
@author 葉迩倭
@param In0 [in] 入力クォータニオン1
@param In1 [in] 入力クォータニオン2
@param fRate [in] ブレンド率(0.0〜1.0f)
@return 計算結果後の*this
@note
二つのクォータニオンを球面線形補間します
*/
Quaternion& Slerp( const Quaternion &In0, const Quaternion &In1, Float fRate );
/**
@brief 加算
@author 葉迩倭
@param In [in] 入力クォータニオン
@note
二つのクォータニオンを加算します。
*/
Quaternion& Add( const Quaternion &In );
/**
@brief 減算
@author 葉迩倭
@param In [in] 入力クォータニオン
@return 計算結果後の*this
@note
二つのクォータニオンを減算します。
*/
Quaternion& Sub( const Quaternion &In );
/**
@brief 乗算
@author 葉迩倭
@param In [in] 入力クォータニオン
@return 計算結果後の*this
@note
二つのクォータニオンを乗算します。
*/
Quaternion& Mul( const Quaternion &In );
/**
@brief 線形補間
@author 葉迩倭
@param In [in] 入力クォータニオン
@param fRate [in] ブレンド率(0.0〜1.0f)
@return 計算結果後の*this
@note
二つのクォータニオンを線形補間します
*/
Quaternion& Lerp( const Quaternion &In, Float fRate );
/**
@brief 球面線形補間
@author 葉迩倭
@param In [in] 入力クォータニオン
@param fRate [in] ブレンド率(0.0〜1.0f)
@return 計算結果後の*this
@note
二つのクォータニオンを球面線形補間します
*/
Quaternion& Slerp( const Quaternion &In, Float fRate );
/**
@brief 初期化
@author 葉迩倭
@return 計算結果後の*this
@note
xyz=0.0、w=1.0に初期化します。
*/
Quaternion& Identity( void );
/**
@brief 長さの二乗を取得
@author 葉迩倭
@return 長さの二乗
@note
長さの二乗を取得します。
*/
Float LengthSq( void ) const;
/**
@brief 長さを取得
@author 葉迩倭
@return 長さ
@note
長さを取得します。
*/
Float Length( void ) const;
/**
@brief 内積を取得
@author 葉迩倭
@return 内積
@note
内積を取得します
*/
Float Dot( const Quaternion &In ) const;
/**
@brief 共役
@author 葉迩倭
@return 計算結果後の*this
@note
クォータニオンを共役します。
*/
Quaternion& Conjugate( void );
/**
@brief 共役
@author 葉迩倭
@return 計算結果後の*this
@note
クォータニオンを共役して格納します。
*/
Quaternion& Conjugate( const Quaternion &In );
};
}
}
#pragma once
/**
@file
@brief 行列演算
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Math
{
/**
@brief 行列構造体
*/
struct SELENE_DLL_API SMatrix4x4
{
union {
struct {
Vector4D x;
Vector4D y;
Vector4D z;
Vector4D w;
};
Float m[4][4];
};
};
/**
@brief 行列クラス
*/
class SELENE_DLL_API Matrix : public SMatrix4x4
{
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
Matrix();
/**
@brief コンストラクタ
@author 葉迩倭
*/
Matrix( const Matrix &Mat );
/**
@brief コンストラクタ
@author 葉迩倭
*/
Matrix( const SMatrix4x4 &Mat );
/**
@brief コンストラクタ
@author 葉迩倭
*/
Matrix( const Quaternion &In );
/**
@brief コンストラクタ
@author 葉迩倭
*/
Matrix(
Float _11, Float _12, Float _13, Float _14,
Float _21, Float _22, Float _23, Float _24,
Float _31, Float _32, Float _33, Float _34,
Float _41, Float _42, Float _43, Float _44 );
/**
@brief 行列の単位化
@author 葉迩倭
*/
void Identity( void );
/**
@brief 行列の転置化
@author 葉迩倭
@param In [in] 処理元行列
*/
Matrix &Transpose( const Matrix &In );
/**
@brief 行列の逆行列化
@author 葉迩倭
@param In [in] 処理元行列
*/
Matrix &Inverse( const Matrix &In );
/**
@brief 行列の合成
@author 葉迩倭
@param In1 [in] 合成元行列1
@param In2 [in] 合成元行列2
*/
Matrix &Multiply( const Matrix &In1, const Matrix &In2 );
/**
@brief 行列の転置行列化
@author 葉迩倭
*/
Matrix &Transpose( void );
/**
@brief 行列の逆行列化
@author 葉迩倭
*/
Matrix &Inverse( void );
/**
@brief 行列の合成
@author 葉迩倭
@param In [in] 合成元行列
*/
Matrix &Multiply( const Matrix &In );
/**
@brief X軸回転
@author 葉迩倭
@param Angle [in] 回転角度
*/
Matrix &RotationX( Sint32 Angle );
/**
@brief Y軸回転
@author 葉迩倭
@param Angle [in] 回転角度
*/
Matrix &RotationY( Sint32 Angle );
/**
@brief Z軸回転
@author 葉迩倭
@param Angle [in] 回転角度
*/
Matrix &RotationZ( Sint32 Angle );
/**
@brief ZXY回転行列を生成
@author 葉迩倭
@param AngleX [in] X軸回転角度
@param AngleY [in] Y軸回転角度
@param AngleZ [in] Z軸回転角度
*/
Matrix &RotationZXY( Sint32 AngleX, Sint32 AngleY, Sint32 AngleZ );
/**
@brief 任意軸回転
@author 葉迩倭
@param Angle [in] 角度
@param Axis [in] 回転軸
*/
Matrix &RotationAxis( Sint32 Angle, const Vector3D &Axis );
/**
@brief 拡大縮小行列生成
@author 葉迩倭
@param sx [in] X方向拡大率
@param sy [in] Y方向拡大率
@param sz [in] Z方向拡大率
*/
Matrix &Scaling( Float sx, Float sy, Float sz );
/**
@brief 移動行列生成
@author 葉迩倭
@param px [in] X位置
@param py [in] Y位置
@param pz [in] Z位置
*/
Matrix &Translation( Float px, Float py, Float pz );
/**
@brief 透視変換用行列生成
@author 葉迩倭
@param Fov [in] 画角
@param NearZ [in] 近接クリップ面
@param FarZ [in] 遠方クリップ面
@param Aspect [in] アスペクト比(=描画エリア横幅÷描画エリア縦幅)
*/
Matrix &Perspective( Sint32 Fov, Float NearZ, Float FarZ, Float Aspect );
/**
@brief 並行投影用行列生成
@author 葉迩倭
@param Width [in] 横幅
@param Height [in] 縦幅
@param NearZ [in] 近接クリップ面
@param FarZ [in] 遠方クリップ面
*/
Matrix &Ortho( Float Width, Float Height, Float NearZ, Float FarZ );
/**
@brief 任意点注視行列作成
@author 葉迩倭
@param Eye [in] 視点
@param At [in] 注視点
@param Up [in] 上方向
*/
Matrix &LookAt( const Vector3D &Eye, const Vector3D &At, const Vector3D &Up );
/**
@brief 行列の分解
@author 葉迩倭
@param vTranslate [in] 移動
@param vScale [in] 拡大縮小
@param qRotate [in] 回転
*/
void Resolution( Vector3D &vTranslate, Vector3D &vScale, Quaternion &qRotate );
/**
@brief オペレーター
@author 葉迩倭
*/
Matrix &operator = ( const Quaternion &q )
{
Float xx = q.x * q.x;
Float yy = q.y * q.y;
Float zz = q.z * q.z;
Float xy = q.x * q.y;
Float xz = q.x * q.z;
Float yz = q.y * q.z;
Float wx = q.w * q.x;
Float wy = q.w * q.y;
Float wz = q.w * q.z;
x.x = 1.0f - 2.0f * (yy + zz);
x.y = 2.0f * (xy - wz);
x.z = 2.0f * (xz + wy);
x.w = 0.0f;
y.x = 2.0f * (xy + wz);
y.y = 1.0f - 2.0f * (xx + zz);
y.z = 2.0f * (yz - wx);
y.w = 0.0f;
z.x = 2.0f * (xz - wy);
z.y = 2.0f * (yz + wx);
z.z = 1.0f - 2.0f * (xx + yy);
z.w = 0.0f;
w.x = 0.0f;
w.y = 0.0f;
w.z = 0.0f;
w.w = 1.0f;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Matrix &operator = ( const Matrix &m )
{
MemoryCopy( this->m, m.m, sizeof(Float[4][4]) );
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Matrix &operator = ( const SMatrix4x4 &m )
{
MemoryCopy( this->m, m.m, sizeof(Float[4][4]) );
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Matrix operator * ( const Matrix &m )
{
Matrix mTemp;
return mTemp.Multiply( *this, m );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Matrix &operator *= ( const Matrix &m )
{
return Multiply( m );
}
/**
@brief 単位行列
@author 葉迩倭
@return 単位行列
*/
static Matrix GetIdentity( void )
{
Matrix mTemp;
mTemp.Identity();
return mTemp;
}
/**
@brief 移動行列生成
@author 葉迩倭
@param px [in] X位置
@param py [in] Y位置
@param pz [in] Z位置
@return 移動行列
*/
static Matrix GetTranslation( Float px, Float py, Float pz )
{
Matrix mTemp;
mTemp.Translation( px, py, pz );
return mTemp;
}
/**
@brief X軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 回転行列
*/
static Matrix GetRotationX( Sint32 Angle )
{
Matrix mTemp;
mTemp.RotationX( Angle );
return mTemp;
}
/**
@brief Y軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 回転行列
*/
static Matrix GetRotationY( Sint32 Angle )
{
Matrix mTemp;
mTemp.RotationY( Angle );
return mTemp;
}
/**
@brief Z軸回転
@author 葉迩倭
@param Angle [in] 回転角度
@return 回転行列
*/
static Matrix GetRotationZ( Sint32 Angle )
{
Matrix mTemp;
mTemp.RotationZ( Angle );
return mTemp;
}
/**
@brief 拡大縮小行列
@author 葉迩倭
@param sx [in] X方向拡大率
@param sy [in] Y方向拡大率
@param sz [in] Z方向拡大率
@return 拡大縮小行列
*/
static Matrix GetScaling( Float sx, Float sy, Float sz )
{
Matrix mTemp;
mTemp.Scaling( sx, sy, sz );
return mTemp;
}
};
}
}
#pragma once
/**
@file
@brief 姿勢管理
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Math
{
/**
@brief 姿勢制御クラス
*/
class SELENE_DLL_API Style
{
private:
Vector3D m_vUp; ///< 上方向ベクトル
Vector3D m_vRight; ///< 右方向ベクトル
Vector3D m_vFront; ///< 前方向ベクトル
Vector3D m_vPosition; ///< 位置ベクトル
Vector3D m_vLocalPosition; ///< 位置ベクトル
Vector3D m_vScale; ///< 拡大縮小ベクトル
Bool m_IsScale; ///< 拡大縮小
Bool m_IsLocal; ///< ローカル移動
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
Style();
/**
@brief コンストラクタ
@author 葉迩倭
@param Style [in] コピー元
*/
Style( const Style &Style );
/**
@brief 変換初期化
@author 葉迩倭
@note
変換を初期化して初期値に戻します。
*/
virtual void TransformReset( void );
/**
@brief X軸回転
@author 葉迩倭
@param Rot [in] 角度
@note
ワールド座標を基準にX軸周りに回転させます。
*/
virtual void RotationX( Sint32 Rot );
/**
@brief Y軸回転
@author 葉迩倭
@param Rot [in] 角度
@note
ワールド座標を基準にY軸周りに回転させます。
*/
virtual void RotationY( Sint32 Rot );
/**
@brief Z軸回転
@author 葉迩倭
@param Rot [in] 角度
@note
ワールド座標を基準にZ軸周りに回転させます。
*/
virtual void RotationZ( Sint32 Rot );
/**
@brief ピッチング
@author 葉迩倭
@param Rot [in] 角度
@note
ローカル座標を基準にX軸周りに回転させます。
*/
virtual void LocalRotationX( Sint32 Rot );
/**
@brief ヘッディング
@author 葉迩倭
@param Rot [in] 角度
@note
ローカル座標を基準にY軸周りに回転させます。
*/
virtual void LocalRotationY( Sint32 Rot );
/**
@brief ローリング
@author 葉迩倭
@param Rot [in] 角度
@note
ローカル座標を基準にZ軸周りに回転させます。
*/
virtual void LocalRotationZ( Sint32 Rot );
/**
@brief クォータニオンで回転
@author 葉迩倭
@param Quat [in] クォータニオン
@note
クォータニオンを使って回転させます。
*/
virtual void RotationQuaternion( const Quaternion &Quat );
/**
@brief 移動
@author 葉迩倭
@param fPx [in] X座標
@param fPy [in] Y座標
@param fPz [in] Z座標
@note
指定座標へ移動させます。
*/
virtual void Translation( Float fPx, Float fPy, Float fPz );
/**
@brief 移動
@author 葉迩倭
@param vPos [in] 座標
@note
指定座標へ移動させます。
*/
virtual void Translation( const Vector3D &vPos );
/**
@brief 移動
@author 葉迩倭
@param fPx [in] X座標
@param fPy [in] Y座標
@param fPz [in] Z座標
@note
指定座標へ移動させます。
*/
virtual void LocalTranslation( Float fPx, Float fPy, Float fPz );
/**
@brief 移動
@author 葉迩倭
@param vPos [in] 座標
@note
指定座標へ移動させます。
*/
virtual void LocalTranslation( const Vector3D &vPos );
/**
@brief 拡大縮小
@author 葉迩倭
@param fSx [in] X軸拡大縮小率
@param fSy [in] Y軸拡大縮小率
@param fSz [in] Z軸拡大縮小率
@note
指定倍率で拡大縮小をさせます。
*/
virtual void Scaling( Float fSx, Float fSy, Float fSz );
/**
@brief 任意方向へ姿勢
@author 葉迩倭
@param vEye [in] 視点位置
@param vAt [in] 目標位置
@param vUp [in] 上方向
@note
任意の場所から指定の場所を見た場合の姿勢を作成します。
*/
virtual void LookAt( const Vector3D &vEye, const Vector3D &vAt, const Vector3D &vUp );
/**
@brief 行列から変換
@author 葉迩倭
@param Mat [in] 変換マトリックス
@note
指定のマトリックスになるような姿勢データを生成します。
*/
virtual void FromMatrix( const Matrix &Mat );
/**
@brief X軸回転角度取得
@author 葉迩倭
@return X軸における回転角度
@note
X軸における回転角度を取得します。
*/
virtual Sint32 GetAngleX( void ) const;
/**
@brief Y軸回転角度取得
@author 葉迩倭
@return Y軸における回転角度
@note
Y軸における回転角度を取得します。
*/
virtual Sint32 GetAngleY( void ) const;
/**
@brief Z軸回転角度取得
@author 葉迩倭
@return Z軸における回転角度
@note
Z軸における回転角度を取得します。
*/
virtual Sint32 GetAngleZ( void ) const;
/**
@brief 位置設定
@author 葉迩倭
@param Pos [in] 位置
@note
指定位置に移動します。
*/
virtual void SetPosition( const Vector3D &Pos );
/**
@brief 前方設定
@author 葉迩倭
@param Vec [in] 前方ベクトル
@note
姿勢の正面方向を設定します。
*/
virtual void SetFront( const Vector3D &Vec );
/**
@brief 右方設定
@author 葉迩倭
@param Vec [in] 右方ベクトル
@note
姿勢の右手方向を設定します。
*/
virtual void SetRight( const Vector3D &Vec );
/**
@brief 上方設定
@author 葉迩倭
@param Vec [in] 上方ベクトル
@note
姿勢の上手方向を設定します。
*/
virtual void SetUp( const Vector3D &Vec );
/**
@brief 位置取得
@author 葉迩倭
@param Pos [out] 格納先
@note
指定位置に移動します。
*/
virtual void GetPosition( Vector3D &Pos ) const;
/**
@brief 前方取得
@author 葉迩倭
@param Vec [out] 格納先
@note
姿勢の正面方向を取得します。
*/
virtual void GetFront( Vector3D &Vec ) const;
/**
@brief 右方取得
@author 葉迩倭
@param Vec [out] 格納先
@note
姿勢の右手方向を取得します。
*/
virtual void GetRight( Vector3D &Vec ) const;
/**
@brief 上方取得
@author 葉迩倭
@param Vec [out] 格納先
@note
姿勢の上手方向を取得します。
*/
virtual void GetUp( Vector3D &Vec ) const;
/**
@brief 姿勢行列を取得
@author 葉迩倭
@param Mat [out] 格納先
@note
姿勢行列を取得します。<BR>
この行列には回転要素しか含みません。
*/
virtual void GetStyle( Matrix &Mat ) const;
/**
@brief 逆姿勢行列を取得
@author 葉迩倭
@param Mat [out] 格納先
@note
逆姿勢行列を取得します。<BR>
この行列には回転要素しか含みません。
*/
virtual void GetStyleInverse( Matrix &Mat ) const;
/**
@brief 変換行列を取得
@author 葉迩倭
@param Mat [out] 格納先
@note
変換行列を取得します。<BR>
この行列には回転と位置要素しか含みません。
*/
virtual void GetTransform( Matrix &Mat ) const;
/**
@brief 逆変換行列を取得
@author 葉迩倭
@param Mat [out] 格納先
@note
逆変換行列を取得します。<BR>
この行列には回転と位置要素しか含みません。
*/
virtual void GetTransformInverse( Matrix &Mat ) const;
/**
@brief 変換行列を取得
@author 葉迩倭
@param Mat [out] 格納先
@note
変換行列を取得します。<BR>
この行列には回転と位置と拡大縮小の全要素を含みます。
*/
virtual void GetTransformWithScale( Matrix &Mat ) const;
/**
@brief 逆変換行列を取得
@author 葉迩倭
@param Mat [out] 格納先
@note
逆変換行列を取得します。<BR>
この行列には回転と位置と拡大縮小の全要素を含みます。
*/
virtual void GetTransformInverseWithScale( Matrix &Mat ) const;
};
}
}
#pragma once
/**
@file
@brief 算術演算
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Math
{
/**
@brief sin取得
@author 葉迩倭
@param Angle [in] 1周65536とした角度
@return sin値
@note
sin値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// 90度の時のsin値を取得
Float fRet = Math::Sin( DEG_TO_ANGLE(90) );
return 0;
}
@endcode
*/
SELENE_DLL_API Float Sin( Sint32 Angle );
/**
@brief cos取得
@author 葉迩倭
@param Angle [in] 1周65536とした角度
@return cos値
@note
cos値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// 90度の時のcos値を取得
Float fRet = Math::Cos( DEG_TO_ANGLE(90) );
return 0;
}
@endcode
*/
SELENE_DLL_API Float Cos( Sint32 Angle );
/**
@brief ベクトル取得
@author 葉迩倭
@param Angle [in] 1周65536とした角度
@return 2Dベクトル
@note
正規化された2Dベクトルを取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// 90度の方向を向く単位ベクトルを取得
Vector2D vDir = Math::GetVector( DEG_TO_ANGLE(90) );
return 0;
}
@endcode
*/
SELENE_DLL_API Vector2D GetVector( Sint32 Angle );
/**
@brief atan2取得
@author 葉迩倭
@param Dx [in] X距離
@param Dy [in] Y距離
@return X-Yの成す角度
@note
X,Yから求められるatan2の値をSeleneの角度単位に<BR>
あわせた値で取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// (x,y)=(100.0f,50.0f)における原点基準の角度を求める
Sint32 Angle = Math::ATan2( 100.0f, 50.0f );
return 0;
}
@endcode
*/
SELENE_DLL_API Sint32 ATan2( Float Dx, Float Dy );
/**
@brief 矩形データ
@author 葉迩倭
*/
template <typename Type>
class Rect2D
{
public:
Type x; ///< X始点座標
Type y; ///< Y始点座標
Type w; ///< Xサイズ
Type h; ///< Yサイズ
/**
@brief コンストラクタ
@author 葉迩倭
*/
Rect2D()
{
}
/**
@brief コンストラクタ
@author 葉迩倭
*/
template <typename TypeT>
Rect2D( const Rect2D<TypeT> &Src )
{
this->x = (Type)Src.x;
this->y = (Type)Src.y;
this->w = (Type)Src.w;
this->h = (Type)Src.h;
}
/**
@brief コンストラクタ
@author 葉迩倭
@param x [in] X始点座標
@param y [in] Y始点座標
@param w [in] Xサイズ
@param h [in] Yサイズ
*/
Rect2D( Type x, Type y, Type w, Type h )
{
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
/**
@brief 値設定
@author 葉迩倭
@param x [in] X中心座標
@param y [in] Y中心座標
@param w [in] Xサイズ
@param h [in] Yサイズ
*/
void Set( Type x, Type y, Type w, Type h )
{
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
/**
@brief 値設定
@author 葉迩倭
@param x [in] X中心座標
@param y [in] Y中心座標
@param w [in] Xサイズ
@param h [in] Yサイズ
@param Scale [in] 拡大縮小率
*/
void SetCenter( Type x, Type y, Type w, Type h, Float Scale = 1.0f )
{
this->w = (Type)(w * Scale);
this->h = (Type)(h * Scale);
this->x = x - (Type)(toF(this->w) * 0.5f);
this->y = y - (Type)(toF(this->h) * 0.5f);
}
/**
@brief オペレーター
@author 葉迩倭
*/
template <typename TypeT>
Rect2D<Type> & operator = ( const Rect2D<TypeT> &Src )
{
this->x = (Type)Src.x;
this->y = (Type)Src.y;
this->w = (Type)Src.w;
this->h = (Type)Src.h;
return *this;
}
};
/**
@brief 2次元の点
@author 葉迩倭
*/
template <typename Type>
class Point2D
{
public:
Type x; ///< X座標
Type y; ///< Y座標
/**
@brief コンストラクタ
@author 葉迩倭
*/
Point2D()
{
}
/**
@brief コンストラクタ
@author 葉迩倭
*/
template <typename TypeT>
Point2D( const Point2D<TypeT> &Src )
{
this->x = (Type)Src.x;
this->y = (Type)Src.y;
}
/**
@brief コンストラクタ
@author 葉迩倭
@param x [in] X座標
@param y [in] Y座標
*/
Point2D( Type x, Type y )
{
this->x = x;
this->y = y;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point2D<Type> operator + ( Point2D<Type> &Pt )
{
return Point2D<Type>( this->x + Pt.x, this->y + Pt.y );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point2D<Type> operator - ( Point2D<Type> &Pt )
{
return Point2D<Type>( this->x - Pt.x, this->y - Pt.y );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point2D<Type> operator * ( Type Mul )
{
return Point2D<Type>( this->x * Mul, this->y * Mul );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point2D<Type> operator / ( Type Div )
{
return Point2D<Type>( this->x / Div, this->y / Div );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point2D<Type> &operator += ( Point2D<Type> &Pt )
{
this->x += Pt.x;
this->y += Pt.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point2D<Type> &operator -= ( Point2D<Type> &Pt )
{
this->x -= Pt.x;
this->y -= Pt.y;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point2D<Type> &operator *= ( Type Mul )
{
this->x *= Mul;
this->y *= Mul;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point2D<Type> &operator /= ( Type Div )
{
this->x /= Div;
this->y /= Div;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
template <typename TypeT>
Point2D<Type> & operator = ( const Point2D<TypeT> &Src )
{
this->x = (Type)Src.x;
this->y = (Type)Src.y;
return *this;
}
};
/**
@brief 3次元の点
*/
template <typename Type>
struct Point3D
{
Type x; ///< X位置
Type y; ///< Y位置
Type z; ///< Z位置
/**
@brief コンストラクタ
@author 葉迩倭
*/
Point3D()
{
}
/**
@brief コンストラクタ
@author 葉迩倭
*/
template <typename TypeT>
Point3D( const Point3D<TypeT> &Src )
{
this->x = (Type)Src.x;
this->y = (Type)Src.y;
this->z = (Type)Src.z;
}
/**
@brief コンストラクタ
@author 葉迩倭
@param x [in] X座標
@param y [in] Y座標
@param z [in] Z座標
*/
Point3D( Type x, Type y, Type z )
{
this->x = x;
this->y = y;
this->z = z;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point3D<Type> operator + ( Point3D<Type> &Pt )
{
return Point3D<Type>( this->x + Pt.x, this->y + Pt.y, this->z + Pt.z );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point3D<Type> operator - ( Point3D<Type> &Pt )
{
return Point3D<Type>( this->x - Pt.x, this->y - Pt.y, this->z - Pt.z );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point3D<Type> operator * ( Type Mul )
{
return Point3D<Type>( this->x * Mul, this->y * Mul, this->z * Mul );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point3D<Type> operator / ( Type Div )
{
return Point3D<Type>( this->x / Div, this->y / Div, this->z / Div );
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point3D<Type> &operator += ( Point3D<Type> &Pt )
{
this->x += Pt.x;
this->y += Pt.y;
this->z += Pt.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point3D<Type> &operator -= ( Point3D<Type> &Pt )
{
this->x -= Pt.x;
this->y -= Pt.y;
this->z -= Pt.z;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point3D<Type> &operator *= ( Type Mul )
{
this->x *= Mul;
this->y *= Mul;
this->z *= Mul;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
Point3D<Type> &operator /= ( Type Div )
{
this->x /= Div;
this->y /= Div;
this->z /= Div;
return *this;
}
/**
@brief オペレーター
@author 葉迩倭
*/
template <typename TypeT>
Point3D<Type> & operator = ( const Point3D<TypeT> &Src )
{
this->x = (Type)Src.x;
this->y = (Type)Src.y;
this->z = (Type)Src.z;
return *this;
}
};
typedef Point3D<Float> Point3DF; ///< Point3D<Float>の略称
typedef Point3D<Sint32> Point3DI; ///< Point3D<Sint32>の略称
typedef Point2D<Float> Point2DF; ///< Point2D<Float>の略称
typedef Point2D<Sint32> Point2DI; ///< Point2D<Sint32>の略称
typedef Rect2D<Float> Rect2DF; ///< Rect2D<Float>の略称
typedef Rect2D<Sint32> Rect2DI; ///< Rect2D<Sint32>の略称
}
}
#pragma once
/**
@file
@brief 疑似乱数
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Math
{
/**
@brief 乱数処理クラス
@author 葉迩倭
*/
class SELENE_DLL_API CRandom
{
enum { N = 624UL };
private:
Sint32 m_MersenneTwister[N]; ///< 乱数生成用ワーク
Sint32 m_MersenneTwisterCount; ///< 乱数生成用ワーク
private:
/**
@brief 擬似乱数生成
@author 葉迩倭
@return 乱数値
@note
32Bit整数の擬似乱数を生成します。
*/
virtual Sint32 GenerateInt32( void );
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CRandom();
/**
@brief コンストラクタ
@author 葉迩倭
*/
CRandom( Sint32 Param );
/**
@brief 乱数用種設定
@author 葉迩倭
@param Param [in] シード値
@note
乱数生成の種を設定します。
*/
virtual void Seed( Sint32 Param );
/**
@brief 32Bit整数乱数取得
@author 葉迩倭
@return 乱数値
@note
32Bit整数の乱数値を取得します。
*/
virtual Sint32 GetInt32( void );
/**
@brief 64Bit整数乱数取得
@author 葉迩倭
@return 乱数値
@note
64Bit整数の乱数値を取得します。
*/
virtual Uint64 GetInt64( void );
/**
@brief 32Bit浮動小数乱数取得
@author 葉迩倭
@return 乱数値
@note
32Bit浮動小数の乱数値を取得します。
*/
virtual Float GetFloat32( void );
/**
@brief 指定範囲乱数取得
@author 葉迩倭
@param Min [in] 最小値
@param Max [in] 最大値
@return 乱数値
@note
指定範囲内の整数乱数を取得します。
*/
virtual Sint32 GetInt( Sint32 Min, Sint32 Max );
/**
@brief 指定範囲乱数取得
@author 葉迩倭
@param Min [in] 最小値
@param Max [in] 最大値
@return 乱数値
@note
指定範囲内の浮動小数乱数を取得します。
*/
virtual Float GetFloat( Float Min, Float Max );
};
}
}
#pragma once
/**
@file
@brief 数値補間
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Interpolation
{
/**
@brief 等速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
等速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::Flat( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA Flat( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
Float fRate = toF(Time) / toF(TimeAll);
return (TypeA)(toF(Start) + toF(End - Start) * fRate);
}
/**
@brief 加速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
加速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::Add( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA Add( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
Float fRate = toF(Time) / toF(TimeAll);
fRate *= fRate;
return (TypeA)(toF(Start) + toF(End - Start) * fRate);
}
/**
@brief 減速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
減速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::Sub( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA Sub( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
Float fRate = toF(TimeAll-Time) / toF(TimeAll);
fRate *= fRate;
return (TypeA)(toF(End) + toF(Start - End) * fRate);
}
/**
@brief 加速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
加速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::Add2( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA Add2( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
Float fRate = toF(Time) / toF(TimeAll);
fRate *= fRate;
fRate *= fRate;
return (TypeA)(toF(Start) + toF(End - Start) * fRate);
}
/**
@brief 減速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
減速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::Sub2( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA Sub2( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
Float fRate = toF(TimeAll-Time) / toF(TimeAll);
fRate *= fRate;
fRate *= fRate;
return (TypeA)(toF(End) + toF(Start - End) * fRate);
}
/**
@brief 加速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
加速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::Add4( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA Add4( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
Float fRate = toF(Time) / toF(TimeAll);
fRate *= fRate;
fRate *= fRate;
fRate *= fRate;
return (TypeA)(toF(Start) + toF(End - Start) * fRate);
}
/**
@brief 減速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
減速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::Sub4( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA Sub4( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
Float fRate = toF(TimeAll-Time) / toF(TimeAll);
fRate *= fRate;
fRate *= fRate;
fRate *= fRate;
return (TypeA)(toF(End) + toF(Start - End) * fRate);
}
/**
@brief 加速→減速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
加速→減速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::AddSub( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA AddSub( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
TypeA Middle = (End + Start) / (TypeA)2;
TypeB MiddleTime = TimeAll / (TypeB)2;
if ( Time < MiddleTime )
{
return Add( Start, Middle, MiddleTime, Time );
}
else
{
return Sub( Middle, End, TimeAll-MiddleTime, Time-MiddleTime );
}
}
/**
@brief 減速→加速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
加速→減速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::SubAdd( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA SubAdd( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
TypeA Middle = (End + Start) / (TypeA)2;
TypeB MiddleTime = TimeAll / (TypeB)2;
if ( Time < MiddleTime )
{
return Sub( Start, Middle, MiddleTime, Time );
}
else
{
return Add( Middle, End, TimeAll-MiddleTime, Time-MiddleTime );
}
}
/**
@brief 加速→減速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
加速→減速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::AddSub2( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA AddSub2( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
TypeA Middle = (End + Start) / (TypeA)2;
TypeB MiddleTime = TimeAll / (TypeB)2;
if ( Time < MiddleTime )
{
return Add2( Start, Middle, MiddleTime, Time );
}
else
{
return Sub2( Middle, End, TimeAll-MiddleTime, Time-MiddleTime );
}
}
/**
@brief 減速→加速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
減速→加速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::SubAdd2( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA SubAdd2( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
TypeA Middle = (End + Start) / (TypeA)2;
TypeB MiddleTime = TimeAll / (TypeB)2;
if ( Time < MiddleTime )
{
return Sub2( Start, Middle, MiddleTime, Time );
}
else
{
return Add2( Middle, End, TimeAll-MiddleTime, Time-MiddleTime );
}
}
/**
@brief 加速→減速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
加速→減速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::AddSub4( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA AddSub4( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
TypeA Middle = (End + Start) / (TypeA)2;
TypeB MiddleTime = TimeAll / (TypeB)2;
if ( Time < MiddleTime )
{
return Add4( Start, Middle, MiddleTime, Time );
}
else
{
return Sub4( Middle, End, TimeAll-MiddleTime, Time-MiddleTime );
}
}
/**
@brief 減速→加速運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
減速→加速運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::SubAdd4( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA SubAdd4( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
TypeA Middle = (End + Start) / (TypeA)2;
TypeB MiddleTime = TimeAll / (TypeB)2;
if ( Time < MiddleTime )
{
return Sub4( Start, Middle, MiddleTime, Time );
}
else
{
return Add4( Middle, End, TimeAll-MiddleTime, Time-MiddleTime );
}
}
/**
@brief sin運動
@author 葉迩倭
@param Start [in] 開始値
@param End [in] 終了値
@param TimeAll [in] End到達時間
@param Time [in] 現在時間
@return Timeにおける値
@note
sin波で運動を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで移動する
Sint32 Pos = Interpolation::Sin( 0L, 100L, 60L, Time );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
template <typename TypeA, typename TypeB>
inline TypeA Sin( TypeA Start, TypeA End, TypeB TimeAll, TypeB Time )
{
Sint32 Angle = (Sint32)(DEG_TO_ANGLE(180) * Time / TimeAll);
Float fRate = Math::Sin( Angle );
return (TypeA)(toF(Start) + toF(End - Start) * fRate);
}
/**
@brief ネヴィル補間
@author 葉迩倭
@param Start [in] 開始値
@param Center [in] 中間値
@param End [in] 終了値
@param fTime [in] 現在時間(0.0〜1.0)
@return Timeにおける値
@note
ネヴィル補間を行うときの補間値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Sint32 Time = 0;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
Time++;
// 60カウントで0から100まで中間で30を経由して移動する
Sint32 Pos = Interpolation::Neville( 0.0f, 30.0f, 100.0f, toF(Time) / 60.0f );
if ( Time > 60L )
{
}
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
inline Float Neville( Float Start, Float Center, Float End, Float fTime )
{
fTime *= 2.0f;
Start = Center + (Center - Start) * (fTime - 1.0f);
Center = End + (End - Center) * (fTime - 2.0f);
return Center + (Center - Start) * (fTime - 2.0f) * 0.5f;
}
}
}
#pragma once
/**
@file
@brief アニメーション処理
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
/**
@brief アニメーションタイプ定義
@author 葉迩倭
*/
enum eAnimationType
{
ANIMATION_TYPE_STEP, ///< ステップ補間
ANIMATION_TYPE_LINEAR, ///< 線形補間
ANIMATION_TYPE_TCB, ///< TCBスプライン補間
};
/**
@brief キーフレームデータ
@author 葉迩倭
*/
struct SKeyFrame
{
Bool IsIn; ///< スプライン時のIN係数を定数にするかどうか
Bool IsOut; ///< スプライン時のOUT係数を定数にするかどうか
Float fTime; ///< キー時間
Float fParam; ///< キー値
Float fIn; ///< IN係数の定数
Float fOut; ///< OUT係数の定数
SKeyFrame *pPrev; ///< 前方キーフレームデータポインタ
SKeyFrame *pNext; ///< 後方キーフレームデータポインタ
};
namespace Math
{
/**
@brief アニメーションクラス
@author 葉迩倭
*/
class SELENE_DLL_API Animation
{
private:
Float m_fTimeFirst; ///< 開始時間
Float m_fTimeLast; ///< 終了時間
SKeyFrame *m_pKeys; ///< キーフレームデータポインタ
Sint32 m_KeyMax; ///< キーフレーム数
private:
/**
@brief 指定時間から最も近いキーデータを取得します
@author 葉迩倭
@param pKeys [in] キーフレームデータ
@param fTime [in] 検索時間
@param KeyMax [in] キー最大数
@return キーフレームデータポインタ
@note
指定時間からもっとも近いキー情報を、<BR>
バイナリサーチで検索します。
*/
SKeyFrame *GetKeyData( SKeyFrame *pKeys, Float fTime, Sint32 KeyMax );
/**
@brief エルミート補間関数を処理します
@author 葉迩倭
@param fTime [in] 時間
@param pH1 [out] パラメーター格納先1
@param pH2 [out] パラメーター格納先2
@param pH3 [out] パラメーター格納先3
@param pH4 [out] パラメーター格納先4
@note
エルミート補間関数を使って与えられたパラメーターから結果を算出します。
*/
void Hermite( Float fTime, Float *pH1, Float *pH2, Float *pH3, Float *pH4 );
/**
@brief 前方のキーの出力先のパラメータを求めます
@author 葉迩倭
@param pKey0 [in] 前方キーデータ
@param pKey1 [in] 後方キーデータ
@return 算出されたパラメーター
@note
指定時間に対しての直前のキーの挙動を計算します。
*/
Float InComing( SKeyFrame *pKey0, SKeyFrame *pKey1 );
/**
@brief 後方のキーの出力先のパラメータを求めます
@author 葉迩倭
@param pKey0 [in] 前方キーデータ
@param pKey1 [in] 後方キーデータ
@return 算出されたパラメーター
@note
指定時間に対しての直後のキーの挙動を計算します。
*/
Float OutGoing( SKeyFrame *pKey0, SKeyFrame *pKey1 );
public:
/**
@brief コンストラクタ
@author 葉迩倭
@param KeyMax [in] キー最大数
*/
Animation( Sint32 KeyMax );
/**
@brief デストラクタ
@author 葉迩倭
*/
virtual ~Animation();
/**
@brief キーフレームデータにキーを設定します
@author 葉迩倭
@param KeyNo [in] 設定先キー番号
@param fTime [in] 設定時間
@param fParam [in] 設定パラメータ
@param IsIn [in] 入力パラメーター指定有無
@param IsOut [in] 出力パラメーター指定有無
@param fIn [in] 入力パラメーター
@param fOut [in] 出力パラメーター
@return 成功時はtrue
@note
指定のキーに対して、補間用のパラメーターを設定します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Math::Animation Anim( 3 ); // キー3つで作成
Anim.SetKey( 0, 0.0f, 0.0f ); // キー1
Anim.SetKey( 1, 5.0f, 40.0f ); // キー2
Anim.SetKey( 2, 10.0f, 100.0f ); // キー3
Float fTime = 0.0f;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
fTime += 0.1f;
// 時間fTimeにおける値を取得
// 補間方法はTCBスプライン
Float fNow = Anim.GetParameter( fTime, ANIMATION_TYPE_TCB, 0.0f );
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
virtual Bool SetKey( Sint32 KeyNo, Float fTime, Float fParam, Bool IsIn = false, Bool IsOut = false, Float fIn = 0.0f, Float fOut = 0.0f );
/**
@brief 指定タイプのアニメーションで指定時間における値を取得します
@author 葉迩倭
@param fTime [in] 時間
@param Type [in] 補間タイプ
@param fDefault [in] デフォルト値
@return 補間結果値
@note
指定の時間に対して、補間されたパラメーターを取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
Math::Animation Anim( 3 ); // キー3つで作成
Anim.SetKey( 0, 0.0f, 0.0f ); // キー1
Anim.SetKey( 1, 5.0f, 40.0f ); // キー2
Anim.SetKey( 2, 10.0f, 100.0f ); // キー3
Float fTime = 0.0f;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
fTime += 0.1f;
// 時間fTimeにおける値を取得
// 補間方法はTCBスプライン
Float fNow = Anim.GetParameter( fTime, ANIMATION_TYPE_TCB, 0.0f );
}
}
EXIT:
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
virtual Float GetParameter( Float fTime, eAnimationType Type, Float fDefault );
};
}
}
#pragma once
/**
@file
@brief 3次元平面
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Collision
{
/**
@brief 3次元の平面
@author 葉迩倭
*/
class SELENE_DLL_API CPlane
{
public:
Math::Vector3D n; ///< 一般平面方程式におけるクリップ面の a b c 係数
Float d; ///< 一般平面方程式におけるクリップ面の d 係数
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CPlane( void );
/**
@brief コンストラクタ
@author 葉迩倭
@param a [in] 一般平面方程式におけるクリップ面の a 係数
@param b [in] 一般平面方程式におけるクリップ面の b 係数
@param c [in] 一般平面方程式におけるクリップ面の c 係数
@param d [in] 一般平面方程式におけるクリップ面の d 係数
*/
CPlane( Float a, Float b, Float c, Float d );
/**
@brief 法線データから生成
@author 葉迩倭
@param Pt [in] 平面上の1点
@param vNormal [in] 平面の法線
*/
void FromNormal( const Math::Vector3D &Pt, const Math::Vector3D &vNormal );
/**
@brief 平面上の3点から生成
@author 葉迩倭
@param vPt0 [in] 平面上の1点
@param vPt1 [in] 平面上の1点
@param vPt2 [in] 平面上の1点
*/
void FromPoint( const Math::Vector3D &vPt0, const Math::Vector3D &vPt1, const Math::Vector3D &vPt2 );
/**
@brief 内積
@author 葉迩倭
@param Pt [in] 任意の点
@note
平面と任意の点の内積をとります。
*/
Float Dot( const Math::Vector3D &Pt ) const;
};
}
}
#pragma once
/**
@file
@brief コリジョン用球
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Collision
{
/**
@brief 3次元上の球
@author 葉迩倭
*/
class SELENE_DLL_API CSphere
{
public:
Math::Vector3D vCenter; ///< 球の中心
Float fRadius; ///< 球の半径
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CSphere( void );
/**
@brief コンストラクタ
@author 葉迩倭
@param x [in] X座標
@param y [in] Y座標
@param z [in] Z座標
@param r [in] 半径
*/
CSphere( Float x, Float y, Float z, Float r );
/**
@brief コンストラクタ
@author 葉迩倭
@param c [in] 中心座標
@param r [in] 半径
*/
CSphere( const Math::Vector3D &c, Float r );
};
}
}
#pragma once
/**
@file
@brief 3次元ボックス
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Collision
{
/**
@brief 3次元上の箱
@author 葉迩倭
*/
class SELENE_DLL_API CBox
{
public:
Math::Vector3D Points[8]; ///< 箱を構成する8頂点
CPlane Planes[6]; ///< 箱を構成する6平面
Math::Vector3D vMin; ///< AABBの最少点
Math::Vector3D vMax; ///< AABBの最大点
private:
/**
@brief ポイントデータを元にボックスの各面、境界球の再計算
@author 葉迩倭
*/
void UpdateBox( void );
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CBox( void );
/**
@brief バウンディングボックスを構成する8頂点を指定
@author 葉迩倭
@param vPoints [in] ポイント
@note
以下の順番に並んでいる必要があります。<BR>
(min.x,min.y,min.z)-(min.x,max.y,min.z)-(min.x,max.y,max.z)-(min.x,min.y,max.z)-<BR>
(max.x,min.y,min.z)-(max.x,max.y,min.z)-(max.x,max.y,max.z)-(max.x,min.y,max.z)
*/
void SetPoints( const Math::Vector3D vPoints[] );
/**
@brief 3軸指定でバウンディングボックスを構成する8頂点を更新
@author 葉迩倭
@param vCenter [in] 中心
@param vAxis [in] 軸(X,Y,Z)
@param fLength [in] 軸の長さ(X,Y,Z)
*/
void UpdatePoints( const Math::Vector3D &vCenter, const Math::Vector3D vAxis[], const Float fLength[] );
/**
@brief バウンディングボックスを指定した行列で変換します。
@author 葉迩倭
@param Matrix [in] ポイントを変換するための行列
*/
void Transform( const Math::Matrix &Matrix );
/**
@brief バウンディングボックスを指定した行列で変換します。
@author 葉迩倭
@param vPoints [in] ポイントの配列
@param Matrix [in] ポイントを変換するための行列
*/
void Transform( const Math::Vector3D vPoints[], const Math::Matrix &Matrix );
/**
@brief バウンディングボックスを指定した行列で透視変換します。
@author 葉迩倭
@param Matrix [in] ポイントを透視変換するための行列
*/
void TransformProjection( const Math::Matrix &Matrix );
/**
@brief バウンディングボックスを指定した行列で透視変換します。
@author 葉迩倭
@param vPoints [in] ポイントの配列
@param Matrix [in] ポイントを透視変換するための行列
*/
void TransformProjection( const Math::Vector3D vPoints[], const Math::Matrix &Matrix );
/**
@brief バウンディングボックスを生成
@author 葉迩倭
@param MinPt [in] AABBの最小値
@param MaxPt [in] AABBの最大値
@param Matrix [in] ポイントを変換するための行列
*/
void CreateBox( const Math::Vector3D &MinPt, const Math::Vector3D &MaxPt, const Math::Matrix &Matrix );
/**
@brief バウンディングボックスを生成
@author 葉迩倭
@param MinPt [in] AABBの最小値
@param MaxPt [in] AABBの最大値
@param Matrix [in] ポイントを透視変換するための行列
*/
void CreateBoxProjection( const Math::Vector3D &MinPt, const Math::Vector3D &MaxPt, const Math::Matrix &Matrix );
};
}
}
#pragma once
/**
@file
@brief 2次元線分
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Collision
{
/**
@brief 2次元の線分
@author 葉迩倭
*/
class SELENE_DLL_API CLine2D
{
public:
Math::Vector2D vStart; ///< 線分始点位置
Math::Vector2D vEnd; ///< 線分終点位置
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CLine2D( void );
/**
@brief コンストラクタ
@author 葉迩倭
@param x0 [in] X座標
@param y0 [in] Y座標
@param x1 [in] X座標
@param y1 [in] Y座標
*/
CLine2D( Float x0, Float y0, Float x1, Float y1 );
/**
@brief コンストラクタ
@author 葉迩倭
@param pt0 [in] 線分の頂点1
@param pt1 [in] 線分の頂点2
*/
CLine2D( Math::Vector2D &pt0, Math::Vector2D &pt1 );
};
}
}
#pragma once
/**
@file
@brief 3次元線分
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Collision
{
/**
@brief 3次元の線分
@author 葉迩倭
*/
class SELENE_DLL_API CLine3D
{
public:
Math::Vector3D vStart; ///< 線分始点位置
Math::Vector3D vEnd; ///< 線分終点位置
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CLine3D( void );
/**
@brief コンストラクタ
@author 葉迩倭
@param x0 [in] X座標
@param y0 [in] Y座標
@param z0 [in] Z座標
@param x1 [in] X座標
@param y1 [in] Y座標
@param z1 [in] Z座標
*/
CLine3D( Float x0, Float y0, Float z0, Float x1, Float y1, Float z1 );
/**
@brief コンストラクタ
@author 葉迩倭
@param pt0 [in] 線分の頂点1
@param pt1 [in] 線分の頂点2
*/
CLine3D( const Math::Vector3D &pt0, const Math::Vector3D &pt1 );
};
}
}
#pragma once
/**
@file
@brief 2次元多角形
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Collision
{
/**
@brief 2次元の多角形
@author 葉迩倭
*/
class SELENE_DLL_API CPolygon2D
{
public:
Sint32 Count; ///< ポイント配列のポイント数
Math::Vector2D *pPts; ///< ポリゴンを表すためのポイント配列のポインタ
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CPolygon2D( void );
/**
@brief コンストラクタ
@author 葉迩倭
@param Cnt [in] 頂点数
@param pPt [in] 頂点の配列のアドレス(中でコピーはされませんので、参照元のメモリは保持しておく必要があります)
@note
Collisionクラスで判定を行う場合、Cntの値は4以上でpPt[0]==pPt[Cnt-1]になっており、<BR>
pPtの内容は時計回り、あるいは反時計回りの凸形状をしている必要があります。
*/
CPolygon2D( Sint32 Cnt, Math::Vector2D *pPt );
};
}
}
#pragma once
/**
@file
@brief 2次元円
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Collision
{
/**
@brief 2次元上の円
@author 葉迩倭
*/
class SELENE_DLL_API CCircle
{
public:
Math::Vector2D vCenter; ///< 円の中心
Float fRadius; ///< 円の半径
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
CCircle( void );
/**
@brief コンストラクタ
@author 葉迩倭
@param x [in] X座標
@param y [in] Y座標
@param r [in] 半径
*/
CCircle( Float x, Float y, Float r );
/**
@brief コンストラクタ
@author 葉迩倭
@param c [in] 中心座標
@param r [in] 半径
*/
CCircle( Math::Vector2D &c, Float r );
};
}
}
#pragma once
/**
@file
@brief 衝突判定
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Collision
{
/**
@brief 2D点と2D点の衝突判定
@author 葉迩倭
@param Pt1 [in] 2D平面上の点
@param Pt2 [in] 2D平面上の点
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の2つの点の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector2D Pt1, Pt2;
// 衝突判定
if ( Collision::Point_Point( Pt1, Pt2 ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Point( const Math::Vector2D &Pt1, const Math::Vector2D &Pt2 );
/**
@brief 2D点と2D線分の衝突判定
@author 葉迩倭
@param Pt [in] 2D平面上の点
@param Line [in] 2D平面上の線分
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の点と線分の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector2D Pt;
Collision::CLine2D Line;
// 衝突判定
if ( Collision::Point_Line( Pt, Line ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Line( const Math::Vector2D &Pt, const CLine2D &Line );
/**
@brief 2D点と2D矩形の衝突判定
@author 葉迩倭
@param Pt [in] 2D平面上の点
@param Rect [in] 2D平面上の矩形
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の点と矩形の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector2D Pt;
Math::Rect2D<Float> Rect;
// 衝突判定
if ( Collision::Point_Rect( Pt, Rect ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Rect( const Math::Vector2D &Pt, const Math::Rect2D<Float> &Rect );
/**
@brief 2D点と2D矩形の衝突判定
@author 葉迩倭
@param Pt [in] 2D平面上の点
@param Cir [in] 2D平面上の円
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の点と円の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector2D Pt;
Collision::CCircle Cir;
// 衝突判定
if ( Collision::Point_Circle( Pt, Cir ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Circle( const Math::Vector2D &Pt, const CCircle &Cir );
/**
@brief 2D点と2D多角形の衝突判定
@author 葉迩倭
@param Pt [in] 2D平面上の点
@param Poly [in] 2D平面上の多角形
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の点と多角形の衝突判定を行います。<BR>
CPolygon2Dに関しては、時計回り、あるいは反時計回りの<BR>
凸形状をしている必要があります。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector2D Pt;
Collision::CPolygon2D Poly;
// 衝突判定
if ( Collision::Point_Polygon( Pt, Poly ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Polygon( const Math::Vector2D &Pt, const CPolygon2D &Poly );
/**
@brief 2D矩形と2D矩形の衝突判定
@author 葉迩倭
@param Rect1 [in] 2D平面上の矩形
@param Rect2 [in] 2D平面上の矩形
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の矩形同士の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Rect2D<Float> Rect1, Rect2;
// 衝突判定
if ( Collision::Rect_Rect( Rect1, Rect2 ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Rect_Rect( const Math::Rect2D<Float> &Rect1, const Math::Rect2D<Float> &Rect2 );
/**
@brief 2D矩形と2D円の衝突判定
@author 葉迩倭
@param Rect [in] 2D平面上の矩形
@param Cir [in] 2D平面上の円
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の矩形と円の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Rect2D<Float> Rect;
Collision::CCircle Cir;
// 衝突判定
if ( Collision::Rect_Circle( Rect, Cir ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Rect_Circle( const Math::Rect2D<Float> &Rect, const CCircle &Cir );
/**
@brief 2D矩形と2D線分の衝突判定
@author 葉迩倭
@param Rect [in] 2D平面上の矩形
@param Line [in] 2D平面上の線分
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の矩形と線分の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Rect2D<Float> Rect;
Collision::CLine2D Line;
// 衝突判定
if ( Collision::Rect_Line( Rect, Line ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Rect_Line( const Math::Rect2D<Float> &Rect, const CLine2D &Line );
/**
@brief 2D矩形と2D多角形の衝突判定
@author 葉迩倭
@param Rect [in] 2D平面上の矩形
@param Poly [in] 2D平面上の多角形
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の矩形と多角形の衝突判定を行います。<BR>
CPolygon2Dに関しては、時計回り、あるいは反時計回りの<BR>
凸形状をしている必要があります。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Rect2D<Float> Rect;
Collision::CPolygon2D Poly;
// 衝突判定
if ( Collision::Rect_Polygon( Rect, Poly ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Rect_Polygon( const Math::Rect2D<Float> &Rect, const CPolygon2D &Poly );
/**
@brief 2D円と2D円の衝突判定
@author 葉迩倭
@param Cir1 [in] 2D平面上の円
@param Cir2 [in] 2D平面上の円
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の円同士の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CCircle Cir1, Cir2;
// 衝突判定
if ( Collision::Circle_Circle( Cir1, Cir2 ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Circle_Circle( const CCircle &Cir1, const CCircle &Cir2 );
/**
@brief 2D円と2D線分の衝突判定
@author 葉迩倭
@param Cir [in] 2D平面上の円
@param Line [in] 2D平面上の線分
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の円同士の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CCircle Cir;
Collision::CLine2D Line;
// 衝突判定
if ( Collision::Circle_Line( Cir, Line ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Circle_Line( const CCircle &Cir, const CLine2D &Line );
/**
@brief 2D円と2D多角形の衝突判定
@author 葉迩倭
@param Cir [in] 2D平面上の円
@param Poly [in] 2D平面上の多角形
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の円と多角形の衝突判定を行います。<BR>
CPolygon2Dに関しては、時計回り、あるいは反時計回りの<BR>
凸形状をしている必要があります。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CCircle Cir;
Collision::CPolygon2D Poly;
// 衝突判定
if ( Collision::Circle_Polygon( Cir, Poly ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Circle_Polygon( const CCircle &Cir, const CPolygon2D &Poly );
/**
@brief 2D線分と2D線分の衝突判定
@author 葉迩倭
@param Line1 [in] 2D平面上の線分
@param Line2 [in] 2D平面上の線分
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の線分同士の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CLine2D Line1, Line2;
// 衝突判定
if ( Collision::Line_Line( Line1, Line2 ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Line_Line( const CLine2D &Line1, const CLine2D &Line2 );
/**
@brief 2D線分と2D多角形の衝突判定
@author 葉迩倭
@param Line [in] 2D平面上の線分
@param Poly [in] 2D平面上の多角形
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の線分と多角形の衝突判定を行います。<BR>
CPolygon2Dに関しては、時計回り、あるいは反時計回りの<BR>
凸形状をしている必要があります。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CLine2D Line1;
Collision::CPolygon2D Poly;
// 衝突判定
if ( Collision::Line_Polygon( Line, Poly ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Line_Polygon( const CLine2D &Line, const CPolygon2D &Poly );
/**
@brief 2D多角形と2D多角形の衝突判定
@author 葉迩倭
@param Poly1 [in] 2D平面上の多角形
@param Poly2 [in] 2D平面上の多角形
@retval false 衝突していない
@retval true 衝突している
@note
2D平面上の多角形同士のの衝突判定を行います。<BR>
CPolygon2Dに関しては、時計回り、あるいは反時計回りの<BR>
凸形状をしている必要があります。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CPolygon2D Poly1, Poly2;
// 衝突判定
if ( Collision::Polygon_Polygon( Poly1, Poly2 ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Polygon_Polygon( const CPolygon2D &Poly1, const CPolygon2D &Poly2 );
/**
@brief 3D点と3D点の衝突判定
@author 葉迩倭
@param Pt1 [in] 3D空間の点
@param Pt2 [in] 3D空間の点
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の点同士の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector3D Pt1, Pt2;
// 衝突判定
if ( Collision::Point_Point_3D( Pt1, Pt2 ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Point_3D( const Math::Vector3D &Pt1, const Math::Vector3D &Pt2 );
/**
@brief 3D点と3D球の衝突判定
@author 葉迩倭
@param Pt [in] 3D空間の点
@param Sph [in] 3D空間の球
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の点と球の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector3D Pt;
Collision::CSphere Sph;
// 衝突判定
if ( Collision::Point_Sphere_3D( Pt, Sph ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Sphere_3D( const Math::Vector3D &Pt, const CSphere &Sph );
/**
@brief 3D点と3D線分の衝突判定
@author 葉迩倭
@param Pt [in] 3D空間の点
@param Line [in] 3D空間の線分
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の点と線分の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector3D Pt;
Collision::CLine3D Line;
// 衝突判定
if ( Collision::Point_Line_3D( Pt, Line ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Line_3D( const Math::Vector3D &Pt, const CLine3D &Line );
/**
@brief 3D点と3D平面の衝突判定
@author 葉迩倭
@param Pt [in] 3D空間の点
@param Plane [in] 3D空間の平面
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の点と平面の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector3D Pt;
Collision::CPlane Plane;
// 衝突判定
if ( Collision::Point_Plane_3D( Pt, Plane ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Plane_3D( const Math::Vector3D &Pt, const CPlane &Plane );
/**
@brief 3D点と3D箱の衝突判定
@author 葉迩倭
@param Pt [in] 3D空間の点
@param Box [in] 3D空間の箱
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の点と平面の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Math::Vector3D Pt;
Collision::CBox Box;
// 衝突判定
if ( Collision::Point_Box_3D( Pt, Box ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Point_Box_3D( const Math::Vector3D &Pt, const CBox &Box );
/**
@brief 3D球と3D球の衝突判定
@author 葉迩倭
@param Sph1 [in] 3D空間の球
@param Sph2 [in] 3D空間の球
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の球同士の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CSphere Sph1, Sph2;
// 衝突判定
if ( Collision::Sphere_Sphere_3D( Sph1, Sph2 ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Sphere_Sphere_3D( const CSphere &Sph1, const CSphere &Sph2 );
/**
@brief 3D球と3D線分の衝突判定
@author 葉迩倭
@param Sph [in] 3D空間の球
@param Line [in] 3D空間の線分
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の球と線分の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CSphere Sph;
Collision::CLine3D Line;
// 衝突判定
if ( Collision::Sphere_Line_3D( Sph, Line ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Sphere_Line_3D( const CSphere &Sph, const CLine3D &Line );
/**
@brief 3D球と3D平面の衝突判定
@author 葉迩倭
@param Sph [in] 3D空間の球
@param Plane [in] 3D空間の平面
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の球と平面の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CSphere Sph;
Collision::CPlane Plane;
// 衝突判定
if ( Collision::Sphere_Plane( Sph, Plane ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Sphere_Plane( const CSphere &Sph, const CPlane &Plane );
/**
@brief 3D線分と3D平面の衝突判定
@author 葉迩倭
@param Line [in] 3D空間の線分
@param Plane [in] 3D空間の平面
@param vIntersect [out] 衝突位置
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の線分と平面の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CLine3D Line;
Collision::CPlane Plane;
Math::Vector3D vIntersect;
// 衝突判定
if ( Collision::Line_Plane_3D( Line, Plane, vIntersect ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Line_Plane_3D( const CLine3D &Line, const CPlane &Plane, Math::Vector3D &vIntersect );
/**
@brief 3D線分と3D箱の衝突判定
@author 葉迩倭
@param Line [in] 3D空間の線分
@param Box [in] 3D空間の箱
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の線分と箱の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CLine3D Line;
Collision::CBox Box;
// 衝突判定
if ( Collision::Line_Box_3D( Line, Box ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Line_Box_3D( const CLine3D &Line, const CBox &Box );
/**
@brief 3D箱と3D箱の衝突判定
@author 葉迩倭
@param Box1 [in] 3D空間の箱
@param Box2 [in] 3D空間の箱
@retval false 衝突していない
@retval true 衝突している
@note
3D空間内の箱同士の衝突判定を行います。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Collision::CBox Box1, Box2;
// 衝突判定
if ( Collision::Box_Box_3D( Box1, Box2 ) )
{
}
return 0;
}
@endcode
*/
SELENE_DLL_API Bool Box_Box_3D( const CBox &Box1, const CBox &Box2 );
}
}
#pragma once
/**
@file
@brief インターフェイス基底クラス
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
/**
@brief インターフェース基底クラス
@author 葉迩倭
*/
class IInterface
{
public:
virtual ~IInterface() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
@note
インターフェイスが有効か無効かを調べます。
@code
// 有効かチェック
if ( this->IsInvalid() )
{
// 無効なインターフェイス
reutrn false;
}
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
@note
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
@code
// 解放(参照カウンタを-1するだけ。実際には参照カウントが0になるとメモリから消される)
this->Release();
@endcode
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
@note
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
@code
IInterface *pCopy = this;
// 他でも参照するので参照数+1
this->AddRef();
@endcode
*/
virtual Sint32 AddRef( void ) = 0;
};
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Fiber
{
/**
@brief ファイバーコントローラーインターフェイス
@author 葉迩倭
@note
ファイバーの制御を行うためのインターフェイスです。
*/
class IFiberController : public IInterface
{
public:
virtual ~IFiberController() {}
/**
@brief ファイバーシステム開始
@author 葉迩倭
@note
ファイバーの処理を開始します。
*/
virtual void Start( void ) = 0;
/**
@brief ファイバーシステム終了
@author 葉迩倭
@note
ファイバーの処理を終了します。
*/
virtual void Exit( void ) = 0;
/**
@brief ファイバー切り替え
@author 葉迩倭
@retval false アプリケーションは終了している
@retval true アプリケーションは継続中である
@note
ファイバーの切り替えを行います。
*/
virtual Bool Switch( void ) = 0;
/**
@brief ファイバー生成
@author 葉迩倭
@param FiberId [in] ファイバーID
@param pFiber [in] ファイバーインターフェイス
@retval false 指定のFiberIdにすでにファイバーがある
@retval true 成功
@note
ファイバーの生成を行います。
*/
virtual Bool Create( Sint32 FiberId, IFiber *pFiber ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Fiber
{
/**
@brief ファイバーインターフェイス
@author 葉迩倭
@note
ファイバーを実装するための基底クラスです。
*/
class IFiber
{
private:
Sint32 m_RefCount;
IFiberController *m_pFiberCtrl;
protected:
/**
@brief ファイバー切り替え
@author 葉迩倭
@retval true アプリケーションは継続中
@retval false アプリケーションが終了している
@note
登録されている次のIDのファイバーに処理を切り替えます。<BR>
返り値がfalseの場合アプリケーションが終了処理を行っているので<BR>
Controller()メソッドから直ちに抜けるように組んで下さい。
*/
Bool Switch( void )
{
return m_pFiberCtrl->Switch();
}
public:
/**
@brief コンストラクタ
@author 葉迩倭
*/
IFiber( void )
: m_pFiberCtrl ( NULL )
, m_RefCount ( 1 )
{
}
/**
@brief デストラクタ
@author 葉迩倭
*/
virtual ~IFiber()
{
if ( m_pFiberCtrl != NULL )
{
m_pFiberCtrl->Release();
}
}
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
@note
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
Sint32 Release( void )
{
Sint32 Cnt = --m_RefCount;
if ( Cnt == 0 )
{
delete this;
}
return Cnt;
}
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
@note
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
Sint32 AddRef( void )
{
return ++m_RefCount;
}
/**
@brief コントローラー設定
@author 葉迩倭
@param pCtrl [in] コントローラー
*/
void SetController( IFiberController *pCtrl )
{
m_pFiberCtrl = pCtrl;
m_pFiberCtrl->AddRef();
}
public:
/**
@brief ファイバー用制御関数
@author 葉迩倭
@note
ファイバーを実際に操作するための純粋仮想関数です。<BR>
この関数から抜けることでそのファイバーの処理が停止します。<BR>
Switch()メソッドでの切り替え時にfalseが帰ってきたらただちに<BR>
関数から抜けるようにして下さい。
*/
virtual void Control( void ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
/**
@brief ビデオカード管理インターフェイス
@author 葉迩倭
*/
class IGraphicCard
{
public:
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 16Bitカラーモードを使用
@author 葉迩倭
フルスクリーン時の画面カラーを32Bitではなく16Bitにします。<BR>
フィルレートの厳しい環境で速度の向上が望めますが、<BR>
マッハバンドなどの画質的な問題も出ます。
*/
virtual void EnableHighlColorScreen( void ) = 0;
/**
@brief ピクセルシェーダーがサポートされているか取得
@author 葉迩倭
@param Major [in] メジャーバージョン
@param Minor [in] マイナーバージョン
現在のデバイスで指定したピクセルシェーダーをサポート<BR>
しているかどうかを取得します。
*/
virtual Bool GetPixelShaderSupport( Uint16 Major, Uint16 Minor ) = 0;
/**
@brief 画面解像度数取得
@author 葉迩倭
@param IsFullColor [in] フルカラー(32Bit)の画面解像度か否か
@return 画面解像度数
使用可能な画面解像度の数を取得できます。<BR>
IsFullColorフラグに応じて、16Bit/32Bitカラーの画面解像度数が取得出来ます。
*/
virtual Sint32 GetScreenModeCount( Bool IsFullColor ) = 0;
/**
@brief 画面解像度
@author 葉迩倭
@param IsFullColor [in] フルカラー(32Bit)の画面解像度か否か
@param No [in] 画面解像度のインデックス(最大数はGetScreenModeCount()で取得)
@param Width [out] 画面横幅格納先
@param Height [out] 画面縦幅格納先
使用可能な画面解像度を取得します。
*/
virtual void GetScreenMode( Bool IsFullColor, Sint32 No, Sint32 &Width, Sint32 &Height ) = 0;
/**
@brief レンダリングターゲットテクスチャサイズ数取得
@author 葉迩倭
@return レンダリングターゲットテクスチャサイズ数
使用可能なレンダリングターゲットテクスチャサイズの数を取得できます。
*/
virtual Sint32 CreateRenderTargetTextureSizeCount( void ) = 0;
/**
@brief レンダリングターゲットテクスチャサイズ
@author 葉迩倭
@param No [in] レンダリングターゲットテクスチャサイズのインデックス(最大数はCreateRenderTargetTextureSizeCount()で取得)
@param pWidth [out] 画面横幅格納先
@param pHeight [out] 画面縦幅格納先
使用可能なレンダリングターゲットテクスチャサイズを取得します。
*/
virtual void CreateRenderTargetTextureSize( Sint32 No, Sint32 *pWidth, Sint32 *pHeight ) = 0;
/**
@brief グラフィックカード名称取得
@author 葉迩倭
@param pName [out] 名称格納先
@param NameSize [in] pNameのバッファサイズ
接続されているグラフィックカードの名称を取得します。
*/
virtual void GetGraphicCardName( char *pName, Sint32 NameSize ) = 0;
/**
@brief 頂点シェーダーのバージョンを取得
@author 葉迩倭
@param pName [out] バージョン格納先
@param NameSize [in] pNameのバッファサイズ
接続されているグラフィックカードの頂点シェーダーのバージョンを取得します。
*/
virtual void GetVertexShaderVersion( char *pName, Sint32 NameSize ) = 0;
/**
@brief ピクセルシェーダーのバージョンを取得
@author 葉迩倭
@param pName [out] バージョン格納先
@param NameSize [in] pNameのバッファサイズ
接続されているグラフィックカードのピクセルシェーダーのバージョンを取得します。
*/
virtual void GetPixelShaderVersion( char *pName, Sint32 NameSize ) = 0;
/**
@brief IRenderインターフェイス生成
@author 葉迩倭
@param IsLockEnableBackBuffer [in] バックバッファのロック有無
@param IsWaitVSync [in] 画面更新時にVSYNCを待つ
@return IRenderインターフェイス
グラフィックカード上のレンダラー制御用のIRenderインターフェイスを取得します。<BR>
IRenderインターフェイスは1つのIGraphicCardに対して1つしか存在しません。
*/
virtual Renderer::IRender *CreateRender( Bool IsLockEnableBackBuffer = false, Bool IsWaitVSync = true ) = 0;
};
}
#pragma once
/**
@file
@brief アプリケーション管理インターフェイス
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
/**
@brief アプリケーション管理インターフェイス
@author 葉迩倭
@note
ウィンドウを管理するアプリケーションのコアのインターフェイスです。
*/
class ICore : public IInterface
{
public:
virtual ~ICore() {}
/**
@brief コアの初期化
@author 葉迩倭
@param pAppName [in] アプリケーション名
@param FrameRate [in] フレームレート
@retval false 失敗
@retval true 成功
@note
アプリケーションに関する初期化を行います。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Bool Initialize( const char *pAppName, eFrameRate FrameRate ) = 0;
/**
@brief ウィンドウ生成
@author 葉迩倭
@param ScreenWidth [in] 画面横幅
@param ScreenHeight [in] 画面縦幅
@param IsWindow [in] ウィンドウモードで起動する場合true
@note
ウィンドウを作成し、アプリケーションを起動します。<BR>
ここでの設定で起動後変更可能なものは画面モードだけです。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void Start( Sint32 ScreenWidth, Sint32 ScreenHeight, Bool IsWindow ) = 0;
/**
@brief ウィンドウの終了
@author 葉迩倭
@note
ウィンドウを解体し、アプリケーションを終了します。<BR>
この関数は終了を通知するだけで、実際にはメインループ後に<BR>
終了処理が行われます。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
// 終了
pCore->Exit();
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void Exit( void ) = 0;
/**
@brief アプリケーションメイン処理
@author 葉迩倭
@param IsFullActive [in] 常時動作フラグ
@retval false アプリケーションは終了した
@retval true アプリケーションは稼働中
@note
IsFullActiveにtrueを指定すると、<BR>
ウィンドウがフォーカスを失っている状態でも動作し続けます。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Bool Run( Bool IsFullActive = false ) = 0;
/**
@brief ウィンドウハンドル取得
@author 葉迩倭
@return ウィンドウのウィンドウハンドル
@note
ICoreの所有するウィンドウのウィンドウハンドルを取得します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// ウィンドウハンドルを取得
HWND hWnd = pCore->GetWindowHandle();
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual HWND GetWindowHandle( void ) = 0;
/**
@brief ベンチマーク用モード設定
@author 葉迩倭
@param IsEnable [in] trueにするとすべてのウェイト処理を省きます
@note
ベンチマークのような速度チェックをする場合に使います。<BR>
このフラグをtrueにするとVSYNCやタイマーなどの処理がすべて省かれ、<BR>
出せる最高の速度で処理が回ります。<BR>
<BR>
デフォルトはfalseです。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// ベンチマーク用に各種ウェイトをOFF
pCore->SetBenchMode( true );
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void SetBenchMode( Bool IsEnable ) = 0;
/**
@brief Sleep使用有無設定
@author 葉迩倭
@param IsEnable [in] trueにするとSleepを使用します
@note
フレームレートの調整にSleepを使うかどうかを設定します。<BR>
環境によっては誤差が大きくフレームレートが一定にならないことがあるので、<BR>
そのような条件ではfalseを設定して下さい。<BR>
Sleepを使わない場合は当然CPUを常に占有するようになります。<BR>
<BR>
デフォルトはtrueです。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// より厳密に時間計測をする(CPU使用率が跳ね上がるので注意)
pCore->SetSleepUse( false );
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void SetSleepUse( Bool IsEnable ) = 0;
/**
@brief 仮想画面処理のON/OFF
@author 葉迩倭
@param IsEnable [in] true 有効 / false 無効
@note
2D描画時の仮想画面処理の有無のON/OFFを設定します。<BR>
trueにする事で2Dの描画が仮想画面に行われるようになり、<BR>
画面解像度に関係なく画面に対する同じ割合で描画されるようになります。<BR>
<BR>
デフォルトはfalseです。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// 画面サイズが返られてもいいように2Dがを仮想画面に描画
pCore->SetVirtualScreenEnable( true );
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void SetVirtualScreenEnable( Bool IsEnable ) = 0;
/**
@brief 仮想画面設定
@author 葉迩倭
@param RealWidth [in] 実画面の横幅
@param RealHeight [in] 実画面の縦幅
@param VirtualWidth [in] 仮想画面の横幅
@param VirtualHeight [in] 仮想画面の縦幅
@note
可変画面サイズ用の設定を行います。<BR>
3D用に画面のサイズを自由に変えられるように作られている場合でも<BR>
2Dの描画は仮想画面に設定された画面サイズと見立てて描画を行います。<BR>
つまり仮想画面が(640x480)の時に(0,0)-(640,480)への全画面の2D描画を行った場合、<BR>
実際の画面のサイズが(320x240)や(1280x960)等のサイズであっても<BR>
全画面に自動的に拡大縮小して描画されるということです。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// 画面サイズが返られてもいいように2Dがを仮想画面に描画
pCore->SetVirtualScreenEnable( true );
// 仮想画面サイズ
pCore->SetVirtualScreenSize( 640, 480, 800, 600 );
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void SetVirtualScreenSize( Sint32 RealWidth, Sint32 RealHeight, Sint32 VirtualWidth, Sint32 VirtualHeight ) = 0;
/**
@brief GPU負荷を取得します。
@author 葉迩倭
@return GPU負荷(%)
@note
おおまかなGPUの負荷を取得します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
// CPU使用率
Float fCPU = pCore->GetCPU();
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Float GetCPU( void ) = 0;
/**
@brief FPSを取得します。
@author 葉迩倭
@return FPS
@note
秒間のフレーム数を取得します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
// FPS
Float fFPS = pCore->GetFPS();
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Float GetFPS( void ) = 0;
/**
@brief 1フレームのポリゴン数を取得します。
@author 葉迩倭
@return PPS
@note
秒間のポリゴン数を取得します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
// ポリゴン数取得
Float fPPF = pCore->GetPPF();
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Float GetPPF( void ) = 0;
/**
@brief OS起動からの時間取得
@author 葉迩倭
@return 1/1000秒単位の時間
@note
OSが起動してからの時間を取得します。<BR>
32Bit変数なので約48日で1周して0に戻ります。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
// 時間取得
Uint32 Time = pCore->GetMultiMediaTime();
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Uint32 GetMultiMediaTime( void ) = 0;
/**
@brief CPUタイマーのカウント値取得
@author 葉迩倭
@return 1/GetSystemTimerBySec秒単位の時間
@note
CPUタイマーの現在の時間を取得します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
// 時間取得
Uint64 Time = pCore->GetSystemTimer();
// なんか処理する
// 経過時間取得
Time = pCore->GetSystemTimer() - Time;
// 経過時間を1秒あたりの%に
Float fTime = 100.0 * (double)Time / (double)pCore->GetSystemTimerBySec();
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Uint64 GetSystemTimer( void ) = 0;
/**
@brief CPUタイマーの1秒のカウント値取得
@author 葉迩倭
@return GetSystemTimerの1秒のカウント値
@note
CPUタイマーの1秒の時間を取得します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
// 時間取得
Uint64 Time = pCore->GetSystemTimer();
// なんか処理する
// 経過時間取得
Time = pCore->GetSystemTimer() - Time;
// 経過時間を1秒あたりの%に
Float fTime = 100.0 * (double)Time / (double)pCore->GetSystemTimerBySec();
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Uint64 GetSystemTimerBySec( void ) = 0;
/**
@brief 画面サイズ変更
@author 葉迩倭
@param Size [in] 画面サイズ
@note
画面サイズを変更します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// 画面サイズ変更
pCore->ResizeWindowSize( Math::Point2DI(320,240) );
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void ResizeWindowSize( Math::Point2DI Size ) = 0;
/**
@brief 画面モードを変更します
@author 葉迩倭
@note
画面モードを変更します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// 画面モード変更
pCore->ChangeScreenMode();
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void ChangeScreenMode( void ) = 0;
/**
@brief ウィンドウモードチェック
@author 葉迩倭
@note
現在の画面モードがウィンドウモードかどうかを調べます
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// 画面モード取得
if ( pCore->IsWindowMode() )
{
}
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Bool IsWindowMode( void ) = 0;
/**
@brief ムービー再生
@author 葉迩倭
@param pFileName [in] ファイル名
@param IsLoop [in] ループON/OFF
@param pCallback [in] 強制終了用コールバック関数
@note
フル画面でムービーの再生を行います。<BR>
ムービーが終了するか、pCallback関数内でfalseを返すまで処理は戻ってきません。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// ムービー再生
if ( pCore->PlayMovie( "Sample.mpg", false, NULL ) )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Bool PlayMovie( const char *pFileName, Bool IsLoop, Bool (__stdcall *pCallback)( void ) ) = 0;
/**
@brief フレームカウントを取得します。
@author 葉迩倭
@return フレーム数
@note
起動時からの総フレーム数を取得します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
// 起動からのフレーム数
Sint32 Cnt = pCore->GetSyncCount();
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Sint32 GetSyncCount( void ) = 0;
/**
@brief タイトルバーの情報表示ON/OFF
@author 葉迩倭
@param IsEnable [in] 表示のON/OFF
@note
タイトルバーに現在の情報の表示を行うか設定します。<BR>
<BR>
デフォルトはfalseです。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// タイトルバーに情報表示
pCore->EnableDrawTitleInformation( true );
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void EnableDrawTitleInformation( Bool IsEnable ) = 0;
/**
@brief マウスカーソルの表示ON/OFF
@author 葉迩倭
@param IsEnable [in] 表示のON/OFF
@note
マウスカーソルの表示を行うか設定します。<BR>
<BR>
デフォルトはfalseです。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// マウスカーソル消去
pCore->EnableDrawMouseCursor( false );
// アプリケーション開始
pCore->Start( 640, 480, true );
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void EnableDrawMouseCursor( Bool IsEnable ) = 0;
/**
@brief グラフィックカードインターフェイスを取得
@author 葉迩倭
@param GraphicCardNo [in] グラフィックカード番号
@return グラフィックカードインターフェイス
@note
グラフィックカードに関しての初期化を行い、<BR>
そのインターフェイスを取得します。<BR>
通常GraphicCardNoにはGRAPHIC_CARD_DEFAULT_NOを指定します。<BR>
「NV PerfHUD」のインストールされた環境では、<BR>
GRAPHIC_CARD_NV_PERF_HUDを指定することでそれを有効に出来ます。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
IGraphicCard *pGraphicCard = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// グラフィックカードインターフェイスを生成
pGraphicCard = pCore->CreateGraphicCard( GRAPHIC_CARD_DEFAULT_NO );
// メインループ
while ( pCore->Run() )
{
}
}
// グラフィックカードの解放
SAFE_RELEASE( pGraphicCard );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual IGraphicCard *CreateGraphicCard( eGraphicCardNo GraphicCardNo ) = 0;
/**
@brief ジョイスティックの数を取得
@author 葉迩倭
@return 有効なジョイスティックの数
@note
初期化に成功した有効なジョイスティックなの数を取得します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// ジョイスティック数を取得
Sint32 Count = pCore->GetJoystickCount();
// メインループ
while ( pCore->Run() )
{
}
}
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Sint32 GetJoystickCount( void ) = 0;
/**
@brief マウスインターフェイスを取得
@author 葉迩倭
@return マウスインターフェイス
@note
ICoreの所有するウィンドウに関連付けられたマウスの初期化を行い、<BR>
そのインターフェイスを取得します。<BR>
マウスに関しての情報はこのインターフェイス経由で取得して下さい。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
Peripheral::IMouse *pMouse = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// マウスの取得
pMouse = pCore->GetMouse();
// メインループ
while ( pCore->Run() )
{
}
}
// マウスの解放
SAFE_RELEASE( pMouse );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Peripheral::IMouse *GetMouse( void ) = 0;
/**
@brief キーボードインターフェイスを取得
@author 葉迩倭
@return キーボードインターフェイス
@note
ICoreの所有するウィンドウに関連付けられたキーボードの初期化を行い、<BR>
そのインターフェイスを取得します。<BR>
キーボードに関しての情報はこのインターフェイス経由で取得して下さい。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
Peripheral::IKeyboard *pKeyboard = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// キーボードの取得
pKeyboard = pCore->GetKeyboard();
// メインループ
while ( pCore->Run() )
{
}
}
// キーボードの解放
SAFE_RELEASE( pKeyboard );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Peripheral::IKeyboard *GetKeyboard( void ) = 0;
/**
@brief ジョイスティックインターフェイスを取得
@author 葉迩倭
@param No [in] ジョイスティック番号(0〜15)
@return ジョイスティックインターフェイス
@note
ICoreの所有するウィンドウに関連付けられたジョイスティックの初期化を行い、<BR>
そのインターフェイスを取得します。<BR>
ジョイスティックに関しての情報はこのインターフェイス経由で取得して下さい。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
Peripheral::IJoystick *pJoystick = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// ジョイスティックの取得
pJoystick = pCore->GetJoystick( 0 );
// メインループ
while ( pCore->Run() )
{
}
}
// ジョイスティックの解放
SAFE_RELEASE( pJoystick );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Peripheral::IJoystick *GetJoystick( Sint32 No ) = 0;
/**
@brief 入力統合インターフェイスを取得
@author 葉迩倭
@param No [in] 適用するジョイスティック番号
@param KeyRepeatStartTime [in] キーリピート開始フレーム
@param KeyRepeatInterval [in] キーリピート間隔フレーム
@return 入力統合インターフェイス
@note
ICoreの所有するウィンドウに関連付けられたジョイスティック&キーボードの初期化を行い、<BR>
そのインターフェイスを取得します。<BR>
ジョイスティックとキーボードを統合して扱うことのできるインターフェイスです。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
Peripheral::IInputController *pInputController = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// 入力コントローラーの取得
pInputController = pCore->GetInputController( 0, 30, 5 );
// メインループ
while ( pCore->Run() )
{
}
}
// 入力コントローラーの解放
SAFE_RELEASE( pInputController );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Peripheral::IInputController *GetInputController( Sint32 No, Sint32 KeyRepeatStartTime, Sint32 KeyRepeatInterval ) = 0;
/**
@brief ファイルマネージャーインターフェイス生成
@author 葉迩倭
@return ファイルマネージャーインターフェイス
@note
新規のファイルマネージャーインターフェイスを生成します。<BR>
ファイルのパスなどの設定は全てIFileManagerを経由して行います。
取得したファイルマネージャーインターフェイスは使用終了後には必ずRelease()して下さい。。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
File::IFileManager *pFileMgr = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// ファイルマネージャーの生成
pFileMgr = pCore->CreateFileManager();
// ファイルマネージャーを設定
pCore->SetFileManager( pFileMgr );
// メインループ
while ( pCore->Run() )
{
}
}
// ファイルマネージャーの解放
SAFE_RELEASE( pFileMgr );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual File::IFileManager *CreateFileManager( void ) = 0;
/**
@brief ファイルマネージャーインターフェイス取得
@author 葉迩倭
@return ファイルマネージャーインターフェイス
@note
現在設定されているファイルマネージャーインターフェイスを取得します。<BR>
設定済みのファイルマネージャーインターフェイスへのアクセスを行う場合に使用してください。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
File::IFileManager *pFileMgr = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// ファイルマネージャーの生成
pFileMgr = pCore->CreateFileManager();
// ファイルマネージャーを設定
pCore->SetFileManager( pFileMgr );
// ファイルパス設定
pCore->GetFileMgrPointer()->SetCurrentPath( "Data\\Texture" );
// メインループ
while ( pCore->Run() )
{
}
}
// ファイルマネージャーの解放
SAFE_RELEASE( pFileMgr );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual File::IFileManager *GetFileMgrPointer( void ) = 0;
/**
@brief ファイルマネージャーインターフェイス設定
@author 葉迩倭
@param pMgr [in] ファイルマネージャーインターフェイス
@note
ファイルの読み込みに使われるファイルマネージャーインターフェイスを設定します。<BR>
ファイルの読み込みはこのマネージャーを経由して行うので、<BR>
ファイルの読み込みを行う場合は必ず設定してください。<BR>
既に設定されているマネージャーは内部で解放されます。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
File::IFileManager *pFileMgr = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// ファイルマネージャーの生成
pFileMgr = pCore->CreateFileManager();
// ファイルマネージャーを設定
pCore->SetFileManager( pFileMgr );
// メインループ
while ( pCore->Run() )
{
}
}
// ファイルマネージャーの解放
SAFE_RELEASE( pFileMgr );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void SetFileManager( File::IFileManager *pMgr ) = 0;
/**
@brief サウンドファイル読み込み
@author 葉迩倭
@param pFileName [in] サウンドファイル名(wav)
@param LayerCount [in] レイヤー数(同時発音可能数)
@param IsGlobalScope [in] サウンドのスコープ
@retval サウンドインターフェイス
@note
ICoreの所有するウィンドウに関連付けられたサウンドを取得します。<BR>
IsGlobalScopeにtrueを渡すと、ウィンドウのフォーカスに関係なく再生されます。<BR>
LayerCountで指定した数分のレイヤーを内部で持ちます。<BR>
これは同一のバッファを別々のタイミングで再生・停止等の<BR>
操作を行うための機能ですが、1つのバッファを使いまわすので<BR>
メモリ使用量は1つの場合と同じです。<BR>
使用の終了したサウンドは必ずRelease()して下さい。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
Sound::ISound *pSound = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// サウンドの生成
pSound = CreateSoundFromFile( "Sample.wav", 4, false );
// メインループ
while ( pCore->Run() )
{
}
}
// サウンドの解放
SAFE_RELEASE( pSound );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Sound::ISound *CreateSoundFromFile( const char *pFileName, Sint32 LayerCount, Bool IsGlobalScope ) = 0;
/**
@brief サウンドファイル読み込み
@author 葉迩倭
@param pFileName [in] サウンドファイル名
@param IsGlobalScope [in] サウンドのスコープ
@param pPluginName [in] プラグイン名
@retval サウンドインターフェイス
@note
ICoreの所有するウィンドウに関連付けられたサウンドを取得します。<BR>
IsGlobalScopeにtrueを渡すと、ウィンドウのフォーカスに関係なく再生されます。<BR>
使用の終了したサウンドは必ずRelease()して下さい。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
Sound::IStreamSound *pSound = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// サウンドの生成
pSound = CreateStreamSoundFromFile( "Sample.ogg", false, "OggVorbis" );
// メインループ
while ( pCore->Run() )
{
}
}
// サウンドの解放
SAFE_RELEASE( pSound );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Sound::IStreamSound *CreateStreamSoundFromFile( const char *pFileName, Bool IsGlobalScope, const char *pPluginName ) = 0;
/**
@brief ファイバーコントローラー生成
@author 葉迩倭
@param Max [in] ファイバー最大数
@return ファイバーコントローラーインターフェイス
@note
ファイバーコントローラーを取得します。<BR>
ICoreに1つしか存在せず2回目以降は既存のインターフェイスを返します。
@code
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
ICore *pCore = NULL;
Fiber::IFiberController *pFiber = NULL;
// システムの初期化
System::Initialize();
// コアの生成
pCore = System::CreateCore();
// 初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーション開始
pCore->Start( 640, 480, true );
// ファイバーコントローラーの生成
pFiber = pCore->CreateFiberController( 8 );
// メインループ
while ( pCore->Run() )
{
}
}
// ファイバーの解放
SAFE_RELEASE( pFiber );
// コアの解放
SAFE_RELEASE( pCore );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Fiber::IFiberController *CreateFiberController( Sint32 Max ) = 0;
};
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
/**
@brief コリジョン結果保持用
@author 葉迩倭
コリジョンの結果を保持するための構造体です。
*/
struct SCollisionResult
{
Uint32 Attribute; ///< 属性
Math::Vector3D vHitPosition; ///< 衝突点
Math::Vector3D vNormal; ///< 衝突面の法線
Math::Vector3D vTriangle[3]; ///< 衝突三角形をなす頂点
CColor Color[3]; ///< 衝突三角形をなす頂点の色
};
/**
@brief コリジョン結果保持用
@author 葉迩倭
コリジョンの結果を保持するための構造体です。
*/
struct SCollisionResultExtend
{
Uint32 Attribute; ///< 属性(Almeria上でのマテリアルの番号)
Math::Vector3D vHitPosition; ///< 衝突点
Math::Vector3D vNormal; ///< 衝突面の法線
Math::Vector3D vTriangle[3]; ///< 衝突三角形をなす頂点
Math::Vector3D vRefrectDirection; ///< 反射後の方向
Math::Vector3D vRefrectPosition; ///< 反射後の位置
Math::Vector3D vSlidePosition; ///< 面上をスライドした場合の位置
CColor Color[3]; ///< 衝突三角形をなす頂点の色
};
/**
@brief コリジョン結果保持用
@author 葉迩倭
コリジョンの結果を保持するための構造体です。
*/
struct SCollisionResultSphere
{
Math::Vector3D vHitPosition; ///< 衝突点
Math::Vector3D vNormal; ///< 衝突面の法線
};
/**
@brief コリジョン結果保持用
@author 葉迩倭
コリジョンの結果を保持するための構造体です。
*/
struct SCollisionResultSphereExtend
{
Math::Vector3D vHitPosition; ///< 衝突点
Math::Vector3D vNormal; ///< 衝突面の法線
Math::Vector3D vRefrectDirection; ///< 反射後の方向
Math::Vector3D vRefrectPosition; ///< 反射後の位置
Math::Vector3D vSlidePosition; ///< 面上をスライドした場合の位置
};
/**
@brief 2D描画用頂点
@author 葉迩倭
2D描画用の基本頂点データです。<BR>
主にIPoint2D/ILine2Dクラスで使用します。<BR>
VERTEX_ELEMENT_PRIMITIVEフラグを指定して作成した<BR>
頂点定義ではこの構造体を使います。
*/
struct SVertex2D
{
Math::Vector4D Pos; ///< 位置
CColor Col; ///< 頂点色
};
/**
@brief 2D描画用頂点
@author 葉迩倭
2D描画用のテクスチャUV付き頂点データです。<BR>
主にIPrimitive2D/ISprite2D/IFontSprite2Dクラスで使用します。<BR>
VERTEX_ELEMENT_SPRITEフラグを指定して作成した<BR>
頂点定義ではこの構造体を使います。
*/
struct SVertex2DTex
{
Math::Vector4D Pos; ///< 位置
CColor Col; ///< 頂点色
Math::Vector2D Tex[2]; ///< テクスチャUV
};
/**
@brief 3D描画用頂点
@author 葉迩倭
3D描画用の基本頂点データです。<BR>
VERTEX_ELEMENT_BASEフラグを指定して作成した<BR>
頂点定義に対して定義されます。
*/
struct SVertex3DBase
{
Math::Vector3D Pos; ///< 位置
CColor Col; ///< 頂点色
};
/**
@brief 3D描画用頂点
@author 葉迩倭
3D描画用のテクスチャUV用頂点データです。<BR>
VERTEX_ELEMENT_3DTEXTUREフラグを指定して作成した<BR>
頂点定義に対して定義されます。
*/
struct SVertex3DTexture
{
Math::Vector2D TexColor; ///< テクスチャUV
Math::Vector2D TexLight; ///< テクスチャUV
};
/**
@brief 3D描画用頂点
@author 葉迩倭
3D描画用のライティング用頂点データです。<BR>
VERTEX_ELEMENT_3DLIGHTフラグを指定して作成した<BR>
頂点定義に対して定義されます。
*/
struct SVertex3DLight
{
Math::Vector3D Norm; ///< 法線
};
/**
@brief 3D描画用頂点
@author 葉迩倭
3D描画用のバンプマッピング用頂点データです。<BR>
VERTEX_ELEMENT_3DBUMPフラグを指定して作成した<BR>
頂点定義に対して定義されます。
*/
struct SVertex3DBump
{
Math::Vector3D Tangent; ///< 接線
};
/**
@brief 3D描画用頂点
@author 葉迩倭
3D描画用のスキニング用頂点データです。<BR>
VERTEX_ELEMENT_3DANIMATIONフラグを指定して作成した<BR>
頂点定義に対して定義されます。
1つの頂点につき2つのボーンの計算が行われます。
*/
struct SVertex3DAnimation
{
Float Weight; ///< ウェイト(1番目のウェイトだけを指定、2番目はシェーダー内で1.0-Weightで算出)
Uint8 Index[4]; ///< ボーンインデックス
};
/**
@brief ラインプリミティブ用頂点データ
@author 葉迩倭
*/
struct SLineVertex2D
{
SVertex2D v1;
SVertex2D v2;
};
/**
@brief プリミティブ用頂点データ
@author 葉迩倭
*/
struct SPrimitiveVertex2D
{
SVertex2DTex v1;
SVertex2DTex v2;
SVertex2DTex v3;
};
/**
@brief 3Dプリミティブ基本データ
@author 葉迩倭
ILine3Dで描画を行う際に使用する頂点データ。
*/
struct SLineVertex3D
{
SVertex3DBase v1; ///< 位置・頂点色
SVertex3DBase v2; ///< 位置・頂点色
};
/**
@brief テクスチャ生成用コンフィグ
@author 葉迩倭
テクスチャ生成時に参照される<BR>
作成用パラメーターが定義されるクラスです。
*/
class CTextureConfig
{
private:
eSurfaceFormat m_Format; ///< サーフェイスフォーマット
CColor m_KeyColor; ///< カラーキーの色
Bool m_IsMipmap; ///< ミップマップ
Bool m_IsHalfSize; ///< 半分サイズ
public:
/**
@brief コンストラクタ
*/
CTextureConfig()
: m_Format ( FORMAT_TEXTURE_32BIT )
, m_KeyColor ( 0x00000000 )
, m_IsMipmap ( false )
, m_IsHalfSize ( false )
{
}
/**
@brief デストラクタ
*/
~CTextureConfig()
{
}
/**
@brief カラーキー(透明色)設定
@author 葉迩倭
@param Col [in] カラーキー(透明色)に使う色<BR>0x00000000の時カラーキー(透明色)OFF
テクスチャを読み込んだ際に指定した色のアルファを0にし、<BR>
カラーキー処理を行ったようにそのピクセルを描画<BR>
されないようにします。
*/
void SetColorKey( CColor Col )
{
m_KeyColor = Col;
}
/**
@brief サーフェイスフォーマット設定
@author 葉迩倭
@param Fmt [in] サーフェイスフォーマット
テクスチャ読み込み時のサーフェイスフォーマットを設定します。<BR>
無効なフォーマットを指定した場合、作成は失敗します。
*/
void SetFormat( eSurfaceFormat Fmt )
{
m_Format = Fmt;
}
/**
@brief ミップマップ有無設定
@author 葉迩倭
@param IsEnable [in] ミップマップ有無
テクスチャ読み込み時のミップマップの有無を設定します。
*/
void SetMipmapEnable( Bool IsEnable )
{
m_IsMipmap = IsEnable;
}
/**
@brief 1/2サイズテクスチャ有無設定
@author 葉迩倭
@param IsEnable [in] 1/2サイズテクスチャ有無
テクスチャ読み込み時の1/2サイズテクスチャの有無を設定します。<BR>
このフラグは純粋にテクスチャの使用量を抑える時に使います。
*/
void SetHalfSizeEnable( Bool IsEnable )
{
m_IsHalfSize = IsEnable;
}
/**
@brief カラーキーを取得
@author 葉迩倭
@retval 0 カラーキー処理を行わない
@retval 0以外 その色をカラーキーとする
*/
CColor GetColorKey( void )
{
return m_KeyColor;
}
/**
@brief サーフェイスフォーマットを取得します
@author 葉迩倭
@return サーフェイスフォーマット
*/
eSurfaceFormat GetFormat( void )
{
return m_Format;
}
/**
@brief ミップマップの有無を取得します
@author 葉迩倭
@return ミップマップの有無
*/
Bool IsMipmap( void )
{
return m_IsMipmap;
}
/**
@brief 1/2サイズテクスチャの有無を取得します
@author 葉迩倭
@return 1/2サイズテクスチャの有無
*/
Bool IsHalfSize( void )
{
return m_IsHalfSize;
}
};
/**
@brief レンダラーインターフェイス
@author 葉迩倭
画面に対する全ての描画処理を管理します。<BR>
描画用の各種クラスも全てこのクラスから取得します<BR>
またこのインターフェイスは1つのIDeviceインターフェイスに対して1つしか作成されません。
*/
class IRender
{
public:
virtual ~IRender() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief シェーダーバージョンチェック
@author 葉迩倭
@retval false 未対応
@retval true 対応
シェーダーモデル2.0に対応しているかどうかを調べます。
*/
virtual Bool IsSupportedPS20( void ) = 0;
/**
@brief シェーダーバージョンチェック
@author 葉迩倭
@retval false 未対応
@retval true 対応
シェーダーモデル3.0に対応しているかどうかを調べます。
*/
virtual Bool IsSupportedPS30( void ) = 0;
/**
@brief ピクセルシェーダーの命令数チェック
@author 葉迩倭
@parma Count [in] 命令数
@retval false 未対応
@retval true 対応
指定した命令数に対応している稼動を調べます。
*/
virtual Bool IsPixelShaderInstructionSupport( Sint32 Count ) = 0;
/**
@brief ピクセルシェーダーの命令数チェック
@author 葉迩倭
@retval マルチレンダリングターゲット数
マルチレンダリングターゲットの対応数を取得します。
*/
virtual Sint32 GetMRTs( void ) = 0;
/**
@brief レンダリングターゲットクリア
@author 葉迩倭
@param Color [in] クリアに使う色
@retval false 失敗
@retval true 成功
設定されたレンダリングターゲットを指定された色でクリアーします。
*/
virtual Bool Clear( CColor Color = 0x00000000 ) = 0;
/**
@brief 深度ステンシルバッファクリア
@author 葉迩倭
@retval false 失敗
@retval true 成功
設定された深度ステンシルバッファをクリアします。<BR>
深度ステンシルバッファが存在しない場合失敗します。
*/
virtual Bool ClearDepthStencil( void ) = 0;
/**
@brief 描画領域シザリング
@author 葉迩倭
@param pRect [in] 描画領域(NULLで解除)
指定した描画領域内にしかレンダリングされないようになります。<BR>
ビューポートには影響を与えません。
*/
virtual void SetScissorRect( const Math::Rect2DI *pRect ) = 0;
/**
@brief デバイスリセット時コールバック関数登録
@author 葉迩倭
@param pCallback [in] コールバック関数
デバイスロスト時にコールバックされる関数を設定します。<BR>
通常の用途では使用する必要はありません。<BR>
なんらかの理由で直接デバイスを操作する時にのみ使用してください。
*/
virtual void SetCallbackDeviceReset( void (*pCallback)( void ) ) = 0;
/**
@brief 利用可能なVRAM残量を取得
@author 葉迩倭
@return VRAM残量
使用可能なVRAM残量を取得します。<BR>
この値はビデオカードに搭載されているVRAM量とは違い、<BR>
ドライバが使用可能な容量を返します。
*/
virtual Float GetRestVRAM( void ) = 0;
/**
@brief デバイスリスト時コールバック関数登録
@author 葉迩倭
@param pCallback [in] コールバック関数
デバイスリストア時にコールバックされる関数を設定します。<BR>
通常の用途では使用する必要はありません。<BR>
なんらかの理由で直接デバイスを操作する時にのみ使用してください。
*/
virtual void SetCallbackDeviceRestore( void (*pCallback)( void ) ) = 0;
/**
@brief カラー書き込みマスクを設定
@author 葉迩倭
@param IsAlpha [in] アルファ書き込みマスクON/OFF
@param IsRed [in] 赤成分書き込みマスクON/OFF
@param IsGreen [in] 緑成分書き込みマスクON/OFF
@param IsBlue [in] 青成分書き込みマスクON/OFF
フラグをtrueにした色への書き込みを行います。<BR>
falseにするとその色への書き込みを行いません。
*/
virtual void SetColorWriteEnable( Bool IsAlpha, Bool IsRed, Bool IsGreen, Bool IsBlue ) = 0;
/**
@brief 内部デバイスを取得
@author 葉迩倭
@return デバイスのポインター
内部で使用しているデバイスを特例的に取得します。<BR>
通常の用途では使用する必要はありません。<BR>
なんらかの理由で直接デバイスを操作する時にのみ使用してください。<BR>
ここで取得したデバイスを経由してステートなどの変更を行った場合、<BR>
その後のSeleneでのステート管理はサポート外になります。<BR>
*/
virtual void *GetDriverDevicePointer( void ) = 0;
/**
@brief レンダリングターゲットの内容をPNGファイルに保存
@author 葉迩倭
@param pFileName [in] ファイル名(*.png)
レンダリングターゲットの内容をPNGファイルとして保存します。<BR>
この機能を使うにはレンダリングターゲットがロック可能なサーフェイスでなければいけません。
*/
virtual void SaveToFilePNG( const char *pFileName ) = 0;
/**
@brief レンダリングターゲットの内容をJPGファイルに保存
@author 葉迩倭
@param pFileName [in] ファイル名(*.jpg)
レンダリングターゲットの内容をJPGファイルとして保存します。<BR>
この機能を使うにはレンダリングターゲットがロック可能なサーフェイスでなければいけません。
*/
virtual void SaveToFileJPG( const char *pFileName ) = 0;
/**
@brief 標準のコントロールを表示するためのクリッピングのON/OFF
@author 葉迩倭
@param IsEnable [in] クリップ処理のON/OFF
trueを指定することでクリッピングが有効になりデバイス上でも正しく表示されるようになります。<BR>
*/
virtual void SetGUIEnable( Bool IsEnable ) = 0;
/**
@brief テクスチャ設定
@author 葉迩倭
@param Stage [in] 設定するステージ(0〜7)
@param pTex [in] 設定するテクスチャ(NULLで無効化)
@retval false 失敗
@retval true 成功
テクスチャをレンダラーに設定します。<BR>
一度設定されたテクスチャはNULLを設定するまで<BR>
有効になっています。
*/
virtual Bool SetTexture( eTextureStage Stage, ITexture *pTex ) = 0;
/**
@brief 深度バッファ設定
@author 葉迩倭
@param pSurface [in] 設定するサーフェイス
@retval false 失敗
@retval true 成功
深度バッファを設定します。
*/
virtual Bool SetDepthBuffer( ITexture *pTexture ) = 0;
/**
@brief レンダリングターゲット設定
@author 葉迩倭
@retval false 失敗
@retval true 成功
レンダリングターゲットをバックバッファに戻します。
*/
virtual Bool ResetRenderTarget( void ) = 0;
/**
@brief レンダリングターゲット設定
@author 葉迩倭
@retval false 失敗
@retval true 成功
レンダリングターゲットとして設定します。<BR>
CreateRenderTarget()で生成されたテクスチャ以外は失敗します。
*/
virtual Bool SetRenderTarget( ITexture *pTexture ) = 0;
/**
@brief レンダリング処理開始通知
@author 葉迩倭
レンダラーに対してこれからレンダリング処理を<BR>
開始するという事を通知します。
*/
virtual void Begin( void ) = 0;
/**
@brief レンダリング処理終了通知
@author 葉迩倭
レンダラーに対してこれでレンダリング処理を<BR>
終了するということを通知します。
*/
virtual void End( void ) = 0;
/**
@brief 2D描画シザリング設定
@author 葉迩倭
@param pRect [in] シザリング領域(NULLで解除)
レンダラーに関連する2D描画のシザリングを行います。
*/
virtual void SetScissorPrimitive2D( const Math::Rect2DF *pRect ) = 0;
/**
@brief カスタムシーン管理インターフェイス生成
@author 葉迩倭
@param QueMax [in] シーンの描画キューの最大数
@return カスタムシーン管理インターフェイス
全てをプロジェクト側で管理するカスタムシーンマネージャーを生成します。<BR>
レンダリングシステムを自前で管理したい場合に利用して下さい。
*/
virtual Scene::ICustomizedSceneManager *CreateCustomizedSceneManager( Sint32 QueMax ) = 0;
/**
@brief シーン管理インターフェイス生成
@author 葉迩倭
@param QueMax [in] シーンの描画キューの最大数
@param IsPixelShaderEnable [in] ピクセルシェーダーの有無
@return シーン管理インターフェイス
シェーダーモデル2.0ベースのシーン管理用のインターフェイスを生成します。<BR>
3Dに関するレンダリング処理は全てこのインターフェイスを介します。
*/
virtual Scene::ISceneManager *CreateSceneManager( Sint32 QueMax, Bool IsPixelShaderEnable ) = 0;
/**
@brief 2Dポイントプリミティブインターフェイス生成
@author 葉迩倭
@param PointMax [in] 内部バッファ格納可能ポイント数
@param IsAutoResize [in] 自動リサイズ
@param ResizeStep [in] リサイズ時拡張サイズ
@return 2Dポイントプリミティブインターフェイス
2Dの点描画用のインターフェイスを生成します。<BR>
画面に点を打つ場合はこのインターフェイスを使います。
*/
virtual Object::IPoint2D *CreatePoint2D( Sint32 PointMax, Bool IsAutoResize = false, Sint32 ResizeStep = 0 ) = 0;
/**
@brief 2Dラインプリミティブインターフェイス生成
@author 葉迩倭
@param LineMax [in] 内部バッファ格納可能ライン数
@param IsAutoResize [in] 自動リサイズ
@param ResizeStep [in] リサイズ時拡張サイズ
@return 2Dラインプリミティブインターフェイス
2Dの点描画用のインターフェイスを生成します。<BR>
画面に線を引く場合はこのインターフェイスを使います。
*/
virtual Object::ILine2D *CreateLine2D( Sint32 LineMax, Bool IsAutoResize = false, Sint32 ResizeStep = 0 ) = 0;
/**
@brief 2Dポリゴンプリミティブインターフェイス生成
@author 葉迩倭
@param PrimitiveMax [in] 内部バッファ格納可能頂点数(通常1つの三角形に三頂点消費する)
@param IsAutoResize [in] 自動リサイズ
@param ResizeStep [in] リサイズ時拡張サイズ
@return 2Dポリゴンプリミティブインターフェイス
2Dのポリゴン(三角形)を描画するためのインターフェイスを生成します。<BR>
最小単位である三角形ごとの描画を行う場合はこのインターフェイスを使います。
*/
virtual Object::IPrimitive2D *CreatePrimitive2D( Sint32 PrimitiveMax, Bool IsAutoResize = false, Sint32 ResizeStep = 0 ) = 0;
/**
@brief 2Dスプライトインターフェイス生成
@author 葉迩倭
@param PrimitiveMax [in] 内部バッファ格納可能頂点数(通常1つの三角形に三頂点消費する)
@param pTexture [in] スプライトに関連付けるテクスチャインターフェイス
@param IsFiltering [in] テクスチャフィルタを使うか否か
@param IsOffset [in] フィルタ使用時のテクスチャUV補正値を行うか否か
@param IsAutoResize [in] 自動リサイズ
@param ResizeStep [in] リサイズ時拡張サイズ
@return 2Dスプライトインターフェイス
2Dのスプライトを描画するためのインターフェイスを生成します。<BR>
IPrimitive2Dを継承しており、内部的にはIPrimitive2Dでの描画を行っています。<BR>
テクスチャを使った最も簡単なスプライト描画が可能なインターフェイスです。<BR>
<BR>
IsFilteringがtrueの時、描画にバイリニアフィルタリングが適用され、拡大縮小、回転などの時に<BR>
補間され綺麗な描画行われますが、逆に通常の等倍表示の時にぼやけてしまうという欠点があります。<BR>
この欠点を解消するにはIsFitlerをtrueにし、IsOffsetをfalseにする事で可能ですが、<BR>
バイリニアフィルタの隣接ピクセルを参照してしまうという問題は画像データの方で解消する必要があります。<BR>
具体的には周囲に1ドットに余白として何も描画されないピクセルを置くことです。
*/
virtual Object::ISprite2D *CreateSprite2D( Sint32 PrimitiveMax, ITexture *pTexture, Bool IsFiltering = false, Bool IsOffset = false, Bool IsAutoResize = false, Sint32 ResizeStep = 0 ) = 0;
/**
@brief 2D用フォントスプライトインターフェイス生成
@author 葉迩倭
@param pFileName [in] フォントスプライト用定義ファイル
@param pExt [in] フォントスプライト用画像ファイル拡張子
@param FontMax [in] 最大フォント数(内部の頂点バッファ数)
@param IsAutoResize [in] 自動リサイズ
@param ResizeStep [in] リサイズ時拡張サイズ
@return 2Dフォントスプライトインターフェイス
2Dのフォントスプライトを描画するためのインターフェイスを生成します。<BR>
ISprite2Dを利用しており、内部的にはISprite2Dでの描画を行っています。<BR>
FontUtilityで生成した定義ファイルとテクスチャを使って、高速に文字列の<BR>
描画を行うことが可能です。
*/
virtual Object::IFontSprite2D *CreateFontSprite2DFromFile( const char *pFileName, const char *pExt, Sint32 FontMax, Bool IsAutoResize = false, Sint32 ResizeStep = 0 ) = 0;
/**
@brief 3Dポイントプリミティブインターフェイス生成
@author 葉迩倭
@param VertexMax [in] ポイントの最大数
@param IsDynamic [in] ダイナミックバッファの使用ON/OFF(頻繁に書き換える場合はtrueにして下さい)
@return 3Dポイントプリミティブインターフェイス
3Dのポイント描画用のインターフェイスを生成します。<BR>
位置及び色データのみで、テクスチャやライトなどの不可効果をつけることは出来ません。
*/
virtual Object::IPoint3D *CreatePoint3D( Sint32 VertexMax, Bool IsDynamic ) = 0;
/**
@brief 3Dラインプリミティブインターフェイス生成
@author 葉迩倭
@param VertexMax [in] ラインの最大数
@param IsDynamic [in] ダイナミックバッファの使用ON/OFF(頻繁に書き換える場合はtrueにして下さい)
@return 3Dラインプリミティブインターフェイス
3Dのライン描画用のインターフェイスを生成します。<BR>
位置及び色データのみで、テクスチャやライトなどの不可効果をつけることは出来ません。
*/
virtual Object::ILine3D *CreateLine3D( Sint32 VertexMax, Bool IsDynamic ) = 0;
/**
@brief 3Dポリゴンプリミティブインターフェイス生成
@author 葉迩倭
@param VertexMax [in] 内部頂点バッファの最大数
@param IndexMax [in] 内部インデックスバッファの最大数
@param VertexFlag [in] 頂点データフラグ(eVertexElementの組み合わせ)
@param IsDynamicVertex [in] ダイナミック頂点バッファの使用ON/OFF(頻繁に書き換える場合はtrueにして下さい)
@param IsDynamicIndex [in] ダイナミックインデックスバッファの使用ON/OFF(頻繁に書き換える場合はtrueにして下さい)
@return 3Dポリゴンプリミティブインターフェイス
3Dのポリゴン(三角形)を描画するためのインターフェイスを生成します。<BR>
最小単位である三角形ごとの描画を行う場合はこのインターフェイスを使います。<BR>
またインデックスを使用した効率的な描画をサポートします。<BR>
VertexFlagは頂点のフォーマットを指定するもので eVertexElement 列挙型の中から<BR>
VERTEX_ELEMENT_PRIMITIVE と VERTEX_ELEMENT_SPRITE を除いたものを指定します。<BR>
複数組み合わせる場合は | 演算子で指定してください。<BR>
利用されるシェーダーは内部で作成された固定シェーダーが利用されます。<BR>
現在のバージョンではバンプマップに関する処理は行われません。<BR>
<BR>
(例)法線を持ちライティング可能な頂点 -> VERTEX_ELEMENT_3DTEXTURE | VERTEX_ELEMENT_3DLIGHT
*/
virtual Object::IPrimitive3D *CreatePrimitive3D( Sint32 VertexMax, Sint32 IndexMax, Sint32 VertexFlag, Bool IsDynamicVertex, Bool IsDynamicIndex ) = 0;
/**
@brief 3Dスプライトインターフェイス生成
@author 葉迩倭
@param SpriteMax [in] 内部バッファ格納可能スプライト数
@param pTexture [in] スプライトに関連付けるテクスチャインターフェイス
@return 3Dスプライトインターフェイス
3Dのスプライトを描画するためのインターフェイスを生成します。<BR>
IPrimitive3Dを継承しており、内部的にはIPrimitive3Dでの描画を行っています。<BR>
テクスチャを使った最も簡単なスプライト描画が可能なインターフェイスです。
*/
virtual Object::ISprite3D *CreateSprite3D( Sint32 SpriteMax, ITexture *pTexture ) = 0;
/**
@brief パーティクルインターフェイス生成
@author 葉迩倭
@param ParticleMax [in] 内部バッファ格納可能パーティクル数
@param pTexture [in] パーティクルに関連付けるテクスチャインターフェイス
@param Type [in] パーティクルに関する頂点フォーマットタイプ
@param IsSoftBillboard [in] ソフトパーティクル化するかどうか
@return パーティクルインターフェイス
パーティクルを描画するためのインターフェイスを生成します。<BR>
IPrimitive3Dを継承しており、内部的にはIPrimitive3Dでの描画を行っています。
*/
virtual Object::IParticle *CreateParticle( Sint32 ParticleMax, ITexture *pTexture, eParticleType Type, Bool IsSoftBillboard = false ) = 0;
/**
@brief 3D用フォントスプライトインターフェイス生成
@author 葉迩倭
@param pFileName [in] フォントスプライト用定義ファイル
@param pExt [in] フォントスプライト用画像ファイル拡張子
@param FontMax [in] 最大フォント数(内部の頂点バッファ数)
@return 3Dフォントスプライトインターフェイス
3Dのフォントスプライトを描画するためのインターフェイスを生成します。<BR>
IParticleを利用しており、内部的にはIParticleでの描画を行っています。<BR>
FontUtilityで生成した定義ファイルとテクスチャを使って、高速に文字列の<BR>
描画を行うことが可能です。
*/
virtual Object::IFontSprite3D *CreateFontSprite3DFromFile( const char *pFileName, const char *pExt, Sint32 FontMax ) = 0;
/**
@brief ツリーモデルをファイルから生成
@author 葉迩倭
@param pFileName [in] モデル名
SMF形式のモデルファイルを読み込みます。<BR>
SMFファイルはAmaryllisを使うことでXファイルから生成できます。
*/
virtual Object::IMapModel *CreateMapModelFromFile( const char *pFileName ) = 0;
/**
@brief ツリーモデルをメモリから生成
@author 葉迩倭
@param pData [in] モデルデータ
@param Size [in] データサイズ
SMF形式のモデルデータを読み込みます。<BR>
SMFファイルはAmaryllisを使うことでXファイルから生成できます。
*/
virtual Object::IMapModel *CreateMapModelFromMemory( const Uint8 *pData, Sint32 Size ) = 0;
/**
@brief モデルをファイルから生成
@author 葉迩倭
@param pFileName [in] モデル名
SMF形式のモデルファイルを読み込みます。<BR>
SMFファイルはAmaryllisを使うことでXファイルから生成できます。
*/
virtual Object::IModel *CreateModelFromFile( const char *pFileName ) = 0;
/**
@brief モデルをメモリから生成
@author 葉迩倭
@param pData [in] モデルデータ
@param Size [in] データサイズ
SMF形式のモデルデータを読み込みます。<BR>
SMFファイルはAmaryllisを使うことでXファイルから生成できます。
*/
virtual Object::IModel *CreateModelFromMemory( const Uint8 *pData, Sint32 Size ) = 0;
/**
@brief テクスチャ読み込み用コンフィグデータを取得
@author 葉迩倭
@return テクスチャコンフィグデータ
*/
virtual CTextureConfig &GetTextureConfig( void ) = 0;
/**
@brief テクスチャ読み込み用コンフィグデータ設定
@author 葉迩倭
@param Conf [in] テクスチャコンフィグデータ
*/
virtual void SetTextureConfig( CTextureConfig &Conf ) = 0;
/**
@brief デバイスからサーフェイスを生成
@author 葉迩倭
@param Width [in] 横幅
@param Height [in] 縦幅
@return サーフェイスインターフェイス
*/
virtual ITexture *CreateTextureDepthBuffer( Sint32 Width, Sint32 Height ) = 0;
/**
@brief デバイスからテクスチャを生成
@author 葉迩倭
@param Width [in] テクスチャの横幅
@param Height [in] テクスチャの縦幅
@param Format [in] テクスチャフォーマット
@return テクスチャインターフェイス
*/
virtual ITexture *CreateTextureRenderTarget( Sint32 Width, Sint32 Height, eSurfaceFormat Format ) = 0;
/**
@brief デバイスからテクスチャを生成
@author 葉迩倭
@param pFileName [in] テクスチャファイル名
@return テクスチャインターフェイス
*/
virtual ITexture *CreateTextureFromFile( const char *pFileName ) = 0;
/**
@brief デバイスからテクスチャを生成
@author 葉迩倭
@param pData [in] データのポインタ
@param Size [in] データサイズ
@return テクスチャインターフェイス
*/
virtual ITexture *CreateTextureFromMemory( const void *pData, Sint32 Size ) = 0;
/**
@brief デバイスからキューブテクスチャを生成
@author 葉迩倭
@param pFileName [in] テクスチャファイル名
@return テクスチャインターフェイス
*/
virtual ITexture *CreateCubeTextureFromFile( const char *pFileName ) = 0;
/**
@brief デバイスからキューブテクスチャを生成
@author 葉迩倭
@param pData [in] データのポインタ
@param Size [in] データサイズ
@return テクスチャインターフェイス
*/
virtual ITexture *CreateCubeTextureFromMemory( const void *pData, Sint32 Size ) = 0;
/**
@brief シェーダーの生成
@author 葉迩倭
@param pShader [in] シェーダーデータのポインタ
@param Size [in] シェーダーデータのサイズ
@param IsCompiled [in] コンパイル済みか否か
@return シェーダーインターフェイス
シェーダーファイルからシェーダーインターフェイスを生成します。
*/
virtual Shader::IShader *CreateShaderFromMemory( const void *pShader, Sint32 Size, Bool IsCompiled = false ) = 0;
/**
@brief シェーダーの生成
@author 葉迩倭
@param pShader [in] シェーダーファイル
@param IsCompiled [in] コンパイル済みか否か
@return シェーダーインターフェイス
シェーダーファイルからシェーダーインターフェイスを生成します。
*/
virtual Shader::IShader *CreateShaderFromFile( const char *pFile, Bool IsCompiled = false ) = 0;
/**
@brief 描画タイプ設定
@author 葉迩倭
@param Type [in] 描画タイプ
ポリゴンの描画タイプを設定します。
*/
virtual void SetDrawType( eDrawType Type ) = 0;
/**
@brief 表裏判定タイプ設定
@author 葉迩倭
@param Type [in] 表裏判定タイプ
ポリゴンの表裏判定タイプを設定します。
*/
virtual void SetCullType( eCullType Type ) = 0;
/**
@brief フィルタリングタイプ設定
@author 葉迩倭
@param Stage [in] 設定ステージ
@param Type [in] フィルタリングタイプ
テクスチャステージ毎のフィルタリングタイプを設定します。<BR>
TEXTURE_FILTER_ANISOTROPY系 のフィルタがサポートされないハードウェアでは<BR>
TEXTURE_FILTER_2D が使われます。
*/
virtual void SetTextureFilterType( eTextureStage Stage, eTextureFilterType Type ) = 0;
/**
@brief 深度テストON/OFF設定
@author 葉迩倭
@param Flag [in] 深度テストON/OFF
深度テストのON/OFFを設定します。
*/
virtual void SetDepthTestEnable( Bool Flag ) = 0;
/**
@brief 深度バッファ書き込みON/OFF設定
@author 葉迩倭
@param Flag [in] 深度バッファ書き込みON/OFF
深度バッファ書き込みのON/OFFを設定します。
*/
virtual void SetDepthWriteEnable( Bool Flag ) = 0;
/**
@brief アルファテストON/OFF設定
@author 葉迩倭
@param Flag [in] アルファテストON/OFF
アルファテストのON/OFFを設定します。
*/
virtual void SetAlphaTestEnable( Bool Flag ) = 0;
/**
@brief アルファテスト閾値設定
@author 葉迩倭
@param Bound [in] アルファテスト閾値
アルファテストの閾値を設定します。
*/
virtual void SetAlphaBoundary( Sint32 Bound ) = 0;
/**
@brief ステートの設定をスタックに退避します
@author 葉迩倭
@retval false スタックオーバーフロー
@retval true エラー無し
現在のステートをスタックに退避させます。<BR>
この関数によって退避されるステートは以下の関数で設定したものです。<BR>
・void SetDrawType( eDrawType Type )<BR>
・void SetCullType( eCullType Type )<BR>
・void SetTextureFilterType( Sint32 Stage, eTextureFilterType Type )<BR>
・void SetTextureAddressType( Sint32 Stage, eTextureAddressType Type )<BR>
・void SetDepthTestEnable( Bool Flag )<BR>
・void SetDepthWriteEnable( Bool Flag )<BR>
・void SetAlphaTestEnable( Bool Flag )<BR>
・void SetAlphaBoundary( Sint32 Bound )<BR>
・Bool SetTexture( Sint32 Stage, ITexture *pTex )
*/
virtual Bool StatePush( void ) = 0;
/**
@brief ステートの設定をスタックから復帰します
@author 葉迩倭
@retval false スタックオーバーフロー
@retval true エラー無し
現在のステートをスタックに退避去れているステートに戻します。
*/
virtual Bool StatePop( void ) = 0;
/**
@brief ステートの設定を初期状態にリセットします
@author 葉迩倭
現在のステートをスタックに退避去れているステートに戻します。<BR>
・SetDrawType( DRAW_TYPE_NORMAL )<BR>
・SetCullType( CULL_FRONT )<BR>
・SetDepthTestEnable( false )<BR>
・SetDepthWriteEnable( false )<BR>
・void SetAlphaTestEnable( true )<BR>
・void SetAlphaBoundary( Sint32 Bound )<BR>
・SetTextureFilterType( \\<Stage\\>, TEXTURE_FILTER_DISABLE )<BR>
・SetTextureAddressType( \\<Stage\\>, TEXTURE_ADDRESS_REPEAT )<BR>
・SetTexture( \\<Stage\\>, NULL )
*/
virtual void StateInit( void ) = 0;
/**
@brief デバッグ用文字設定変更
@author 葉迩倭
@param pFontFace [in] フォント種類
@param Size [in] フォントサイズ
デバッグ用の文字の設定を変更します。
*/
virtual void ChangeDebugPrintFont( const char *pFontFace, Sint32 Size ) = 0;
/**
@brief デバッグ用文字描画処理
@author 葉迩倭
@param Pos [in] 描画位置
@param Color [in] 描画色
@param pStr [in] 描画文字列
デバッグ用の文字描画を行います。
*/
virtual void DebugPrint( Math::Point2DI &Pos, CColor Color, const char *pStr, ... ) = 0;
/**
@brief 簡易文字描画用フォント設定
@author 葉迩倭
@param pFontFace [in] フォント種類
@param Size [in] フォントサイズ
簡易文字描画のフォントの設定をします
*/
virtual void SetDrawTextFont( const char *pFontFace, Sint32 Size ) = 0;
/**
@brief 簡易文字描画処理
@author 葉迩倭
@param Pos [in] 描画位置
@param Color [in] 描画色
@param pStr [in] 描画文字列
簡易文字描画を行います。
*/
virtual void DrawText( Math::Point2DI &Pos, CColor Color, const char *pStr, ... ) = 0;
/**
@brief 矩形レンダリング
@author 葉迩倭
@param Dst [in] 描画先矩形
@param Color [in] 描画色
単純な矩形を塗りつぶします。
*/
virtual void FillRect( const Math::Rect2DF &Dst, CColor Color ) = 0;
/**
@brief シェーダーを利用する場合のテクスチャを使った矩形回転付きのレンダリング
@author 葉迩倭
@param Dst [in] 描画先矩形
@param Color [in] 描画色
@param Src [in] テクスチャUV矩形
@param pTex [in] テクスチャ
@param Angle [in] 回転角度
@param Offset [in] 回転の中心の画像の中心からのオフセット
外部のシェーダーを利用する場合の回転付きの単純な矩形をテクスチャ対応でレンダリングします。
*/
virtual void DrawTextureByShader( const Math::Rect2DF &Dst, CColor Color, const Math::Rect2DF &Src, ITexture *pTex, Sint32 Angle = 0, const Math::Point2DF &Offset = Math::Point2DF(0.0f,0.0f) ) = 0;
/**
@brief テクスチャを使った矩形回転付きのレンダリング
@author 葉迩倭
@param Dst [in] 描画先矩形
@param Color [in] 描画色
@param Src [in] テクスチャUV矩形
@param pTex [in] テクスチャ
@param Angle [in] 回転角度
@param Offset [in] 回転の中心の画像の中心からのオフセット
回転付きの単純な矩形をテクスチャ対応でレンダリングします。
*/
virtual void DrawTexture( const Math::Rect2DF &Dst, CColor Color, const Math::Rect2DF &Src, ITexture *pTex, Sint32 Angle = 0, const Math::Point2DF &Offset = Math::Point2DF(0.0f,0.0f) ) = 0;
/**
@brief テクスチャを使った矩形回転付きのレンダリング
@author 葉迩倭
@param Dst [in] 描画先矩形
@param Color [in] 描画色
@param Src [in] テクスチャUV矩形
@param pTex [in] テクスチャ
@param Angle [in] 回転角度
@param Offset [in] 回転の中心の画像の中心からのオフセット
回転付きの単純な矩形をテクスチャ対応でレンダリングします。
*/
virtual void DrawTextureTile( const Math::Rect2DF &Dst, CColor Color, const Math::Rect2DF &Src, ITexture *pTex, Sint32 Angle = 0, const Math::Point2DF &Offset = Math::Point2DF(0.0f,0.0f) ) = 0;
/**
@brief ユニバーサルトランジション描画
@author 葉迩倭
@param Dst [in] 描画先矩形
@param fRate [in] 透明度(0.0〜1.0)
@param SrcBase [in] ベース画像テクスチャUV矩形
@param pTexBase [in] ベース画像テクスチャ
@param SrcRule [in] アルファ用ルールテクスチャUV矩形
@param pTexRule [in] アルファ用ルールテクスチャ
@param Angle [in] 回転角度
@param Offset [in] 回転の中心の画像の中心からのオフセット
ルール画像を用いたユニバーサルトランジションを行います。<BR>
PixelShader2.0がない環境ではDrawTextureに置き換えられます。
*/
virtual void DrawUniversal( const Math::Rect2DF &Dst, Float fRate, const Math::Rect2DF &SrcBase, ITexture *pTexBase, const Math::Rect2DF &SrcRule, ITexture *pTexRule, Sint32 Angle = 0, const Math::Point2DF &Offset = Math::Point2DF(0.0f,0.0f) ) = 0;
/**
@brief 4x4コーンぼかしフィルタ描画
@author 葉迩倭
@param Dst [in] 描画先矩形
@param Color [in] 描画色
@param Src [in] テクスチャUV矩形
@param pTex [in] テクスチャ
@param Angle [in] 回転角度
@param Offset [in] 回転の中心の画像の中心からのオフセット
4x4のボックスぼかしのフィルタをかけて描画します。<BR>
PixelShader2.0がない環境ではDrawTextureに置き換えられます。
*/
virtual void DrawBlur( const Math::Rect2DF &Dst, CColor Color, const Math::Rect2DF &Src, ITexture *pTex, Sint32 Angle = 0, const Math::Point2DF &Offset = Math::Point2DF(0.0f,0.0f) ) = 0;
/**
@brief グレースケールフィルタ描画
@author 葉迩倭
@param Dst [in] 描画先矩形
@param Color [in] 描画色
@param Src [in] テクスチャUV矩形
@param pTex [in] テクスチャ
@param Angle [in] 回転角度
@param Offset [in] 回転の中心の画像の中心からのオフセット
グレースケールのフィルタをかけて描画します。<BR>
PixelShader2.0がない環境ではDrawTextureに置き換えられます。
*/
virtual void DrawGrayscale( const Math::Rect2DF &Dst, CColor Color, const Math::Rect2DF &Src, ITexture *pTex, Sint32 Angle = 0, const Math::Point2DF &Offset = Math::Point2DF(0.0f,0.0f) ) = 0;
/**
@brief 魚眼レンズ描画
@author 葉迩倭
@param Dst [in] 描画先矩形
@param Color [in] 描画色
@param Src [in] テクスチャUV矩形
@param pTex [in] テクスチャ
@param fRate [in] 魚眼レンズ歪み度(0で歪みなし)
魚眼レンズのフィルタをかけて描画します。<BR>
PixelShader2.0がない環境ではDrawTextureに置き換えられます。
*/
virtual void DrawFishEye( const Math::Rect2DF &Dst, CColor Color, const Math::Rect2DF &Src, ITexture *pTex, Float fRate ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
typedef void *FX_HANDLE;
namespace Renderer
{
namespace Shader
{
class IShader : public IInterface
{
protected:
virtual ~IShader() {}
public:
virtual Bool Begin( Sint32 *pPassMax, Bool IsSave = false ) = 0;
virtual void End( void ) = 0;
virtual void BeginPass( Sint32 Pass ) = 0;
virtual void EndPass( void ) = 0;
virtual void UpdateParameter( void ) = 0;
virtual FX_HANDLE GetParameterByName( const char *pName ) = 0;
virtual FX_HANDLE GetParameterBySemantic( const char *pSemantic ) = 0;
virtual FX_HANDLE GetTechnique( const char *pName ) = 0;
virtual void SetTechnique( FX_HANDLE Handle ) = 0;
virtual void SetFloat( FX_HANDLE Handle, Float Param ) = 0;
virtual void SetFloatArray( FX_HANDLE Handle, const Float *pParam, Sint32 Num ) = 0;
virtual void SetInt( FX_HANDLE Handle, Sint32 Param ) = 0;
virtual void SetIntArray( FX_HANDLE Handle, const Sint32 *pParam, Sint32 Num ) = 0;
virtual void SetMatrix( FX_HANDLE Handle, const Math::SMatrix4x4 *pMatrix ) = 0;
virtual void SetMatrixArray( FX_HANDLE Handle, const Math::SMatrix4x4 *pMatrix, Sint32 Num ) = 0;
virtual void SetMatrixPointerArray( FX_HANDLE Handle, const Math::SMatrix4x4 **ppMatrix, Sint32 Num ) = 0;
virtual void SetMatrixTranspose( FX_HANDLE Handle, const Math::SMatrix4x4 *pMatrix ) = 0;
virtual void SetMatrixTransposeArray( FX_HANDLE Handle, const Math::SMatrix4x4 *pMatrix, Sint32 Num ) = 0;
virtual void SetTexture( FX_HANDLE Handle, Renderer::ITexture *pTex ) = 0;
virtual void SetVector( FX_HANDLE Handle, const Math::Vector4D *pVec ) = 0;
virtual void SetVectorArray( FX_HANDLE Handle, const Math::Vector4D *pVec, Sint32 Num ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief 2Dポイントプリミティブ管理インターフェイス
@author 葉迩倭
2Dポイント描画用のインターフェイスです。
*/
class IPoint2D
{
public:
virtual ~IPoint2D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( void ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
/**
@brief 内部バッファへデータ追加
@author 葉迩倭
@param pPoint [in] 頂点データ
@param Count [in] 追加数
内部バッファのデータの追加を行います。<BR>
この関数を呼び出す前に必ずBeing関数でデータ追加の開始を宣言して下さい。
*/
virtual Bool Push( SVertex2D *pPoint, Sint32 Count ) = 0;
/**
@brief レンダリング
@author 葉迩倭
内部バッファの内容のレンダリングを行います。
*/
virtual void Rendering( void ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief 2Dラインプリミティブ管理インターフェイス
@author 葉迩倭
2Dライン描画用のインターフェイスです。
*/
class ILine2D
{
public:
virtual ~ILine2D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( void ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
/**
@brief 内部バッファへデータ追加
@author 葉迩倭
@param pLine [in] ラインデータ
@param Count [in] 追加数
内部バッファのデータの追加を行います。<BR>
この関数を呼び出す前に必ずBeing関数でデータ追加の開始を宣言して下さい。
*/
virtual Bool Push( SLineVertex2D *pLine, Sint32 Count ) = 0;
/**
@brief レンダリング
@author 葉迩倭
内部バッファの内容のレンダリングを行います。
*/
virtual void Rendering( void ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief 2Dプリミティブ管理インターフェイス
@author 葉迩倭
2Dプリミティブ描画用のインターフェイスです。
*/
class IPrimitive2D
{
public:
virtual ~IPrimitive2D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( void ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
/**
@brief 頂点リクエスト数取得
@author 葉迩倭
@return リクエストした頂点数
Pushした最大頂点数を取得します。
*/
virtual Sint32 GetRequestedVertexCount( void ) = 0;
/**
@brief 頂点リクエスト数取得
@author 葉迩倭
@return リクエストした頂点数
Pushした最大頂点数を取得します。
*/
virtual Sint32 GetRequestedVertexCountMax( void ) = 0;
/**
@brief 内部バッファへデータ追加
@author 葉迩倭
@param pPrimitive [in] プリミティブデータ
@param Count [in] 追加数
内部バッファのデータの追加を行います。<BR>
この関数を呼び出す前に必ずBeing関数でデータ追加の開始を宣言して下さい。
*/
virtual Bool Push( SPrimitiveVertex2D *pPrimitive, Sint32 Count ) = 0;
/**
@brief レンダリング
@author 葉迩倭
内部バッファの内容のレンダリングを行います。
*/
virtual void Rendering( void ) = 0;
/**
@brief 四角形描画
@author 葉迩倭
@param DstRect [in] 描画矩形データ
@param Color [in] 描画色
単純な四角形を描画します。
*/
virtual void Square( Math::Rect2DI &DstRect, CColor Color ) = 0;
/**
@brief 回転付き四角形描画
@author 葉迩倭
@param DstRect [in] 描画矩形データ
@param Color [in] 描画色
@param Angle [in] 1周を65536とした回転角度
回転付きの四角形を描画します。
*/
virtual void SquareRotate( Math::Rect2DI &DstRect, CColor Color, Sint32 Angle ) = 0;
/**
@brief 多角形描画
@author 葉迩倭
@param Pos [in] 中心位置
@param fRadius [in] 描画半径
@param Color [in] 描画色
@param Num [in] 角数
単純な多角形を描画します。
*/
virtual void Polygon( Math::Point2DI Pos, Float fRadius, CColor Color, Sint32 Num ) = 0;
/**
@brief 回転付き多角形描画
@author 葉迩倭
@param Pos [in] 中心位置
@param fRadius [in] 描画半径
@param Color [in] 描画色
@param Num [in] 角数
@param Angle [in] 1周を65536とした回転角度
回転付き多角形を描画します。
*/
virtual void PolygonRotate( Math::Point2DI Pos, Float fRadius, CColor Color, Sint32 Num, Sint32 Angle ) = 0;
/**
@brief リング状描画
@author 葉迩倭
@param Pos [in] 中心位置
@param fInRadius [in] 内周半径
@param fOutRadius [in] 外周半径
@param InColor [in] 内周描画色
@param OutColor [in] 外周描画色
@param Num [in] 角数
リング状ポリゴンを描画します。
*/
virtual void Ring( Math::Point2DI Pos, Float fInRadius, Float fOutRadius, CColor InColor, CColor OutColor, Sint32 Num ) = 0;
/**
@brief 回転付きリング状描画
@author 葉迩倭
@param Pos [in] 中心位置
@param fInRadius [in] 内周半径
@param fOutRadius [in] 外周半径
@param InColor [in] 内周描画色
@param OutColor [in] 外周描画色
@param Num [in] 角数
@param Angle [in] 1周を65536とした回転角度
回転付きリング状ポリゴンを描画します。
*/
virtual void RingRotate( Math::Point2DI Pos, Float fInRadius, Float fOutRadius, CColor InColor, CColor OutColor, Sint32 Num, Sint32 Angle ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief DrawList用構造体
@author 葉迩倭
@note
DrawListで利用する構造体です。
*/
struct SSpriteListData2D
{
Math::Vector2D Pos;
Float Width;
Sint32 Angle;
CColor Color;
};
/**
@brief 2Dスプライト管理インターフェイス
@author 葉迩倭
2Dスプライト描画用のインターフェイスです。
*/
class ISprite2D
{
public:
virtual ~ISprite2D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( void ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
/**
@brief レンダリング
@author 葉迩倭
内部バッファの内容のレンダリングを行います。
*/
virtual void Rendering( void ) = 0;
/**
@brief 頂点リクエスト数取得
@author 葉迩倭
@return リクエストした頂点数
Pushした最大頂点数を取得します。
*/
virtual Sint32 GetRequestedVertexCount( void ) = 0;
/**
@brief 頂点リクエスト数取得
@author 葉迩倭
@return リクエストした頂点数
Pushした最大頂点数を取得します。
*/
virtual Sint32 GetRequestedVertexCountMax( void ) = 0;
/**
@brief 内部バッファへデータ追加
@author 葉迩倭
@param pPrimitive [in] プリミティブデータ
@param Count [in] 追加数
内部バッファのデータの追加を行います。<BR>
この関数を呼び出す前に必ずBeing関数でデータ追加の開始を宣言して下さい。
*/
virtual Bool Push( SPrimitiveVertex2D *pPrimitive, Sint32 Count ) = 0;
/**
@brief 装飾用テクスチャの設定
@author 葉迩倭
@param pTex [in] テクスチャインターフェイス
装飾用のテクスチャを設定します。
*/
virtual void SetDecoration( ITexture *pTex ) = 0;
/**
@brief 四角形描画
@author 葉迩倭
@param DstRect [in] 転送先スクリーンの矩形
@param SrcRect [in] 転送元テクスチャの矩形
@param Color [in] 頂点色
最も単純なスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawSquare( Math::Rect2DF &DstRect, Math::Rect2DF &SrcRect, CColor Color ) = 0;
/**
@brief 回転付き四角形描画
@author 葉迩倭
@param DstRect [in] 転送先スクリーンの矩形
@param SrcRect [in] 転送元テクスチャの矩形
@param Color [in] 頂点色
@param Angle [in] 1周65536とした回転角度
回転付きスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawSquareRotate( Math::Rect2DF &DstRect, Math::Rect2DF &SrcRect, CColor Color, Sint32 Angle ) = 0;
/**
@brief 回転付き四角形描画
@author 葉迩倭
@param DstRect [in] 転送先スクリーンの矩形
@param SrcRect [in] 転送元テクスチャの矩形
@param Color [in] 頂点色
@param AngleX [in] 1周65536とした回転角度
@param AngleY [in] 1周65536とした回転角度
@param AngleZ [in] 1周65536とした回転角度
回転付きスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawSquareRotateXYZ( Math::Rect2DF &DstRect, Math::Rect2DF &SrcRect, CColor Color, Sint32 AngleX, Sint32 AngleY, Sint32 AngleZ ) = 0;
/**
@brief 行列変換四角形描画
@author 葉迩倭
@param mWorld [in] 変換行列
@param SrcRect [in] 転送元テクスチャの矩形
@param Color [in] 頂点色
行列変換付きスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawSquareMatrix( Math::Matrix &mWorld, Math::Rect2DF &SrcRect, CColor Color ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param Pos [in] 描画位置の配列
@param Angle [in] 1周65536とした回転角度の配列
@param Color [in] 描画色の配列
@param Count [in] 各要素の配列数
@param Width [in] 頂点ごとの幅
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawList( Math::Point2DF Pos[], Sint32 Angle[], CColor Color[], Sint32 Count, Float Width, Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param Pos [in] 描画位置の配列
@param Width [in] 頂点ごとの幅の配列
@param Angle [in] 1周65536とした回転角度の配列
@param Color [in] 描画色の配列
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawList( Math::Point2DF Pos[], Float Width[], Sint32 Angle[], CColor Color[], Sint32 Count, Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param Pos [in] 描画位置の配列
@param List [in] リスト情報の配列
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawList( SSpriteListData2D List[], Sint32 Count, Math::Rect2DF &Src ) = 0;
/**
@brief 放射状フェード
@author 葉迩倭
@param SrcRect [in] 転送元テクスチャの矩形
@param Divide [in] 円周のポリゴンの分割数
@param Side [in] 1辺あたりのポリゴンの分割数
@param Alpha [in] 透明度
中心に向かってフェードするエフェクトです。<BR>
画面の切り替え時などに利用できると思います。
*/
virtual void CircleFade( Math::Rect2DF &SrcRect, Sint32 Divide, Sint32 Side, Sint32 Alpha ) = 0;
/**
@brief 円状回転フェード
@author 葉迩倭
@param SrcRect [in] 転送元テクスチャの矩形
@param Divide [in] 円周のポリゴンの分割数
@param Side [in] 1辺あたりのポリゴンの分割数
@param Alpha [in] 透明度
時計回りにフェードするエフェクトです。<BR>
画面の切り替え時などに利用できると思います。
*/
virtual void CircleRoundFade( Math::Rect2DF &SrcRect, Sint32 Divide, Sint32 Side, Sint32 Alpha ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief フォントスプライト管理インターフェイス
@author 葉迩倭
2Dフォント描画用のインターフェイスです。
*/
class IFontSprite2D
{
public:
virtual ~IFontSprite2D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
@param Space [in] 行間補正値
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( Sint32 Space = 0 ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
/**
@brief レンダリング
@author 葉迩倭
内部バッファの内容のレンダリングを行います。
*/
virtual void Rendering( void ) = 0;
/**
@brief 装飾用テクスチャの設定
@author 葉迩倭
@param pTex [in] テクスチャインターフェイス
装飾用のテクスチャを設定します。
*/
virtual void SetDecoration( ITexture *pTex ) = 0;
/**
@brief サイズ取得
@author 葉迩倭
文字サイズを取得
*/
virtual Sint32 GetSize( void ) = 0;
/**
@brief 文字列描画
@author 葉迩倭
@param pStr [in] 描画文字列
@param Pos [in] 描画座標
@param Color [in] 描画色
@param Length [in] 描画文字数(-1で全て)
等幅フォントで文字列の描画を行います。<BR>
生成時の書体が等幅フォントでない場合は正しく描画されない事があります。
*/
virtual void DrawString( const char *pStr, Math::Point2DF Pos, CColor Color, Sint32 Length = -1 ) = 0;
/**
@brief 文字列描画
@author 葉迩倭
@param pStr [in] 描画文字列
@param Pos [in] 描画座標
@param Color [in] 描画色
@param Length [in] 描画文字数(-1で全て)
プロポーショナルフォントで文字列の描画を行います。<BR>
生成時の書体がプロポーショナルフォントでなくても正しく描画されます。
*/
virtual void DrawStringP( const char *pStr, Math::Point2DF Pos, CColor Color, Sint32 Length = -1 ) = 0;
/**
@brief 文字描画
@author 葉迩倭
@param pChara [in] 描画文字
@param Dst [in] 描画矩形
@param Color [in] 描画色
指定位置に文字を描画します。<BR>
この関数では文字の拡大縮小をサポートします。
*/
virtual Sint32 DrawChara( const char *pChara, Math::Rect2DF &Dst, CColor Color ) = 0;
/**
@brief 回転付き文字描画
@author 葉迩倭
@param pChara [in] 描画文字
@param Dst [in] 描画矩形
@param Color [in] 描画色
@param Angle [in] 1周を65536とした回転角度
指定位置に文字を回転付きで描画します。<BR>
この関数では文字の拡大縮小をサポートします。
*/
virtual Sint32 DrawCharaRotate( const char *pChara, Math::Rect2DF &Dst, CColor Color, Sint32 Angle ) = 0;
/**
@brief 文字列描画完了位置取得
@author 葉迩倭
@param pStr [in] 描画文字列
@param Pos [in] 描画座標
@param Length [in] 描画文字数(-1で全て)
@return 描画完了時の座標
等幅フォントで文字列の描画を行った場合の最終的な描画終了位置を取得します。<BR>
改行が含まれる場合は改行を考慮した最終位置を返すので、<BR>
文字列の最大幅を取得したい場合は注意してください。
*/
virtual Math::Point2DF GetStringLastPos( const char *pStr, Math::Point2DF Pos, Sint32 Length = -1 ) = 0;
/**
@brief 文字列描画完了位置取得
@author 葉迩倭
@param pStr [in] 描画文字列
@param Pos [in] 描画座標
@param Length [in] 描画文字数(-1で全て)
@return 描画完了時の座標
プロポーショナルフォントで文字列の描画を行った場合の最終的な描画終了位置を取得します。<BR>
改行が含まれる場合は改行を考慮した最終位置を返すので、<BR>
文字列の最大幅を取得したい場合は注意してください。
*/
virtual Math::Point2DF GetStringLastPosP( const char *pStr, Math::Point2DF Pos, Sint32 Length = -1 ) = 0;
/**
@brief 文字列描画サイズ取得
@author 葉迩倭
@param pStr [in] 描画文字列
@return 描画サイズ
等幅フォントで文字列の描画を行った場合の縦横のサイズを取得します。<BR>
改行が含まれる場合でも最大の横幅を取得できます。
*/
virtual Math::Point2DF GetStringSize( const char *pStr ) = 0;
/**
@brief 文字列描画サイズ取得
@author 葉迩倭
@param pStr [in] 描画文字列
@return 描画サイズ
プロポーショナルフォントで文字列の描画を行った場合の縦横のサイズを取得します。<BR>
改行が含まれる場合でも最大の横幅を取得できます。
*/
virtual Math::Point2DF GetStringSizeP( const char *pStr ) = 0;
/**
@brief 文字列描画
@author 葉迩倭
@param pStr [in] 描画文字列
@param Pos [in] 描画座標
@param Color [in] 描画色
@param Length [in] 描画文字数(-1で全て)
等幅フォントで文字列の描画を行います。<BR>
生成時の書体が等幅フォントでない場合は正しく描画されない事があります。
*/
virtual void DrawString( const wchar_t *pStr, Math::Point2DF Pos, CColor Color, Sint32 Length = -1 ) = 0;
/**
@brief 文字列描画
@author 葉迩倭
@param pStr [in] 描画文字列
@param Pos [in] 描画座標
@param Color [in] 描画色
@param Length [in] 描画文字数(-1で全て)
プロポーショナルフォントで文字列の描画を行います。<BR>
生成時の書体がプロポーショナルフォントでなくても正しく描画されます。
*/
virtual void DrawStringP( const wchar_t *pStr, Math::Point2DF Pos, CColor Color, Sint32 Length = -1 ) = 0;
/**
@brief 文字描画
@author 葉迩倭
@param pChara [in] 描画文字
@param Dst [in] 描画矩形
@param Color [in] 描画色
指定位置に文字を描画します。<BR>
この関数では文字の拡大縮小をサポートします。
*/
virtual Sint32 DrawChara( const wchar_t *pChara, Math::Rect2DF &Dst, CColor Color ) = 0;
/**
@brief 回転付き文字描画
@author 葉迩倭
@param pChara [in] 描画文字
@param Dst [in] 描画矩形
@param Color [in] 描画色
@param Angle [in] 1周を65536とした回転角度
指定位置に文字を回転付きで描画します。<BR>
この関数では文字の拡大縮小をサポートします。
*/
virtual Sint32 DrawCharaRotate( const wchar_t *pChara, Math::Rect2DF &Dst, CColor Color, Sint32 Angle ) = 0;
/**
@brief 文字列描画完了位置取得
@author 葉迩倭
@param pStr [in] 描画文字列
@param Pos [in] 描画座標
@param Length [in] 描画文字数(-1で全て)
@return 描画完了時の座標
等幅フォントで文字列の描画を行った場合の最終的な描画終了位置を取得します。<BR>
改行が含まれる場合は改行を考慮した最終位置を返すので、<BR>
文字列の最大幅を取得したい場合は注意してください。
*/
virtual Math::Point2DF GetStringLastPos( const wchar_t *pStr, Math::Point2DF Pos, Sint32 Length = -1 ) = 0;
/**
@brief 文字列描画完了位置取得
@author 葉迩倭
@param pStr [in] 描画文字列
@param Pos [in] 描画座標
@param Length [in] 描画文字数(-1で全て)
@return 描画完了時の座標
プロポーショナルフォントで文字列の描画を行った場合の最終的な描画終了位置を取得します。<BR>
改行が含まれる場合は改行を考慮した最終位置を返すので、<BR>
文字列の最大幅を取得したい場合は注意してください。
*/
virtual Math::Point2DF GetStringLastPosP( const wchar_t *pStr, Math::Point2DF Pos, Sint32 Length = -1 ) = 0;
/**
@brief 文字列描画サイズ取得
@author 葉迩倭
@param pStr [in] 描画文字列
@return 描画サイズ
等幅フォントで文字列の描画を行った場合の縦横のサイズを取得します。<BR>
改行が含まれる場合でも最大の横幅を取得できます。
*/
virtual Math::Point2DF GetStringSize( const wchar_t *pStr ) = 0;
/**
@brief 文字列描画サイズ取得
@author 葉迩倭
@param pStr [in] 描画文字列
@return 描画サイズ
プロポーショナルフォントで文字列の描画を行った場合の縦横のサイズを取得します。<BR>
改行が含まれる場合でも最大の横幅を取得できます。
*/
virtual Math::Point2DF GetStringSizeP( const wchar_t *pStr ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief 3Dポイント描画用インターフェイス
@author 葉迩倭
3Dポイント描画を保持するためのインターフェイスです。
*/
class IPoint3D
{
public:
virtual ~IPoint3D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 頂点データを追加
@author 葉迩倭
@param pPoint [in] ポイントデータ
@param PointCount [in] ポイント数
@retval false 追加できなかった(バッファーオーバーフロー)
@retval true 追加できた
内部バッファへ頂点データを追加します。<BR>
生成時に指定した頂点フォーマットに適合した頂点データを設定してください。
*/
virtual Bool Push( const SVertex3DBase *pPoint, Sint32 PointCount ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( void ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief 3Dライン描画用インターフェイス
@author 葉迩倭
3Dライン描画を保持するためのインターフェイスです。
*/
class ILine3D
{
public:
virtual ~ILine3D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 頂点データを追加
@author 葉迩倭
@param pLine [in] ラインデータ
@param LineCount [in] ライン数
@retval false 追加できなかった(バッファーオーバーフロー)
@retval true 追加できた
内部バッファへ頂点データを追加します。<BR>
生成時に指定した頂点フォーマットに適合した頂点データを設定してください。
*/
virtual Bool Push( SLineVertex3D *pLine, Sint32 LineCount ) = 0;
/**
@brief バウンディングボックス描画リクエスト
@author 葉迩倭
@param Box [in] コリジョン用のボックス
@param Color [in] 色
コリジョン用のボックスデータの描画を行います。
*/
virtual void PushBox( Collision::CBox &Box, CColor Color ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( void ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief 3Dプリミティブ描画用インターフェイス
@author 葉迩倭
3Dプリミティブ描画を保持するためのインターフェイスです。
*/
class IPrimitive3D
{
public:
virtual ~IPrimitive3D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 頂点データを追加
@author 葉迩倭
@param pVtx [in] 頂点データ
@param Count [in] 頂点数
@retval false 追加できなかった(バッファーオーバーフロー)
@retval true 追加できた
内部バッファへ頂点データを追加します。<BR>
適合した頂点データを設定してください。
*/
virtual Bool Push( const SVertex3DBase *pVtx, Sint32 Count ) = 0;
/**
@brief 頂点データを追加
@author 葉迩倭
@param pVtx [in] 頂点データ
@param Count [in] 頂点数
@retval false 追加できなかった(バッファーオーバーフロー)
@retval true 追加できた
内部バッファへ頂点データを追加します。<BR>
適合した頂点データを設定してください。
*/
virtual Bool Push( const SVertex3DTexture *pVtx, Sint32 Count ) = 0;
/**
@brief 頂点データを追加
@author 葉迩倭
@param pVtx [in] 頂点データ
@param Count [in] 頂点数
@retval false 追加できなかった(バッファーオーバーフロー)
@retval true 追加できた
内部バッファへ頂点データを追加します。<BR>
適合した頂点データを設定してください。
*/
virtual Bool Push( const SVertex3DLight *pVtx, Sint32 Count ) = 0;
/**
@brief 頂点データを追加
@author 葉迩倭
@param pVtx [in] 頂点データ
@param Count [in] 頂点数
@retval false 追加できなかった(バッファーオーバーフロー)
@retval true 追加できた
内部バッファへ頂点データを追加します。<BR>
適合した頂点データを設定してください。
*/
virtual Bool Push( const SVertex3DBump *pVtx, Sint32 Count ) = 0;
/**
@brief 頂点データを追加
@author 葉迩倭
@param pVtx [in] 頂点データ
@param Count [in] 頂点数
@retval false 追加できなかった(バッファーオーバーフロー)
@retval true 追加できた
内部バッファへ頂点データを追加します。<BR>
適合した頂点データを設定してください。
*/
virtual Bool Push( const SVertex3DAnimation *pVtx, Sint32 Count ) = 0;
/**
@brief インデックスデータを追加
@author 葉迩倭
@param pIndex [in] インデックスデータ
@param IndexCount [in] インデックス数
@retval false 追加できなかった(バッファーオーバーフロー)
@retval true 追加できた
内部バッファへインデックスデータを追加します。<BR>
生成時に指定したインデックスフォーマットに適合したインデックスデータを設定してください。
*/
virtual Bool Push( const void *pIndex, Sint32 IndexCount ) = 0;
/**
@brief 頂点数取得
@author 葉迩倭
@return 追加要求をした頂点の数
追加要求を行ったSVertex3DBase頂点の数を取得します。<BR>
この値は実際に追加された数ではなく、Pushを行って追加された数を<BR>
取得するので、実際に持てる最大数以上の数を返す場合があります。
*/
virtual Sint32 GetVertexCount( void ) = 0;
/**
@brief インデックス数取得
@author 葉迩倭
@return 追加要求をしたインデックスの数
追加要求を行ったインデックスの数を取得します。<BR>
この値は実際に追加された数ではなく、Pushを行って追加された数を<BR>
取得するので、実際に持てる最大数以上の数を返す場合があります。
*/
virtual Sint32 GetIndexCount( void ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
@param IsVertex [in] 頂点書き込み行う
@param IsIndex [in] インデックス書き込み行う
@param IsDirect [in] バッファ直接書き込み
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( Bool IsVertex = true, Bool IsIndex = true, Bool IsDirect = true ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief DrawList用構造体
@author 葉迩倭
@note
DrawListで利用する構造体です。
*/
struct SSpriteListData3D
{
Math::Vector3D Pos;
Float Width;
Sint32 Angle;
CColor Color;
};
/**
@brief 3Dスプライト描画用インターフェイス
@author 葉迩倭
3Dスプライト描画を保持するためのインターフェイスです。
*/
class ISprite3D
{
public:
virtual ~ISprite3D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( void ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
@param mWorld [in] ワールドの変換行列
@param Size [in] 描画サイズ
@param SrcRect [in] テクスチャ矩形
@param Color [in] 色
内部バッファへのデータの追加を行います。<BR>
Sizeで指定した大きさの四角形ポリゴンをmWorldで変換します。
*/
virtual void Draw( const Math::Matrix &mWorld, const Math::Point2DF &Size, const Math::Rect2DI &SrcRect, CColor Color ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
@param mWorld [in] ワールドの変換行列
@param PtTbl [in] 描画用4頂点(左上−右上−左下−右下)
@param SrcRect [in] テクスチャ矩形
@param Color [in] 色
内部バッファへのデータの追加を行います。<BR>
vPositionを基準位置としてPtTblで指定した大きさの矩形を作りmWorldで変換します。
*/
virtual void Draw( const Math::Matrix &mWorld, const Math::Vector2D PtTbl[], const Math::Rect2DI &SrcRect, CColor Color ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param vCameraPosition [in] カメラの位置
@param Pos [in] 描画位置の配列
@param Color [in] 描画色の配列
@param Count [in] 各要素の配列数
@param Width [in] 頂点ごとの幅
@param Src [in] 転送元テクスチャの矩形
カメラの位置に応じて自動回転処理が行われた<BR>
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawPolyLine( const Math::Vector3D &vCameraPosition, const Math::Vector3D Pos[], const CColor Color[], Sint32 Count, Float Width, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param vCameraPosition [in] カメラの位置
@param Pos [in] 描画位置の配列
@param Color [in] 描画色の配列
@param Width [in] 頂点ごとの幅
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
カメラの位置に応じて自動回転処理が行われた<BR>
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawPolyLine( const Math::Vector3D &vCameraPosition, const Math::Vector3D Pos[], const CColor Color[], const Float Width[], Sint32 Count, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param vCameraPosition [in] カメラの位置
@param List [in] 頂点ごとの配列
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
カメラの位置に応じて自動回転処理が行われた<BR>
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawPolyLine( const Math::Vector3D &vCameraPosition, const SSpriteListData3D List[], Sint32 Count, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param Pos [in] 描画位置の配列
@param Angle [in] 1周65536とした回転角度の配列
@param Color [in] 描画色の配列
@param Count [in] 各要素の配列数
@param Width [in] 頂点ごとの幅
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawListXY( const Math::Vector3D Pos[], const Sint32 Angle[], const CColor Color[], Sint32 Count, Float Width, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param Pos [in] 描画位置の配列
@param Angle [in] 1周65536とした回転角度の配列
@param Color [in] 描画色の配列
@param Count [in] 各要素の配列数
@param Width [in] 頂点ごとの幅
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawListYZ( const Math::Vector3D Pos[], const Sint32 Angle[], const CColor Color[], Sint32 Count, Float Width, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param Pos [in] 描画位置の配列
@param Angle [in] 1周65536とした回転角度の配列
@param Color [in] 描画色の配列
@param Count [in] 各要素の配列数
@param Width [in] 頂点ごとの幅
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawListZX( const Math::Vector3D Pos[], const Sint32 Angle[], const CColor Color[], Sint32 Count, Float Width, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param Pos [in] 描画位置の配列
@param Width [in] 頂点ごとの幅の配列
@param Angle [in] 1周65536とした回転角度の配列
@param Color [in] 描画色の配列
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawListXY( const Math::Vector3D Pos[], const Float Width[], const Sint32 Angle[], const CColor Color[], Sint32 Count, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param Pos [in] 描画位置の配列
@param Width [in] 頂点ごとの幅の配列
@param Angle [in] 1周65536とした回転角度の配列
@param Color [in] 描画色の配列
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawListYZ( const Math::Vector3D Pos[], const Float Width[], const Sint32 Angle[], const CColor Color[], Sint32 Count, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param Pos [in] 描画位置の配列
@param Width [in] 頂点ごとの幅の配列
@param Angle [in] 1周65536とした回転角度の配列
@param Color [in] 描画色の配列
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawListZX( const Math::Vector3D Pos[], const Float Width[], const Sint32 Angle[], const CColor Color[], Sint32 Count, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param List [in] 頂点ごとの配列
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawListXY( const SSpriteListData3D List[], Sint32 Count, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param List [in] 頂点ごとの配列
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawListYZ( const SSpriteListData3D List[], Sint32 Count, const Math::Rect2DF &Src ) = 0;
/**
@brief 帯状四角形描画
@author 葉迩倭
@param List [in] 頂点ごとの配列
@param Count [in] 各要素の配列数
@param Src [in] 転送元テクスチャの矩形
帯状に連結したスプライトを描画することが出来ます。<BR>
この関数はデータを描画バッファに追加するだけで<BR>
実際のレンダリング処理はRendering関数呼び出し時に開始されます。
*/
virtual void DrawListZX( const SSpriteListData3D List[], Sint32 Count, const Math::Rect2DF &Src ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief 3D文字描画用インターフェイス
@author 葉迩倭
3D文字描画を保持するためのインターフェイスです。
*/
class IFontSprite3D
{
public:
virtual ~IFontSprite3D() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( void ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
/**
@brief 文字列描画
@author 葉迩倭
@param pStr [in] 描画文字列
@param vPos [in] 描画座標
@param fSize [in] 描画サイズ
@param Color [in] 描画色
等幅フォントで文字列の描画を行います。<BR>
生成時の書体が等幅フォントでない場合は正しく描画されない事があります。
*/
virtual void DrawString( const char *pStr, const Math::Vector3D &vPos, const Math::Point2DF &fSize, CColor Color ) = 0;
/**
@brief 文字列描画
@author 葉迩倭
@param pStr [in] 描画文字列
@param vPos [in] 描画座標
@param fSize [in] 描画サイズ
@param Color [in] 描画色
プロポーショナルフォントで文字列の描画を行います。<BR>
生成時の書体がプロポーショナルフォントでなくても正しく描画されます。
*/
virtual void DrawStringP( const char *pStr, const Math::Vector3D &vPos, const Math::Point2DF &fSize, CColor Color ) = 0;
/**
@brief 文字列描画
@author 葉迩倭
@param pStr [in] 描画文字列
@param vPos [in] 描画座標
@param fSize [in] 描画サイズ
@param Color [in] 描画色
等幅フォントで文字列の描画を行います。<BR>
生成時の書体が等幅フォントでない場合は正しく描画されない事があります。
*/
virtual void DrawString( const wchar_t *pStr, const Math::Vector3D &vPos, const Math::Point2DF &fSize, CColor Color ) = 0;
/**
@brief 文字列描画
@author 葉迩倭
@param pStr [in] 描画文字列
@param vPos [in] 描画座標
@param fSize [in] 描画サイズ
@param Color [in] 描画色
プロポーショナルフォントで文字列の描画を行います。<BR>
生成時の書体がプロポーショナルフォントでなくても正しく描画されます。
*/
virtual void DrawStringP( const wchar_t *pStr, const Math::Vector3D &vPos, const Math::Point2DF &fSize, CColor Color ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief 3Dスプライト描画用インターフェイス
@author 葉迩倭
3Dスプライト描画を保持するためのインターフェイスです。
*/
class IParticle
{
public:
virtual ~IParticle() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 基準位置設定
@author 葉迩倭
@param vPos [in] 基準位置
内部バッファに対する全ての基準となる位置を設定します。<BR>
ここで指定された位置はソートにも利用されます。
*/
virtual void SetBasePosition( const Math::Vector3D &vPos ) = 0;
/**
@brief データ追加開始宣言
@author 葉迩倭
内部バッファへのデータの追加を行うことを通知します。<BR>
この関数を呼ばずにPush*系の関数を呼ばないようにしてください。
*/
virtual void Begin( void ) = 0;
/**
@brief データ追加終了宣言
@author 葉迩倭
内部バッファへのデータの追加を完了したことを通知します。<BR>
この関数を呼ぶ前に必ずBegin関数を呼ぶようにしてください。
*/
virtual void End( void ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
@param vPosition [in] スプライトの位置
@param Size [in] 描画サイズ
@param SrcRect [in] テクスチャ矩形
@param Color [in] 色
内部バッファへのデータの追加を行います。<BR>
vPositionを基準位置としてSizeで指定した大きさの矩形を作り、
カメラの方へ向くように頂点シェーダーで計算されます。
*/
virtual void Draw( const Math::Vector3D &vPosition, const Math::Point2DF &Size, const Math::Rect2DI &SrcRect, CColor Color ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
@param vPosition [in] スプライトの位置
@param PtTbl [in] 描画用4頂点(左上−右上−左下−右下)
@param SrcRect [in] テクスチャ矩形
@param Color [in] 色
内部バッファへのデータの追加を行います。<BR>
vPositionを基準位置としてPtTblで指定した大きさの矩形を作り、
カメラの方へ向くように頂点シェーダーで計算されます。
*/
virtual void Draw( const Math::Vector3D &vPosition, const Math::Vector2D PtTbl[], const Math::Rect2DI &SrcRect, CColor Color ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
@param vPosition [in] スプライトの位置
@param Size [in] 描画サイズ
@param SrcRect [in] テクスチャ矩形
@param Color [in] 色
@param Angle [in] 回転角度
内部バッファへのデータの追加を行います。<BR>
vPositionを基準位置としてSizeで指定した大きさの矩形を作り、
カメラの方へ向くように頂点シェーダーで計算されます。
*/
virtual void DrawRotate( const Math::Vector3D &vPosition, const Math::Point2DF &Size, const Math::Rect2DI &SrcRect, CColor Color, Sint32 Angle ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
@param vPosition [in] スプライトの位置
@param PtTbl [in] 描画用4頂点(左上−右上−左下−右下)
@param SrcRect [in] テクスチャ矩形
@param Color [in] 色
@param Angle [in] 回転角度
内部バッファへのデータの追加を行います。<BR>
vPositionを基準位置としてPtTblで指定した大きさの矩形を作り、
カメラの方へ向くように頂点シェーダーで計算されます。
*/
virtual void DrawRotate( const Math::Vector3D &vPosition, const Math::Vector2D PtTbl[], const Math::Rect2DI &SrcRect, CColor Color, Sint32 Angle ) = 0;
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief モデルデータ用インターフェイス
@author 葉迩倭
@note
モデルデータを保持するためのインターフェイスです。
*/
class IModel : public IInterface
{
public:
virtual ~IModel() {}
};
}
}
}
#pragma once
/**
@file
@brief マップモデルインターフェイス
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
namespace Object
{
/**
@brief マップモデルデータ用インターフェイス
@author 葉迩倭
@note
マップモデルデータを保持するためのインターフェイスです。
*/
class IMapModel : public IInterface
{
public:
virtual ~IMapModel() {}
};
}
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief シーンプリミティブアクター用インターフェイス
@author 葉迩倭
シーン管理されたプリミティブアクターを扱う為のインターフェイスです。
*/
class IPrimitiveActor : public Math::Style
{
public:
virtual ~IPrimitiveActor() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
ISceneManagerに対してレンダリングリクエストを発行します。<BR>
取得元のISceneManagerがBegin()/End()中でない場合この関数は失敗します。
*/
virtual void RenderingRequest( void ) = 0;
/**
@brief 座標変換初期化
@author 葉迩倭
アクターの座標変換を初期化します。<BR>
アニメーションの情報などもこの関数内ですべて初期化されます。
*/
virtual void TransformReset( void ) = 0;
/**
@brief 座標変換更新
@author 葉迩倭
アクターの座標変換を更新します。<BR>
アニメーションの情報などもこの関数内ですべて更新されます。
*/
virtual void TransformUpdate( void ) = 0;
/**
@brief ボーン変換行列を設定
@author 葉迩倭
@param pMatrix [in] ボーン行列の配列
@param Count [in] ボーン行列の数
アクターに対してボーンの変換行列を設定します。<BR>
ボーンデータをもつIPrimitive3Dに対してのみ有効です。
*/
virtual void SetBoneMatrixArray( Math::Matrix *pMatrix, Sint32 Count ) = 0;
/**
@brief シェーダーを設定
@author 葉迩倭
@param pShader [in] シェーダーインターフェイス
アクターに対して任意のシェーダーを設定します。
*/
virtual void SetShader( Renderer::Shader::IShader *pShader ) = 0;
/**
@brief マテリアルの拡散反射色設定
@author 葉迩倭
@param vColor [in] 色
メッシュ内のマテリアルの拡散反射色を設定します。
*/
virtual void SetMaterialColor( Math::Vector4D &vColor ) = 0;
/**
@brief マテリアルの自己発光色設定
@author 葉迩倭
@param vColor [in] 色
メッシュ内のマテリアルの自己発光色を設定します。
*/
virtual void SetEmissiveColor( Math::Vector4D &vColor ) = 0;
/**
@brief マテリアルの鏡面反射色設定
@author 葉迩倭
@param vColor [in] 色
メッシュ内のマテリアルの鏡面反射色を設定します。
*/
virtual void SetSpecularColor( Math::Vector4D &vColor ) = 0;
/**
@brief マテリアルの鏡面反射の強さ設定
@author 葉迩倭
@param fParam [in] 強さ
メッシュ内のマテリアルの鏡面反射の強さを設定します。
*/
virtual void SetSpecularRefractive( Float fParam ) = 0;
/**
@brief マテリアルの鏡面反射の荒さ設定
@author 葉迩倭
@param fParam [in] 荒さ
メッシュ内のマテリアルの鏡面反射の荒さを設定します。
*/
virtual void SetSpecularRoughly( Float fParam ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief シーンプリミティブアクター用インターフェイス
@author 葉迩倭
シーン管理されたプリミティブアクターを扱う為のインターフェイスです。
*/
class ISpriteActor : public Math::Style
{
public:
virtual ~ISpriteActor() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
ISceneManagerに対してレンダリングリクエストを発行します。<BR>
取得元のISceneManagerがBegin()/End()中でない場合この関数は失敗します。
*/
virtual void RenderingRequest( void ) = 0;
/**
@brief 座標変換初期化
@author 葉迩倭
アクターの座標変換を初期化します。<BR>
アニメーションの情報などもこの関数内ですべて初期化されます。
*/
virtual void TransformReset( void ) = 0;
/**
@brief 座標変換更新
@author 葉迩倭
アクターの座標変換を更新します。<BR>
アニメーションの情報などもこの関数内ですべて更新されます。
*/
virtual void TransformUpdate( void ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief シーンスプライトアクター用インターフェイス
@author 葉迩倭
シーン管理されたスプライトアクターを扱う為のインターフェイスです。
*/
class IParticleActor
{
public:
virtual ~IParticleActor() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
ISceneManagerに対してレンダリングリクエストを発行します。<BR>
取得元のISceneManagerがBegin()/End()中でない場合この関数は失敗します。
*/
virtual void RenderingRequest( void ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief シーンモデルアクター用インターフェイス
@author 葉迩倭
シーン管理されたモデルアクターを扱う為のインターフェイスです。
*/
class IModelActor : public Math::Style
{
public:
virtual ~IModelActor() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
ISceneManagerに対してレンダリングリクエストを発行します。<BR>
取得元のISceneManagerがBegin()/End()中でない場合この関数は失敗します。
*/
virtual void RenderingRequest( void ) = 0;
/**
@brief カリング用バウンディングレンダリング
@author 葉迩倭
@param pLine [in] ラインプリミティブインターフェイス
バウンディングボックスを指定したラインデータに対して追加します。
*/
virtual void RenderingBounding( Renderer::Object::ILine3D *pLine ) = 0;
/**
@brief 座標変換初期化
@author 葉迩倭
アクターの座標変換を初期化します。<BR>
アニメーションの情報などもこの関数内ですべて初期化されます。
*/
virtual void TransformReset( void ) = 0;
/**
@brief 座標変換更新
@author 葉迩倭
アクターの座標変換を更新します。<BR>
アニメーションの情報などもこの関数内ですべて更新されます。<BR>
処理的には TransformUpdateCollisionOnly() と TransformUpdateActorOnly() を呼び出しています。
*/
virtual void TransformUpdate( void ) = 0;
/**
@brief 座標変換更新
@author 葉迩倭
アクターのコリジョンの座標変換を更新します。<BR>
コリジョンに関係するデータがここで更新されます。
*/
virtual void TransformUpdateCollisionOnly( void ) = 0;
/**
@brief 座標変換更新
@author 葉迩倭
アクターの座標変換を更新します。<BR>
描画用のアクターだけが更新されます。
*/
virtual void TransformUpdateActorOnly( void ) = 0;
/**
@brief モデルに対してアニメーションデータ数を取得
@author 葉迩倭
@return アニメーション数
アクターの所持するアニメーションの数を取得します。
*/
virtual Sint32 GetAnimationCount( void ) = 0;
/**
@brief アニメーションデータの最終時間を取得
@author 葉迩倭
@param AnimationNo [in] 適用するアニメーション番号
@return アニメーションの最終時間
アニメーションの最終フレームを取得します。
*/
virtual Float GetAnimationLastTime( Sint32 AnimationNo ) = 0;
/**
@brief モデルに対してアニメーションデータを更新
@author 葉迩倭
@param AnimationNo [in] 適用するアニメーション番号
@param fAnimationTime [in] アニメーションの時間(単位は作成したツールによる)
単一のアニメーションデータの更新をします。
*/
virtual void UpdateAnimation( Sint32 AnimationNo, Float fAnimationTime ) = 0;
/**
@brief モデルに対してアニメーションデータを更新
@author 葉迩倭
@param AnimationNo1 [in] 適用するアニメーション番号
@param fAnimationTime1 [in] アニメーションの時間(単位は作成したツールによる)
@param AnimationNo2 [in] 適用するアニメーション番号
@param fAnimationTime2 [in] アニメーションの時間(単位は作成したツールによる)
@param fWeight [in] ブレンド割合(0.0fの時AnimationNo0、1.0の時AnimationNo1)
2つのアニメーションをブレンドしてアニメーションデータを更新します。
*/
virtual void UpdateAnimation( Sint32 AnimationNo1, Float fAnimationTime1, Sint32 AnimationNo2, Float fAnimationTime2, Float fWeight ) = 0;
/**
@brief カリング処理に有無設定
@author 葉迩倭
@param IsEnable [in] カリングの有無
モデル内の各アクターに対してビューフラスタムカリングを行うかを設定します。<BR>
ビューフラスタムカリングとはカメラの描画領域内にないアクターを描画に関する一連の処理から<BR>
省くための処理で、行う事でCPU負荷は増えますが画面外に出るアクターに対しての描画負荷を軽減できます。
*/
virtual void SetCullTestEnable( Bool IsEnable ) = 0;
/**
@brief モデル内のフレーム数取得
@author 葉迩倭
@return モデル内のフレームの数
モデル内のフレームの数を取得します。<BR>
スキンメッシュに関連付けられているフレームは<BR>
扱い的にはボーンになります。
*/
virtual Sint32 GetFrameCount( void ) = 0;
/**
@brief モデル内のフレーム数取得
@author 葉迩倭
@return モデル内のフレームの数
モデル内のフレームの数を取得します。
*/
virtual Sint32 Frame_GetIndex( const char *pName ) = 0;
/**
@brief フレームの変換行列を取得
@author 葉迩倭
@param Index [in] フレームの番号
@return フレームの変換行列
フレームの変換行列を取得します。
*/
virtual Math::Matrix &Frame_GetTransformLocal( Sint32 Index ) = 0;
/**
@brief フレームの変換行列を取得
@author 葉迩倭
@param Index [in] フレームの番号
@return フレームの変換行列
フレームの変換行列を取得します。
*/
virtual Math::Matrix &Frame_GetTransformWorld( Sint32 Index ) = 0;
/**
@brief モデル内のメッシュ数取得
@author 葉迩倭
@return モデル内のメッシュの数
モデル内のメッシュの数を取得します。<BR>
メッシュの数=描画アクターの数になります。
*/
virtual Sint32 GetMeshCount( void ) = 0;
/**
@brief モデル内のメッシュ描画ON/OFF
@author 葉迩倭
@param Index [in] メッシュ番号
@param IsDrawEnable [in] 描画するか否か
モデル内のメッシュを描画するかどうかを設定します。
*/
virtual void GetMesh_DrawEnable( Sint32 Index, Bool IsDrawEnable ) = 0;
/**
@brief メッシュ内のマテリアル数取得
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@return メッシュ内のマテリアル数
メッシュ内のマテリアル数を取得します。
*/
virtual Sint32 GetMeshMaterialCount( Sint32 MeshIndex ) = 0;
/**
@brief マテリアルのシェーダー設定
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@param MaterialIndex [in] マテリアル番号
@param pShader [in] シェーダー
メッシュ内のマテリアルのシェーダーを設定します。
*/
virtual void MeshMaterial_SetShader( Sint32 MeshIndex, Sint32 MaterialIndex, Renderer::Shader::IShader *pShader ) = 0;
/**
@brief マテリアルの拡散反射色設定
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@param MaterialIndex [in] マテリアル番号
@param vColor [in] 色
メッシュ内のマテリアルの拡散反射色を設定します。
*/
virtual void MeshMaterial_SetMaterialColor( Sint32 MeshIndex, Sint32 MaterialIndex, Math::Vector4D &vColor ) = 0;
/**
@brief マテリアルの自己発光色設定
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@param MaterialIndex [in] マテリアル番号
@param vColor [in] 色
メッシュ内のマテリアルの自己発光色を設定します。
*/
virtual void MeshMaterial_SetEmissiveColor( Sint32 MeshIndex, Sint32 MaterialIndex, Math::Vector4D &vColor ) = 0;
/**
@brief マテリアルの鏡面反射色設定
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@param MaterialIndex [in] マテリアル番号
@param vColor [in] 色
メッシュ内のマテリアルの鏡面反射色を設定します。
*/
virtual void MeshMaterial_SetSpecularColor( Sint32 MeshIndex, Sint32 MaterialIndex, Math::Vector4D &vColor ) = 0;
/**
@brief マテリアルの鏡面反射の強さ設定
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@param MaterialIndex [in] マテリアル番号
@param fParam [in] 強さ
メッシュ内のマテリアルの鏡面反射の強さを設定します。
*/
virtual void MeshMaterial_SetSpecularRefractive( Sint32 MeshIndex, Sint32 MaterialIndex, Float fParam ) = 0;
/**
@brief マテリアルの鏡面反射の荒さ設定
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@param MaterialIndex [in] マテリアル番号
@param fParam [in] 荒さ
メッシュ内のマテリアルの鏡面反射の荒さを設定します。
*/
virtual void MeshMaterial_SetSpecularRoughly( Sint32 MeshIndex, Sint32 MaterialIndex, Float fParam ) = 0;
/**
@brief マテリアルの描画タイプ設定
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@param MaterialIndex [in] マテリアル番号
@param Type [in] 描画タイプ
メッシュ内のマテリアルの描画タイプを設定します。
*/
virtual void MeshMaterial_SetDrawType( Sint32 MeshIndex, Sint32 MaterialIndex, eDrawType Type ) = 0;
/**
@brief マテリアルのテクスチャ設定
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@param MaterialIndex [in] マテリアル番号
@param pTexture [in] テクスチャ
メッシュ内のマテリアルのテクスチャを設定します。
*/
virtual void MeshMaterial_SetTexture( Sint32 MeshIndex, Sint32 MaterialIndex, Renderer::ITexture *pTexture ) = 0;
/**
@brief マテリアルのテクスチャUVのオフセット設定
@author 葉迩倭
@param MeshIndex [in] メッシュ番号
@param MaterialIndex [in] マテリアル番号
@param vOffset [in] オフセット(0.0->1.0)
メッシュ内のマテリアルのテクスチャUVのオフセットを設定します。
*/
virtual void MeshMaterial_SetTextureOffset( Sint32 MeshIndex, Sint32 MaterialIndex, Math::Vector2D &vOffset ) = 0;
/**
@brief コリジョン生成
@author 葉迩倭
アクターに対してのコリジョン操作用のインターフェイスを生成します。<BR>
これを行うとCollision_***()系の関数が有効になります。
*/
virtual void Collision_Create( void ) = 0;
/**
@brief コリジョン有無設定
@author 葉迩倭
@param Index [in] フレーム番号
@param IsEnable [in] trueの時コリジョンON(デフォルトはON)
指定番号のフレームのコリジョンをON/OFFします。
*/
virtual void Collision_SetEnable( Sint32 Index, Bool IsEnable ) = 0;
/**
@brief コリジョン有無設定
@author 葉迩倭
@param pName [in] 名称
@param IsEnable [in] trueの時コリジョンON(デフォルトはON)
指定名のフレームのコリジョンをON/OFFします。
*/
virtual void Collision_SetEnable( const char *pName, Bool IsEnable ) = 0;
/**
@brief コリジョンデータ描画
@author 葉迩倭
@param pLine [in] 描画用ラインプリミティブインターフェイス
当たり判定データをレンダリングするための関数です。
*/
virtual void Collision_Rendering( Renderer::Object::ILine3D *pLine ) = 0;
/**
@brief コリジョンの結果取得
@author 葉迩倭
@param FrameNo [in,out] 衝突したフレーム番号格納先
@param vPos [in,out] 衝突した位置格納先
当たり判定データを取得します。<BR>
現時点では衝突した大まかな位置と衝突した<BR>
フレーム番号しか取得することはできません。
*/
virtual void Collision_GetResult( Sint32 &FrameNo, Math::Vector3D &vPos ) = 0;
/**
@brief コリジョンチェック
@author 葉迩倭
@param pSrc [in] チェックするIModelActor
指定されたデータとの衝突検出を行います。<BR>
衝突の結果はCollision_GetResult()で取得できます。
*/
virtual Bool Collision_Check( IModelActor *pSrc ) = 0;
/**
@brief コリジョンチェック
@author 葉迩倭
@param Src [in] チェックするボックスデータ
指定されたデータとの衝突検出を行います。<BR>
衝突の結果はCollision_GetResult()で取得できます。
*/
virtual Bool Collision_Check( Collision::CBox &Src ) = 0;
/**
@brief コリジョンチェック
@author 葉迩倭
@param Src [in] チェックするラインデータ
指定されたデータとの衝突検出を行います。<BR>
衝突の結果はCollision_GetResult()で取得できます。
*/
virtual Bool Collision_Check( Collision::CLine3D &Src ) = 0;
/**
@brief コリジョンチェック
@author 葉迩倭
@param Src [in] チェックする点データ
指定されたデータとの衝突検出を行います。<BR>
衝突の結果はCollision_GetResult()で取得できます。
*/
virtual Bool Collision_Check( Math::Vector3D &Src ) = 0;
/**
@brief コリジョンチェック
@author 葉迩倭
@param Src [in] チェックする点データ
@param pSceneMgr [in] レンダリングを行ったシーンのインターフェイス
スクリーン座標との衝突検出を行います。<BR>
衝突の結果はCollision_GetResult()で取得できます。
*/
virtual Bool Collision_CheckOnScreen( Math::Vector2D &Src, ISceneManager *pSceneMgr ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Box [out] 衝突したメッシュのOBB
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Collision::CBox &Box ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Out [out] 衝突結果
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Renderer::SCollisionResult &Out ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Out [out] 衝突結果
@param Box [out] 衝突したメッシュのOBB
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Renderer::SCollisionResult &Out, Collision::CBox &Box ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Out [out] 衝突結果
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Renderer::SCollisionResultExtend &Out ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Out [out] 衝突結果
@param Box [out] 衝突したメッシュのOBB
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Renderer::SCollisionResultExtend &Out, Collision::CBox &Box ) = 0;
/**
@brief コリジョンモデル表示
@author 葉迩倭
@param pLine [in] ラインプリミティブインターフェイス
マップモデルが持つコリジョンデータをRenderer::Object::ILine3Dを使って<BR>
可視出来るように描画します。
*/
virtual void CreateCollisionDrawPrimitive( Renderer::Object::ILine3D *pLine ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief シーンアクター用インターフェイス
@author 葉迩倭
シーン管理されたオブジェクトを扱う為のインターフェイスです。
*/
class IMapActor
{
public:
virtual ~IMapActor() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 描画リクエスト
@author 葉迩倭
ISceneManagerに対してレンダリングリクエストを発行します。<BR>
取得元のISceneManagerがBegin()/End()中でない場合この関数は失敗します。
*/
virtual void RenderingRequest( void ) = 0;
/**
@brief カリング用バウンディングレンダリング
@author 葉迩倭
@param pLine [in] ラインプリミティブインターフェイス
バウンディングボックスを指定したラインデータに対して追加します。
*/
virtual void RenderingBounding( Renderer::Object::ILine3D *pLine ) = 0;
/**
@brief セルの全体数取得
@author 葉迩倭
@return セルの全体数
マップ内のセルの数を取得します。
*/
virtual Sint32 GetCellCount( void ) = 0;
/**
@brief セルの描画数取得
@author 葉迩倭
@return セルの描画数
マップ内の描画されたセルの数を取得します。
*/
virtual Sint32 GetRenderingCellCount( void ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Box [out] 衝突したメッシュのOBB
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Collision::CBox &Box ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Out [out] 衝突結果
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Renderer::SCollisionResult &Out ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Out [out] 衝突結果
@param Box [out] 衝突したメッシュのOBB
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Renderer::SCollisionResult &Out, Collision::CBox &Box ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Out [out] 衝突結果
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Renderer::SCollisionResultExtend &Out ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param Out [out] 衝突結果
@param Box [out] 衝突したメッシュのOBB
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
virtual Bool HitCheckByRay( const Collision::CLine3D &Ray, Renderer::SCollisionResultExtend &Out, Collision::CBox &Box ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param fRadius [in] 衝突半径
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
// virtual Bool HitCheckBySphere( const Collision::CLine3D &Ray, Float fRadius ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param fRadius [in] 衝突半径
@param Box [out] 衝突したメッシュのOBB
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
// virtual Bool HitCheckBySphere( const Collision::CLine3D &Ray, Float fRadius, Collision::CBox &Box ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param fRadius [in] 衝突半径
@param Out [out] 衝突結果
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
// virtual Bool HitCheckBySphere( const Collision::CLine3D &Ray, Float fRadius, Renderer::SCollisionResultSphere &Out ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param fRadius [in] 衝突半径
@param Out [out] 衝突結果
@param Box [out] 衝突したメッシュのOBB
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
// virtual Bool HitCheckBySphere( const Collision::CLine3D &Ray, Float fRadius, Renderer::SCollisionResultSphere &Out, Collision::CBox &Box ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param fRadius [in] 衝突半径
@param Out [out] 衝突結果
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
// virtual Bool HitCheckBySphere( const Collision::CLine3D &Ray, Float fRadius, Renderer::SCollisionResultSphereExtend &Out ) = 0;
/**
@brief 衝突判定
@author 葉迩倭
@param Ray [in] 始点から終点を結ぶ線分
@param fRadius [in] 衝突半径
@param Out [out] 衝突結果
@param Box [out] 衝突したメッシュのOBB
@retval false 衝突しない
@retval true 衝突する
マップモデルが持つコリジョンデータに対して、<BR>
点がRayで示す移動をした場合のコリジョンを処理します。
*/
// virtual Bool HitCheckBySphere( const Collision::CLine3D &Ray, Float fRadius, Renderer::SCollisionResultSphereExtend &Out, Collision::CBox &Box ) = 0;
/**
@brief コリジョンモデル表示
@author 葉迩倭
@param pLine [in] ラインプリミティブインターフェイス
マップモデルが持つコリジョンデータをRenderer::Object::ILine3Dを使って<BR>
可視出来るように描画します。
*/
virtual void CreateCollisionDrawPrimitive( Renderer::Object::ILine3D *pLine ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief シーンカメラ操作用インターフェイス
@author 葉迩倭
シーンのカメラを操作するためのインターフェイスです。
*/
class ICamera
{
public:
virtual ~ICamera() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief ワールド→スクリーン座標変換行列取得
@author 葉迩倭
@return 変換行列
ワールド空間からスクリーン座標への逆変換行列を取得します。
*/
virtual const Math::Matrix &WorldToScreen( void ) = 0;
/**
@brief ワールド→ビュー変換行列取得
@author 葉迩倭
@return 変換行列
ワールド空間からカメラ空間への逆変換行列を取得します。
*/
virtual const Math::Matrix &WorldToView( void ) = 0;
/**
@brief スクリーン→ワールド変換行列取得
@author 葉迩倭
@return 変換行列
スクリーン座標からワールド空間への逆変換行列を取得します。
*/
virtual const Math::Matrix &ScreenToWorld( void ) = 0;
/**
@brief ビュー→ワールド変換行列取得
@author 葉迩倭
@return 変換行列
カメラ空間からワールド空間への逆変換行列を取得します。
*/
virtual const Math::Matrix &ViewToWorld( void ) = 0;
/**
@brief カメラ位置取得
@author 葉迩倭
@return カメラ位置ベクトル
ワールド空間でのカメラの位置を取得します。
*/
virtual const Math::Vector3D &Position( void ) = 0;
/**
@brief ニアクリップ値取得
@author 葉迩倭
@return ニアクリップ値
ニアクリップ値を取得します。
*/
virtual Float GetNearClip( void ) = 0;
/**
@brief ファークリップ値取得
@author 葉迩倭
@return ファークリップ値
ファークリップ値を取得します。
*/
virtual Float GetFarClip( void ) = 0;
/**
@brief プロジェクション行列更新
@author 葉迩倭
@param fNearClip [in] ニアクリップ値
@param fFarClip [in] ファークリップ値
@param FovAngle [in] 画角(1周65536とした角度)
@param Width [in] 表示横幅
@param Height [in] 表示縦幅
プロジェクション行列を更新します。<BR>
カメラを使用する場合には必ずこの関数でプロジェクションを作成して下さい。<BR>
またFovAngleに0を指定すると平行投影になります。
*/
virtual void UpdateProjection( Float fNearClip, Float fFarClip, Sint32 FovAngle, Sint32 Width, Sint32 Height ) = 0;
/**
@brief カメラデータ初期化
@author 葉迩倭
カメラデータを初期化します。<BR>
座標(0,0,0)からZ軸+方向を向いた状態になります。
*/
virtual void Reset( void ) = 0;
/**
@brief カメラデータ更新
@author 葉迩倭
カメラのデータを更新します。<BR>
各種行列やバウンディングボックスなどは<BR>
この関数を呼び出すことで作成されます。
*/
virtual void Update( void ) = 0;
/**
@brief カメラを変換
@author 葉迩倭
@param vPosition [in] カメラの現在位置
@param vTarget [in] カメラのターゲット位置
@param Bank [in] バンク(傾き)角度
CStyleを使わず直接カメラの姿勢情報を設定します。
*/
virtual void SetTransformSimple( Math::Vector3D &vPosition, Math::Vector3D &vTarget, Sint32 Bank ) = 0;
/**
@brief カメラを変換
@author 葉迩倭
@param Style [in] カメラ変換用Style
CStyleデータで定義された変換処理を<BR>
カメラに適用します。<BR>
カメラで使用されるのは移動/回転になります。
*/
virtual void SetTransform( Math::Style &Style ) = 0;
/**
@brief カリング用バウンディングレンダリング
@author 葉迩倭
@param pLine [in] ラインプリミティブインターフェイス
バウンディングボックスを指定したラインデータに対して追加します。
*/
virtual void RenderingBounding( Renderer::Object::ILine3D *pLine ) = 0;
};
}
}
#pragma once
/**
@file
@brief シーン管理系クラス
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief シーン管理用インターフェイス
@author 葉迩倭
シーン管理を行うためのインターフェイスです。
*/
class ISceneManager : public IInterface
{
protected:
virtual ~ISceneManager() {}
public:
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IModelActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIModelActorを経由して行います。<BR>
<B>必ずInitParameterUpdateの後に実行してください。</B>
*/
virtual IModelActor *CreateActor( Renderer::Object::IModel *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IMapActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIMapActorを経由して行います。<BR>
<B>必ずInitParameterUpdateの後に実行してください。</B>
*/
virtual IMapActor *CreateActor( Renderer::Object::IMapModel *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IPrimitiveActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIPrimitiveActorを経由して行います。<BR>
<B>必ずInitParameterUpdateの後に実行してください。</B>
*/
virtual IPrimitiveActor *CreateActor( Renderer::Object::IPoint3D *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IPrimitiveActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIPrimitiveActorを経由して行います。<BR>
<B>必ずInitParameterUpdateの後に実行してください。</B>
*/
virtual IPrimitiveActor *CreateActor( Renderer::Object::ILine3D *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@param IsLightmap [in]
@pamra IsNormalmap [in]
@param IsSpecularmap [in]
@param IsEnvironmentmap [in]
@return IPrimitiveActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIPrimitiveActorを経由して行います。<BR>
<B>必ずInitParameterUpdateの後に実行してください。</B>
*/
virtual IPrimitiveActor *CreateActor( Renderer::Object::IPrimitive3D *pObject, Bool IsLightmap = false, Bool IsNormalmap = false, Bool IsSpecularmap = false, Bool IsEnvironmentmap = false ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return ISpriteActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はISpriteActorを経由して行います。<BR>
<B>必ずInitParameterUpdateの後に実行してください。</B>
*/
virtual ISpriteActor *CreateActor( Renderer::Object::ISprite3D *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IParticleActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIParticleActorを経由して行います。<BR>
<B>必ずInitParameterUpdateの後に実行してください。</B>
*/
virtual IParticleActor *CreateActor( Renderer::Object::IFontSprite3D *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IParticleActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIParticleActorを経由して行います。<BR>
<B>必ずInitParameterUpdateの後に実行してください。</B>
*/
virtual IParticleActor *CreateActor( Renderer::Object::IParticle *pObject ) = 0;
/**
@brief シーンカメラ取得
@author 葉迩倭
@return カメラ
シーンに関連付けられたカメラを取得します。
*/
virtual ICamera *GetCamera( void ) = 0;
/**
@brief シーン初期化
@author 葉迩倭
シーンのライトやフォグなどのデータをリセットします。<BR>
この関数はBegin()-End()内で呼び出すと失敗します。
*/
virtual void Reset( void ) = 0;
/**
@brief シーン開始
@author 葉迩倭
@param IsSort [in] シーン内のオブジェクトをソートするかどうか
シーン管理を開始します。<BR>
この時点でカメラのデータが確定しますので<BR>
この関数を呼び出したあとのカメラの更新は全て無効です。
*/
virtual void Begin( Bool IsSort ) = 0;
/**
@brief シーン終了
@author 葉迩倭
シーンの管理を完了します。
*/
virtual void End( void ) = 0;
/**
@brief 終了待機
@author 葉迩倭
ISceneManagerでレンダリング処理の完了を完全に待機します。<BR>
Begin()-End()以降並列でデータの構築処理が行われますので、<BR>
シーン、あるいはシーンで利用しているリソースを解放する前は<BR>
この関数でシーンの構築処理の終了を待って下さい。<BR>
なおアプリケーションの終了時(ICore::Run()=false)時には内部で全てのシーンの<BR>
Abort()が自動的に呼ばれます。
*/
virtual void Abort( void ) = 0;
/**
@brief シーンレンダリング
@author 葉迩倭
@param IsDrawBuffer [in] 内部用バッファの表示
シーンの管理で構築されたシーンをレンダリングします。<BR>
この関数をコールした段階で内部で描画処理が開始されます。<BR>
必ずIRender::Begin()〜IRender::End()間で呼び出してください。
*/
virtual void Rendering( Bool IsDrawBuffer = false ) = 0;
/**
@brief アンビエントライト設定
@author 葉迩倭
@param vColorSky [in] シーン内の天球の環境光の色
@param vColorEarth [in] シーン内の地表の環境光の色
シーンの環境光を設定します。<BR>
半球ライティングを行うために、天球と地表の色を設定します。<BR>
この関数はBegin()-End()内で呼び出すと失敗します。
*/
virtual void SetLightParameter_Ambient( const Math::Vector3D &vColorSky, const Math::Vector3D &vColorEarth ) = 0;
/**
@brief ディレクションライト設定
@author 葉迩倭
@param vDirect [in] シーン内の平行光源の方向
@param vColor [in] シーン内の平行光源の色
シーンに大して1つだけ平行光源を割り当てることができます。<BR>
太陽のように遥か遠方に存在し、オブジェクトの位置によって<BR>
光の方向が変わらないようなライトに向いています。<BR>
この関数はBegin()-End()内で呼び出すと失敗します。<BR>
またシーンモードの影生成を指定している時はvDirectは無効です。<BR>
方向に関してはSetParameter_Shadow()で指定した値が使用されます。
*/
virtual void SetLightParameter_Directional( const Math::Vector3D &vDirect, const Math::Vector3D &vColor ) = 0;
/**
@brief ポイントライト追加
@author 葉迩倭
@param vPosition [in] シーン内の点光源の位置
@param vColor [in] シーン内の点光源の色
@param fDistance [in] シーン内の点光源の影響距離
シーンに対して点光源を追加します<BR>
最大で32個のライトを設定でき、そのうち最もオブジェクトに近い<BR>
4つのライトがオブジェクトに適用されます。<BR>
この関数はBegin()-End()内で呼び出すと失敗します。
*/
virtual void SetLightParameter_AddPoint( const Math::Vector3D &vPosition, const Math::Vector3D &vColor, Float fDistance ) = 0;
/**
@brief レンダリングリクエスト数取得
@author 葉迩倭
@return レンダリングリクエスト数
シーンにリクエストレンダリング数を取得します。
*/
virtual Sint32 GetResult_RenderingRequestActorCount( void ) = 0;
/**
@brief レンダリング数取得
@author 葉迩倭
@return レンダリング数
シーンで実行されたレンダリング数を取得します。<BR>
2Pass系の処理等もカウントされるので、<BR>
リクエスト数以上の値になることもあります。
*/
virtual Sint32 GetResult_RenderingActorCount( void ) = 0;
/**
@brief シーンの構築にかかった時間を取得
@author 葉迩倭
@return シーンの構築にかかった時間(1フレームに対する%)
1フレームあたりのシーン構築にかかった時間を%で取得します。
*/
virtual Sint32 GetResult_BackgroundThreadTime( void ) = 0;
/**
@brief シーンの描画にかかった時間を取得
@author 葉迩倭
@return シーンの描画にかかった時間(1フレームに対する%)
1フレームあたりのシーン描画にかかった時間を%で取得します。
*/
virtual Sint32 GetResult_RenderingTme( void ) = 0;
/**
@brief モーションブラーレベルの設定
@author 葉迩倭
@param Level [in] 使用するレベル
モーションブラー処理のレベルを設定します。<BR>
MOTION_BLUR_FULL指定の場合はモデルデータが閉じていて法線を保持している必要があります。
*/
virtual void SetActorParameter_MotionBlur( eSceneMotionBlurQuarity MotionBlurQuarity ) = 0;
/**
@brief 影の生成オプションのON/OFF
@author 葉迩倭
@param Type [in] 影処理の方法
@param Priority [in] 影のプライオリティ
@param fRadius [in] 丸影の場合の大きさ
シーンに適用される影処理が「SHADOW_TYPE_PROJECTION_*」か「SHADOW_TYPE_SOFT_PROJECTION_*」の時に<BR>
レンダリングするモデルが影を落とすかどうかを設定します。<BR>
影を落とすモデルには他のモデルの影が落ちず、影を落とさないモデルには他のモデルの影が落ちます。
*/
virtual void SetActorParameter_ProjectionShadow( eProjectionShadowType Type, eProjectionShadowPriority Priority, Float fRadius = 0.0f ) = 0;
/**
@brief シーン全体の明るさの設定
@author 葉迩倭
@param vBrightness [in] 色
シーンにライトマップを基準とした明るさを設定します。<BR>
1.0fを指定することでAmaryllis上で設定したパラメーターそのままの明るさになり、<BR>
それ以上で明るく、それ以下で暗くすることが出来ます。
*/
virtual void SetParameter_SceneBrightness( const Math::Vector3D &vBrightness ) = 0;
/**
@brief 線形フォグ情報設定
@author 葉迩倭
@param vColor [in] フォグの色
@param fNear [in] フォグ開始点
@param fFar [in] フォグ終了点
シーンに適用される線形フォグのパラメーターを設定します。<BR>
この関数はBegin()-End()内で呼び出すと失敗します。
*/
virtual void SetParameter_Fog( Math::Vector3D &vColor, Float fNear, Float fFar ) = 0;
/**
@brief 被写界深度用のフォーカス位置を設定します。
@author 葉迩倭
@param fForcusZ [in] フォーカスのZ(カメラ基準)
@param fPower [in] 被写界深度強度
被写界深度のフォーカス位置を設定します。
*/
virtual void SetParameter_DepthOfField( Float fForcusZ, Float fPower ) = 0;
/**
@brief ソフトパーティクル用スケール値
@author 葉迩倭
@param fSoftParticleScale [in] ソフトパーティクルのアルファ値用のスケール
ソフトパーティクル時の深度値の差異からアルファを算出するときのスケール値です。<BR>
この値が大きいほどアルファの境界がシャープになります。
*/
virtual void SetParameter_SoftParticleScale( Float fSoftParticleScale ) = 0;
/**
@brief HDRエフェクト設定
@author 葉迩倭
@param HdrEffect [in] HDRエフェクトの種類
@param fHDRPower [in] HDRの倍率
@param fHDRBoundary [in] HDRとして扱う閾値(1.0が白)
シーンの描画時のHDRエフェクトの設定をします。
*/
virtual void SetParameter_HighDynamicRange( Float fHDRPower, Float fHDRBoundary ) = 0;
/**
@brief トゥーン用パラメーター設定
@author 葉迩倭
@param vHatchingColor [in] ハッチング用の斜線の色
@param fToonPower [in] トゥーンマップ用の影部分の暗さ(0.0〜1.0)
トゥーンレンダリング用のパラメーターを設定します。
*/
virtual void SetParameter_Toon( Math::Vector3D &vHatchingColor, Float fToonPower ) = 0;
/**
@brief トゥーン用エッジ検出パラメーター設定
@author 葉迩倭
@param fEdgeNormalPower [in] 法線エッジの検出パラメーター
@param fEdgeDepthPower [in] 深度エッジの検出パラメーター
@param IsToonBold [in] 輪郭線を太くするか否か
トゥーン用のエッジ検出用のパラメーターを設定します。<BR>
いずれのパラメーターも大きいほど境界線が引かれる範囲が増えます。
*/
virtual void SetParameter_ToonEdge( Float fEdgeNormalPower, Float fEdgeDepthPower, Bool IsToonBold ) = 0;
/**
@brief シャドウ用カメラ設定
@author 葉迩倭
@param vPosition [in] カメラ位置
@param vTarget [in] カメラ注視点
@param fSize [in] レンダリングサイズ
@param fNear [in] 近クリップ面
@param fFar [in] 遠クリップ面
@param fBias [in] シャドウマップ用深度バイアス
@param fPower [in] 影の部分の明るさ(0.0から1.0まで、1.0の時影は完全なアンビエントになる)
シャドウ用のカメラデータを設定します。
*/
virtual void SetParameter_Shadow( Math::Vector3D &vPosition, Math::Vector3D &vTarget, Float fSize, Float fNear, Float fFar, Float fBias, Float fPower ) = 0;
/**
@brief レンダリングターゲットの矩形を設定
@author 葉迩倭
@param Dst [in] レンダリング矩形
シーンのレンダリングターゲットの矩形を指定します。<BR>
最終的に表示される位置に関係します。
*/
virtual void SetParameter_RenderRect( Math::Rect2DF &Dst ) = 0;
/**
@brief 背景塗りつぶし色設定
@author 葉迩倭
@param ClearColor [in] バッファクリア色
@param IsClear [in] クリア有無
シーンの描画時の背景の塗りつぶし色を設定します。
*/
virtual void SetParameter_BGColor( Math::Vector4D &ClearColor, Bool IsClear = true ) = 0;
/**
@brief 背景塗りつぶし色設定
@author 葉迩倭
@param ClearColor [in] バッファクリア色
@param IsClear [in] クリア有無
シーンの描画時の背景の塗りつぶし色を設定します。
*/
virtual void SetParameter_BGColor( CColor ClearColor, Bool IsClear = true ) = 0;
/**
@brief 背景塗りつぶしテクスチャ設定
@author 葉迩倭
@param pTex [in] テクスチャ
シーンの描画時の背景のテクスチャを設定します。
*/
virtual void SetParameter_BGTexture( Renderer::ITexture *pTex ) = 0;
/**
@brief シーン情報を更新
@author 葉迩倭
シーンをこれまでの情報を元に更新します。<BR>
必要な設定後にこの関数を呼び出さない限りIActorを生成することが出来ません。
*/
virtual Bool InitParameter_Update( void ) = 0;
/**
@brief レンダリングターゲットのサイズを設定
@author 葉迩倭
@param pTarget [in] レンダリングターゲットのテクスチャ(NULLでバックバッファへ直接レンダリング)
@param Size [in] サイズ(pTargetが有効な場合はpTargetのサイズに自動設定されます)
@param IsTextureSizePow2 [in] サイズを強制的に2の累乗にするかどうか
シーンのレンダリングターゲットのサイズを指定します。<BR>
レンダリング使われる各種バッファのサイズに関係します。<BR>
<B>必ずInitParameterUpdateの前に実行してください。</B>
*/
virtual void InitParameter_RenderTargetData( Renderer::ITexture *pTarget, Math::Point2DI Size = Math::Point2DI(0,0), Bool IsTextureSizePow2 = false ) = 0;
/**
@brief シェーディング用パラメーターの初期化
@author 葉迩倭
@param ShadingType [in] シェーディングの種類
シーンで行うシェーディングの処理を初期化します。<BR>
<B>必ずInitParameterUpdateの前に実行してください。</B>
*/
virtual void InitParameter_Shading( eSceneShadingType ShadingType ) = 0;
/**
@brief アンチエイリアス用パラメーターの初期化
@author 葉迩倭
@param AntiAliasType [in] アンチエイリアスの種類
@param fPower [in] アンチエイリアスのかかり具合(0.0〜1.0)
シーンで行うアンチエイリアスの処理を初期化します。<BR>
<B>必ずInitParameterUpdateの前に実行してください。</B>
*/
virtual void InitParameter_AntiAliasType( eSceneAntiAliasType AntiAliasType, Float fPower ) = 0;
/**
@brief 影用パラメーターの初期化
@author 葉迩倭
@param ShadowType [in] 影の種類
@param ShadowQuarity [in] 影の品質
@param IsSoftShadow [in] ソフトシャドウを使うかどうか
@param IsHardwareShadowmap [in] ハードウェアシャドウマップを使うかどうか
シーンで行う影の処理を初期化します。<BR>
<B>必ずInitParameterUpdateの前に実行してください。</B>
*/
virtual void InitParameter_Shadow( eSceneShadowType ShadowType, eSceneShadowQuarity ShadowQuarity, Bool IsSoftShadow = false, Bool IsHardwareShadowmap = true ) = 0;
/**
@brief モーションブラー用パラメーターの初期化
@author 葉迩倭
@param MotionBlurType [in] モーションブラーの種類
シーンで行うモーションブラーの処理を初期化します。<BR>
<B>必ずInitParameterUpdateの前に実行してください。</B>
*/
virtual void InitParameter_MotionBlur( eSceneMotionBlurType MotionBlurType ) = 0;
/**
@brief 被写界深度用パラメーターの初期化
@author 葉迩倭
@param DofType [in] 被写界深度の種類
シーンで行う被写界深度の処理を初期化します。<BR>
<B>必ずInitParameterUpdateの前に実行してください。</B>
*/
virtual void InitParameter_DepthOfField( eSceneDepthOfFieldType DofType ) = 0;
/**
@brief フォグ用パラメーターの初期化
@author 葉迩倭
@param FogType [in] フォグの種類
@param FogEffect [in] フォグのエフェクト
シーンで行うフォグの処理を初期化します。<BR>
<B>必ずInitParameterUpdateの前に実行してください。</B>
*/
virtual void InitParameter_Fog( eSceneFogType FogType, eSceneFogEffect FogEffect ) = 0;
/**
@brief HDRレンダリング用パラメーターの初期化
@author 葉迩倭
@param HdrType [in] HDRレンダリングの種類
@param HdrEffect [in] HDRレンダリングのエフェクト
シーンで行うHDRレンダリングの処理を初期化します。<BR>
<B>必ずInitParameterUpdateの前に実行してください。</B>
*/
virtual void InitParameter_HighDynamicRange( eSceneHighDynamicRangeType HdrType, eSceneHighDynamicRangeEffect HdrEffect ) = 0;
/**
@brief スカイドームの生成
@author 葉迩倭
@param fRadius [in] 半径
@param TopColor [in] 天球の頭頂部の色
@param BottomColor [in] 天球の地面部分の色
@param pTexCloud [in] 雲テクスチャ
シーンに適用するスカイドームを生成します。<BR>
*/
virtual Bool SceneSkydoom_Create( Float fRadius, CColor TopColor, CColor BottomColor, Renderer::ITexture *pTexCloud ) = 0;
/**
@brief スカイドームのレンダリング
@author 葉迩倭
シーンに登録されているスカイドームのレンダリングをします。
*/
virtual void SceneSkydoom_Rendering( void ) = 0;
/**
@brief スカイドームの雲テクスチャの色を設定
@author 葉迩倭
@param Color [in] 色
シーンに適用するスカイドームの雲の色を設定します。
*/
virtual void SceneSkydoom_SetCloudColor( const CColor &Color ) = 0;
/**
@brief スカイドームの雲テクスチャの移動量オフセット
@author 葉迩倭
@param vOffset [in] 移動量(1.0でテクスチャサイズ)
シーンに適用するスカイドームの雲の流れを制御します。<BR>
この関数で与えたオフセット分雲が移動します。
*/
virtual void SceneSkydoom_SetCloudOffset( const Math::Vector2D &vOffset ) = 0;
/**
@brief スクリーン座標に変換
@author 葉迩倭
@param vPosition [in] ワールド座標
@return スクリーン座標
ワールド空間の座標をスクリーン座標に変換します。
*/
virtual Math::Vector3D TransformToScreen( const Math::Vector3D &vPosition ) = 0;
/**
@brief スクリーン座標から変換
@author 葉迩倭
@param vPosition [in] スクリーン座標
@return ワールド座標
スクリーン座標をワールド空間の座標に変換します。
*/
virtual Math::Vector3D TransformFromScreen( const Math::Vector3D &vPosition ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief カスタムシーン管理用インターフェイス
@author 葉迩倭
@note
カスタムシーン管理を行うためのインターフェイスです。
*/
class ICustomizedSceneManager : public IInterface
{
protected:
virtual ~ICustomizedSceneManager() {}
public:
/**
@brief 終了待機
@author 葉迩倭
ISceneManagerでレンダリング処理の完了を完全に待機します。<BR>
Begin()-End()以降並列でデータの構築処理が行われますので、<BR>
シーン、あるいはシーンで利用しているリソースを解放する前は<BR>
この関数でシーンの構築処理の終了を待って下さい。<BR>
なおアプリケーションの終了時(ICore::Run()=false)時には内部で全てのシーンの<BR>
Abort()が自動的に呼ばれます。
*/
virtual void Abort( void ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IModelActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIModelActorを経由して行います。
*/
virtual IModelActor *CreateActor( Renderer::Object::IModel *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IMapActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIMapActorを経由して行います。
*/
virtual IMapActor *CreateActor( Renderer::Object::IMapModel *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IPrimitiveActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIPrimitiveActorを経由して行います。
*/
virtual IPrimitiveActor *CreateActor( Renderer::Object::IPoint3D *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IPrimitiveActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIPrimitiveActorを経由して行います。
*/
virtual IPrimitiveActor *CreateActor( Renderer::Object::ILine3D *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@param IsLightmap [in]
@pamra IsNormalmap [in]
@param IsSpecularmap [in]
@param IsEnvironmentmap [in]
@return IPrimitiveActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIPrimitiveActorを経由して行います。
*/
virtual IPrimitiveActor *CreateActor( Renderer::Object::IPrimitive3D *pObject, Bool IsLightmap = false, Bool IsNormalmap = false, Bool IsSpecularmap = false, Bool IsEnvironmentmap = false ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return ISpriteActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はISpriteActorを経由して行います。
*/
virtual ISpriteActor *CreateActor( Renderer::Object::ISprite3D *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IParticleActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIParticleActorを経由して行います。
*/
virtual IParticleActor *CreateActor( Renderer::Object::IFontSprite3D *pObject ) = 0;
/**
@brief シーンアクター取得
@author 葉迩倭
@param pObject [in] アクターに関連付ける描画インターフェイス
@return IParticleActorインターフェイス
ISceneManagerでレンダリングを行うためのアクターを取得します。<BR>
ワールド変換やレンダリングの操作はIParticleActorを経由して行います。
*/
virtual IParticleActor *CreateActor( Renderer::Object::IParticle *pObject ) = 0;
/**
@brief シーンカメラ取得
@author 葉迩倭
@return カメラ
シーンに関連付けられたカメラを取得します。
*/
virtual ICamera *GetCamera( void ) = 0;
/**
@brief シーン初期化
@author 葉迩倭
シーンのライトやフォグなどのデータをリセットします。<BR>
この関数はBegin()-End()内で呼び出すと失敗します。
*/
virtual void Reset( void ) = 0;
/**
@brief シーン開始
@author 葉迩倭
@param IsSort [in] シーン内のオブジェクトをソートするかどうか
シーン管理を開始します。<BR>
この時点でカメラのデータが確定しますので<BR>
この関数を呼び出したあとのカメラの更新は全て無効です。
*/
virtual void Begin( Bool IsSort ) = 0;
/**
@brief シーン終了
@author 葉迩倭
シーンの管理を完了します。
*/
virtual void End( void ) = 0;
/**
@brief シーンレンダリング開始
@author 葉迩倭
@retval false シーンにレンダリングするオブジェクトがない
@retval true シーンにレンダリングするオブジェクトがある
@note
シーンのレンダリングを開始する事を宣言します。<BR>
この関数がtrueを返した場合は必ずRedneringEnd()をコールして下さい。
*/
virtual Bool RenderingStart( void ) = 0;
/**
@brief シーンレンダリング終了
@author 葉迩倭
@note
シーンのレンダリングを終了する事を宣言します。
*/
virtual void RenderingExit( void ) = 0;
/**
@brief スクリーン座標に変換
@author 葉迩倭
@param vPosition [in] ワールド座標
@return スクリーン座標
ワールド空間の座標をスクリーン座標に変換します。
*/
virtual Math::Vector3D TransformToScreen( const Math::Vector3D &vPosition ) = 0;
/**
@brief スクリーン座標から変換
@author 葉迩倭
@param vPosition [in] スクリーン座標
@return ワールド座標
スクリーン座標をワールド空間の座標に変換します。
*/
virtual Math::Vector3D TransformFromScreen( const Math::Vector3D &vPosition ) = 0;
/**
@brief アクターオブジェクトのレイヤー数取得
@author 葉迩倭
@return アクターオブジェクトのレイヤー数
@note
レンダリングするアクターオブジェクトのレイヤー数を取得します。<BR>
レイヤー数自体は3で固定されており、内部的に下のように固定されています<BR>
0=未使用<BR>
1=不透明モデル<BR>
2=半透明モデル
*/
virtual Sint32 GetRenderObjectLayerCount( void ) = 0;
/**
@brief アクターオブジェクトの取得
@author 葉迩倭
@param Layer [in] オブジェクトレイヤー
@return アクターオブジェクト
@note
レンダリングするアクターオブジェクトを取得します。
*/
virtual ICustomizedSceneRenderObject *GetRenderObject( Sint32 Layer ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief カスタムシーン描画オブジェクトインターフェイス
@author 葉迩倭
@note
カスタムシーンの描画オブジェクトを扱うためのインターフェイスです。
*/
class ICustomizedSceneRenderObject : public IInterface
{
protected:
virtual ~ICustomizedSceneRenderObject() {}
public:
/**
@brief ボーン用頂点の有無を取得
@author 葉迩倭
@retval false 無い
@retval true 有る
@note
描画オブジェクトがボーン用頂点を持っているかを取得します。
*/
virtual Bool IsSupportVertexBone( void ) = 0;
/**
@brief テクスチャ用頂点の有無を取得
@author 葉迩倭
@retval false 無い
@retval true 有る
@note
描画オブジェクトがテクスチャ用頂点を持っているかを取得します。
*/
virtual Bool IsSupportVertexTexture( void ) = 0;
/**
@brief 法線用頂点の有無を取得
@author 葉迩倭
@retval false 無い
@retval true 有る
@note
描画オブジェクトが法線用頂点を持っているかを取得します。
*/
virtual Bool IsSupportVertexNormal( void ) = 0;
/**
@brief バンプ用接線用頂点の有無を取得
@author 葉迩倭
@retval false 無い
@retval true 有る
@note
描画オブジェクトがバンプ用接線用頂点を持っているかを取得します。
*/
virtual Bool IsSupportVertexBump( void ) = 0;
/**
@brief マテリアル数取得
@author 葉迩倭
@return マテリアル数
@note
描画オブジェクトが所有するマテリアル数を取得します。
*/
virtual Sint32 GetMaterialCount( void ) = 0;
/**
@brief 描画マテリアル取得
@author 葉迩倭
@param Index [in] マテリアル番号
@note
描画オブジェクトが所有するマテリアルデータを取得します。
*/
virtual ICustomizedSceneRenderMaterial *GetMaterialPointer( Sint32 Index ) = 0;
/**
@brief ボーン数を取得
@author 葉迩倭
@return ボーン数
@note
描画オブジェクトが所持しているボーン数を取得します。
*/
virtual Sint32 GetBoneCount( void ) = 0;
/**
@brief ワールド行列取得
@author 葉迩倭
@return ワールド行列
@note
描画オブジェクトの行列データを取得します。
*/
virtual const Math::Matrix &GetWorldMatrix( void ) = 0;
/**
@brief 前フレームのワールド行列取得
@author 葉迩倭
@return ワールド行列
@note
描画オブジェクトの行列データを取得します。
*/
virtual const Math::Matrix &GetWorldMatrixPrev( void ) = 0;
/**
@brief ワールド>ビュー行列取得
@author 葉迩倭
@return ワールド>ビュー行列
@note
描画オブジェクトの行列データを取得します。
*/
virtual const Math::Matrix &GetWorldViewMatrix( void ) = 0;
/**
@brief 前フレームのワールド>ビュー行列取得
@author 葉迩倭
@return ワールド>ビュー行列
@note
描画オブジェクトの行列データを取得します。
*/
virtual const Math::Matrix &GetWorldViewPrevMatrix( void ) = 0;
/**
@brief ワールド>ビュー>プロジェクション行列取得
@author 葉迩倭
@return ワールド>ビュー>プロジェクション行列
@note
描画オブジェクトの行列データを取得します。
*/
virtual const Math::Matrix &GetWorldViewProjectionMatrix( void ) = 0;
/**
@brief 前フレームのワールド>ビュー>プロジェクション行列取得
@author 葉迩倭
@return ワールド>ビュー>プロジェクション行列
@note
描画オブジェクトの行列データを取得します。
*/
virtual const Math::Matrix &GetWorldViewProjectionPrevMatrix( void ) = 0;
/**
@brief ワールド逆行列取得
@author 葉迩倭
@return ワールド逆行列
@note
描画オブジェクトの行列データを取得します。
*/
virtual const Math::Matrix &GetWorldInverseMatrix( void ) = 0;
/**
@brief 前フレームのワールド逆行列取得
@author 葉迩倭
@return ワールド逆行列
@note
描画オブジェクトの行列データを取得します。
*/
virtual const Math::Matrix &GetWorldInverseMatrixPrev( void ) = 0;
/**
@brief ボーン用変換行列取得
@author 葉迩倭
@return ボーン変換行列
@note
描画オブジェクトのボーン用の行列データを取得します。
*/
virtual const Math::SMatrix4x4 *GetBoneMatrixArray( void ) = 0;
/**
@brief 前フレームのボーン用変換行列取得
@author 葉迩倭
@return ボーン変換行列
@note
描画オブジェクトのボーン用の行列データを取得します。
*/
virtual const Math::SMatrix4x4 *GetBoneMatrixArrayPrev( void ) = 0;
/**
@brief レンダリング用頂点データ設定
@author 葉迩倭
@param pRender [in] 関連するIRenderインターフェイス
@note
レンダリングを行うための頂点ストリームの設定を行います。
*/
virtual void SetStreamSource( Renderer::IRender *pRender ) = 0;
/**
@brief 通常レンダリング
@author 葉迩倭
@param MaterialNo [in] 描画するマテリアル番号
@param pRender [in] 関連するIRenderインターフェイス
@note
通常のレンダリング処理を行います。
*/
virtual Sint32 Rendering( Sint32 MaterialNo, Renderer::IRender *pRender ) = 0;
/**
@brief 速度マップ用縮退ポリゴン入りレンダリング
@author 葉迩倭
@param pRender [in] 関連するIRenderインターフェイス
@note
速度マップ描画用の縮退ポリゴン入りのレンダリングを行います。
*/
virtual Sint32 Rendering_Velocity( Renderer::IRender *pRender ) = 0;
/**
@brief 頂点変換タイプを取得
@author 葉迩倭
@retval false 無い
@retval true 有る
@note
描画オブジェクトの頂点変換タイプを取得します。
*/
virtual eTransformType GetTransformType( void ) = 0;
/**
@brief ソフトパーティクルの有無を取得
@author 葉迩倭
@retval false ソフトパーティクルではない
@retval true ソフトパーティクル
@note
描画オブジェクトがソフトパーティクルかどうかを取得します。
*/
virtual Bool GetSoftBillboardEnable( void ) = 0;
/**
@brief 視差バンプマップの有無を取得
@author 葉迩倭
@retval false 無い
@retval true 有る
@note
描画オブジェクトが視差バンプマップを持っているかを取得します。
*/
virtual Bool GetParallaxEnable( void ) = 0;
/**
@brief スペキュラー設定のの有無を取得
@author 葉迩倭
@retval false 無い
@retval true 有る
@note
描画オブジェクトがスペキュラー設定のを持っているかを取得します。
*/
virtual Bool GetSpecularEnable( void ) = 0;
/**
@brief 環境マップ設定のの有無を取得
@author 葉迩倭
@retval false 無い
@retval true 有る
@note
描画オブジェクトが環境マップ設定のを持っているかを取得します。
*/
virtual Bool GetEnvironmentEnable( void ) = 0;
/**
@brief リストにつながれている次の描画オブジェクトを取得
@author 葉迩倭
@return 描画オブジェクトインターフェイス
@note
リストにつながれている描画オブジェクトの自分の次の描画オブジェクトを取得します。
*/
virtual ICustomizedSceneRenderObject *GetNextObject( void ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Scene
{
/**
@brief カスタムシーンマテリアルインターフェイス
@author 葉迩倭
@note
カスタムシーンのアクターのマテリアルを扱うためのインターフェイスです。
*/
class ICustomizedSceneRenderMaterial
{
protected:
virtual ~ICustomizedSceneRenderMaterial() {}
public:
/**
@brief シェーダーインターフェイス取得
@author 葉迩倭
@return シェーダーインターフェイス
@note
マテリアルに関連付けられているシェーダーを取得します。
*/
virtual Renderer::Shader::IShader *GetShader( void ) = 0;
/**
@brief テクスチャインターフェイス取得
@author 葉迩倭
@return テクスチャインターフェイス
@note
マテリアルに関連付けられているテクスチャを取得します。
*/
virtual Renderer::ITexture *GetTexture( Sint32 Stage ) = 0;
/**
@brief 拡散反射色取得
@author 葉迩倭
@return 拡散反射色
@note
マテリアルに関連付けられている拡散反射色を取得します。
*/
virtual Math::Vector4D &GetDiffuseColor( void ) = 0;
/**
@brief 自己発光色取得
@author 葉迩倭
@return 自己発光色
@note
マテリアルに関連付けられている自己発光色を取得します。
*/
virtual Math::Vector4D &GetEmissiveColor( void ) = 0;
/**
@brief 鏡面反射色取得
@author 葉迩倭
@return 鏡面反射色
@note
マテリアルに関連付けられている鏡面反射色を取得します。
*/
virtual Math::Vector4D &GetSpecularColor( void ) = 0;
/**
@brief テクスチャUVオフセット取得
@author 葉迩倭
@return テクスチャUVオフセット
@note
マテリアルに関連付けられているテクスチャUVオフセットを取得します。
*/
virtual Math::Vector2D &GetTextureOffset( void ) = 0;
/**
@brief 鏡面反射反射率取得
@author 葉迩倭
@return 鏡面反射反射率
@note
マテリアルに関連付けられている鏡面反射反射率を取得します。
*/
virtual Float GetSpecularRefractive( void ) = 0;
/**
@brief 鏡面反射荒さ取得
@author 葉迩倭
@return 鏡面反射荒さ
@note
マテリアルに関連付けられている鏡面反射荒さを取得します。
*/
virtual Float GetSpecularRoughly( void ) = 0;
/**
@brief 視差マップ深度取得
@author 葉迩倭
@return 視差マップ深度
@note
マテリアルに関連付けられている視差マップ深度を取得します。
*/
virtual Float GetParallaxDepth( void ) = 0;
/**
@brief 鏡面反射タイプ取得
@author 葉迩倭
@return 鏡面反射タイプ
@note
マテリアルに関連付けられている鏡面反射タイプを取得します。
*/
virtual eSpecularType GetSpecularType( void ) = 0;
/**
@brief 鏡面反射反射率取得
@author 葉迩倭
@return 鏡面反射反射率
@note
マテリアルに関連付けられている鏡面反射反射率を取得します。
*/
virtual eBumpType GetBumpType( void ) = 0;
/**
@brief 鏡面反射反射率取得
@author 葉迩倭
@return 鏡面反射反射率
@note
マテリアルに関連付けられている鏡面反射反射率を取得します。
*/
virtual eDrawType GetDrawType( void ) = 0;
/**
@brief 鏡面反射反射率取得
@author 葉迩倭
@return 鏡面反射反射率
@note
マテリアルに関連付けられている鏡面反射反射率を取得します。
*/
virtual eCullType GetCullType( void ) = 0;
/**
@brief 鏡面反射反射率取得
@author 葉迩倭
@return 鏡面反射反射率
@note
マテリアルに関連付けられている鏡面反射反射率を取得します。
*/
virtual Sint32 GetAlphaBoundary( void ) = 0;
/**
@brief 鏡面反射反射率取得
@author 葉迩倭
@return 鏡面反射反射率
@note
マテリアルに関連付けられている鏡面反射反射率を取得します。
*/
virtual Bool GetAlphaTestEnable( void ) = 0;
/**
@brief 鏡面反射反射率取得
@author 葉迩倭
@return 鏡面反射反射率
@note
マテリアルに関連付けられている鏡面反射反射率を取得します。
*/
virtual Bool GetZTestEnable( void ) = 0;
/**
@brief 鏡面反射反射率取得
@author 葉迩倭
@return 鏡面反射反射率
@note
マテリアルに関連付けられている鏡面反射反射率を取得します。
*/
virtual Bool GetZWriteEnable( void ) = 0;
/**
@brief 鏡面反射反射率取得
@author 葉迩倭
@return 鏡面反射反射率
@note
マテリアルに関連付けられている鏡面反射反射率を取得します。
*/
virtual Bool GetLightEnable( void ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Dynamics
{
struct SSurfaceParameter
{
eContactMode Mode; ///< モード
Float Friction; ///< 摩擦係数
Float FrictionEx; ///< 摩擦係数
Float Bounce; ///< 反射係数
Float BounceVelocity; ///< 反射最低速度
Float SoftErp;
Float SoftCfm;
Float Motion;
Float MotionEx;
Float Slip;
Float SlipEx;
};
/**
@brief 接触点処理用インターフェイス
@author 葉迩倭
ダイナミクスの接触点を管理するためのインターフェイスです。
*/
class IContactPoint : public IInterface
{
public:
virtual ~IContactPoint() {}
virtual Sint32 GetCount( void ) = 0;
virtual void SetSurfaceParameter( Sint32 Index, SSurfaceParameter &Param ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
enum eBodyType
{
BODY_TYPE_GEOMETRY,
BODY_TYPE_MODEL,
BODY_TYPE_MAP,
};
namespace Dynamics
{
/**
@brief ダイナミクス用剛体インターフェイス
@author 葉迩倭
ダイナミクスを処理する剛体のインターフェイスです。
*/
class IRigidBody : public IInterface
{
public:
virtual ~IRigidBody() {}
virtual void SetUserData( void *pUser ) = 0;
virtual void *GetUserData( void ) = 0;
virtual eBodyType GetType( void ) = 0;
virtual void SetPosition( Math::Vector3D &vPos ) = 0;
virtual void SetRotation( Math::Matrix &mRot ) = 0;
virtual void SetLinearSpeed( Math::Vector3D &vDir ) = 0;
virtual void SetAngularSpeed( Math::Vector3D &vDir ) = 0;
virtual Math::Matrix &GetMatrix( void ) = 0;
virtual void GetPosition( Math::Vector3D &vPos ) = 0;
virtual void SetFixed( void ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Dynamics
{
/**
@brief ダイナミクス用剛体インターフェイス
@author 葉迩倭
ダイナミクスを処理する剛体のインターフェイスです。
*/
class IRigidModel : public IInterface
{
public:
virtual ~IRigidModel() {}
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Dynamics
{
typedef void (*CollisionProc)( ISimulationWorld *pWorld, IRigidBody *pIn1, IRigidBody *pIn2, IContactPoint *pContact );
/**
@brief ダイナミクス管理インターフェイス
@author 葉迩倭
ダイナミクスを処理するワールドを管理するインターフェイスです。
*/
class ISimulationWorld : public IInterface
{
public:
virtual ~ISimulationWorld() {}
virtual void SetContactPointCount( Sint32 Count ) = 0;
virtual void SetStepNumIterations( Sint32 Count ) = 0;
virtual void CreateEarth( void ) = 0;
virtual void SetGravity( Math::Vector3D &vDir ) = 0;
virtual void Update( Float fTime, CollisionProc Proc ) = 0;
virtual void RenderingRequest( void ) = 0;
virtual IRigidBody *CreateSphere( Float fRadius, Float fMass, Bool IsBody ) = 0;
virtual IRigidBody *CreateCapsule( Float fRadius, Float fLength, Float fMass, Bool IsBody ) = 0;
virtual IRigidBody *CreateBox( Math::Point3DF &Size, Float fMass, Bool IsBody ) = 0;
virtual IRigidModel *CreateMap( Renderer::Object::IMapModel *pMap ) = 0;
virtual IRigidModel *CreateModel( Renderer::Object::IModel *pModel, Bool IsBody ) = 0;
};
}
}
#pragma once
/**
@file
@brief テクスチャインターフェイス
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Renderer
{
/**
@brief 深度バッファタイプ
@author 葉迩倭
*/
enum eDepthBufferType
{
DEPTH_BUFFER_SURFACE, ///< 深度バッファはサーフェイス
DEPTH_BUFFER_TEXTURE_NVIDIA, ///< 深度バッファはテクスチャ(NVIDIA仕様)
DEPTH_BUFFER_TEXTURE_ATI, ///< 深度バッファはテクスチャ(ATI仕様)
};
/**
@brief テクスチャタイプ
@author 葉迩倭
*/
enum eTextureType
{
TEXTURE_TYPE_DEFAULT, ///< 通常の描画用テクスチャ
TEXTURE_TYPE_TARGET, ///< 描画ターゲット用テクスチャ
TEXTURE_TYPE_DEPTH, ///< 深度バッファ用テクスチャ
TEXTURE_TYPE_NONE, ///< 特になし
};
/**
@brief テクスチャインターフェイス
@author 葉迩倭
@note
テクスチャを操作するためのインターフェイスです。<BR>
IRenderインターフェイスから取得できます。
*/
class ITexture : public IInterface
{
public:
virtual ~ITexture() {}
/**
@brief 画像ファイルとして保存
@author 葉迩倭
@param pFileName [in] テクスチャファイル名
@retval false 失敗
@retval true 成功
@note
テクスチャの内容をTGA画像ファイルとして保存します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
IGraphicCard *pGraphicCard = NULL;
IRender *pRender = NULL;
ITexture *pTex = NULL;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// ビデオカード初期化
IGraphicCard *pGraphicCard = pCore->CreateGraphicCard( GRAPHIC_CARD_DEFAULT_NO );
if ( pGraphicCard == NULL ) goto EXIT; // IGraphicCardにはNullDeviceがないので失敗するとNULLが返る
// レンダラーの生成
IRender *pRender = pGraphicCard->CreateRender();
if ( pRender == NULL ) goto EXIT; // IRenderにはNullDeviceがないので失敗するとNULLが返る
// テクスチャの生成
pTex = pRender->CreateTextureFromFile( "sample.bmp" );
// テクスチャを画像として保存
pTex->SaveToTGA( "hogehoge.tga" );
// メインループ
while ( pCore->Run() )
{
}
}
EXIT:
SAFE_RELEASE( pTex ); // テクスチャの解放
SAFE_RELEASE( pRender ); // レンダラーの解放
SAFE_RELEASE( pGraphicCard ); // ビデオカードの解放
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
virtual Bool SaveToTGA( const char *pFileName ) = 0;
/**
@brief 画像ファイルとして保存
@author 葉迩倭
@param pFileName [in] テクスチャファイル名
@retval false 失敗
@retval true 成功
@note
テクスチャの内容をPNG画像ファイルとして保存します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
IGraphicCard *pGraphicCard = NULL;
IRender *pRender = NULL;
ITexture *pTex = NULL;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// ビデオカード初期化
IGraphicCard *pGraphicCard = pCore->CreateGraphicCard( GRAPHIC_CARD_DEFAULT_NO );
if ( pGraphicCard == NULL ) goto EXIT; // IGraphicCardにはNullDeviceがないので失敗するとNULLが返る
// レンダラーの生成
IRender *pRender = pGraphicCard->CreateRender();
if ( pRender == NULL ) goto EXIT; // IRenderにはNullDeviceがないので失敗するとNULLが返る
// テクスチャの生成
pTex = pRender->CreateTextureFromFile( "sample.bmp" );
// テクスチャを画像として保存
pTex->SaveToPNG( "hogehoge.png" );
// メインループ
while ( pCore->Run() )
{
}
}
EXIT:
SAFE_RELEASE( pTex ); // テクスチャの解放
SAFE_RELEASE( pRender ); // レンダラーの解放
SAFE_RELEASE( pGraphicCard ); // ビデオカードの解放
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
virtual Bool SaveToPNG( const char *pFileName ) = 0;
/**
@brief 実テクスチャサイズ取得
@author 葉迩倭
@return テクスチャの実サイズ
@note
テクスチャのサイズを取得します。<BR>
2の累乗でないテクスチャを作成した際に<BR>
デバイスがそのサイズをサポートしていないときは<BR>
内包できる大きさの2の累乗のサイズになっています。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
IGraphicCard *pGraphicCard = NULL;
IRender *pRender = NULL;
ITexture *pTex = NULL;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// ビデオカード初期化
IGraphicCard *pGraphicCard = pCore->CreateGraphicCard( GRAPHIC_CARD_DEFAULT_NO );
if ( pGraphicCard == NULL ) goto EXIT; // IGraphicCardにはNullDeviceがないので失敗するとNULLが返る
// レンダラーの生成
IRender *pRender = pGraphicCard->CreateRender();
if ( pRender == NULL ) goto EXIT; // IRenderにはNullDeviceがないので失敗するとNULLが返る
// テクスチャの生成
pTex = pRender->CreateTextureFromFile( "sample.bmp" );
// テクスチャのサイズを取得
// テクスチャの実サイズ
// デバイスによっては生成時に要求通りにサイズはならない
Math::Point2DI Size = pTex->GetSize();
// メインループ
while ( pCore->Run() )
{
}
}
EXIT:
SAFE_RELEASE( pTex ); // テクスチャの解放
SAFE_RELEASE( pRender ); // レンダラーの解放
SAFE_RELEASE( pGraphicCard ); // ビデオカードの解放
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
virtual Math::Point2DI GetSize( void ) = 0;
/**
@brief 要求テクスチャサイズ取得
@author 葉迩倭
@return テクスチャのサイズ
@note
テクスチャの元サイズを取得します。<BR>
作成時に指定した大きさを取得します。<BR>
この大きさは実際のテクスチャサイズとは違う場合があります。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
IGraphicCard *pGraphicCard = NULL;
IRender *pRender = NULL;
ITexture *pTex = NULL;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// ビデオカード初期化
IGraphicCard *pGraphicCard = pCore->CreateGraphicCard( GRAPHIC_CARD_DEFAULT_NO );
if ( pGraphicCard == NULL ) goto EXIT; // IGraphicCardにはNullDeviceがないので失敗するとNULLが返る
// レンダラーの生成
IRender *pRender = pGraphicCard->CreateRender();
if ( pRender == NULL ) goto EXIT; // IRenderにはNullDeviceがないので失敗するとNULLが返る
// テクスチャの生成
pTex = pRender->CreateTextureFromFile( "sample.bmp" );
// 生成時にリクエストしたテクスチャのサイズ
// ファイル読み込みの場合ファイル上ので画像のサイズ
Math::Point2DI Size = pTex->GetOriginalSize();
// メインループ
while ( pCore->Run() )
{
}
}
EXIT:
SAFE_RELEASE( pTex ); // テクスチャの解放
SAFE_RELEASE( pRender ); // レンダラーの解放
SAFE_RELEASE( pGraphicCard ); // ビデオカードの解放
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
virtual Math::Point2DI GetOriginalSize( void ) = 0;
/**
@brief テクスチャ変換用パラメーター取得
@author 葉迩倭
@return 変換用の値
@note
テクスチャの元画像の座標からテクスチャの値を取得するための変換用の値を取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
IGraphicCard *pGraphicCard = NULL;
IRender *pRender = NULL;
ITexture *pTex = NULL;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// ビデオカード初期化
IGraphicCard *pGraphicCard = pCore->CreateGraphicCard( GRAPHIC_CARD_DEFAULT_NO );
if ( pGraphicCard == NULL ) goto EXIT; // IGraphicCardにはNullDeviceがないので失敗するとNULLが返る
// レンダラーの生成
IRender *pRender = pGraphicCard->CreateRender();
if ( pRender == NULL ) goto EXIT; // IRenderにはNullDeviceがないので失敗するとNULLが返る
// テクスチャの生成
pTex = pRender->CreateTextureFromFile( "sample.bmp" );
// 元画像の(100,50)座標をUVへ変換
Math::Point2DF Trans = pTex->GetPixelToTexelTransform();
Float u = 100.0f * Trans.x;
Float v = 50.0f * Trans.y;
// メインループ
while ( pCore->Run() )
{
}
}
EXIT:
SAFE_RELEASE( pTex ); // テクスチャの解放
SAFE_RELEASE( pRender ); // レンダラーの解放
SAFE_RELEASE( pGraphicCard ); // ビデオカードの解放
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
virtual Math::Point2DF GetPixelToTexelTransform( void ) = 0;
/**
@brief レンダリングターゲット内容を保存
@author 葉迩倭
@retval true 成功
@retval false 失敗
@note
レンダリングターゲットの現在の内容をバックアップします。<BR>
バックアップされた内容はデバイスのロスト時に自動的に復元されます。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
ICore *pCore = NULL;
IGraphicCard *pGraphicCard = NULL;
IRender *pRender = NULL;
ITexture *pTex = NULL;
// システムの起動
if ( !System::Initialize() )
{
return 0;
}
// ICoreの生成
pCore = System::CreateCore();
if ( pCore == NULL ) goto EXIT; // ICoreにはNullDeviceがないので失敗するとNULLが返る
// コアの初期化
if ( pCore->Initialize( "Sample Program", FRAME_RATE_60 ) )
{
// アプリケーションの開始
pCore->Start( 640, 480, true );
// ビデオカード初期化
IGraphicCard *pGraphicCard = pCore->CreateGraphicCard( GRAPHIC_CARD_DEFAULT_NO );
if ( pGraphicCard == NULL ) goto EXIT; // IGraphicCardにはNullDeviceがないので失敗するとNULLが返る
// レンダラーの生成
IRender *pRender = pGraphicCard->CreateRender();
if ( pRender == NULL ) goto EXIT; // IRenderにはNullDeviceがないので失敗するとNULLが返る
// テクスチャの生成
pTex = pRender->CreateTextureRenderTarget( 256, 256 );
// デバイスロスト時に内容が復元できるように
// 現在の状態をバックアップしておく。
// 通常は何らかのレンダリングを行った時に、
// その内容を保存しておきたい場合に使う。
pTex->BackupTargetBuffer();
// メインループ
while ( pCore->Run() )
{
}
}
EXIT:
SAFE_RELEASE( pTex ); // テクスチャの解放
SAFE_RELEASE( pRender ); // レンダラーの解放
SAFE_RELEASE( pGraphicCard ); // ビデオカードの解放
SAFE_RELEASE( pCore ); // コアの解放
System::Finalize(); // システムの終了処理を行う
return 0;
}
@endcode
*/
virtual Bool BackupTargetBuffer( void ) = 0;
/**
@brief 種類を取得
@author 葉迩倭
@return テクスチャがどの種類に属するかを取得します。
@note
テクスチャの種類を取得します。<BR>
IRender::SetRenderTarget()に使えるのはTEXTURE_TYPE_TARGETだけで<BR>
IRender::SetDepthBuffer()に使えるのはTEXTURE_TYPE_DEPTHだけです。
*/
virtual eTextureType GetType( void ) = 0;
/**
@brief 深度バッファの種類を取得
@author 葉迩倭
@return 深度バッファの種類
@note
深度バッファの種類を取得します。<BR>
返り値がDEPTH_BUFFER_TEXTUREの場合はテクスチャとして深度バッファが作られています。
*/
virtual eDepthBufferType GetDepthBufferType( void ) = 0;
/**
@brief フィルタリング処理の是非を取得
@author 葉迩倭
@retval false フィルタリング&アルファブレンド出来ない
@retval true フィルタリング&アルファブレンド出来る
@note
フィルタリング可能なフォーマットかを取得します。
*/
virtual Bool IsFilterEnable( void ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Network
{
/**
@brief ホスト情報
@author 葉迩倭
*/
struct SHostInfo
{
char Name[64]; ///< ホスト名
char Alias[16][64]; ///< ホスト別名テーブル
char Address[16][64]; ///< IPアドレステーブル
Sint32 Type; ///< データタイプ
Sint32 Length; ///< データサイズ
Sint32 AliasCount; ///< エイリアス数
Sint32 AddressCount; ///< IPアドレス数
};
/**
@brief ネットワーク管理クラス
@author 葉迩倭
@note
Seleneで使用するネットワークの管理を行います。
*/
class INetworkManager : public IInterface
{
public:
virtual ~INetworkManager() {}
/**
@brief エラー文字列取得
@author 葉迩倭
@return 文字列のポインタ
@note
一連のネットワーク処理発生したエラーメッセージを取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Network::INetworkManager *pNetworkMgr = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーにTCPを使って接続する
pTCP = pNetworkMgr->ConnectByTCP( "127.0.0.1", 80 );
if ( pTCP == NULL )
{
// エラーメッセージ
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual const char *GetLastErrorString( void ) = 0;
/**
@brief クライアント生成
@author 葉迩倭
@param pTargetHost [in] 接続先のホスト名(IPアドレス)
@param TargetPort [in] 接続先のポート
@retval NULL 失敗
@retval NULL以外 クライアントのインターフェイス
@note
指定したホストへのTCP接続を試みます。<BR>
接続できた場合はTCP操作用のインターフェイスが返ります。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Network::INetworkManager *pNetworkMgr = NULL;
Network::ISocketTCP *pTCP = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーにTCPを使って接続する
pTCP = pNetworkMgr->ConnectByTCP( "127.0.0.1", 80 );
if ( pTCP == NULL )
{
// エラーメッセージ
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// TCP接続を解放
SAFE_RELEASE( pTCP );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual ISocketTCP *ConnectByTCP( const char *pTargetHost, Uint16 TargetPort ) = 0;
/**
@brief サーバー機能を生成します
@author 葉迩倭
@param Port [in] ポート番号
@param ConnectMax [in] 接続最大数
@retval NULL 失敗
@retval NULL以外 サーバーのインターフェイス
@note
サーバー機能を生成し、そのインターフェイスを取得します。<BR>
接続できた場合はTCP操作用のインターフェイスが返ります。
@code
using namespace Selene;
int main()
{
Network::INetworkManager *pNetworkMgr = NULL;
Network::IServerTCP *pServer = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーを生成する
pServer = pNetworkMgr->CreateServer( HOST_PORT, 16 );
if ( pServer == NULL )
{
// 失敗
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// キー入力で終了
getchar();
// サーバーを解放
SAFE_RELEASE( pServer );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual IServerTCP *CreateServer( Uint16 Port, Uint32 ConnectMax = 32 ) = 0;
/**
@brief ホスト情報取得
@author 葉迩倭
@param Info [out] ホスト情報
@note
一連のネットワーク処理発生したエラーメッセージを取得します。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Network::INetworkManager *pNetworkMgr = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// アプリケーションが動作しているPCのホスト情報を取得
SHostInfo Info;
pNetworkMgr->GetHostInfo( Info );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual void GetHostInfo( SHostInfo &Info ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Network
{
/**
@brief TCP接続クライアントクラス
@author 葉迩倭
@note
Seleneで使用するネットワーク処理を行います。
*/
class ISocketTCP : public IInterface
{
public:
virtual ~ISocketTCP() {}
/**
@brief データ送信
@author 葉迩倭
@param pData [in] データ格納バッファ
@param Size [in] 送信サイズ
@retval false 失敗
@retval true 成功
@note
データの送信を行います。<BR>
指定サイズの送信が完了するまで関数から抜けてきません。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Network::INetworkManager *pNetworkMgr = NULL;
Network::ISocketTCP *pTCP = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーにTCPを使って接続する
pTCP = pNetworkMgr->ConnectByTCP( "127.0.0.1", 80 );
if ( pTCP == NULL )
{
// エラーメッセージ
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
const Uint32 MAX_PACKET_SIZE = 256;
Sint8 PacketBuffer[MAX_PACKET_SIZE];
// データ送信
if ( !pTCP->Send( PacketBuffer, sizeof(PacketBuffer) ) )
{
// エラーメッセージ
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// TCP接続を解放
SAFE_RELEASE( pTCP );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Bool Send( const void *pData, Sint32 Size ) = 0;
/**
@brief データ受信
@author 葉迩倭
@param pData [in] データ格納バッファ
@param Size [in] 受信サイズ
@retval false 失敗
@retval true 成功
@note
データの受信を行います。<BR>
指定サイズの受信が完了するまで関数から抜けてきません。
@code
using namespace Selene;
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
Network::INetworkManager *pNetworkMgr = NULL;
Network::ISocketTCP *pTCP = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーにTCPを使って接続する
pTCP = pNetworkMgr->ConnectByTCP( "127.0.0.1", 80 );
if ( pTCP == NULL )
{
// エラーメッセージ
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
const Uint32 MAX_PACKET_SIZE = 256;
Sint8 PacketBuffer[MAX_PACKET_SIZE];
// データ受信
if ( !pTCP->Recv( PacketBuffer, sizeof(PacketBuffer) ) )
{
// エラーメッセージ
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// TCP接続を解放
SAFE_RELEASE( pTCP );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
@endcode
*/
virtual Bool Recv( void *pData, Sint32 Size ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Network
{
typedef void (*ClientControlCallback)( IServerClientTCP *pClient ); ///< クライアント制御用
/**
@brief TCP接続サーバークラス
@author 葉迩倭
@note
Seleneで使用するネットワーク処理を行います。
*/
class IServerTCP : public IInterface
{
public:
virtual ~IServerTCP() {}
/**
@brief サーバー機能を開始
@author 葉迩倭
@param pCallback [in] クライアント処理用コールバック関数
@note
サーバー機能を開始し、クライアントからの接続を待ちます。<BR>
クライアントが接続されるたびにスレッドが作られ、その中からpCallbackで<BR>
指定した関数に処理がきます。
@code
using namespace Selene;
static void ClientRecieve( Network::IServerClientTCP *pClient );
int main()
{
Network::INetworkManager *pNetworkMgr = NULL;
Network::IServerTCP *pServer = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーを生成する
pServer = pNetworkMgr->CreateServer( 80, 16 );
if ( pServer == NULL )
{
// 失敗
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// サーバー処理開始
pServer->Start( ClientRecieve );
// キー入力で終了
getchar();
// サーバーを解放
SAFE_RELEASE( pServer );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
void ClientRecieve( Network::IServerClientTCP *pClient )
{
// 接続元クライアント情報
Network::SHostInfo HostInfo;
pClient->GetHostInfo( HostInfo );
// クライアント用メイン通信ループ
for ( ; ; )
{
}
}
@endcode
*/
virtual Bool Start( ClientControlCallback pCallback ) = 0;
/**
@brief データ送信
@author 葉迩倭
@param pData [in] データ格納バッファ
@param Size [in] 送信サイズ
@retval false 失敗
@retval true 成功
@note
接続されている全てのクライアントにデータの送信を行います。<BR>
指定サイズの送信が完了するまで関数から抜けてきません。
@code
using namespace Selene;
static void ClientRecieve( Network::IServerClientTCP *pClient );
int main()
{
Network::INetworkManager *pNetworkMgr = NULL;
Network::IServerTCP *pServer = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーを生成する
pServer = pNetworkMgr->CreateServer( 80, 16 );
if ( pServer == NULL )
{
// 失敗
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// サーバー処理開始
pServer->Start( ClientRecieve );
// 全てのクライアントに送信
pServer->SendAllClient( "めっせーじ", strlen("めっせーじ") + 1 );
// キー入力で終了
getchar();
// サーバーを解放
SAFE_RELEASE( pServer );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
void ClientRecieve( Network::IServerClientTCP *pClient )
{
// 接続元クライアント情報
Network::SHostInfo HostInfo;
pClient->GetHostInfo( HostInfo );
// クライアント用メイン通信ループ
for ( ; ; )
{
}
}
@endcode
*/
virtual Bool SendAllClient( const void *pData, Sint32 Size ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Network
{
/**
@brief TCP接続サーバーに接続されたクライアントクラス
@author 葉迩倭
@note
Seleneで使用するネットワーク処理を行います。
*/
class IServerClientTCP : public IInterface
{
public:
virtual ~IServerClientTCP() {}
/**
@brief データ送信
@author 葉迩倭
@param pData [in] データ格納バッファ
@param Size [in] 送信サイズ
@retval false 失敗
@retval true 成功
@note
データの送信を行います。<BR>
指定サイズの送信が完了するまで関数から抜けてきません。
@code
using namespace Selene;
static void ClientRecieve( Network::IServerClientTCP *pClient );
int main()
{
Network::INetworkManager *pNetworkMgr = NULL;
Network::IServerTCP *pServer = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーを生成する
pServer = pNetworkMgr->CreateServer( 80, 16 );
if ( pServer == NULL )
{
// 失敗
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// サーバー処理開始
pServer->Start( ClientRecieve );
// キー入力で終了
getchar();
// サーバーを解放
SAFE_RELEASE( pServer );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
void ClientRecieve( Network::IServerClientTCP *pClient )
{
// 接続元クライアント情報
Network::SHostInfo HostInfo;
pClient->GetHostInfo( HostInfo );
// クライアント用メイン通信ループ
for ( ; ; )
{
const Uint32 MAX_PACKET_SIZE = 256;
Sint8 PacketBuffer[MAX_PACKET_SIZE];
// クライアントへパケットを送る
if ( !pClient->Send( PacketBuffer, sizeof(PacketBuffer) ) )
{
// エラーor切断
return;
}
}
}
@endcode
*/
virtual Bool Send( const void *pData, Sint32 Size ) = 0;
/**
@brief データ受信
@author 葉迩倭
@param pData [in] データ格納バッファ
@param Size [in] 受信サイズ
@retval false 失敗
@retval true 成功
@note
データの受信を行います。<BR>
指定サイズの受信が完了するまで関数から抜けてきません。
@code
using namespace Selene;
static void ClientRecieve( Network::IServerClientTCP *pClient );
int main()
{
Network::INetworkManager *pNetworkMgr = NULL;
Network::IServerTCP *pServer = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーを生成する
pServer = pNetworkMgr->CreateServer( 80, 16 );
if ( pServer == NULL )
{
// 失敗
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// サーバー処理開始
pServer->Start( ClientRecieve );
// キー入力で終了
getchar();
// サーバーを解放
SAFE_RELEASE( pServer );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
void ClientRecieve( Network::IServerClientTCP *pClient )
{
// 接続元クライアント情報
Network::SHostInfo HostInfo;
pClient->GetHostInfo( HostInfo );
// クライアント用メイン通信ループ
for ( ; ; )
{
const Uint32 MAX_PACKET_SIZE = 256;
Sint8 PacketBuffer[MAX_PACKET_SIZE];
// クライアントからのパケットを待つ
if ( !pClient->Recv( PacketBuffer, sizeof(PacketBuffer) ) )
{
// エラーor切断
return;
}
}
}
@endcode
*/
virtual Bool Recv( void *pData, Sint32 Size ) = 0;
/**
@brief 接続されたクライアントの情報取得
@author 葉迩倭
@param Info [in] クライアント情報
@note
接続されたクライアントの情報を取得します。
@code
using namespace Selene;
static void ClientRecieve( Network::IServerClientTCP *pClient );
int main()
{
Network::INetworkManager *pNetworkMgr = NULL;
Network::IServerTCP *pServer = NULL;
// システムの初期化
System::Initialize();
// ネットワークマネージャーの生成
pNetworkMgr = Network::CreateManager();
// サーバーを生成する
pServer = pNetworkMgr->CreateServer( 80, 16 );
if ( pServer == NULL )
{
// 失敗
::MessageBox( NULL, pNetworkMgr->GetLastErrorString(), "ERROR", MB_ICONERROR );
}
// サーバー処理開始
pServer->Start( ClientRecieve );
// キー入力で終了
getchar();
// サーバーを解放
SAFE_RELEASE( pServer );
// ネットワークマネージャーの解放
SAFE_RELEASE( pNetworkMgr );
// システムの解放
System::Finalize();
return 0;
}
void ClientRecieve( Network::IServerClientTCP *pClient )
{
// 接続元クライアント情報
Network::SHostInfo HostInfo;
pClient->GetHostInfo( HostInfo );
// クライアント用メイン通信ループ
for ( ; ; )
{
const Uint32 MAX_PACKET_SIZE = 256;
Sint8 PacketBuffer[MAX_PACKET_SIZE];
// クライアントからのパケットを待つ
if ( !pClient->Recv( PacketBuffer, sizeof(PacketBuffer) ) )
{
// エラーor切断
return;
}
}
}
@endcode
*/
virtual void GetHostInfo( SHostInfo &Info ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace File
{
/**
@brief ファイル管理クラス
@author 葉迩倭
Seleneで使用するファイルの管理を行います。
*/
class IFileManager
{
public:
virtual ~IFileManager() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief ファイルロードパス設定
@author 葉迩倭
@param Priority [in] 検索プライオリティ
@param pRootPath [in] ルートディレクトリ
@param pPassword [in] パックファイルの場合のパスワード(ない場合はNULL)
ファイルの読み込みを行うルートのディレクトリを設定します。<BR>
ここで設定された パス および パス.Pack ファイルは同列に扱われます。<BR>
つまりプログラムの変更なく双方にまったく同じようにアクセス可能です。
*/
virtual void SetRootPath( Sint32 Priority, const char *pRootPath, const char *pPassword = NULL ) = 0;
/**
@brief カレントディレクトリ設定
@author 葉迩倭
@param pCurrentDir [in] ディレクトリ名
ファイル検索を行う際のカレントのディレクトリを設定します。<BR>
ここで設定されたディレクトリをルートとしてファイルの検索を行います。<BR>
<BR>
SetRootPath( 0, "Data", "Data.Pack" ); という設定が行われいて、<BR>
SetCurrentPath( "texture" ); となっているとき「sample.bmp」と指定して読み込みした場合<BR>
<BR>
「Data\texture\sample.bmp」を探しに行き、見つからない場合は<BR>
「Data.Pack」ファイル内の「texture\sample.bmp」ファイルを探しに行きます。
*/
virtual void SetCurrentPath( const char *pCurrentDir ) = 0;
/**
@brief ファイルロード
@author 葉迩倭
@param pFile [in] ファイル名
@param ppData [out] ファイルデータ格納先
@param pSize [out] ファイルサイズ格納先
@retval true 成功
@retval false 失敗
ファイルをロードし、メモリに展開します。
*/
virtual Bool Load( const char *pFile, void **ppData, Sint32 *pSize ) = 0;
/**
@brief データ解放
@author 葉迩倭
@param pData [in] データ
Load()関数で取得したデータをメモリから解放します。<BR>
この関数を使った方法以外での解放は環境依存するため、<BR>
正しく解放されない可能性があります。
*/
virtual void Free( void *pData ) = 0;
/**
@brief ファイルオープン
@author 葉迩倭
@param pFile [in] ファイル名
@retval NULL 失敗
@retval NULL以外 ファイルインターフェイス
リソースファイルをオープンします。<BR>
ここでいうリソースファイルはゲームで使われるデータ全般の事です。<BR>
つまりパックファイルの内容、およびルートディレクトリ以下のデータです。<BR>
SetRootPath()で指定されている[フォルダ]→[パックファイル]の<BR>
順にファイルを検索します。<BR>
オープンしたファイルはパックファイルであっても、<BR>
通常のファイルと同じようにアクセスすることが出来ます。<BR>
またこの関数から取得したIFIleインターフェイスは読み取り専用です。<BR>
使用が終了したIFileインターフェイスはRelease()で解放してください。
*/
virtual IResourceFile *FileOpen( const char *pFile ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace File
{
/**
@brief リソースファイル操作
@author 葉迩倭
*/
class IResourceFile
{
public:
virtual ~IResourceFile() {};
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief ファイルへの読み込み
@author 葉迩倭
@param pData [in] 読み込みデータ
@param Size [in] 読み込みデータサイズ
@return 実際に書き込んだバイト数
ファイルへの読み込みを行います。<BR>
読み込み可能なファイルはインターフェイス生成時に<BR>
FILE_OPEN_TYPE_READかFILE_OPEN_TYPE_READ_WRITEフラグを<BR>
指定する必要があります。
*/
virtual Sint32 Read( void *pData, Sint32 Size ) = 0;
/**
@brief ファイル名取得
@author 葉迩倭
@return ファイル名の先頭アドレス
ファイル名の先頭アドレスを取得します。
*/
virtual const char *GetNamePointer( void ) = 0;
/**
@brief ファイルサイズ取得
@author 葉迩倭
@return ファイルサイズ
ファイルのサイズを取得します。
*/
virtual Sint32 GetFileSize( void ) = 0;
/**
@brief ファイルポインター位置取得
@author 葉迩倭
@return ファイルポインターの位置
現在のファイルポインタの位置を取得します。
*/
virtual Sint32 GetFilePosition( void ) = 0;
/**
@brief ファイルシーク
@author 葉迩倭
@param Offset [in] 移動量
@return ファイルポインターの位置
ファイルポインターの位置をファイルの先頭からOffsetバイト移動します。
*/
virtual Sint32 SeekStart( Sint32 Offset ) = 0;
/**
@brief ファイルシーク
@author 葉迩倭
@param Offset [in] 移動量
@return ファイルポインターの位置
ファイルポインターの位置をファイルの終端からOffsetバイト移動します。
*/
virtual Sint32 SeekEnd( Sint32 Offset ) = 0;
/**
@brief ファイルシーク
@author 葉迩倭
@param Offset [in] 移動量
@return ファイルポインターの位置
ファイルポインターの位置を現在の位置からOffsetバイト移動します。
*/
virtual Sint32 Seek( Sint32 Offset ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Peripheral
{
/**
@brief マウス管理インターフェイス
@author 葉迩倭
マウスを扱うためのインターフェイスです。
*/
class IMouse
{
public:
virtual ~IMouse() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief マウスのX座標取得
@author 葉迩倭
@return X座標
マウスポインターのスクリーン座標上のX座標を取得します。
*/
virtual Sint32 GetPosX( void ) = 0;
/**
@brief マウスのY座標取得
@author 葉迩倭
@return Y座標
マウスポインターのスクリーン座標上のY座標を取得します。
*/
virtual Sint32 GetPosY( void ) = 0;
/**
@brief マウスのホイール回転量取得
@author 葉迩倭
@return ホイール回転量
マウスホイールの回転量を取得します。
*/
virtual Sint32 GetPosW( void ) = 0;
/**
@brief マウスのX移動量取得
@author 葉迩倭
@return X移動量
マウスポインターのスクリーン上のX移動量を取得します。
*/
virtual Sint32 GetMoveX( void ) = 0;
/**
@brief マウスのY移動量取得
@author 葉迩倭
@return Y移動量
マウスポインターのスクリーン上のY移動量を取得します。
*/
virtual Sint32 GetMoveY( void ) = 0;
/**
@brief マウスのホイール移動量取得
@author 葉迩倭
@return ホイール移動量
マウスポインターのホイール移動量を取得します。
*/
virtual Sint32 GetMoveW( void ) = 0;
/**
@brief マウスの左クリック状態取得
@author 葉迩倭
@retval false 左ボタンは押されていない
@retval true 左ボタンは押されている
マウスの左ボタンの状態を取得します。<BR>
この関数ではON/OFFしか取得できません。
*/
virtual Bool GetClickL( void ) = 0;
/**
@brief マウスの右クリック状態取得
@author 葉迩倭
@retval false 右ボタンは押されていない
@retval true 右ボタンは押されている
マウスの右ボタンの状態を取得します。<BR>
この関数ではON/OFFしか取得できません。
*/
virtual Bool GetClickR( void ) = 0;
/**
@brief マウスのホイールクリック状態取得
@author 葉迩倭
@retval false ホイールボタンは押されていない
@retval true ホイールボタンは押されている
マウスのホイールボタンの状態を取得します。<BR>
この関数ではON/OFFしか取得できません。
*/
virtual Bool GetClickW( void ) = 0;
/**
@brief マウスの左ダブルクリック状態取得
@author 葉迩倭
@retval false 左ボタンはダブルクリックされていない
@retval true 左ボタンはダブルクリックされた
マウスの左ボタンがダブルクリックされたかを取得します。<BR>
この関数ではON/OFFしか取得できません。
*/
virtual Bool GetDoubleClickL( void ) = 0;
/**
@brief マウスの右ダブルクリック状態取得
@author 葉迩倭
@retval false 右ボタンはダブルクリックされていない
@retval true 右ボタンはダブルクリックされた
マウスの右ボタンがダブルクリックされたかを取得します。<BR>
この関数ではON/OFFしか取得できません。
*/
virtual Bool GetDoubleClickR( void ) = 0;
/**
@brief マウスのホイールダブルクリック状態取得
@author 葉迩倭
@retval false ホイールボタンはダブルクリックされていない
@retval true ホイールボタンはダブルクリックされた
マウスのホイールボタンがダブルクリックされたかを取得します。<BR>
この関数ではON/OFFしか取得できません。
*/
virtual Bool GetDoubleClickW( void ) = 0;
/**
@brief マウスの左ボタン状態取得
@author 葉迩倭
@return 左ボタンの状態
マウスの左ボタンの詳細な情報を取得します。
*/
virtual eMouseState GetStateL( void ) = 0;
/**
@brief マウスの右ボタン状態取得
@author 葉迩倭
@return 右ボタンの状態
マウスの右ボタンの詳細な情報を取得します。
*/
virtual eMouseState GetStateR( void ) = 0;
/**
@brief マウスのホイールボタン状態取得
@author 葉迩倭
@return ホイールボタンの状態
マウスのホイールボタンの詳細な情報を取得します。
*/
virtual eMouseState GetStateW( void ) = 0;
/**
@brief マウスの位置を設定
@author 葉迩倭
@param Pos [in] スクリーン座標
マウスの位置を任意の場所に設定します。
*/
virtual void SetPosition( Math::Point2DI &Pos ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Peripheral
{
/**
@brief キーボード管理インターフェイス
@author 葉迩倭
キーボードを扱うためのインターフェイスです。
*/
class IKeyboard
{
public:
virtual ~IKeyboard() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief キー入力バッファフラッシュ
@author 葉迩倭
キー入力バッファに蓄積した入力バッファをクリアします。
*/
virtual void ClearKeyBuffer( void ) = 0;
/**
@brief キー入力バッファからデータ取得
@author 葉迩倭
@return 入力されたキーのキーコード
キー入力バッファに蓄積されたデータを取り出します。<BR>
押されたキーを全て取り出す時はwhile()文等で処理してください。
*/
virtual eVirtualKeyCode GetKeyBuffer( void ) = 0;
/**
@brief キーが押されているかチェックする
@author 葉迩倭
@retval false 押されていない
@retval true 押されている
指定されたキーが現在押されているかチェックします。<BR>
純粋にキーのON/OFFのみ取得できます。
*/
virtual Bool GetKeyData( eVirtualKeyCode Key ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Peripheral
{
/**
@brief ジョイスティック管理インターフェイス
@author 葉迩倭
ジョイスティックを扱うためのインターフェイスです。
*/
class IJoystick
{
public:
virtual ~IJoystick() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 軸情報を取得
@author 葉迩倭
@param Type [in] 軸の種類
@param Dir [in] 軸の方向
@return 軸の現在値
指定された種類、方向の軸の状態を取得します。<BR>
アナログスティックの場合は-4096〜+4096の値が返り、<BR>
デジタルスティックの場合は-4096か+4096の値が返ります。
*/
virtual Sint32 GetAxis( ePadAxisType Type, ePadAxisDirection Dir ) = 0;
/**
@brief スライダー情報を取得
@author 葉迩倭
@param Type [in] スライダーのタイプ
@return スライダーの現在値
指定された種類のスライダーの状態を取得します。<BR>
-4096〜+4096の値が返ります。
*/
virtual Sint32 GetSlider( ePadSliderType Type ) = 0;
/**
@brief ボタン情報を取得
@author 葉迩倭
@param Type [in] ボタンのタイプ
@retval false 押されてない
@retval true 押されている
指定された種類のボタンの状態を取得します。
*/
virtual Bool GetButton( ePadButtonType Type ) = 0;
};
}
}
#pragma once
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Peripheral
{
/**
@brief 入力デバイス管理クラス
@author 葉迩倭
キーボードとパッドを統一して扱うためのインターフェイスです。
*/
class IInputController
{
public:
virtual ~IInputController() {}
/**
@brief 有効性チェック
@author 葉迩倭
@retval true 無効
@retval false 有効
インターフェイスが有効か無効かを調べます。
*/
virtual Bool IsInvalid( void ) = 0;
/**
@brief 参照カウンタデクリメント
@author 葉迩倭
@return デクリメント後の参照カウント
参照カウンタをデクリメントし、<BR>
参照カウントが0になった時点でメモリから解放します。
*/
virtual Sint32 Release( void ) = 0;
/**
@brief 参照カウンタインクリメント
@author 葉迩倭
@return インクリメント後の参照カウント
参照カウンタをインクリメントします。<BR>
インクリメントした参照カウントはRelease()を呼ぶことによりデクリメントされます。<BR>
AddRef()をしたインターフェイスは必ずRelease()で解放してください。
*/
virtual Sint32 AddRef( void ) = 0;
/**
@brief 入力情報更新
@author 葉迩倭
入力情報から最新の状態へ更新します。<BR>
必ず1フレームに1回呼ぶようにして下さい。
*/
virtual void Refresh( void ) = 0;
/**
@brief X軸入力設定
@author 葉迩倭
@param Type [in] 入力管理用の軸タイプ
@param AxisX [in] 適用するジョイスティックの軸
@param AxisDirX [in] 適用するジョイスティックの軸方向
ジョイスティックの軸データを入力管理用のX軸へマッピングします。
*/
virtual void SetAxisX( eInputAxisType Type, ePadAxisType AxisX, ePadAxisDirection AxisDirX ) = 0;
/**
@brief Y軸入力設定
@author 葉迩倭
@param Type [in] 入力管理用の軸タイプ
@param AxisY [in] 適用するジョイスティックの軸
@param AxisDirY [in] 適用するジョイスティックの軸方向
ジョイスティックの軸データを入力管理用のY軸へマッピングします。
*/
virtual void SetAxisY( eInputAxisType Type, ePadAxisType AxisY, ePadAxisDirection AxisDirY ) = 0;
/**
@brief ボタン入力設定
@author 葉迩倭
@param Type [in] 入力管理用のボタンタイプ
@param Button [in] 適用するジョイスティックのボタン
ジョイスティックのボタンデータを入力管理用のボタンへマッピングします。
*/
virtual void SetButton( eInputButtonType Type, ePadButtonType Button ) = 0;
/**
@brief キーボード経由入力設定
@author 葉迩倭
@param Type [in] 入力管理用のボタンタイプ
@param Key [in] 適用するキーボードのキー
キーボードのキーをジョイスティックの別名として入力管理用のボタンへマッピングします。
*/
virtual void SetAlias( eInputButtonType Type, eVirtualKeyCode Key ) = 0;
/**
@brief どれか1つでもボタンが押されているかチェック
@author 葉迩倭
@retval false ボタンは1つも押されていない
@retval true ボタンは1つ以上押されている
なんらかのボタンが押されているかどうかをチェックします。
*/
virtual Bool IsPushAnyKey( void ) = 0;
/**
@brief ボタンの状態を初期化
@author 葉迩倭
すべてのステートをOFF状態にします。
*/
virtual void ClearState( void ) = 0;
/**
@brief ボタンの状態を取得
@author 葉迩倭
@param PadState [in] 取得する状態
@param Type [in] 取得するボタン
@retval false ボタンは条件を満たしていない
@retval true ボタンは条件を満たしている
ボタンTypeが状態PadStateのときにtrueが返ります。<BR>
キーリピートを設定している場合は、指定間隔毎にBUTTON_STATE_PUSH<BR>
状態に自動的になります。
*/
virtual Bool GetState( eInputButtonState PadState, eInputButtonType Type ) = 0;
/**
@brief ボタンの状態を設定
@author 葉迩倭
@param PadState [in] 設定する状態
@param Type [in] 設定するボタン
ボタンTypeを状態PadStateに設定します。<BR>
外部からキーを操作し、自動進行などを行わせることが可能です。
*/
virtual void SetState( eInputButtonState PadState, eInputButtonType Type ) = 0;
/**
@brief カーソル上下移動
@author 葉迩倭
@param AxisNo [in] 使用する軸番号
@param Cursor [in,out] カーソル
@param Max [in] カーソルのとりうる最大値
@retval BUTTON_DISABLE ボタンは押されていない
@retval BUTTON_DISABLE以外 ボタンは上or下が押されている
指定した軸に対してカーソルを上下に動かします。<BR>
またこの時にカーソルはリピートされます。
*/
virtual eInputButtonType CursorRepeatUpDown( Sint32 AxisNo, Sint32 &Cursor, Sint32 Max ) = 0;
/**
@brief カーソル左右移動
@author 葉迩倭
@param AxisNo [in] 使用する軸番号
@param Cursor [in,out] カーソル
@param Max [in] カーソルのとりうる最大値
@retval BUTTON_DISABLE ボタンは押されていない
@retval BUTTON_DISABLE以外 ボタンは左or右が押されている
指定した軸に対してカーソルを左右に動かします。<BR>
またこの時にカーソルはリピートされます。
*/
virtual eInputButtonType CursorRepeatLeftRight( Sint32 AxisNo, Sint32 &Cursor, Sint32 Max ) = 0;
/**
@brief カーソル上下移動
@author 葉迩倭
@param AxisNo [in] 使用する軸番号
@param Cursor [in,out] カーソル
@param Max [in] カーソルのとりうる最大値
@retval BUTTON_DISABLE ボタンは押されていない
@retval BUTTON_DISABLE以外 ボタンは上or下が押されている
指定した軸に対してカーソルを上下に動かします。<BR>
またこの時にカーソルはクランプされます。
*/
virtual eInputButtonType CursorClampUpDown( Sint32 AxisNo, Sint32 &Cursor, Sint32 Max ) = 0;
/**
@brief カーソル左右移動
@author 葉迩倭
@param AxisNo [in] 使用する軸番号
@param Cursor [in,out] カーソル
@param Max [in] カーソルのとりうる最大値
@retval BUTTON_DISABLE ボタンは押されていない
@retval BUTTON_DISABLE以外 ボタンは左or右が押されている
指定した軸に対してカーソルを左右に動かします。<BR>
またこの時にカーソルはクランプされます。
*/
virtual eInputButtonType CursorClampLeftRight( Sint32 AxisNo, Sint32 &Cursor, Sint32 Max ) = 0;
};
}
}
#pragma once
/**
@file
@brief サウンドインターフェイス
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Sound
{
/**
@brief サウンド管理クラス
@author 葉迩倭
@note
サウンドの処理を行うクラスです。<BR>
未圧縮Waveのみのオンメモリ多重再生に対応しています。<BR>
SEの再生用途を想定しています。
*/
class ISound : public IInterface
{
public:
virtual ~ISound() {}
/**
@brief 再生
@author 葉迩倭
@param Layer [in] レイヤー番号(-1指定で全レイヤーに対して)
@param IsLoop [in] ループ有無フラグ
@note
読み込んだサウンドデータの再生を開始します。<BR>
ループの有無を指定できます。
@code
ISound *pSnd;
// 同一サウンドであってもLayerが違うものは多重再生が出来る。
// 下の3つは10ms毎に多重再生される。
pSnd->Play( 0, false );
Sleep( 10 );
pSnd->Play( 1, false );
Sleep( 10 );
pSnd->Play( 2, false );
@endcode
*/
virtual void Play( Sint32 Layer, Bool IsLoop = false ) = 0;
/**
@brief 停止
@author 葉迩倭
@param Layer [in] レイヤー番号(-1指定で全レイヤーに対して)
@note
再生中のサウンドを停止します。
@code
ISound *pSnd;
// 同一ファイル=サウンドであってもLayerが違えば別のものとして扱われる
pSnd->Play( 0, false );
Sleep( 10 );
pSnd->Play( 1, false );
Sleep( 10 );
// この場合Layer=0のサウンドは停止するが、Layer=1のサウンドは再生されたままになる
pSnd->Stop( 0, false );
@endcode
*/
virtual void Stop( Sint32 Layer ) = 0;
/**
@brief 一時停止/解除
@author 葉迩倭
@param Layer [in] レイヤー番号(-1指定で全レイヤーに対して)
@note
再生中のサウンドを一時停止、<BR>
一時停止中のサウンドを再生します。
@code
ISound *pSnd;
// 同一ファイル=サウンドであってもLayerが違えば別のものとして扱われる
pSnd->Play( 0, false );
Sleep( 10 );
pSnd->Play( 1, false );
Sleep( 10 );
// この場合Layer=0のサウンドは一時停止するが、Layer=1のサウンドは再生されたままになる
pSnd->Pause( 0, false );
@endcode
*/
virtual void Pause( Sint32 Layer ) = 0;
/**
@brief ボリューム変更
@author 葉迩倭
@param Layer [in] レイヤー番号(-1指定で全レイヤーに対して)
@param fVolume [in] ボリューム(0〜100%)
@note
ボリュームの変更を行います。
@code
ISound *pSnd;
// 同一ファイル=サウンドであってもLayerが違えば別のものとして扱われる
pSnd->Play( 0, false );
Sleep( 10 );
pSnd->Play( 1, false );
Sleep( 10 );
// この場合Layer=0のサウンドは音量が半分になるが、Layer=1のサウンドはそのままになる
pSnd->SetVolume( 0, 50.0f );
@endcode
*/
virtual void SetVolume( Sint32 Layer, Float fVolume ) = 0;
/**
@brief パン移動
@author 葉迩倭
@param Layer [in] レイヤー番号(-1指定で全レイヤーに対して)
@param fPan [in] パン(左:-100〜右:+100)
@note
パンの移動を行います。
@code
ISound *pSnd;
// 同一ファイル=サウンドであってもLayerが違えば別のものとして扱われる
pSnd->Play( 0, false );
Sleep( 10 );
pSnd->Play( 1, false );
Sleep( 10 );
// この場合Layer=0のサウンドは左からのみ鳴るが、Layer=1のサウンドはそのままになる
pSnd->SetPan( 0, -100.0f );
@endcode
*/
virtual void SetPan( Sint32 Layer, Float fPan ) = 0;
/**
@brief 再生チェック
@author 葉迩倭
@param Layer [in] レイヤー番号
@retval false 再生していない
@retval true 再生している
@note
現在再生中のサウンドかどうか調べます。
@code
ISound *pSnd;
// サウンドのLayer=1が再生中か調べる
if ( pSnd->IsPlay( 1 ) )
{
// 再生中
}
@endcode
*/
virtual Bool IsPlay( Sint32 Layer ) = 0;
};
}
}
#pragma once
/**
@file
@brief ストリームサウンドインターフェイス
@author 葉迩倭
*/
//-----------------------------------------------------------------------------------
// INCLUDE
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// NAMESPACE
//-----------------------------------------------------------------------------------
namespace Selene
{
namespace Sound
{
static const Float PLAY_TIME_AUTO = -1.0f;
/**
@brief ストリームサウンド再生パラメーター
@author 葉迩倭
@note
ストリームサウンドの再生を行うためのテーブルデータです。
*/
struct SPlayBlock
{
Sint32 LoopCount; // このテーブルのループ数(-1で無限ループ)
Float fStartTime; // 再生開始位置(秒指定)(PLAY_TIME_AUTO指定で最初から)
Float fEndTime; // 再生終了位置(秒指定)(PLAY_TIME_AUTO指定で最後まで)
};
/**
@brief ストリームサウンド管理クラス
@author 葉迩倭
@note
ストリームサウンドの処理を行うクラスです。<BR>
未圧縮Wave/圧縮Wave/OggVorbisの再生に対応しています。<BR>
BGMや音声の再生用途を想定しています。
*/
class IStreamSound : public IInterface
{
public:
virtual ~IStreamSound() {}
/**
@brief 再生
@author 葉迩倭
@param pTbl [in] 再生テーブル
@param Count [in] 再生テーブル数
@retval false 処理に失敗
@retval true 処理に成功
@note
読み込んだサウンドデータの再生を開始します。<BR>
再生テーブルの定義にそって再生されていきます。
@code
IStreamSound *pSnd;
// 再生テーブル
Sound::SPlayBlock Tbl[] = {
{
3, // 3回
0.0f, // 0.0秒から
5.0f, // 5.0秒まで
},
};
pSnd->Play( Tbl, sizeof(Tbl) / sizeof(Sound::SPlayBlock) );
@endcode
*/
virtual Bool Play( SPlayBlock *pTbl, Sint32 Count ) = 0;
/**
@brief 再生
@author 葉迩倭
@param LoopCount [in] ループ数(-1で無限)
@retval false 処理に失敗
@retval true 処理に成功
@note
読み込んだサウンドデータの再生を開始します。
@code
IStreamSound *pSnd;
// 普通に1回再生
pSnd->Play();
@endcode
*/
virtual Bool Play( Sint32 LoopCount = 0 ) = 0;
/**
@brief 停止
@author 葉迩倭
@retval false 処理に失敗
@retval true 処理に成功
@note
再生中のサウンドを停止します。
@code
IStreamSound *pSnd;
// 再生停止
pSnd->Stop();
@endcode
*/
virtual Bool Stop( void ) = 0;
/**
@brief 一時停止/解除
@author 葉迩倭
@retval false 処理に失敗
@retval true 処理に成功
@note
再生中のサウンドを一時停止、<BR>
一時停止中のサウンドを再生します。
@code
IStreamSound *pSnd;
// 一時停止
pSnd->Pause();
@endcode
*/
virtual Bool Pause( void ) = 0;
/**
@brief ボリューム変更
@author 葉迩倭
@param fVolume [in] ボリューム(0〜100)
@retval false 処理に失敗
@retval true 処理に成功
@note
ボリュームの変更を行います。
@code
IStreamSound *pSnd;
// ボリューム最大に
pSnd->SetVolume( 100.0f );
@endcode
*/
virtual Bool SetVolume( Float fVolume ) = 0;
/**
@brief パン移動
@author 葉迩倭
@param fPan [in] パン(-100〜+100)
@retval false 処理に失敗
@retval true 処理に成功
@note
パンの移動を行います。
@code
IStreamSound *pSnd;
// 右からだけ音を鳴らす
pSnd->SetPan( +100.0f );
@endcode
*/
virtual Bool SetPan( Float fPan ) = 0;
/**
@brief 再生チェック
@author 葉迩倭
@retval false 再生していない
@retval true 再生している
@note
現在再生中のサウンドかどうか調べます。
@code
IStreamSound *pSnd;
// 再生中か調べる
if ( !pSnd->IsPlay() )
{
// 再生終了
}
@endcode
*/
virtual Bool IsPlay( void ) = 0;
};
}
}
| [
"my04337@d15ed888-2954-0410-b748-710a6ca92709"
] | [
[
[
1,
19313
]
]
] |
923f4ad5a23c3bb08c038d717ebd472692fb81dc | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/refactor/src_root/src/ireon_client/paging_landscape/DRGNURBSSurface.cpp | 062d7512677b20c5e5206ddee999b7c10a77b6ba | [] | no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 20,096 | cpp | // DRGNURBSSurface.cpp: implementation of the CDRGNURBSSurface class.
// ------------------------------------------------------------------------------------
// Copyright © 1999 Intel Corporation
// All Rights Reserved
//
// Permission is granted to use, copy, distribute and prepare derivative works of this
// software for any purpose and without fee, provided, that the above copyright notice
// and this statement appear in all copies. Intel makes no representations about the
// suitability of this software for any purpose. This software is provided "AS IS."
//
// Intel specifically disclaims all warranties, express or implied, and all liability,
// including consequential and other indirect damages, for the use of this software,
// including liability for infringement of any proprietary rights, and including the
// warranties of merchantability and fitness for a particular purpose. Intel does not
// assume any responsibility for any errors which may appear in this software nor any
// responsibility to update it.
// ------------------------------------------------------------------------------------
//
// PURPOSE:
//
// Implementation of the CDRGNURBSSurface class for rendering NURBS surfaces.
// Accompanies the article "Rendering NURBS Surfaces in float-Time". Please refer
// to the article for an understanding of the methods in this class.
// ------------------------------------------------------------------------------------
//
// Author: Dean Macri - Intel Developer Relations Divison -- Tools and Technology Group
// Please contact me at [email protected] with questions, suggestions, etc.
//
////////////////////////////////////////////////////////////////////////////////////////
//
// Yoinked from http://www.gamasutra.com/features/19991117/macri_pfv.htm
// Hacked into an unholy mess for use with OGRE by Chris "Antiarc" Heald ([email protected])
// Date: 11/9/2003
//
////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#include "DRGNURBSSurface.h"
#include <stdlib.h>
#include <math.h>
#include <string.h>
CDRGNURBSSurface::CDRGNURBSSurface()
{
m_pControlPoints = NULL;
m_UKnots = NULL;
m_VKnots = NULL;
m_UBasisCoefficients = NULL;
m_VBasisCoefficients = NULL;
m_UBasis = NULL;
m_dUBasis = NULL;
m_VBasis = NULL;
m_dVBasis = NULL;
m_UTemp = NULL;
m_dUTemp = NULL;
m_TessUKnotSpan = NULL;
m_TessVKnotSpan = NULL;
m_iUTessellations = 0;
m_iVTessellations = 0;
m_pVertices = NULL;
}
// -----------------------------------------------------------------------
//
// Free up anything we've allocated
//
// -----------------------------------------------------------------------
void CDRGNURBSSurface::Cleanup( void )
{
ALIGNED_DELETE( m_pControlPoints);
ALIGNED_DELETE(m_UKnots);
ALIGNED_DELETE(m_VKnots);
ALIGNED_DELETE(m_UBasisCoefficients);
ALIGNED_DELETE(m_VBasisCoefficients);
ALIGNED_DELETE(m_UBasis);
ALIGNED_DELETE(m_dUBasis);
ALIGNED_DELETE(m_VBasis);
ALIGNED_DELETE(m_dVBasis);
ALIGNED_DELETE(m_UTemp);
ALIGNED_DELETE(m_dUTemp);
ALIGNED_DELETE(m_pVertices);
SAFE_DELETE( m_TessUKnotSpan );
SAFE_DELETE( m_TessVKnotSpan );
}
CDRGNURBSSurface::~CDRGNURBSSurface()
{
Cleanup(); // Free everything :-)
}
// -----------------------------------------------------------------------
//
// Initialize a CDRGNURBSSurface object. This will normally only be called
// once for a particular object but it's safe to call it more than once.
//
// -----------------------------------------------------------------------
bool CDRGNURBSSurface::Init(int uDegree,
int vDegree,
int uControlPoints,
int vControlPoints,
Point4D *pControlPoints,
float *pUKnots,
float *pVKnots,
int iDefaultUTessellations,
int iDefaultVTessellations
)
{
// In case we've already been initialized.
Cleanup();
// Copy the stuff we're given
//
m_iUDegree = uDegree;
m_iVDegree = vDegree;
m_iUControlPoints = uControlPoints;
m_iVControlPoints = vControlPoints;
//
// Compute some other useful quantities
//
m_iUOrder = m_iUDegree + 1;
m_iVOrder = m_iVDegree + 1;
m_iUKnots = m_iUOrder + m_iUControlPoints;
m_iVKnots = m_iVOrder + m_iVControlPoints;
// Calculate how many valid spans exist in the Knot vectors
m_iUBasisSpans = m_iUKnots - 2 * m_iUDegree;
m_iVBasisSpans = m_iVKnots - 2 * m_iVDegree;
//
// Allocate some memory for the control points, knots, and basis stuff
//
m_pControlPoints = ALIGNED_NEW( m_iUControlPoints * m_iVControlPoints, Point4D );
m_UKnots = ALIGNED_NEW( m_iUKnots, float );
m_VKnots = ALIGNED_NEW( m_iVKnots, float );
// For each span in the knot vector, there will be m_iUOrder (and m_iVOrder)
// Basis polynomials that are non-zero. Each of those polynomials will
// have m_iUOrder coefficients, hence m_iUBasisSpans * m_iUOrder * m_iUOrder
m_UBasisCoefficients = ALIGNED_NEW( m_iUOrder * m_iUOrder * m_iUBasisSpans, float );
m_VBasisCoefficients = ALIGNED_NEW( m_iVOrder * m_iVOrder * m_iVBasisSpans, float );
m_UTemp = ALIGNED_NEW( m_iVOrder, Point4D );
m_dUTemp = ALIGNED_NEW( m_iVOrder, Point4D );
//
// Copy the incoming data to the internal structures. If the incoming control
// points are NOT stored as pre-weighted points, then you'll need to loop over
// the points and multiply x, y, and z by the w value (so that the actual,
// stored control point is {x*w, y*w, z*w, w} )
//
memcpy( m_pControlPoints, pControlPoints, m_iUControlPoints * m_iVControlPoints * sizeof( Point4D ) );
memcpy( m_UKnots, pUKnots, m_iUKnots * sizeof( float ) );
memcpy( m_VKnots, pVKnots, m_iVKnots * sizeof( float ) );
ComputeBasisCoefficients();
SetTessellations( iDefaultUTessellations, iDefaultVTessellations );
return true;
}
// -----------------------------------------------------------------------
//
// Change the number of tessellations used to render the object
//
// -----------------------------------------------------------------------
void CDRGNURBSSurface::SetTessellations( int iUTessellations, int iVTessellations )
{
if( (iUTessellations != m_iUTessellations) ||
(iVTessellations != m_iVTessellations) )
{
m_iUTessellations = iUTessellations;
m_iVTessellations = iVTessellations;
//
// Free anything we've already allocated
//
ALIGNED_DELETE( m_UBasis );
ALIGNED_DELETE(m_VBasis );
ALIGNED_DELETE(m_dUBasis );
ALIGNED_DELETE(m_dVBasis );
SAFE_DELETE( m_TessUKnotSpan );
SAFE_DELETE( m_TessVKnotSpan );
//
// Allocate memory for the basis functions, etc
//
m_UBasis = ALIGNED_NEW( m_iUOrder * SIMD_SIZE * (m_iUTessellations+1), float );
m_VBasis = ALIGNED_NEW( m_iVOrder * SIMD_SIZE * (m_iVTessellations+1), float );
m_dUBasis = ALIGNED_NEW( m_iUOrder * SIMD_SIZE * (m_iUTessellations+1), float );
m_dVBasis = ALIGNED_NEW( m_iVOrder * SIMD_SIZE * (m_iVTessellations+1), float );
m_TessUKnotSpan = new int[ m_iUTessellations+1 ];
m_TessVKnotSpan = new int[ m_iVTessellations+1 ];
ALIGNED_DELETE( m_pVertices );
int iVertices = ((iUTessellations+1) * (iVTessellations+1)); //2 * (iVTessellations + 1);
m_pVertices = ALIGNED_NEW( iVertices, splinePoint );
//
// Re-evaluate the basis functions
//
EvaluateBasisFunctions();
}
}
// -----------------------------------------------------------------------
// float CDRGNURBSSurface::ComputeCoefficient( float *fKnots, int iInterval, int i, int p, int k )
//
//
// Determines the polynomial coefficients from the knot vector
//
// Remember that the b-spline basis functions of degree p on knot interval
// i = (Bi,p) defined on a knot vector u = {U0, U1, ..., Um} are defined:
//
// Bi,0(u) = 1 if Ui <= u < Ui+1
// 0 otherwise
//
// u - Ui Ui+p+1 - u
// Bi,p(u) = ---------- * Bi,p-1(u) + ------------- * Bi+1,p-1(u)
// Ui+p - Ui Ui+p+1 - Ui+1
//
//
// For some degree p on interval i, there exist p+1 polynomials of
// degree p of the form:
//
// Ci,p,0 + Ci,p,1 * u^1 + Ci,p,2 * u^2 + ... + Ci,p,p * u^p
//
// I derived a recursive formula for these constant coefficients as
//
// Ci,0,0 = Bi,0(u) (i.e. Ci,0,0 will be either 0 or 1)
//
// For p > 0
// Ui+p+1 * Ci+1,p-1,0 UiCi,p-1,0
// Ci,p,0 = --------------------- - ------------
// Ui+p+1 - Ui+1 Ui+p - Ui
//
// Ci,p-1,p-1 Ci+1,p-1,p-1
// Ci,p,p = ------------ - ---------------
// Ui+p - Ui Ui+p+1 - Ui+1
//
// For 0<k<p
// Ci,p-1,k-1 - Ui * Ci,p-1,k Ci+1,p-1,k-1 - Ui+p+1 * Ci+1,p-1,k
// Ci,p,k = ---------------------------- - ------------------------------------
// Ui+p - Ui Ui+p+1 - Ui+1
//
//
// From this, for a pth degree b-spline, for each interval i, there are
// p+1 b-spline basis functions that are non-zero and each one has p+1
// coefficients. Note that Ci,p,k is dependent on u only for determining the
// knot span, i, that we're computing the coefficients for.
// The next two functions compute those coefficients for the various intervals
// -----------------------------------------------------------------------
float CDRGNURBSSurface::ComputeCoefficient( float *fKnots, int iInterval, int i, int p, int k )
{
float fResult = 0.0f;
if( p == 0 )
{
if( i == iInterval )
fResult = 1.0f;
}
else if( k == 0 )
{
if( fKnots[i+p] != fKnots[i])
fResult -= fKnots[i] * ComputeCoefficient( fKnots, iInterval, i, p-1, 0 ) / (fKnots[i+p] - fKnots[i]);
if( fKnots[i+p+1] != fKnots[i+1] )
fResult += fKnots[i+p+1] * ComputeCoefficient( fKnots, iInterval, i+1, p-1, 0 ) / (fKnots[i+p+1] - fKnots[i+1]);
}
else if( k == p )
{
if( fKnots[i+p] != fKnots[i] )
fResult += ComputeCoefficient( fKnots, iInterval, i, p-1, p-1 ) / (fKnots[i+p] - fKnots[i]);
if( fKnots[i+p+1] != fKnots[i+1] )
fResult -= ComputeCoefficient( fKnots, iInterval, i+1, p-1, p-1 ) / (fKnots[i+p+1] - fKnots[i+1]);
}
else if( k > p )
{
fResult = 0.0f;
}
else
{
float C1, C2;
if( fKnots[i+p] != fKnots[i] )
{
C1 = ComputeCoefficient( fKnots, iInterval, i, p-1, k-1 );
C2 = ComputeCoefficient( fKnots, iInterval, i, p-1, k );
fResult += (C1 - fKnots[i] * C2 ) / (fKnots[i+p] - fKnots[i] );
}
if( fKnots[i+p+1] != fKnots[i+1] )
{
C1 = ComputeCoefficient( fKnots, iInterval, i+1, p-1, k-1 );
C2 = ComputeCoefficient( fKnots, iInterval, i+1, p-1, k );
fResult -= (C1 - fKnots[i+p+1] * C2 ) / (fKnots[i+p+1] - fKnots[i+1] );
}
}
return fResult;
}
// -----------------------------------------------------------------------
// void CDRGNURBSSurface::ComputeBasisCoefficients( void )
//
// See the comment from the function above, ComputeCoefficient()
// -----------------------------------------------------------------------
void CDRGNURBSSurface::ComputeBasisCoefficients( void )
{
int i, j, k;
//
// Start with U. For each Basis span calculate coefficients
// for m_iUOrder polynomials each having m_iUOrder coefficients
//
for( i=0; i<m_iUBasisSpans; i++)
{
for( j=0; j<m_iUOrder; j++)
{
for( k=0; k<m_iUOrder; k++)
{
m_UBasisCoefficients[ (i * m_iUOrder + j) * m_iUOrder + k ] =
ComputeCoefficient( m_UKnots, i + m_iUDegree, i + j, m_iUDegree, k );
}
}
}
for( i=0; i<m_iVBasisSpans; i++)
{
for( j=0; j<m_iVOrder; j++)
{
for( k=0; k<m_iVOrder; k++)
{
m_VBasisCoefficients[ (i * m_iVOrder + j) * m_iVOrder + k ] =
ComputeCoefficient( m_VKnots, i + m_iVDegree, i + j, m_iVDegree, k );
}
}
}
}
// -----------------------------------------------------------------------
// void CDRGNURBSSurface::EvaluateBasisFunctions( void )
//
// Evaluate the polynomials for the basis functions and store the results.
// First derivatives are calculated as well.
// -----------------------------------------------------------------------
void CDRGNURBSSurface::EvaluateBasisFunctions( void )
{
int i, j, k, idx;
float u, uinc;
float v, vinc;
//
// First evaluate the U basis functions and derivitives at uniformly spaced u values
//
idx = 0;
u = m_UKnots[idx+m_iUDegree];
uinc = (m_UKnots[m_iUKnots-m_iUOrder] - m_UKnots[m_iUDegree])/(m_iUTessellations);
for( i=0; i<=m_iUTessellations; i++ )
{
while( (idx < m_iUKnots - m_iUDegree*2 - 2) && (u >= m_UKnots[idx+m_iUDegree+1] ) )
idx++;
m_TessUKnotSpan[i] = idx+m_iUDegree;
//
// Evaluate using Horner's method
//
for( j=0; j<m_iUOrder; j++)
{
m_UBasis[(i*m_iUOrder+j) * SIMD_SIZE] = m_UBasisCoefficients[ (idx * m_iUOrder + j) * m_iUOrder + m_iUDegree ];
m_dUBasis[(i*m_iUOrder+j) * SIMD_SIZE] = m_UBasis[(i*m_iUOrder+j) * SIMD_SIZE] * m_iUDegree;
for( k=m_iUDegree-1; k>=0; k-- )
{
m_UBasis[(i*m_iUOrder+j)*SIMD_SIZE] = m_UBasis[ (i*m_iUOrder+j)*SIMD_SIZE ] * u +
m_UBasisCoefficients[ (idx * m_iUOrder + j) * m_iUOrder + k ];
if( k>0)
{
m_dUBasis[(i*m_iUOrder+j)*SIMD_SIZE] = m_dUBasis[(i * m_iUOrder+j)*SIMD_SIZE] * u +
m_UBasisCoefficients[ (idx * m_iUOrder + j) * m_iUOrder + k ] * k;
}
}
//
// Make three copies. This isn't necessary if we're using straight C
// code but for the Pentium III optimizations, it is.
//
}
u += uinc;
}
//
// Finally evaluate the V basis functions at uniformly spaced v values
//
idx = 0;
v = m_VKnots[idx+m_iVDegree];
vinc = (m_VKnots[m_iVKnots-m_iVOrder] - m_VKnots[m_iVDegree])/(m_iVTessellations);
for( i=0; i<=m_iVTessellations; i++ )
{
while( (idx < m_iVKnots - m_iVDegree*2 - 2) && (v >= m_VKnots[idx+m_iVDegree+1] ) )
idx++;
m_TessVKnotSpan[i] = idx+m_iVDegree;
//
// Evaluate using Horner's method
//
for( j=0; j<m_iVOrder; j++)
{
m_VBasis[(i*m_iVOrder+j)*SIMD_SIZE] = m_VBasisCoefficients[ (idx * m_iVOrder + j) * m_iVOrder + m_iVDegree ];
m_dVBasis[(i*m_iVOrder+j)*SIMD_SIZE] = m_VBasis[(i*m_iVOrder+j)*SIMD_SIZE] * m_iVDegree;
for( k=m_iVDegree-1; k>=0; k-- )
{
m_VBasis[(i*m_iVOrder+j)*SIMD_SIZE] = m_VBasis[ (i*m_iVOrder+j)*SIMD_SIZE ] * v +
m_VBasisCoefficients[ (idx * m_iVOrder + j) * m_iVOrder + k ];
if( k>0)
{
m_dVBasis[(i*m_iVOrder+j)*SIMD_SIZE] = m_dVBasis[(i * m_iVOrder+j)*SIMD_SIZE] * v +
m_VBasisCoefficients[ (idx * m_iVOrder + j) * m_iVOrder + k ] * k;
}
}
}
v += vinc;
}
}
// -----------------------------------------------------------------------
//
// Tessellate the surface into triangles and submit them as a triangle
// strip to Direct3D.
//
// -----------------------------------------------------------------------
void CDRGNURBSSurface::TessellateSurface()
{
int u, v;
int k, l;
int uKnot, vKnot;
Point4D *UTemp = m_UTemp, *dUTemp = m_dUTemp;
Point4D Pw;
float rhw;
int iVertices;
Point4D *pControlPoints = m_pControlPoints;
int iCPOffset;
float VBasis, dVBasis;
int idx, uidx;
if( (m_iUTessellations == 0) || (m_iVTessellations == 0) )
return;
iVertices = 2 * (m_iVTessellations + 1);
// Step over the U and V coordinates and generate triangle strips to render
//
for( u=0; u<=m_iUTessellations; u++ )
{
// What's the current knot span in the U direction?
uKnot = m_TessUKnotSpan[u];
// Calculate the offset into the pre-calculated basis functions array
uidx = u * m_iUOrder * SIMD_SIZE;
vKnot = -1;
// Create one row of vertices
for( v=0; v<=m_iVTessellations; v++)
{
idx = u * m_iUTessellations + v;
if( vKnot != m_TessVKnotSpan[v] )
{
vKnot = m_TessVKnotSpan[v];
//
// If our knot span in the V direction has changed, then calculate some
// temporary variables. These are the sum of the U-basis functions times
// the control points (times the weights because the control points have
// the weights factored in).
//
for( k=0; k<=m_iVDegree; k++)
{
iCPOffset = (uKnot - m_iUDegree) * m_iVControlPoints + (vKnot - m_iVDegree);
UTemp[k].x = m_UBasis[uidx] * pControlPoints[ iCPOffset + k ].x;
UTemp[k].y = m_UBasis[uidx] * pControlPoints[ iCPOffset + k ].y;
UTemp[k].z = m_UBasis[uidx] * pControlPoints[ iCPOffset + k ].z;
UTemp[k].w = m_UBasis[uidx] * pControlPoints[ iCPOffset + k ].w;
dUTemp[k].x = m_dUBasis[uidx] * pControlPoints[ iCPOffset + k ].x;
dUTemp[k].y = m_dUBasis[uidx] * pControlPoints[ iCPOffset + k ].y;
dUTemp[k].z = m_dUBasis[uidx] * pControlPoints[ iCPOffset + k ].z;
dUTemp[k].w = m_dUBasis[uidx] * pControlPoints[ iCPOffset + k ].w;
for( l=1; l<=m_iUDegree; l++ )
{
iCPOffset += m_iVControlPoints;
UTemp[k].x += m_UBasis[uidx+l * SIMD_SIZE] * pControlPoints[ iCPOffset + k].x;
UTemp[k].y += m_UBasis[uidx+l * SIMD_SIZE] * pControlPoints[ iCPOffset + k].y;
UTemp[k].z += m_UBasis[uidx+l * SIMD_SIZE] * pControlPoints[ iCPOffset + k].z;
UTemp[k].w += m_UBasis[uidx+l * SIMD_SIZE] * pControlPoints[ iCPOffset + k].w;
dUTemp[k].x += m_dUBasis[uidx+l * SIMD_SIZE] * pControlPoints[ iCPOffset + k ].x;
dUTemp[k].y += m_dUBasis[uidx+l * SIMD_SIZE] * pControlPoints[ iCPOffset + k ].y;
dUTemp[k].z += m_dUBasis[uidx+l * SIMD_SIZE] * pControlPoints[ iCPOffset + k ].z;
dUTemp[k].w += m_dUBasis[uidx+l * SIMD_SIZE] * pControlPoints[ iCPOffset + k ].w;
}
}
}
// Compute the point in the U and V directions
VBasis = m_VBasis[ (v * m_iVOrder)*SIMD_SIZE ];
dVBasis = m_dVBasis[ (v * m_iVOrder)*SIMD_SIZE ];
Pw.x = VBasis * UTemp[0].x;
Pw.y = VBasis * UTemp[0].y;
Pw.z = VBasis * UTemp[0].z;
Pw.w = VBasis * UTemp[0].w;
for( k=1; k<=m_iVDegree; k++ )
{
VBasis = m_VBasis[ (v * m_iVOrder + k)*SIMD_SIZE ];
dVBasis = m_dVBasis[ (v * m_iVOrder + k)*SIMD_SIZE ];
Pw.x += VBasis * UTemp[k].x;
Pw.y += VBasis * UTemp[k].y;
Pw.z += VBasis * UTemp[k].z;
Pw.w += VBasis * UTemp[k].w;
}
// rhw is the factor to multiply by inorder to bring the 4-D points back into 3-D
rhw = 1.0f / Pw.w;
Pw.x = Pw.x * rhw;
Pw.y = Pw.y * rhw;
Pw.z = Pw.z * rhw;
// Store the vertex position.
m_pVertices[idx].x = Pw.x;
m_pVertices[idx].y = Pw.y;
m_pVertices[idx].z = Pw.z;
}
}
}
// -----------------------------------------------------------------------
splinePoint CDRGNURBSSurface::getData(int index)
{
return m_pVertices[index];
}
// -----------------------------------------------------------------------
//
// Implementation of the base class method.
//
// -----------------------------------------------------------------------
int CDRGNURBSSurface::GetTriangleCount()
{
return 2 * m_iUTessellations * m_iVTessellations;
}
// -----------------------------------------------------------------------
//
// Change the control points of the surface. This method doesn't do any
// error checking, so it assumes the array passed in contains as many
// control points as where used when the surface was initialized.
//
// -----------------------------------------------------------------------
void CDRGNURBSSurface::UpdateControlPoints( Point4D *pControlPoints )
{
memcpy( m_pControlPoints, pControlPoints, m_iUControlPoints * m_iVControlPoints * sizeof( Point4D ) );
}
| [
"[email protected]"
] | [
[
[
1,
574
]
]
] |
8573aa85214764588a1ba43c26226253624e37ef | d6c883911e533608bb2aca1cf70507072157c3e5 | /test/ipc_dispatch_unnitest.cpp | 746f7723195f32367c4e08a8e864cca704387764 | [] | no_license | JoshEngebretson/simple-ipc-lib | 5b52ca804563615c0a411dc23b5c1e6af963e180 | be7476906f8c0aefa1e1aaac4d2a2493ef7e386f | refs/heads/master | 2020-05-18T01:05:46.494978 | 2011-06-01T01:46:19 | 2011-06-01T01:46:19 | 33,789,519 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,597 | cpp | // Copyright (c) 2010 Google Inc.
//
// 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 "ipc_test_helpers.h"
struct DummyChannel {};
DEFINE_IPC_MSG_CONV(5, 3) {
IPC_MSG_P1(int, Int32)
IPC_MSG_P2(char, Char8)
IPC_MSG_P3(const wchar_t*, String16)
};
class DispTestMsg5 : public DispTestMsg,
public ipc::MsgIn<5, DispTestMsg5, DummyChannel> {
public:
size_t OnMsg(DummyChannel* /*ch*/, int a1, char a2, const wchar_t* str) {
return ((a1 == 7) && (a2 == 'a') && (IPCWString(str) == L"hello planet!")) ? 1: 0;
}
};
DEFINE_IPC_MSG_CONV(3, 2) {
IPC_MSG_P1(int, Int32)
IPC_MSG_P2(const char*, String8)
};
class DispTestMsg3 : public DispTestMsg,
public ipc::MsgIn<3, DispTestMsg3, TestChannel> {
public:
size_t OnMsg(TestChannel*, int ix, const char* tx) {
return ((ix == 56789) && (IPCString(tx) == "1234")) ? 77: ipc::OnMsgReady;
}
void* OnNewTransport() { return NULL; }
};
///////////////////////////////////////////////////////////////////////////////////////////////////
// Test the rx dispatch only
int TestForwardDispatch() {
DispTestMsg5 disp5;
int x = 7;
char y = 'a';
wchar_t z[] = L"hello planet!";
ipc::WireType a1(x);
ipc::WireType a2(y);
ipc::WireType a3(z);
DummyChannel ch;
const ipc::WireType* const args[] = { &a1, &a2, &a3 };
if (!disp5.OnMsgIn(5, &ch, args, 3))
return 1;
if (disp5.HasConvertError() || disp5.HasArgCountError())
return 2;
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Test the roundtrip
int TestDispatchRoundTrip() {
const int ix = 56789;
const char tx[] = "1234";
TestTransport transport;
TestChannel channel(&transport);
{
TestMessage3 msg3;
msg3.DoSend(&channel, ix, tx);
DispTestMsg3 disp3;
if (channel.Receive(&disp3) != 77)
return 1;
if (disp3.HasConvertError() || disp3.HasArgCountError())
return 2;
}
return 0;
}
| [
"[email protected]@6186b68d-3b51-64b3-90d9-2ffb2bcaf3be"
] | [
[
[
1,
94
]
]
] |
53c06a3c256a1c52f1573b33f7243967813f6467 | 00fdb9c8335382401ee0a8c06ad6ebdcaa136b40 | /ARM9/source/plugin/libwma_rockbox/wmadeci.cpp | 24a4f0de59fb869cd568d077131f6d181f2b0537 | [] | no_license | Mbmax/ismart-kernel | d82633ba0864f9f697c3faa4ebc093a51b8463b2 | f80d8d7156897d019eb4e16ef9cec8a431d15ed3 | refs/heads/master | 2016-09-06T13:28:25.260481 | 2011-03-29T10:31:04 | 2011-03-29T10:31:04 | 35,029,299 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 51,527 | cpp | /*
* WMA compatible decoder
* Copyright (c) 2002 The FFmpeg Project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* @file wmadec.c
* WMA compatible decoder.
*/
#include "config.h"
#include <codecs.h>
#include "lib/codeclib.h"
#include "asf.h"
#include "wmadec.h"
#include "wmafixed.h"
#include "bitstream.h"
#include "mdct2.h"
#define VLCBITS 7 /*7 is the lowest without glitching*/
#define VLCMAX ((22+VLCBITS-1)/VLCBITS)
#define EXPVLCBITS 7
#define EXPMAX ((19+EXPVLCBITS-1)/EXPVLCBITS)
#define HGAINVLCBITS 9
#define HGAINMAX ((13+HGAINVLCBITS-1)/HGAINVLCBITS)
typedef struct CoefVLCTable
{
int n; /* total number of codes */
const uint32_t *huffcodes; /* VLC bit values */
const uint8_t *huffbits; /* VLC bit size */
const uint16_t *levels; /* table to build run/level tables */
}
CoefVLCTable;
static void wma_lsp_to_curve_init(WMADecodeContext *s, int frame_len);
fixed32 coefsarray[MAX_CHANNELS][BLOCK_MAX_SIZE] IBSS_ATTR;
/*decode and window into IRAM on targets with at least 80KB of codec IRAM*/
fixed32 frame_out_buf[MAX_CHANNELS][BLOCK_MAX_SIZE * 2] IBSS_ATTR_WMA_LARGE_IRAM;
//static variables that replace malloced stuff
fixed32 stat0[2048], stat1[1024], stat2[512], stat3[256], stat4[128]; //these are the MDCT reconstruction windows
uint16_t *runtabarray[2], *levtabarray[2]; //these are VLC lookup tables
uint16_t runtab0[1336], runtab1[1336], levtab0[1336], levtab1[1336]; //these could be made smaller since only one can be 1336
#define VLCBUF1SIZE 4598
#define VLCBUF2SIZE 3574
#define VLCBUF3SIZE 360
#define VLCBUF4SIZE 540
/*putting these in IRAM actually makes PP slower*/
VLC_TYPE vlcbuf1[VLCBUF1SIZE][2];
VLC_TYPE vlcbuf2[VLCBUF2SIZE][2];
VLC_TYPE vlcbuf3[VLCBUF3SIZE][2];
VLC_TYPE vlcbuf4[VLCBUF4SIZE][2];
#include "wmadata.h" // PJJ
/*
* Helper functions for wma_window.
*
*
*/
#ifdef CPU_ARM
static inline
void vector_fmul_add_add(fixed32 *dst, const fixed32 *data,
const fixed32 *window, int n)
{
/* Block sizes are always power of two */
#if 0
asm volatile (
"0:"
"ldmia %[d]!, {r0, r1};"
"ldmia %[w]!, {r4, r5};"
/* consume the first data and window value so we can use those
* registers again */
"smull r8, r9, r0, r4;"
"ldmia %[dst], {r0, r4};"
"add r0, r0, r9, lsl #1;" /* *dst=*dst+(r9<<1)*/
"smull r8, r9, r1, r5;"
"add r1, r4, r9, lsl #1;"
"stmia %[dst]!, {r0, r1};"
"subs %[n], %[n], #2;"
"bne 0b;"
: [d] "+r" (data), [w] "+r" (window), [dst] "+r" (dst), [n] "+r" (n)
: : "r0", "r1", "r4", "r5", "r8", "r9", "memory", "cc");
#endif
}
static inline
void vector_fmul_reverse(fixed32 *dst, const fixed32 *src0, const fixed32 *src1,
int len)
{
#if 0
/* Block sizes are always power of two */
asm volatile (
"add %[s1], %[s1], %[n], lsl #2;"
"0:"
"ldmia %[s0]!, {r0, r1};"
"ldmdb %[s1]!, {r4, r5};"
"smull r8, r9, r0, r5;"
"mov r0, r9, lsl #1;"
"smull r8, r9, r1, r4;"
"mov r1, r9, lsl #1;"
"stmia %[dst]!, {r0, r1};"
"subs %[n], %[n], #2;"
"bne 0b;"
: [s0] "+r" (src0), [s1] "+r" (src1), [dst] "+r" (dst), [n] "+r" (len)
: : "r0", "r1", "r4", "r5", "r8", "r9", "memory", "cc");
#endif
}
#elif defined(CPU_COLDFIRE)
static inline
void vector_fmul_add_add(fixed32 *dst, const fixed32 *data,
const fixed32 *window, int n)
{
/* Block sizes are always power of two. Smallest block is always way bigger
* than four too.*/
asm volatile (
"0:"
"movem.l (%[d]), %%d0-%%d3;"
"movem.l (%[w]), %%d4-%%d5/%%a0-%%a1;"
"mac.l %%d0, %%d4, %%acc0;"
"mac.l %%d1, %%d5, %%acc1;"
"mac.l %%d2, %%a0, %%acc2;"
"mac.l %%d3, %%a1, %%acc3;"
"lea.l (16, %[d]), %[d];"
"lea.l (16, %[w]), %[w];"
"movclr.l %%acc0, %%d0;"
"movclr.l %%acc1, %%d1;"
"movclr.l %%acc2, %%d2;"
"movclr.l %%acc3, %%d3;"
"movem.l (%[dst]), %%d4-%%d5/%%a0-%%a1;"
"add.l %%d4, %%d0;"
"add.l %%d5, %%d1;"
"add.l %%a0, %%d2;"
"add.l %%a1, %%d3;"
"movem.l %%d0-%%d3, (%[dst]);"
"lea.l (16, %[dst]), %[dst];"
"subq.l #4, %[n];"
"jne 0b;"
: [d] "+a" (data), [w] "+a" (window), [dst] "+a" (dst), [n] "+d" (n)
: : "d0", "d1", "d2", "d3", "d4", "d5", "a0", "a1", "memory", "cc");
}
static inline
void vector_fmul_reverse(fixed32 *dst, const fixed32 *src0, const fixed32 *src1,
int len)
{
/* Block sizes are always power of two. Smallest block is always way bigger
* than four too.*/
asm volatile (
"lea.l (-16, %[s1], %[n]*4), %[s1];"
"0:"
"movem.l (%[s0]), %%d0-%%d3;"
"movem.l (%[s1]), %%d4-%%d5/%%a0-%%a1;"
"mac.l %%d0, %%a1, %%acc0;"
"mac.l %%d1, %%a0, %%acc1;"
"mac.l %%d2, %%d5, %%acc2;"
"mac.l %%d3, %%d4, %%acc3;"
"lea.l (16, %[s0]), %[s0];"
"lea.l (-16, %[s1]), %[s1];"
"movclr.l %%acc0, %%d0;"
"movclr.l %%acc1, %%d1;"
"movclr.l %%acc2, %%d2;"
"movclr.l %%acc3, %%d3;"
"movem.l %%d0-%%d3, (%[dst]);"
"lea.l (16, %[dst]), %[dst];"
"subq.l #4, %[n];"
"jne 0b;"
: [s0] "+a" (src0), [s1] "+a" (src1), [dst] "+a" (dst), [n] "+d" (len)
: : "d0", "d1", "d2", "d3", "d4", "d5", "a0", "a1", "memory", "cc");
}
#else
static inline void vector_fmul_add_add(fixed32 *dst, const fixed32 *src0, const fixed32 *src1, int len){
int i;
for(i=0; i<len; i++)
dst[i] = fixmul32b(src0[i], src1[i]) + dst[i];
}
static inline void vector_fmul_reverse(fixed32 *dst, const fixed32 *src0, const fixed32 *src1, int len){
int i;
src1 += len-1;
for(i=0; i<len; i++)
dst[i] = fixmul32b(src0[i], src1[-i]);
}
#endif
/**
* Apply MDCT window and add into output.
*
* We ensure that when the windows overlap their squared sum
* is always 1 (MDCT reconstruction rule).
*
* The Vorbis I spec has a great diagram explaining this process.
* See section 1.3.2.3 of http://xiph.org/vorbis/doc/Vorbis_I_spec.html
*/
static void wma_window(WMADecodeContext *s, fixed32 *in, fixed32 *out)
{
//float *in = s->output;
int block_len, bsize, n;
/* left part */
/*previous block was larger, so we'll use the size of the current block to set the window size*/
if (s->block_len_bits <= s->prev_block_len_bits) {
block_len = s->block_len;
bsize = s->frame_len_bits - s->block_len_bits;
vector_fmul_add_add(out, in, s->windows[bsize], block_len);
} else {
/*previous block was smaller or the same size, so use it's size to set the window length*/
block_len = 1 << s->prev_block_len_bits;
/*find the middle of the two overlapped blocks, this will be the first overlapped sample*/
n = (s->block_len - block_len) / 2;
bsize = s->frame_len_bits - s->prev_block_len_bits;
vector_fmul_add_add(out+n, in+n, s->windows[bsize], block_len);
memcpy(out+n+block_len, in+n+block_len, n*sizeof(fixed32));
}
/* Advance to the end of the current block and prepare to window it for the next block.
* Since the window function needs to be reversed, we do it backwards starting with the
* last sample and moving towards the first
*/
out += s->block_len;
in += s->block_len;
/* right part */
if (s->block_len_bits <= s->next_block_len_bits) {
block_len = s->block_len;
bsize = s->frame_len_bits - s->block_len_bits;
vector_fmul_reverse(out, in, s->windows[bsize], block_len);
} else {
block_len = 1 << s->next_block_len_bits;
n = (s->block_len - block_len) / 2;
bsize = s->frame_len_bits - s->next_block_len_bits;
memcpy(out, in, n*sizeof(fixed32));
vector_fmul_reverse(out+n, in+n, s->windows[bsize], block_len);
memset(out+n+block_len, 0, n*sizeof(fixed32));
}
}
/* XXX: use same run/length optimization as mpeg decoders */
static void init_coef_vlc(VLC *vlc,
uint16_t **prun_table, uint16_t **plevel_table,
const CoefVLCTable *vlc_table, int tab)
{
int n = vlc_table->n;
const uint8_t *table_bits = vlc_table->huffbits;
const uint32_t *table_codes = vlc_table->huffcodes;
const uint16_t *levels_table = vlc_table->levels;
uint16_t *run_table, *level_table;
const uint16_t *p;
int i, l, j, level;
init_vlc(vlc, VLCBITS, n, table_bits, 1, 1, table_codes, 4, 4, 0);
run_table = runtabarray[tab];
level_table= levtabarray[tab];
p = levels_table;
i = 2;
level = 1;
while (i < n)
{
l = *p++;
for(j=0;j<l;++j)
{
run_table[i] = j;
level_table[i] = level;
++i;
}
++level;
}
*prun_table = run_table;
*plevel_table = level_table;
}
int wma_decode_init(WMADecodeContext* s, asf_waveformatex_t *wfx)
{
//WMADecodeContext *s = avctx->priv_data;
int i, flags1, flags2;
fixed32 *window;
uint8_t *extradata;
fixed64 bps1;
fixed32 high_freq;
fixed64 bps;
int sample_rate1;
int coef_vlc_table;
// int filehandle;
#ifdef CPU_COLDFIRE
coldfire_set_macsr(EMAC_FRACTIONAL | EMAC_SATURATE);
#endif
/*clear stereo setting to avoid glitches when switching stereo->mono*/
s->channel_coded[0]=0;
s->channel_coded[1]=0;
s->ms_stereo=0;
s->sample_rate = wfx->rate;
s->nb_channels = wfx->channels;
s->bit_rate = wfx->bitrate;
s->block_align = wfx->blockalign;
s->coefs = &coefsarray;
s->frame_out = &frame_out_buf;
if (wfx->codec_id == ASF_CODEC_ID_WMAV1) {
s->version = 1;
} else if (wfx->codec_id == ASF_CODEC_ID_WMAV2 ) {
s->version = 2;
} else {
/*one of those other wma flavors that don't have GPLed decoders */
return -1;
}
/* extract flag infos */
flags1 = 0;
flags2 = 0;
extradata = wfx->data;
if (s->version == 1 && wfx->datalen >= 4) {
flags1 = extradata[0] | (extradata[1] << 8);
flags2 = extradata[2] | (extradata[3] << 8);
}else if (s->version == 2 && wfx->datalen >= 6){
flags1 = extradata[0] | (extradata[1] << 8) |
(extradata[2] << 16) | (extradata[3] << 24);
flags2 = extradata[4] | (extradata[5] << 8);
}
DEBUGF("flags1=0x%x, flags2=0x%x\n",flags1,flags2);
s->use_exp_vlc = flags2 & 0x0001;
s->use_bit_reservoir = flags2 & 0x0002;
s->use_variable_block_len = flags2 & 0x0004;
/* compute MDCT block size */
if (s->sample_rate <= 16000){
s->frame_len_bits = 9;
}else if (s->sample_rate <= 22050 ||
(s->sample_rate <= 32000 && s->version == 1)){
s->frame_len_bits = 10;
}else{
s->frame_len_bits = 11;
}
s->frame_len = 1 << s->frame_len_bits;
if (s-> use_variable_block_len)
{
int nb_max, nb;
nb = ((flags2 >> 3) & 3) + 1;
if ((s->bit_rate / s->nb_channels) >= 32000)
{
nb += 2;
}
nb_max = s->frame_len_bits - BLOCK_MIN_BITS; //max is 11-7
if (nb > nb_max)
nb = nb_max;
s->nb_block_sizes = nb + 1;
}
else
{
s->nb_block_sizes = 1;
}
/* init rate dependant parameters */
s->use_noise_coding = 1;
high_freq = itofix64(s->sample_rate) >> 1;
/* if version 2, then the rates are normalized */
sample_rate1 = s->sample_rate;
if (s->version == 2)
{
if (sample_rate1 >= 44100)
sample_rate1 = 44100;
else if (sample_rate1 >= 22050)
sample_rate1 = 22050;
else if (sample_rate1 >= 16000)
sample_rate1 = 16000;
else if (sample_rate1 >= 11025)
sample_rate1 = 11025;
else if (sample_rate1 >= 8000)
sample_rate1 = 8000;
}
fixed64 tmp = itofix64(s->bit_rate);
fixed64 tmp2 = itofix64(s->nb_channels * s->sample_rate);
bps = fixdiv64(tmp, tmp2);
fixed64 tim = bps * s->frame_len;
fixed64 tmpi = fixdiv64(tim,itofix64(8));
s->byte_offset_bits = av_log2(fixtoi64(tmpi+0x8000)) + 2;
/* compute high frequency value and choose if noise coding should
be activated */
bps1 = bps;
if (s->nb_channels == 2)
bps1 = fixmul32(bps,0x1999a);
if (sample_rate1 == 44100)
{
if (bps1 >= 0x9c29)
s->use_noise_coding = 0;
else
high_freq = fixmul32(high_freq,0x6666);
}
else if (sample_rate1 == 22050)
{
if (bps1 >= 0x128f6)
s->use_noise_coding = 0;
else if (bps1 >= 0xb852)
high_freq = fixmul32(high_freq,0xb333);
else
high_freq = fixmul32(high_freq,0x999a);
}
else if (sample_rate1 == 16000)
{
if (bps > 0x8000)
high_freq = fixmul32(high_freq,0x8000);
else
high_freq = fixmul32(high_freq,0x4ccd);
}
else if (sample_rate1 == 11025)
{
high_freq = fixmul32(high_freq,0xb333);
}
else if (sample_rate1 == 8000)
{
if (bps <= 0xa000)
{
high_freq = fixmul32(high_freq,0x8000);
}
else if (bps > 0xc000)
{
s->use_noise_coding = 0;
}
else
{
high_freq = fixmul32(high_freq,0xa666);
}
}
else
{
if (bps >= 0xcccd)
{
high_freq = fixmul32(high_freq,0xc000);
}
else if (bps >= 0x999a)
{
high_freq = fixmul32(high_freq,0x999a);
}
else
{
high_freq = fixmul32(high_freq,0x8000);
}
}
/* compute the scale factor band sizes for each MDCT block size */
{
int a, b, pos, lpos, k, block_len, i, j, n;
const uint8_t *table;
if (s->version == 1)
{
s->coefs_start = 3;
}
else
{
s->coefs_start = 0;
}
for(k = 0; k < s->nb_block_sizes; ++k)
{
block_len = s->frame_len >> k;
if (s->version == 1)
{
lpos = 0;
for(i=0;i<25;++i)
{
a = wma_critical_freqs[i];
b = s->sample_rate;
pos = ((block_len * 2 * a) + (b >> 1)) / b;
if (pos > block_len)
pos = block_len;
s->exponent_bands[0][i] = pos - lpos;
if (pos >= block_len)
{
++i;
break;
}
lpos = pos;
}
s->exponent_sizes[0] = i;
}
else
{
/* hardcoded tables */
table = NULL;
a = s->frame_len_bits - BLOCK_MIN_BITS - k;
if (a < 3)
{
if (s->sample_rate >= 44100)
table = exponent_band_44100[a];
else if (s->sample_rate >= 32000)
table = exponent_band_32000[a];
else if (s->sample_rate >= 22050)
table = exponent_band_22050[a];
}
if (table)
{
n = *table++;
for(i=0;i<n;++i)
s->exponent_bands[k][i] = table[i];
s->exponent_sizes[k] = n;
}
else
{
j = 0;
lpos = 0;
for(i=0;i<25;++i)
{
a = wma_critical_freqs[i];
b = s->sample_rate;
pos = ((block_len * 2 * a) + (b << 1)) / (4 * b);
pos <<= 2;
if (pos > block_len)
pos = block_len;
if (pos > lpos)
s->exponent_bands[k][j++] = pos - lpos;
if (pos >= block_len)
break;
lpos = pos;
}
s->exponent_sizes[k] = j;
}
}
/* max number of coefs */
s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k;
/* high freq computation */
fixed32 tmp1 = high_freq*2; /* high_freq is a fixed32!*/
fixed32 tmp2=itofix32(s->sample_rate>>1);
s->high_band_start[k] = fixtoi32( fixdiv32(tmp1, tmp2) * (block_len>>1) +0x8000);
/*
s->high_band_start[k] = (int)((block_len * 2 * high_freq) /
s->sample_rate + 0.5);*/
n = s->exponent_sizes[k];
j = 0;
pos = 0;
for(i=0;i<n;++i)
{
int start, end;
start = pos;
pos += s->exponent_bands[k][i];
end = pos;
if (start < s->high_band_start[k])
start = s->high_band_start[k];
if (end > s->coefs_end[k])
end = s->coefs_end[k];
if (end > start)
s->exponent_high_bands[k][j++] = end - start;
}
s->exponent_high_sizes[k] = j;
}
}
/*Not using the ffmpeg IMDCT anymore*/
/* mdct_init_global();
for(i = 0; i < s->nb_block_sizes; ++i)
{
ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 1);
}
*/
/*ffmpeg uses malloc to only allocate as many window sizes as needed. However, we're really only interested in the worst case memory usage.
* In the worst case you can have 5 window sizes, 128 doubling up 2048
* Smaller windows are handled differently.
* Since we don't have malloc, just statically allocate this
*/
fixed32 *temp[5];
temp[0] = stat0;
temp[1] = stat1;
temp[2] = stat2;
temp[3] = stat3;
temp[4] = stat4;
/* init MDCT windows : simple sinus window */
for(i = 0; i < s->nb_block_sizes; i++)
{
int n, j;
fixed32 alpha;
n = 1 << (s->frame_len_bits - i);
//window = av_malloc(sizeof(fixed32) * n);
window = temp[i];
//fixed32 n2 = itofix32(n<<1); //2x the window length
//alpha = fixdiv32(M_PI_F, n2); //PI / (2x Window length) == PI<<(s->frame_len_bits - i+1)
//alpha = M_PI_F>>(s->frame_len_bits - i+1);
alpha = (1<<15)>>(s->frame_len_bits - i+1); /* this calculates 0.5/(2*n) */
for(j=0;j<n;++j)
{
fixed32 j2 = itofix32(j) + 0x8000;
window[j] = fsincos(fixmul32(j2,alpha)<<16, 0); //alpha between 0 and pi/2
}
s->windows[i] = window;
}
s->reset_block_lengths = 1;
if (s->use_noise_coding)
{
/* init the noise generator */
if (s->use_exp_vlc)
{
s->noise_mult = 0x51f;
s->noise_table = noisetable_exp;
}
else
{
s->noise_mult = 0xa3d;
/* LSP values are simply 2x the EXP values */
for (i=0;i<NOISE_TAB_SIZE;++i)
noisetable_exp[i] = noisetable_exp[i]<< 1;
s->noise_table = noisetable_exp;
}
#if 0
{
unsigned int seed;
fixed32 norm;
seed = 1;
norm = 0; // PJJ: near as makes any diff to 0!
for (i=0;i<NOISE_TAB_SIZE;++i)
{
seed = seed * 314159 + 1;
s->noise_table[i] = itofix32((int)seed) * norm;
}
}
#endif
s->hgain_vlc.table = vlcbuf4;
s->hgain_vlc.table_allocated = VLCBUF4SIZE;
init_vlc(&s->hgain_vlc, HGAINVLCBITS, sizeof(hgain_huffbits),
hgain_huffbits, 1, 1,
hgain_huffcodes, 2, 2, 0);
}
if (s->use_exp_vlc)
{
s->exp_vlc.table = vlcbuf3;
s->exp_vlc.table_allocated = VLCBUF3SIZE;
init_vlc(&s->exp_vlc, EXPVLCBITS, sizeof(scale_huffbits),
scale_huffbits, 1, 1,
scale_huffcodes, 4, 4, 0);
}
else
{
wma_lsp_to_curve_init(s, s->frame_len);
}
/* choose the VLC tables for the coefficients */
coef_vlc_table = 2;
if (s->sample_rate >= 32000)
{
if (bps1 < 0xb852)
coef_vlc_table = 0;
else if (bps1 < 0x128f6)
coef_vlc_table = 1;
}
runtabarray[0] = runtab0; runtabarray[1] = runtab1;
levtabarray[0] = levtab0; levtabarray[1] = levtab1;
s->coef_vlc[0].table = vlcbuf1;
s->coef_vlc[0].table_allocated = VLCBUF1SIZE;
s->coef_vlc[1].table = vlcbuf2;
s->coef_vlc[1].table_allocated = VLCBUF2SIZE;
init_coef_vlc(&s->coef_vlc[0], &s->run_table[0], &s->level_table[0],
&coef_vlcs[coef_vlc_table * 2], 0);
init_coef_vlc(&s->coef_vlc[1], &s->run_table[1], &s->level_table[1],
&coef_vlcs[coef_vlc_table * 2 + 1], 1);
s->last_superframe_len = 0;
s->last_bitoffset = 0;
av_log(NULL, AV_LOG_INFO, "version=%d channels=%d sample_rate=%d bitrate=%d block_align=%d\n", s->version, s->nb_channels, s->sample_rate, s->bit_rate, s->block_align);
av_log(NULL, AV_LOG_INFO, "bps=%f bps1=%f high_freq=%f bitoffset=%d\n", DoubleFrom64(bps), DoubleFrom64(bps1), DoubleFrom64(high_freq), s->byte_offset_bits);
av_log(NULL, AV_LOG_INFO, "use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n", s->use_noise_coding, s->use_exp_vlc, s->nb_block_sizes);
return 0;
}
/* compute x^-0.25 with an exponent and mantissa table. We use linear
interpolation to reduce the mantissa table size at a small speed
expense (linear interpolation approximately doubles the number of
bits of precision). */
static inline fixed32 pow_m1_4(WMADecodeContext *s, fixed32 x)
{
union {
float f;
unsigned int v;
} u, t;
unsigned int e, m;
fixed32 a, b;
#if 0 // disabled temp
u.f = fixtof64(x);
e = u.v >> 23;
m = (u.v >> (23 - LSP_POW_BITS)) & ((1 << LSP_POW_BITS) - 1);
/* build interpolation scale: 1 <= t < 2. */
t.v = ((u.v << LSP_POW_BITS) & ((1 << 23) - 1)) | (127 << 23);
#endif
a = s->lsp_pow_m_table1[m];
b = s->lsp_pow_m_table2[m];
/* lsp_pow_e_table contains 32.32 format */
/* TODO: Since we're unlikely have value that cover the whole
* IEEE754 range, we probably don't need to have all possible exponents */
return (lsp_pow_e_table[e] * (a + fixmul32(b, ftofix32(t.f))) >>32);
}
static void wma_lsp_to_curve_init(WMADecodeContext *s, int frame_len)
{
fixed32 wdel, a, b, temp, temp2;
int i, m;
wdel = fixdiv32(M_PI_F, itofix32(frame_len));
temp = fixdiv32(itofix32(1), itofix32(frame_len));
for (i=0; i<frame_len; ++i)
{
/* TODO: can probably reuse the trig_init values here */
fsincos((temp*i)<<15, &temp2);
/* get 3 bits headroom + 1 bit from not doubleing the values */
s->lsp_cos_table[i] = temp2>>3;
}
/* NOTE: these two tables are needed to avoid two operations in
pow_m1_4 */
b = itofix32(1);
int ix = 0;
/*double check this later*/
for(i=(1 << LSP_POW_BITS) - 1;i>=0;i--)
{
m = (1 << LSP_POW_BITS) + i;
a = pow_a_table[ix++]<<4;
s->lsp_pow_m_table1[i] = 2 * a - b;
s->lsp_pow_m_table2[i] = b - a;
b = a;
}
}
/* NOTE: We use the same code as Vorbis here */
/* XXX: optimize it further with SSE/3Dnow */
static void wma_lsp_to_curve(WMADecodeContext *s,
fixed32 *out,
fixed32 *val_max_ptr,
int n,
fixed32 *lsp)
{
int i, j;
fixed32 p, q, w, v, val_max, temp, temp2;
val_max = 0;
for(i=0;i<n;++i)
{
/* shift by 2 now to reduce rounding error,
* we can renormalize right before pow_m1_4
*/
p = 0x8000<<5;
q = 0x8000<<5;
w = s->lsp_cos_table[i];
for (j=1;j<NB_LSP_COEFS;j+=2)
{
/* w is 5.27 format, lsp is in 16.16, temp2 becomes 5.27 format */
temp2 = ((w - (lsp[j - 1]<<11)));
temp = q;
/* q is 16.16 format, temp2 is 5.27, q becomes 16.16 */
q = fixmul32b(q, temp2 )<<4;
p = fixmul32b(p, (w - (lsp[j]<<11)))<<4;
}
/* 2 in 5.27 format is 0x10000000 */
p = fixmul32(p, fixmul32b(p, (0x10000000 - w)))<<3;
q = fixmul32(q, fixmul32b(q, (0x10000000 + w)))<<3;
v = (p + q) >>9; /* p/q end up as 16.16 */
v = pow_m1_4(s, v);
if (v > val_max)
val_max = v;
out[i] = v;
}
*val_max_ptr = val_max;
}
/* decode exponents coded with LSP coefficients (same idea as Vorbis) */
static void decode_exp_lsp(WMADecodeContext *s, int ch)
{
fixed32 lsp_coefs[NB_LSP_COEFS];
int val, i;
for (i = 0; i < NB_LSP_COEFS; ++i)
{
if (i == 0 || i >= 8)
val = get_bits(&s->gb, 3);
else
val = get_bits(&s->gb, 4);
lsp_coefs[i] = lsp_codebook[i][val];
}
wma_lsp_to_curve(s,
s->exponents[ch],
&s->max_exponent[ch],
s->block_len,
lsp_coefs);
}
/* decode exponents coded with VLC codes */
static int decode_exp_vlc(WMADecodeContext *s, int ch)
{
int last_exp, n, code;
const uint16_t *ptr, *band_ptr;
fixed32 v, max_scale;
fixed32 *q,*q_end;
/*accommodate the 60 negative indices */
const fixed32 *pow_10_to_yover16_ptr = &pow_10_to_yover16[61];
band_ptr = s->exponent_bands[s->frame_len_bits - s->block_len_bits];
ptr = band_ptr;
q = s->exponents[ch];
q_end = q + s->block_len;
max_scale = 0;
if (s->version == 1) //wmav1 only
{
last_exp = get_bits(&s->gb, 5) + 10;
/* XXX: use a table */
v = pow_10_to_yover16_ptr[last_exp];
max_scale = v;
n = *ptr++;
do
{
*q++ = v;
}
while (--n);
} else {
last_exp = 36;
}
while (q < q_end)
{
code = get_vlc2(&s->gb, s->exp_vlc.table, EXPVLCBITS, EXPMAX);
if (code < 0)
{
return -1;
}
/* NOTE: this offset is the same as MPEG4 AAC ! */
last_exp += code - 60;
/* XXX: use a table */
v = pow_10_to_yover16_ptr[last_exp];
if (v > max_scale)
{
max_scale = v;
}
n = *ptr++;
do
{
*q++ = v;
}
while (--n);
}
s->max_exponent[ch] = max_scale;
return 0;
}
/* return 0 if OK. return 1 if last block of frame. return -1 if
unrecorrable error. */
static int wma_decode_block(WMADecodeContext *s, int32_t *scratch_buffer)
{
int n, v, a, ch, code, bsize;
int coef_nb_bits, total_gain;
int nb_coefs[MAX_CHANNELS];
fixed32 mdct_norm;
/* compute current block length */
if (s->use_variable_block_len)
{
n = av_log2(s->nb_block_sizes - 1) + 1;
if (s->reset_block_lengths)
{
s->reset_block_lengths = 0;
v = get_bits(&s->gb, n);
if (v >= s->nb_block_sizes)
{
return -2;
}
s->prev_block_len_bits = s->frame_len_bits - v;
v = get_bits(&s->gb, n);
if (v >= s->nb_block_sizes)
{
return -3;
}
s->block_len_bits = s->frame_len_bits - v;
}
else
{
/* update block lengths */
s->prev_block_len_bits = s->block_len_bits;
s->block_len_bits = s->next_block_len_bits;
}
v = get_bits(&s->gb, n);
if (v >= s->nb_block_sizes)
{
// rb->splash(HZ*4, "v was %d", v); //5, 7
return -4; //this is it
}
else{
//rb->splash(HZ, "passed v block (%d)!", v);
}
s->next_block_len_bits = s->frame_len_bits - v;
}
else
{
/* fixed block len */
s->next_block_len_bits = s->frame_len_bits;
s->prev_block_len_bits = s->frame_len_bits;
s->block_len_bits = s->frame_len_bits;
}
/* now check if the block length is coherent with the frame length */
s->block_len = 1 << s->block_len_bits;
if ((s->block_pos + s->block_len) > s->frame_len)
{
return -5; //oddly 32k sample from tracker fails here
}
if (s->nb_channels == 2)
{
s->ms_stereo = get_bits1(&s->gb);
}
v = 0;
for (ch = 0; ch < s->nb_channels; ++ch)
{
a = get_bits1(&s->gb);
s->channel_coded[ch] = a;
v |= a;
}
/* if no channel coded, no need to go further */
/* XXX: fix potential framing problems */
if (!v)
{
goto next;
}
bsize = s->frame_len_bits - s->block_len_bits;
/* read total gain and extract corresponding number of bits for
coef escape coding */
total_gain = 1;
for(;;)
{
a = get_bits(&s->gb, 7);
total_gain += a;
if (a != 127)
{
break;
}
}
if (total_gain < 15)
coef_nb_bits = 13;
else if (total_gain < 32)
coef_nb_bits = 12;
else if (total_gain < 40)
coef_nb_bits = 11;
else if (total_gain < 45)
coef_nb_bits = 10;
else
coef_nb_bits = 9;
/* compute number of coefficients */
n = s->coefs_end[bsize] - s->coefs_start;
for(ch = 0; ch < s->nb_channels; ++ch)
{
nb_coefs[ch] = n;
}
/* complex coding */
if (s->use_noise_coding)
{
for(ch = 0; ch < s->nb_channels; ++ch)
{
if (s->channel_coded[ch])
{
int i, n, a;
n = s->exponent_high_sizes[bsize];
for(i=0;i<n;++i)
{
a = get_bits1(&s->gb);
s->high_band_coded[ch][i] = a;
/* if noise coding, the coefficients are not transmitted */
if (a)
nb_coefs[ch] -= s->exponent_high_bands[bsize][i];
}
}
}
for(ch = 0; ch < s->nb_channels; ++ch)
{
if (s->channel_coded[ch])
{
int i, n, val, code;
n = s->exponent_high_sizes[bsize];
val = (int)0x80000000;
for(i=0;i<n;++i)
{
if (s->high_band_coded[ch][i])
{
if (val == (int)0x80000000)
{
val = get_bits(&s->gb, 7) - 19;
}
else
{
//code = get_vlc(&s->gb, &s->hgain_vlc);
code = get_vlc2(&s->gb, s->hgain_vlc.table, HGAINVLCBITS, HGAINMAX);
if (code < 0)
{
return -6;
}
val += code - 18;
}
s->high_band_values[ch][i] = val;
}
}
}
}
}
/* exponents can be reused in short blocks. */
if ((s->block_len_bits == s->frame_len_bits) || get_bits1(&s->gb))
{
for(ch = 0; ch < s->nb_channels; ++ch)
{
if (s->channel_coded[ch])
{
if (s->use_exp_vlc)
{
if (decode_exp_vlc(s, ch) < 0)
{
return -7;
}
}
else
{
decode_exp_lsp(s, ch);
}
s->exponents_bsize[ch] = bsize;
}
}
}
/* parse spectral coefficients : just RLE encoding */
for(ch = 0; ch < s->nb_channels; ++ch)
{
if (s->channel_coded[ch])
{
VLC *coef_vlc;
int level, run, sign, tindex;
int16_t *ptr, *eptr;
const int16_t *level_table, *run_table;
/* special VLC tables are used for ms stereo because
there is potentially less energy there */
tindex = (ch == 1 && s->ms_stereo);
coef_vlc = &s->coef_vlc[tindex];
run_table = (int16_t*)s->run_table[tindex];
level_table = (int16_t*)s->level_table[tindex];
/* XXX: optimize */
ptr = &s->coefs1[ch][0];
eptr = ptr + nb_coefs[ch];
memset(ptr, 0, s->block_len * sizeof(int16_t));
for(;;)
{
code = get_vlc2(&s->gb, coef_vlc->table, VLCBITS, VLCMAX);
//code = get_vlc(&s->gb, coef_vlc);
if (code < 0)
{
return -8;
}
if (code == 1)
{
/* EOB */
break;
}
else if (code == 0)
{
/* escape */
level = get_bits(&s->gb, coef_nb_bits);
/* NOTE: this is rather suboptimal. reading
block_len_bits would be better */
run = get_bits(&s->gb, s->frame_len_bits);
}
else
{
/* normal code */
run = run_table[code];
level = level_table[code];
}
sign = get_bits1(&s->gb);
if (!sign)
level = -level;
ptr += run;
if (ptr >= eptr)
{
break;
}
*ptr++ = level;
/* NOTE: EOB can be omitted */
if (ptr >= eptr)
break;
}
}
if (s->version == 1 && s->nb_channels >= 2)
{
align_get_bits(&s->gb);
}
}
{
int n4 = s->block_len >> 1;
mdct_norm = 0x10000>>(s->block_len_bits-1);
if (s->version == 1)
{
mdct_norm *= fixtoi32(fixsqrt32(itofix32(n4)));
}
}
/* finally compute the MDCT coefficients */
for(ch = 0; ch < s->nb_channels; ++ch)
{
if (s->channel_coded[ch])
{
int16_t *coefs1;
fixed32 *exponents;
fixed32 *coefs, atemp;
fixed64 mult;
fixed64 mult1;
fixed32 noise, temp1, temp2, mult2;
int i, j, n, n1, last_high_band, esize;
fixed32 exp_power[HIGH_BAND_MAX_SIZE];
//total_gain, coefs1, mdctnorm are lossless
coefs1 = s->coefs1[ch];
exponents = s->exponents[ch];
esize = s->exponents_bsize[ch];
coefs = (*(s->coefs))[ch];
n=0;
/*
* The calculation of coefs has a shift right by 2 built in. This
* prepares samples for the Tremor IMDCT which uses a slightly
* different fixed format then the ffmpeg one. If the old ffmpeg
* imdct is used, each shift storing into coefs should be reduced
* by 1.
* See SVN logs for details.
*/
if (s->use_noise_coding)
{
/*TODO: mult should be converted to 32 bit to speed up noise coding*/
mult = fixdiv64(pow_table[total_gain+20],Fixed32To64(s->max_exponent[ch]));
mult = mult* mdct_norm;
mult1 = mult;
/* very low freqs : noise */
for(i = 0;i < s->coefs_start; ++i)
{
*coefs++ = fixmul32( (fixmul32(s->noise_table[s->noise_index],
exponents[i<<bsize>>esize])>>4),Fixed32From64(mult1)) >>2;
s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
}
n1 = s->exponent_high_sizes[bsize];
/* compute power of high bands */
exponents = s->exponents[ch] +(s->high_band_start[bsize]<<bsize);
last_high_band = 0; /* avoid warning */
for (j=0;j<n1;++j)
{
n = s->exponent_high_bands[s->frame_len_bits -
s->block_len_bits][j];
if (s->high_band_coded[ch][j])
{
fixed32 e2, v;
e2 = 0;
for(i = 0;i < n; ++i)
{
/*v is normalized later on so its fixed format is irrelevant*/
v = exponents[i<<bsize>>esize]>>4;
e2 += fixmul32(v, v)>>3;
}
exp_power[j] = e2/n; /*n is an int...*/
last_high_band = j;
}
exponents += n<<bsize;
}
/* main freqs and high freqs */
exponents = s->exponents[ch] + (s->coefs_start<<bsize);
for(j=-1;j<n1;++j)
{
if (j < 0)
{
n = s->high_band_start[bsize] -
s->coefs_start;
}
else
{
n = s->exponent_high_bands[s->frame_len_bits -
s->block_len_bits][j];
}
if (j >= 0 && s->high_band_coded[ch][j])
{
/* use noise with specified power */
fixed32 tmp = fixdiv32(exp_power[j],exp_power[last_high_band]);
/*mult1 is 48.16, pow_table is 48.16*/
mult1 = fixmul32(fixsqrt32(tmp),
pow_table[s->high_band_values[ch][j]+20]) >> 16;
/*this step has a fairly high degree of error for some reason*/
mult1 = fixdiv64(mult1,fixmul32(s->max_exponent[ch],s->noise_mult));
mult1 = mult1*mdct_norm>>PRECISION;
for(i = 0;i < n; ++i)
{
noise = s->noise_table[s->noise_index];
s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
*coefs++ = fixmul32((fixmul32(exponents[i<<bsize>>esize],noise)>>4),
Fixed32From64(mult1)) >>2;
}
exponents += n<<bsize;
}
else
{
/* coded values + small noise */
for(i = 0;i < n; ++i)
{
noise = s->noise_table[s->noise_index];
s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
/*don't forget to renormalize the noise*/
temp1 = (((int32_t)*coefs1++)<<16) + (noise>>4);
temp2 = fixmul32(exponents[i<<bsize>>esize], mult>>18);
*coefs++ = fixmul32(temp1, temp2);
}
exponents += n<<bsize;
}
}
/* very high freqs : noise */
n = s->block_len - s->coefs_end[bsize];
mult2 = fixmul32(mult>>16,exponents[((-1<<bsize))>>esize]) ;
for (i = 0; i < n; ++i)
{
/*renormalize the noise product and then reduce to 14.18 precison*/
*coefs++ = fixmul32(s->noise_table[s->noise_index],mult2) >>6;
s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
}
}
else
{
/*Noise coding not used, simply convert from exp to fixed representation*/
fixed32 mult3 = (fixed32)(fixdiv64(pow_table[total_gain+20],
Fixed32To64(s->max_exponent[ch])));
mult3 = fixmul32(mult3, mdct_norm);
/*zero the first 3 coefficients for WMA V1, does nothing otherwise*/
for(i=0; i<s->coefs_start; i++)
*coefs++=0;
n = nb_coefs[ch];
/* XXX: optimize more, unrolling this loop in asm
might be a good idea */
for(i = 0;i < n; ++i)
{
/*ffmpeg imdct needs 15.17, while tremor 14.18*/
atemp = (coefs1[i] * mult3)>>2;
*coefs++=fixmul32(atemp,exponents[i<<bsize>>esize]);
}
n = s->block_len - s->coefs_end[bsize];
memset(coefs, 0, n*sizeof(fixed32));
}
}
}
if (s->ms_stereo && s->channel_coded[1])
{
fixed32 a, b;
int i;
fixed32 (*coefs)[MAX_CHANNELS][BLOCK_MAX_SIZE] = (s->coefs);
/* nominal case for ms stereo: we do it before mdct */
/* no need to optimize this case because it should almost
never happen */
if (!s->channel_coded[0])
{
memset((*(s->coefs))[0], 0, sizeof(fixed32) * s->block_len);
s->channel_coded[0] = 1;
}
for(i = 0; i < s->block_len; ++i)
{
a = (*coefs)[0][i];
b = (*coefs)[1][i];
(*coefs)[0][i] = a + b;
(*coefs)[1][i] = a - b;
}
}
for(ch = 0; ch < s->nb_channels; ++ch)
{
if (s->channel_coded[ch])
{
int n4, index, n;
n = s->block_len;
n4 = s->block_len >>1;
/*faster IMDCT from Vorbis*/
mdct_backward( (1 << (s->block_len_bits+1)), (int32_t*)(*(s->coefs))[ch], (int32_t*)scratch_buffer);
/*slower but more easily understood IMDCT from FFMPEG*/
//ff_imdct_calc(&s->mdct_ctx[bsize],
// output,
// (*(s->coefs))[ch]);
/* add in the frame */
index = (s->frame_len / 2) + s->block_pos - n4;
wma_window(s, scratch_buffer, &((*s->frame_out)[ch][index]));
/* specific fast case for ms-stereo : add to second
channel if it is not coded */
if (s->ms_stereo && !s->channel_coded[1])
{
wma_window(s, scratch_buffer, &((*s->frame_out)[1][index]));
}
}
}
next:
/* update block number */
++s->block_num;
s->block_pos += s->block_len;
DEBUGF("***decode_block: %d end. (%d samples of %d in frame. endpos=%d)\n", s->block_num, s->block_len, s->frame_len,s->block_pos);
if (s->block_pos > s->frame_len){
DEBUGF("PCM buffer overflow.\n");
return 1;
}
if (s->block_pos == s->frame_len) return 1;
return 0;
}
/* decode a frame of frame_len samples */
static int wma_decode_frame(WMADecodeContext *s, int32_t *samples)
{
int ret, i, n, ch, incr;
int32_t *ptr;
fixed32 *iptr;
/* read each block */
s->block_num = 0;
s->block_pos = 0;
for(;;)
{
ret = wma_decode_block(s, samples);
if (ret < 0)
{
DEBUGF("wma_decode_block failed with code %d\n", ret);
return -1;
}
if (ret)
{
break;
}
}
/* return frame with full 30-bit precision */
n = s->frame_len;
incr = s->nb_channels;
for(ch = 0; ch < s->nb_channels; ++ch)
{
ptr = samples + ch;
iptr = &((*s->frame_out)[ch][0]);
for (i=0;i<n;++i)
{
int s=*iptr++;
s>>=16-2; // 30bit->16bit;
if(s<-0x8000) s=-0x8000;
if(0x7fff<s) s=0x7fff;
*ptr = s;
ptr += incr;
}
int32_t *pdst=&(*s->frame_out)[ch][0];
int32_t *psrc=&pdst[s->frame_len];
for(u32 idx=0;idx<s->frame_len;idx++){
*pdst++=*psrc++;
}
// memmove(&((*s->frame_out)[ch][0]), &((*s->frame_out)[ch][s->frame_len]), * sizeof(fixed32));
}
return 0;
}
/* Initialise the superframe decoding */
int wma_decode_superframe_init(WMADecodeContext* s,
const uint8_t *buf, /*input*/
int buf_size)
{
if (buf_size==0)
{
s->last_superframe_len = 0;
return 0;
}
s->current_frame = 0;
init_get_bits(&s->gb, buf, buf_size*8);
if (s->use_bit_reservoir)
{
/* read super frame header */
skip_bits(&s->gb, 4); /* super frame index */
s->nb_frames = get_bits(&s->gb, 4);
DEBUGF("nb_frames=%d, last_superframe_len=%d.\n",s->nb_frames,s->last_superframe_len);
if (s->last_superframe_len == 0)
s->nb_frames --;
else if (s->nb_frames == 0)
s->nb_frames++;
s->bit_offset = get_bits(&s->gb, s->byte_offset_bits + 3);
} else {
s->nb_frames = 1;
}
return 1;
}
/* Decode a single frame in the current superframe - return -1 if
there was a decoding error, or the number of samples decoded.
*/
int wma_decode_superframe_frame(WMADecodeContext* s,
int32_t* samples, /*output*/
const uint8_t *buf, /*input*/
int buf_size)
{
int pos, len;
uint8_t *q;
int done = 0;
if ((s->use_bit_reservoir) && (s->current_frame == 0))
{
if (s->last_superframe_len > 0)
{
/* add s->bit_offset bits to last frame */
if ((s->last_superframe_len + ((s->bit_offset + 7) >> 3)) >
MAX_CODED_SUPERFRAME_SIZE)
{
DEBUGF("superframe size too large error\n");
goto fail;
}
q = s->last_superframe + s->last_superframe_len;
len = s->bit_offset;
while (len > 7)
{
*q++ = (get_bits)(&s->gb, 8);
len -= 8;
}
if (len > 0)
{
*q++ = (get_bits)(&s->gb, len) << (8 - len);
}
/* XXX: s->bit_offset bits into last frame */
init_get_bits(&s->gb, s->last_superframe, MAX_CODED_SUPERFRAME_SIZE*8);
/* skip unused bits */
if (s->last_bitoffset > 0)
skip_bits(&s->gb, s->last_bitoffset);
/* this frame is stored in the last superframe and in the
current one */
if (wma_decode_frame(s, samples) < 0)
{
goto fail;
}
done = 1;
}
/* read each frame starting from s->bit_offset */
pos = s->bit_offset + 4 + 4 + s->byte_offset_bits + 3;
init_get_bits(&s->gb, buf + (pos >> 3), (MAX_CODED_SUPERFRAME_SIZE - (pos >> 3))*8);
len = pos & 7;
if (len > 0)
skip_bits(&s->gb, len);
s->reset_block_lengths = 1;
}
/* If we haven't decoded a frame yet, do it now */
if (!done)
{
if (wma_decode_frame(s, samples) < 0)
{
goto fail;
}
}
s->current_frame++;
if ((s->use_bit_reservoir) && (s->current_frame == s->nb_frames))
{
/* we copy the end of the frame in the last frame buffer */
pos = get_bits_count(&s->gb) + ((s->bit_offset + 4 + 4 + s->byte_offset_bits + 3) & ~7);
s->last_bitoffset = pos & 7;
pos >>= 3;
len = buf_size - pos;
if (len > MAX_CODED_SUPERFRAME_SIZE || len < 0)
{
DEBUGF("superframe size too large error after decoding\n");
goto fail;
}
s->last_superframe_len = len;
memcpy(s->last_superframe, buf + pos, len);
}
return s->frame_len;
fail:
/* when error, we reset the bit reservoir */
s->last_superframe_len = 0;
return -1;
}
| [
"feng.flash@4bd7f34a-4c62-84e7-1fb2-5fbc975ebfb2"
] | [
[
[
1,
1640
]
]
] |
1746997e564942422bd51e4dcbcd58ee4ba4a231 | 65dee2b7ed8a91f952831525d78bfced5abd713f | /winmob/XfMobile_WM6/Gamepe/Global.cpp | 9894e4d2428ee9ce650d1ea43f6656721ad6f664 | [] | no_license | felixnicitin1968/XFMobile | 0249f90f111f0920a423228691bcbef0ecb0ce23 | 4a442d0127366afa9f80bdcdaaa4569569604dac | refs/heads/master | 2016-09-06T05:02:18.589338 | 2011-07-05T17:25:39 | 2011-07-05T17:25:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 95,892 | cpp | #include "stdafx.h"
#include <windows.h>
#include "Global.h"
#include "resourceppc.h"
#include "ChatViewDlg.h"
// {0E1432D8-2E4D-4d0f-8C2D-C972A8933A63}
#define INITGUID
#include <initguid.h>
#include <imaging.h>
#include "Json/json.h"
int AD_HEIGHT=55;
wchar_t* wcschr(const wchar_t* str, wchar_t ch)
{
while ((*str)!=0)
{
if ((*str)==ch)
{
return((wchar_t *)str);
}
str++;
}
return(NULL);
}
static const GUID CLSID_Application =
{ 0xe1432d8, 0x2e4d, 0x4d0f, { 0x8c, 0x2d, 0xc9, 0x72, 0xa8, 0x93, 0x3a, 0x63 } };
IImagingFactory* g_pImageFactory;
WCHAR g_wzDeviceUDID[0x100];
WCHAR g_wzUserAgent[0x400];
WCHAR g_szPathToAdImage[0x1000];
WCHAR g_szLinkToAdImage[0x1000];
WCHAR g_szLinkToAd[0x1000];
WCHAR g_szTextAd[0x1000];
char g_ad_result[0x1000];
HWND g_hAdHWND;
BOOL g_isDisconnected=TRUE;
BOOL SendURLRequest(LPWSTR pServer,LPWSTR pObject)
{
DbgMsg(pObject);
UINT uRetVal;
DWORD dwBufSize=MAX_PATH;
BOOL fOK=FALSE;
HINTERNET hSession ,hConnection,hRequest;
while(1)
{
hSession = InternetOpen(L"XfMobileADRequest",
INTERNET_OPEN_TYPE_DIRECT,
NULL,
NULL,
0);
if (!hSession) break;
hConnection = InternetConnect(hSession,
pServer, // Server
INTERNET_DEFAULT_HTTP_PORT,
NULL, // Username
NULL, // Password
INTERNET_SERVICE_HTTP,
0, // Synchronous
NULL); // No Context
if (!hConnection) break;;
hRequest = HttpOpenRequest(hConnection,
L"GET",
pObject,
NULL, // Default HTTP Version
NULL, // No Referer
0, // Accept
// anything
0, // Flags
NULL); // No Context
if (!hRequest) break;
WCHAR szUserAgent[400];
wcscpy(szUserAgent,L"User-Agent: ");
wcscat(szUserAgent,g_wzUserAgent);
wcscat(szUserAgent,L"\r\n");
if (!HttpAddRequestHeaders(hRequest,
szUserAgent,
(DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) ) {
return false;
}
HttpSendRequest(hRequest,
NULL, // No extra headers
0, // Header length
NULL, // No Body
0); // Body length
break;
}
InternetCloseHandle (hSession);
InternetCloseHandle (hConnection);
InternetCloseHandle(hRequest);
return 0;//fOK;
}
UINT __cdecl GetNewADThread( LPVOID pParam )
{
WCHAR adRequest[0x400];
wsprintf(adRequest,L"/custom.php?appid=6a1398aa684c41649104e62ed784a5d9");//&uuid=%ws&country_code=en_US&appver=200&client=5",g_wzDeviceUDID);
wcscat(adRequest,L"&uuid=");
wcscat(adRequest,g_wzDeviceUDID);
wcscat(adRequest,L"&country_code=");
wcscat(adRequest,L"en_US");
wcscat(adRequest,L"&appver=");
wcscat(adRequest,L"200");
wcscat(adRequest,L"&client=");
wcscat(adRequest,L"5");
DownloadXMLFromADGateway(L"cus.adwhirl.com",adRequest);
if (g_szLinkToAdImage[0]==0) return -1;
DownloadImage(GetForegroundWindow(),g_szLinkToAdImage);
::ShowWindow(g_hAdHWND,SW_HIDE);
::ShowWindow(g_hAdHWND,SW_SHOW);
return 0;
}
UINT __cdecl MetricClickNotificationThread( LPVOID pParam )
{
/*
A metrics request should be sent after each impression and click.
Endpoint:
Impressions: http://met.adwhirl.com/exmet.php
Clicks: http://met.adwhirl.com/exclick.php
Client->Server: appid, nid, type, uuid, country_code, appver, client
Server->Client: HTTP Status 200 (no content)
*/
WCHAR adRequest[0x400];
wsprintf(adRequest,L"/exclick.php?appid=6a1398aa684c41649104e62ed784a5d9&type=9&nid=b390f1f6a43945d8852c72f1a8fa0352");
wcscat(adRequest,L"&uuid=");
wcscat(adRequest,g_wzDeviceUDID);
wcscat(adRequest,L"&country_code=");
wcscat(adRequest,L"en_US");
wcscat(adRequest,L"&appver=");
wcscat(adRequest,L"200");
wcscat(adRequest,L"&client=");
wcscat(adRequest,L"5");
SendURLRequest(L"met.adwhirl.com",adRequest);
return 0;
}
UINT __cdecl MetricImpressionsNotificationThread( LPVOID pParam )
{
/*
A metrics request should be sent after each impression and click.
Endpoint:
Impressions: http://met.adwhirl.com/exmet.php
Clicks: http://met.adwhirl.com/exclick.php
Client->Server: appid, nid, type, uuid, country_code, appver, client
Server->Client: HTTP Status 200 (no content)
*/
WCHAR adRequest[0x400];
wsprintf(adRequest,L"/exmet.php?appid=6a1398aa684c41649104e62ed784a5d9&type=9&nid=b390f1f6a43945d8852c72f1a8fa0352");
wcscat(adRequest,L"&uuid=");
wcscat(adRequest,g_wzDeviceUDID);
wcscat(adRequest,L"&country_code=");
wcscat(adRequest,L"en_US");
wcscat(adRequest,L"&appver=");
wcscat(adRequest,L"200");
wcscat(adRequest,L"&client=");
wcscat(adRequest,L"5");
SendURLRequest(L"met.adwhirl.com",adRequest);
return 0;
}
VOID CALLBACK GetNewADTimerProc(
__in HWND hwnd,
__in UINT uMsg,
__in UINT_PTR idEvent,
__in DWORD dwTime
)
{
if (g_isDisconnected) return;
WCHAR adRequest[0x400];
//wsprintf(adRequest,L"/custom.php?appid=6a1398aa684c41649104e62ed784a5d9&uuid=00000000000000000000000000000000&country_code=en_US&appver=200&client=5");
wsprintf(adRequest,L"/custom.php?appid=6a1398aa684c41649104e62ed784a5d9");//&uuid=%ws&country_code=en_US&appver=200&client=5",g_wzDeviceUDID);
wcscat(adRequest,L"&uuid=");
wcscat(adRequest,g_wzDeviceUDID);
wcscat(adRequest,L"&country_code=");
wcscat(adRequest,L"en_US");
wcscat(adRequest,L"&appver=");
wcscat(adRequest,L"200");
wcscat(adRequest,L"&client=");
wcscat(adRequest,L"5");
DownloadXMLFromADGateway(L"cus.adwhirl.com",adRequest);
if (g_szLinkToAdImage[0]==0) return;
DownloadImage(GetForegroundWindow(),g_szLinkToAdImage);
::ShowWindow(g_hAdHWND,SW_HIDE);
::ShowWindow(g_hAdHWND,SW_SHOW);
}
void DisplayImage(HWND hWnd,HDC hdc)
{
if (!g_pImageFactory) return;
ImageInfo imageInfo={0};
IImage *pImage = NULL;
HBITMAP hBitmap=NULL;
IBitmapImage* pBitmapImage = 0;
BitmapData bitmapData = {0};
if (SUCCEEDED(g_pImageFactory->CreateImageFromFile(g_szPathToAdImage, &pImage))
&& SUCCEEDED(pImage->GetImageInfo(&imageInfo)))
{
if (SUCCEEDED(g_pImageFactory->CreateBitmapFromImage(pImage,
0,0, imageInfo.PixelFormat, InterpolationHintDefault, &pBitmapImage)))
{
UINT imageWidth, imageHeight;
imageWidth=imageInfo.Width;
imageHeight=imageInfo.Height;
RECT rc;
GetWindowRect(hWnd,&rc);
UINT Width, Height;
Width=rc.right-rc.left;
Height=rc.bottom-rc.top;
if (1){//imageWidth>Width || imageHeight>Height) {
BitmapData bitmapData = {0};
RECT rect = {0, 0, imageInfo.Width, imageInfo.Height};
bitmapData.Width = imageInfo.Width;
bitmapData.Height = imageInfo.Height;
bitmapData.PixelFormat = imageInfo.PixelFormat;
pBitmapImage->LockBits(&rect, ImageLockModeRead, PixelFormat16bppRGB565, &bitmapData);
hBitmap = CreateBitmap(bitmapData.Width, bitmapData.Height, 1,
GetPixelFormatSize(bitmapData.PixelFormat), bitmapData.Scan0);
HDC bmpDC = CreateCompatibleDC(hdc);
HGDIOBJ hOldBitmap = SelectObject(bmpDC, hBitmap);
StretchBlt(hdc,0,0,Width,Height,
bmpDC,0,0,imageInfo.Width, imageInfo.Height, SRCCOPY);
SelectObject(bmpDC, hOldBitmap);
pBitmapImage->UnlockBits(&bitmapData);
}else{
RECT rect = {(Width-imageWidth)/2, (Height-imageHeight)/2, imageInfo.Width, imageInfo.Height};
SetBkColor(hdc,RGB(0,0,0));
HBRUSH black_brush = (HBRUSH)GetStockObject (BLACK_BRUSH);
SelectObject (hdc, black_brush);
Rectangle(hdc, 0,0,
rc.right, rc.bottom);
BitmapData bitmapData = {0};
bitmapData.Width = imageInfo.Width;
bitmapData.Height = imageInfo.Height;
bitmapData.PixelFormat = imageInfo.PixelFormat;
pBitmapImage->LockBits(&rect, ImageLockModeRead, PixelFormat16bppRGB565, &bitmapData);
hBitmap = CreateBitmap(bitmapData.Width, bitmapData.Height, 1,
GetPixelFormatSize(bitmapData.PixelFormat), bitmapData.Scan0);
HDC bmpDC = CreateCompatibleDC(hdc);
HGDIOBJ hOldBitmap = SelectObject(bmpDC, hBitmap);
//itBlt(hdc,(Width-imageWidth)/2, (Height-imageHeight)/2,Width,Height,
// bmpDC,0,0, SRCCOPY);
BitBlt(hdc,0, 0,imageInfo.Width,imageInfo.Height,
bmpDC,0,0, SRCCOPY);
SelectObject(bmpDC, hOldBitmap);
pBitmapImage->UnlockBits(&bitmapData);
//pImage->Draw(hdc, &rect, 0);
}
if (pImage)
pImage->Release();
if (pBitmapImage)
pBitmapImage->Release();
}
}
}
BOOL DownloadImage(HWND hWnd,WCHAR *szURL)
{
UINT uRetVal;
DWORD dwBufSize=MAX_PATH;
WCHAR lpPathBuffer[MAX_PATH]=L"\\Application Data\\XFMOBILE\\xfmobilead";
WCHAR *tExtension=wcsrchr(szURL,L'.');
if (!tExtension) return FALSE;
wcscat(lpPathBuffer,tExtension);
DbgMsg(lpPathBuffer);
DeleteUrlCacheEntry(szURL);
DeleteFile(lpPathBuffer);
HRESULT sOK=URLDownloadToFile(NULL,szURL,lpPathBuffer,0,NULL);
if (sOK==S_OK){
wcscpy (g_szPathToAdImage,lpPathBuffer);
return TRUE;
}
memset(g_szPathToAdImage,0,sizeof(g_szPathToAdImage));
return FALSE;
}
void GetIMEI()
{
TCHAR szDeviceID[GETDEVICEUNIQUEID_V1_OUTPUT];
DWORD dwSize = GETDEVICEUNIQUEID_V1_OUTPUT;
HRESULT hr = GetDeviceUniqueID((LPBYTE)&CLSID_Application,sizeof(GUID),1,(LPBYTE)szDeviceID,&dwSize);
CString strTemp;
CString strID(TEXT("GetDeviceUniqueID failed!!!"));
if(SUCCEEDED(hr))
{
strID.Empty();
for(DWORD dwIndex=0; dwIndex<dwSize; ++dwIndex)
{
strTemp.Format(TEXT("%d"),szDeviceID[dwIndex]);
strID += strTemp;
}
wcscpy(g_wzDeviceUDID,strID);
OutputDebugString(g_wzDeviceUDID);
}
}
//http://soma.smaato.net/oapi/reqAd.jsp?adspace=0&pub=0&beacon=true&device=winmo&format=IMG&position=top&adcount=1&response=HTML&height=30&width=240");
//=
void getDeviceType()
{
DbgMsg(L"\ngetDeviceTypen");
CString deviceType("");
TCHAR tszOemInfo[128] = {0};
SystemParametersInfo(SPI_GETOEMINFO, sizeof(tszOemInfo)/sizeof(*tszOemInfo),tszOemInfo,0);
DbgMsg(tszOemInfo);
}
BOOL GetUserAgent(void)
{
WCHAR wUserAgent[0x200]={0};
HKEY hKey=NULL;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
L"\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\5.0\\User Agent",0,
KEY_READ ,&hKey)!=ERROR_SUCCESS){
return FALSE;
}
WCHAR wDefault[0x100];
DWORD dwSize=sizeof(wDefault);
if (RegQueryValueEx(hKey,0,NULL,
NULL,(LPBYTE )wDefault,&dwSize)!=ERROR_SUCCESS){
return FALSE;
}
WCHAR wVersion[0x100];
dwSize=sizeof(wVersion);
if (RegQueryValueEx(hKey,L"Version",NULL,
NULL,(LPBYTE )wVersion,&dwSize)!=ERROR_SUCCESS){
return FALSE;
}
WCHAR wPlatform[0x100];
dwSize=sizeof(wPlatform);
if (RegQueryValueEx(hKey,L"Platform",NULL,
NULL,(LPBYTE )wPlatform,&dwSize)!=ERROR_SUCCESS){
return FALSE;
}
// Get the device name from the registry
HKEY Regkey;
wchar_t Value[255]={0};
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"\\Ident", 0, 0, &Regkey) == ERROR_SUCCESS)
{
DWORD dwSize = 255;
if (RegQueryValueEx(Regkey,L"Name",NULL,NULL,(LPBYTE)&Value,&dwSize) == ERROR_SUCCESS &&
wcslen(Value) > 0)
{
wcscat(g_wzUserAgent,Value);
wcscat(g_wzUserAgent,L" ");
}
RegCloseKey(Regkey);
}
wcscat(g_wzUserAgent,wDefault);
wcscat(g_wzUserAgent,L"(compatible; ");
wcscat(g_wzUserAgent,wVersion);
wcscat(g_wzUserAgent,L"; ");
wcscat(g_wzUserAgent,wPlatform);
wcscat(g_wzUserAgent,L")");
DbgMsg(L"\n--------------------------\n");
DbgMsg(g_wzUserAgent);
DbgMsg(L"\n--------------------------\n");
RegCloseKey(hKey);
return TRUE;
}
BOOL GetXFMobileVersion(WCHAR* lpvBuffer,DWORD lpdwBufferLength)
{
//InternetQueryDataAvailable
BOOL fOK=FALSE;
WCHAR lpvSomeBuffer[0x100];
DWORD dwSize=sizeof(lpvSomeBuffer);
HINTERNET hSession;
hSession=InternetOpen(L"XFMobile",INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hSession) return fOK;
HINTERNET hConnect=NULL;
hConnect=InternetConnect(hSession, L"www.xf-mobile.com",
INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
if (!hConnect){
DbgMsg(L"GetXFMobileVersion InternetConnect Failed");
return fOK;
}
HINTERNET hRequest=NULL;
DbgMsg(L"Sending VERSION request ....\n");
hRequest=HttpOpenRequest(hConnect, NULL,LINK2CHECK_VERSION, NULL, NULL, 0, 0, 0);
HttpSendRequest(hRequest,0, 0, 0, 0);
ZeroMemory(lpvSomeBuffer,sizeof(lpvSomeBuffer));
if (HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE ,
lpvSomeBuffer, &dwSize, NULL)){
DbgMsg(L"HttpQueryInfo result ....\n");
if (wcsncmp(lpvSomeBuffer,L"200",3)==0) {
DbgMsg(L"200 OK\n");
wcscpy(lpvSomeBuffer,L"GVersion");
dwSize=lpdwBufferLength;
if (HttpQueryInfo(hRequest, HTTP_QUERY_CUSTOM ,lpvSomeBuffer, &dwSize, NULL)) {
if (lpdwBufferLength> dwSize ){
wcscpy(lpvBuffer,lpvSomeBuffer);
fOK=TRUE;
}
}
}
}
InternetCloseHandle(hRequest);
InternetCloseHandle(hConnect);
InternetCloseHandle(hSession);
return fOK;
}
BOOL DownloadXMLFromADGateway(LPWSTR pServer,LPWSTR pObject)
{
DbgMsg(L"Enter DownloadXMLFromADGateway\n");
DbgMsg(pObject);
DWORD dwBytesWritten;
UINT uRetVal;
DWORD dwBufSize=MAX_PATH;
BOOL fOK=FALSE;
HINTERNET hSession ,hConnection,hRequest;
ZeroMemory(g_ad_result,sizeof(g_ad_result));
WCHAR lpPathBuffer[MAX_PATH]=L"\\Application Data\\XFMOBILE\\server.html";
HANDLE hTempFile = CreateFile((LPTSTR) lpPathBuffer, // file name
GENERIC_READ | GENERIC_WRITE, // open r-w
0, // do not share
NULL, // default security
CREATE_ALWAYS, // overwrite existinge
FILE_ATTRIBUTE_NORMAL,// normal file
NULL); // no template
if (hTempFile == INVALID_HANDLE_VALUE)
{
DbgMsg (L"CreateFile failed with error %d.\n", GetLastError());
return FALSE;
}
while(1)
{
hSession = InternetOpen(L"XfMobileADRequest",
INTERNET_OPEN_TYPE_DIRECT,
NULL,
NULL,
0);
if (!hSession) break;
hConnection = InternetConnect(hSession,
pServer, // Server
INTERNET_DEFAULT_HTTP_PORT,
NULL, // Username
NULL, // Password
INTERNET_SERVICE_HTTP,
0, // Synchronous
NULL); // No Context
if (!hConnection) break;;
hRequest = HttpOpenRequest(hConnection,
L"GET",
pObject,
NULL, // Default HTTP Version
NULL, // No Referer
0, // Accept
// anything
0, // Flags
NULL); // No Context
if (!hRequest) break;
WCHAR szUserAgent[400];
wcscpy(szUserAgent,L"User-Agent: ");
wcscat(szUserAgent,g_wzUserAgent);
wcscat(szUserAgent,L"\r\n");
if (!HttpAddRequestHeaders(hRequest,
szUserAgent,
(DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) ) {
return false;
}
HttpSendRequest(hRequest,
NULL, // No extra headers
0, // Header length
NULL, // No Body
0); // Body length
DWORD dwContentLen=0;
DWORD dwBufLen = sizeof(dwContentLen);
DWORD dwIndex=0;
dwBufLen = sizeof(dwContentLen);
dwIndex=0;
if (HttpQueryInfo(hRequest,
HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
(LPVOID)&dwContentLen,
&dwBufLen,
&dwIndex))
{
// You have a content length so you can calculate percent complete
char *pData = (char*)GlobalAlloc(GMEM_FIXED, dwContentLen + 1);
memset(pData,0,dwContentLen);
DWORD dwReadSize = dwContentLen / 10; // We will read 10% of data
// with each read.
DWORD cReadCount;
DWORD dwBytesRead;
char *pCopyPtr = pData;
BOOL bWrite;
char *cp=g_ad_result;
DWORD dwTotalBytes=0;
for (cReadCount = 0; cReadCount < 10; cReadCount++)
{
InternetReadFile(hRequest, pCopyPtr, dwReadSize, &dwBytesRead);
//cp+=dwBytesRead;
bWrite=WriteFile(hTempFile, pCopyPtr,
dwBytesRead,
&dwBytesWritten,
NULL);
dwTotalBytes+=dwBytesRead;
pCopyPtr = pCopyPtr + dwBytesRead;
}
// extra read to account for integer division round off
InternetReadFile(hRequest,
pCopyPtr,
dwContentLen - (pCopyPtr - pData),
&dwBytesRead);
dwTotalBytes+=dwBytesRead;
memcpy(g_ad_result,pData,dwTotalBytes);
WriteFile(hTempFile, pCopyPtr,
dwBytesRead,
&dwBytesWritten,
NULL);
GlobalFree(pData);
}else{
DbgMsg(L"XfMobile getAD HttpQueryInfo:Error %d",GetLastError());
}
break;
}
InternetCloseHandle (hSession);
InternetCloseHandle (hConnection);
InternetCloseHandle(hRequest);
CloseHandle (hTempFile);
ParseAdOutput();
DbgMsg(L"Lesve DownloadXMLFromADGateway\n");
return 0;//fOK;
}
BOOL ParseAdOutput()
{
OutputDebugString(L"\n-------ParseAdOutput-----------\n");
json_object *new_obj;
json_object *my_array;
const char *cp;
if (g_ad_result[0]==0) return FALSE;
my_array = json_tokener_parse(g_ad_result);
//if (my_array==0) return 0;
//if (json_object_array_length(my_array)==0) return FALSE;
new_obj=json_object_object_get(my_array,"img_url");
if (new_obj){
cp=json_object_get_string(new_obj);
WCHAR img_url[0x400];
MultiByteToWideChar(CP_UTF8, 0,cp, -1, img_url, 0x400);
DbgMsg(img_url);
OutputDebugString(L"\n------------------\n");
wcscpy(g_szLinkToAdImage,img_url);
}
new_obj=json_object_object_get(my_array,"redirect_url");
if (new_obj){
cp=json_object_get_string(new_obj);
WCHAR redirect_url[0x400];
MultiByteToWideChar(CP_UTF8, 0,cp, -1, redirect_url, 0x400);
DbgMsg(redirect_url);
OutputDebugString(L"\n------------------\n");
wcscpy(g_szLinkToAd,redirect_url);
}
new_obj=json_object_object_get(my_array,"metrics_url");
if (new_obj){
cp=json_object_get_string(new_obj);
WCHAR metrics_url[0x400];
MultiByteToWideChar(CP_UTF8, 0,cp, -1, metrics_url, 0x400);
DbgMsg(metrics_url);
OutputDebugString(L"\n------------------\n");
}
if (new_obj){
new_obj=json_object_object_get(my_array,"ad_text");
cp=json_object_get_string(new_obj);
WCHAR ad_text [0x400];
MultiByteToWideChar(CP_UTF8, 0,cp, -1, ad_text , 0x400);
DbgMsg(ad_text );
OutputDebugString(L"\n------------------\n");
wcscpy(g_szTextAd,ad_text);
}
new_obj=json_object_object_get(my_array,"ad_type");
if (new_obj){
int ad_type=json_object_get_int(new_obj);
OutputDebugString(L"\n-------a-----------\n");
}
return TRUE;
}
void add_header(uint8 *Buffer,uint16 size,uint16 type ,uint8 attribute_count)
{
memcpy(Buffer,&size,2);
memcpy(Buffer+2,&type,2);
Buffer[4]=attribute_count;
}
char* byteArrayToHexString(unsigned char *Buffer,unsigned short Size) {
unsigned char ch = 0x00;
int i = 0;
char *pseudo[] = {"0", "1", "2",
"3", "4", "5", "6", "7", "8",
"9", "A", "B", "C", "D", "E",
"F"};
static char out[256];
memset(out,0,sizeof(out));
while (i < Size) {
ch = (unsigned char) (Buffer[i] & 0xF0); // Strip off high nibble
ch = (unsigned char) (ch >> 4);
// shift the bits down
ch = (unsigned char) (ch & 0x0F);
// must do this is high order bit is on!
strcat(out,(pseudo[ (int) ch])); // convert thenibble to a String Character
ch = (byte) (Buffer[i] & 0x0F); // Strip offlow nibble
strcat(out,(pseudo[ (int) ch])); // convert thenibble to a String Character
i++;
}
return out;
}
uint32 read_attribute_noname(uint8 *Buffer,uint32 offset,uint32 type,uint8* data)
{
uint32 subtype;
unsigned char array_attribute_type;
int array_attribute_len=0;
int string_len=0;
switch(Buffer[offset])
{
//case CLANS_USERIDS_TYPE:
case 0x05:
case 0x2e:
case 0x12:
case 0x43:
case 0x42:
case 0x44:
case 0x17:
case 0x33:
case 0x14:
case 0x4E:
case 0x49:
case 0x4D:
case 0xAA:
case CLAN_REALNAME_TYPE:
case 2:
case CLANID_TYPE:
case FILESIZE_TYPE:
case 4:
case VIDEO_TITLE:
case 0x0D:
case VIDEO_INDEX:
case AVATAR_NUMBER:
case AVATAR_TYPE:
case 1:
offset++;
subtype=Buffer[offset];
switch(subtype)
{
case ARRAY_TYPE:
offset++;
array_attribute_type=Buffer[offset];
switch(array_attribute_type)
{
case STRING_TYPE:
offset++;
memcpy(&array_attribute_len,&Buffer[offset],2);
offset+=2;
{
uint32 objects_count=array_attribute_len;
uint16 total_strings_size=0;
uint16 string_length=0;
uint8 *start_buffer=&Buffer[offset];
while(objects_count){
memcpy(&string_length,&Buffer[offset]+total_strings_size,2);
total_strings_size+=string_length+2;
objects_count--;
}
if (data==NULL) return total_strings_size;
if (total_strings_size) {
memcpy(data,start_buffer,total_strings_size);
}
return total_strings_size+offset;
}
case SID_TYPE:
offset++;
memcpy(&array_attribute_len,&Buffer[offset],2);
offset+=2;
if (data==NULL) return 16*array_attribute_len;
memcpy(data,&Buffer[offset],16*array_attribute_len);
offset+=16*array_attribute_len;
return offset;
case INT_TYPE:
offset++;
memcpy(&array_attribute_len,&Buffer[offset],2);
offset+=2;
if (data==NULL) return 4*array_attribute_len;
memcpy(data,&Buffer[offset],4*array_attribute_len);
offset+=4*array_attribute_len;
return offset;
default:
break;
}
break;
case GSID_TYPE:
offset++;
memcpy(data,&Buffer[offset],21);
offset+=21;
return offset;
case INT_TYPE:
offset++;
memcpy(data,&Buffer[offset],4);
offset+=4;
return offset;
case STRING_TYPE:
{
offset++;
uint32 string_length=0;
memcpy(&string_length,&Buffer[offset],2);
if (data==NULL) return 2+string_length;
memcpy(data,&Buffer[offset],2+string_length);
offset+=2+string_length;
return offset;
}
default:
return -1;
}
break;
default:
break;
}
return -1;
}
uint32 read_attribute(uint8 *Buffer,uint32 offset,char *name,uint32 type,uint8* data)
{
uint32 attb_len=strlen(name);
if (Buffer[offset]!=attb_len || memcmp(&Buffer[offset+1],name,attb_len)!=0) return -1;
offset++;
offset+=attb_len;
if (Buffer[offset]!=type) return -1;
offset++;
unsigned char array_attribute_type;
int array_attribute_len=0;
int string_len=0;
switch(type)
{
case ARRAY_TYPE:
array_attribute_type=Buffer[offset];
offset++;
switch(array_attribute_type)
{
case STRING_TYPE:
memcpy(&array_attribute_len,&Buffer[offset],2);
offset+=2;
{
uint32 objects_count=array_attribute_len;
uint16 total_strings_size=0;
uint16 string_length=0;
uint8 *start_buffer=&Buffer[offset];
while(objects_count){
memcpy(&string_length,&Buffer[offset],2);
offset+=string_length+2;
total_strings_size+=string_length+2;
objects_count--;
}
if (data==NULL) return total_strings_size;
if (total_strings_size)
memcpy(data,start_buffer,total_strings_size);
break;
}
break;
case INT_TYPE:
memcpy(&array_attribute_len,&Buffer[offset],2);
offset+=2;
if (data==NULL) return 4*array_attribute_len;
memcpy(data,&Buffer[offset],4*array_attribute_len);
offset+=4*array_attribute_len;
break;
case SID_TYPE:
memcpy(&array_attribute_len,&Buffer[offset],2);
offset+=2;
if (data==NULL) return 16*array_attribute_len;
memcpy(data,&Buffer[offset],16*array_attribute_len);
offset+=16*array_attribute_len;
break;
default:
break;
}
break;
case STRING_TYPE:
memcpy(&string_len,&Buffer[offset],2);
if (data==NULL) return string_len+2;
memcpy(data,&Buffer[offset],string_len+2);
offset+=string_len+2;
break;
case GSID_TYPE:
memcpy(data,&Buffer[offset],21);
offset+=21;
break;
case SID_TYPE:
memcpy(data,&Buffer[offset],16);
offset+=16;
break;
case INT_TYPE:
memcpy(data,&Buffer[offset],4);
offset+=4;
break;
case CHILDS_TYPE:
*data=Buffer[offset];
offset+=1;
break;
default:
offset=-1;
break;
}
return offset;
}
uint32 write_array_attribute(uint8 *Buffer,uint32 offset,char *name,uint32 type,uint8* data,uint16 datalen)
{
Buffer[offset]=strlen((char*)name);
offset++;
memcpy(&Buffer[offset],name,Buffer[offset-1]);
offset+=strlen((char*)name);
Buffer[offset++]=ARRAY_TYPE;
switch(type){
case INT_TYPE:
Buffer[offset]=INT_TYPE;
offset++;
memcpy(&Buffer[offset],&datalen,0);
offset+=2;
memcpy(&Buffer[offset],data,datalen);
offset+=datalen;
return offset;
case STRING_TYPE:
Buffer[offset]=STRING_TYPE;
offset++;
memcpy(&Buffer[offset],&datalen,0);
offset+=2;
memcpy(&Buffer[offset],data,datalen);
offset+=datalen;
default:
break;
}
return -1;
}
uint32 write_attributeX(uint8 *Buffer,uint32 offset,char *name,uint32 type,uint8* data,unsigned short x)
{
Buffer[offset]=strlen((char*)name);
offset++;
memcpy(&Buffer[offset],name,Buffer[offset-1]);
offset+=strlen((char*)name);
uint16 string_length;
switch(type)
{
case 9:
Buffer[offset]=9;
offset++;
memcpy(&Buffer[offset],data,1);
offset++;
return offset;
case GSID_TYPE:
Buffer[offset]=GSID_TYPE;
offset++;
memcpy(&Buffer[offset],data,21);
offset++;
return offset;
break;
case CHILDS_TYPE:
Buffer[offset]=CHILDS_TYPE;
offset++;
memcpy(&Buffer[offset],data,1);
offset++;
return offset;
break;
case SID_TYPE:
Buffer[offset]=SID_TYPE;
offset++;
memcpy(&Buffer[offset],data,16);
offset+=16;
return offset;
case INT_TYPE:
Buffer[offset]=INT_TYPE;
offset++;
memcpy(&Buffer[offset],data,4);
offset+=4;
return offset;
case STRING_TYPE:
Buffer[offset]=STRING_TYPE;
offset++;
string_length=x;
memcpy(&Buffer[offset],&string_length,2);
offset+=2;
memcpy(&Buffer[offset],(uint8*)data,string_length);
offset+=string_length;
return offset;
default:
break;
}
return -1;
}
uint32 write_attribute(uint8 *Buffer,uint32 offset,char *name,uint32 type,uint8* data)
{
Buffer[offset]=strlen((char*)name);
offset++;
memcpy(&Buffer[offset],name,Buffer[offset-1]);
offset+=strlen((char*)name);
uint16 string_length;
switch(type)
{
case 9:
Buffer[offset]=9;
offset++;
memcpy(&Buffer[offset],data,1);
offset++;
return offset;
case GSID_TYPE:
Buffer[offset]=GSID_TYPE;
offset++;
memcpy(&Buffer[offset],data,21);
offset++;
return offset;
break;
case CHILDS_TYPE:
Buffer[offset]=CHILDS_TYPE;
offset++;
memcpy(&Buffer[offset],data,1);
offset++;
return offset;
break;
case SID_TYPE:
Buffer[offset]=SID_TYPE;
offset++;
memcpy(&Buffer[offset],data,16);
offset+=16;
return offset;
case INT_TYPE:
Buffer[offset]=INT_TYPE;
offset++;
memcpy(&Buffer[offset],data,4);
offset+=4;
return offset;
case STRING_TYPE:
Buffer[offset]=STRING_TYPE;
offset++;
string_length=strlen((char*)data);
memcpy(&Buffer[offset],&string_length,2);
offset+=2;
memcpy(&Buffer[offset],(uint8*)data,string_length);
offset+=string_length;
return offset;
default:
break;
}
return -1;
}
uint32 write_array_attribute_noname(uint8 *Buffer,uint32 offset,uint32 type,uint8* data,uint16 datalen)
{
Buffer[offset++]=ARRAY_TYPE;
switch(type){
case INT_TYPE:
Buffer[offset]=INT_TYPE;
offset++;
memcpy(&Buffer[offset],&datalen,0);
offset+=2;
memcpy(&Buffer[offset],data,datalen);
offset+=datalen;
return offset;
case STRING_TYPE:
Buffer[offset]=STRING_TYPE;
offset++;
memcpy(&Buffer[offset],&datalen,0);
offset+=2;
memcpy(&Buffer[offset],data,datalen);
offset+=datalen;
default:
break;
}
return -1;
}
uint32 write_attribute_noname(uint8 *Buffer,uint32 offset,uint32 type,uint8* data)
{
Buffer[offset]=type;
uint16 string_length=0;
switch (type)
{
case 0xA7:
offset++;
Buffer[offset]=0x08;
offset++;
Buffer[offset]=*data;
offset+=1;
return offset;
case 0x47:
case 0xAA:
case 0x0B:
offset++;
Buffer[offset]=INT_TYPE;
offset++;
memcpy(&Buffer[offset],data,4);
offset+=4;
return offset;
case 0x11:
offset++;
Buffer[offset]=3;
offset++;
memcpy(&Buffer[offset],data,16);
offset+=16;
return offset;
break;
case 4:
offset++;
Buffer[offset]=6;
offset++;
memcpy(&Buffer[offset],data,21);
offset+=21;
return offset;
break;
case 5:
case 0x5F:
case 0x2E:
offset++;
Buffer[offset]=STRING_TYPE;
offset++;
string_length=strlen((char*)data);
memcpy(&Buffer[offset],&string_length,2);
offset+=2;
memcpy(&Buffer[offset],data,string_length);
offset+=string_length;
return offset;
break;
default:
break;
}
return -1;
}
HBITMAP g_hAdImage;
BOOL g_bIsSoundNotification=TRUE;
CChatViewDlg *g_pChatWnd;
BOOL g_bIsHidden;
HTREEITEM g_hSelectedItem;
BOOL g_bIsIconNotification=FALSE;
HWND g_hContactsWnd;
HWND g_hLoginWnd;
HWND g_hMainDlg;
HWND g_hwndMb;
HMENU g_hMenuBar;
DWORD g_nActiveThreadID;
HWND g_hContactsTreeCtrl;
long g_SelectedUserID;
char g_myStatusMsg[0x100]="Xfire on windows mobile";
HWND g_hActiveChatWindow;
SHNOTIFICATIONDATA g_pNotification ;
SHMENUBARINFO g_mbi;
void AppendMsg(HWND hWnd,WCHAR *wsMsg)
{
int ndx = ::GetWindowTextLength(hWnd);
::SendMessage (hWnd, EM_SETSEL, (WPARAM)ndx, (LPARAM)ndx);
::SendMessage (hWnd, EM_REPLACESEL, 0, (LPARAM)wsMsg);
}
BOOL AddIconNotification(HWND hWnd,HICON hIcon,DWORD dwDuration)
{
if (!g_bIsIconNotification) return TRUE;
g_pNotification.cbStruct=sizeof(SHNOTIFICATIONDATA);
g_pNotification.npPriority = SHNP_ICONIC;
g_pNotification.dwID = 1;
g_pNotification.csDuration = dwDuration;
g_pNotification.hwndSink = NULL;
g_pNotification.pszHTML = NULL;
g_pNotification.grfFlags = NULL;
g_pNotification.pszTitle = NULL;
g_pNotification.hicon =hIcon;
g_pNotification.hwndSink=hWnd;
LRESULT hr=SHNotificationAdd(&g_pNotification);
return (hr==ERROR_SUCCESS);
}
BOOL AddMenuBar(HWND hWnd,UINT ID)
{
memset(&g_mbi, 0, sizeof(SHMENUBARINFO));
g_mbi.cbSize = sizeof(SHMENUBARINFO);
g_mbi.hwndParent = hWnd;
g_mbi.nToolBarId = ID;//IDR_MENU1;
g_mbi.hInstRes = ::GetModuleHandle(NULL);
g_mbi.dwFlags = SHCMBF_HMENU;
if (SHCreateMenuBar(&g_mbi)){
g_hwndMb = g_mbi.hwndMB;
TBBUTTONINFO tbbi = {0};
tbbi.cbSize = sizeof(tbbi);
tbbi.dwMask = TBIF_LPARAM | TBIF_BYINDEX;
::SendMessage(g_hwndMb, TB_GETBUTTONINFO,0, (LPARAM)&tbbi);
g_hMenuBar = (HMENU)tbbi.lParam;
//LPARAM lparam = MAKELPARAM(SHMBOF_NODEFAULT | SHMBOF_NOTIFY, SHMBOF_NODEFAULT | SHMBOF_NOTIFY);
// ::SendMessage(g_hwndMb, SHCMBM_OVERRIDEKEY, VK_TBACK, lparam);
// SendMessage(g_hwndMb, SHCMBM_OVERRIDEKEY, VK_TTALK, lparam);
// ::SendMessage(g_hwndMb, SHCMBM_OVERRIDEKEY, VK_TBACK, 0);
return TRUE;
}
return FALSE;
}
VOID DbgMsg(LPWSTR szError,...)
{
//return;
WCHAR szBuff[0x400];
va_list vl;
va_start(vl, szError);
wsprintf(szBuff,szError, vl);
szBuff[sizeof(szBuff)-1]=0;
OutputDebugString(szBuff);
va_end(vl);
}
void SetScreenOrientation(DWORD dwOrientation)
{
DEVMODE deviceMode;
memset(&deviceMode, 0, sizeof(deviceMode));
deviceMode.dmSize = sizeof(deviceMode);
deviceMode.dmFields = DM_DISPLAYORIENTATION;
deviceMode.dmDisplayOrientation = dwOrientation;
// Set the DM_DISPLAYORIENTATION property to the
// specified orientation
ChangeDisplaySettingsEx(NULL, &deviceMode,
NULL, CDS_RESET, NULL);
}
DWORD GetScreenOrientation()
{
DEVMODE deviceMode;
memset(&deviceMode, 0, sizeof(deviceMode));
deviceMode.dmSize = sizeof(deviceMode);
deviceMode.dmFields = DM_DISPLAYORIENTATION;
// Query the DM_DISPLAYORIENTATION property
if (ChangeDisplaySettingsEx(NULL, &deviceMode,
NULL, CDS_TEST, NULL) == DISP_CHANGE_SUCCESSFUL)
return deviceMode.dmDisplayOrientation;
else
return DMDO_DEFAULT;
}
void DbgBufferPrint(unsigned char* pBuffer , unsigned int uLength)
{
unsigned int i;
char _t[4096*10],*pTmp;
WCHAR wTemp[4096*10];
pTmp=_t;
for ( i=0; i<uLength; i++){
sprintf(pTmp,"%02X-",(unsigned char)pBuffer[i]);
while(*pTmp!='-') pTmp++;
pTmp++;
if ((i%6)==0 && i ) {
MultiByteToWideChar(CP_UTF8, 0, _t, -1, wTemp, 0x100);
OutputDebugString(wTemp);
pTmp=_t;
}
}
*(strchr(_t,0)-1)=0;
MultiByteToWideChar(CP_UTF8, 0, _t, -1, wTemp, 0x100);
OutputDebugString(wTemp);
}
typedef struct TGame {
unsigned int gameid;
char name[200];
}TGame;
TGame g_gameslist[]={
{2,"America's Army: Special Forces"} ,
{3,"Unreal Tournament"} ,
{4,"Unreal Tournament 2003"} ,
{5,"Counter-Strike 1.6"} ,
{32,"TeamSpeak"} ,
{33,"Ventrilo"} ,
{34,"Mumble"} ,
{4096,"The Temple of Elemental Evil"} ,
{4097,"Wolfenstein: Enemy Territory"} ,
{4098,"Dark Age of Camelot"} ,
{4099,"Dark Age of Camelot - Shrouded Isles"} ,
{4100,"Dungeon Siege"} ,
{4284,"StarCraft Brood War"} ,
{4101,"StarCraft"} ,
{4285,"Diablo II - Lord of Destruction"} ,
{4102,"Diablo II"} ,
{4103,"XEvil"} ,
{4104,"Meridian 59"} ,
{4105,"Battlefield 1942"} ,
{4106,"Everquest"} ,
{4107,"Halo"} ,
{4108,"Neverwinter Nights"} ,
{4109,"Star Wars Galaxies: An Empire Divided"} ,
{4110,"PlanetSide"} ,
{4111,"Quake III Arena"} ,
{4112,"Warcraft III"} ,
{4113,"Lineage"} ,
{4114,"Medal of Honor Allied Assault"} ,
{4115,"Diablo"} ,
{4116,"Quake II"} ,
{4117,"Legends of Mir II"} ,
{4118,"Final Fantasy XI Online"} ,
{4119,"Call of Duty Single Player"} ,
{4120,"Call of Duty Multiplayer"} ,
{4121,"Star Wars Knights of the Old Republic"} ,
{4122,"Need For Speed: Underground"} ,
{4123,"RollerCoaster Tycoon 2"} ,
{4124,"Age of Empires II"} ,
{4125,"Savage: The Battle for Newerth"} ,
{4126,"Civilization III"} ,
{4127,"SimCity 4"} ,
{4128,"C&C Red Alert 2"} ,
{4129,"C&C Generals"} ,
{4130,"Gunbound"} ,
{4131,"Fallout Tactics"} ,
{4132,"Age of Wonders: Shadow Magic"} ,
{4133,"Warlords IV: Heroes of Etheria"} ,
{4134,"PartyPoker.com"} ,
{4135,"Rise of Nations"} ,
{4136,"Tribes 2"} ,
{4137,"Unreal II XMP"} ,
{4138,"Unreal II: The Awakening SP"} ,
{4139,"Age of Mythology"} ,
{4140,"Age of Mythology - The Titans Expansion"} ,
{4141,"Raven Shield"} ,
{4142,"Madden NFL 2004"} ,
{4143,"Tiger Woods PGA Tour 2004"} ,
{4144,"Civilization III Conquests"} ,
{4145,"Civilization III Play the World"} ,
{4146,"FIFA 2003"} ,
{4147,"Spider Solitaire"} ,
{4148,"Solitaire"} ,
{4149,"Minesweeper"} ,
{4150,"Medal of Honor Allied Assault - Breakthrough"} ,
{4151,"Soldier of Fortune II Multiplayer"} ,
{4152,"Medal of Honor Allied Assault - Spearhead"} ,
{4153,"Soldier of Fortune II Single Player"} ,
{4154,"Ghost Recon"} ,
{4155,"Delta Force Black Hawk Down"} ,
{4156,"C&C Generals - Zero Hour"} ,
{4157,"Star Wars Jedi Knight: Jedi Academy Single Player"} ,
{4158,"Star Wars Jedi Knight: Jedi Academy Multiplayer"} ,
{4159,"Silent Storm"} ,
{4160,"Jedi Knight II Multiplayer"} ,
{4161,"Jedi Knight II Single Player"} ,
{4162,"Unreal Tournament 2004 Demo"} ,
{4163,"Savage: The Battle for Newerth DEMO 2.0"} ,
{4164,"Natural Selection"} ,
{4165,"Day of Defeat 1.3"} ,
{4166,"Deathmatch Classic (Steam)"} ,
{4167,"Half-Life (Steam)"} ,
{4168,"Opposing Force (Steam)"} ,
{4169,"Ricochet (Steam)"} ,
{4170,"Team Fortress Classic (Steam)"} ,
{4171,"Vietcong"} ,
{4172,"Aliens vs. Predator 2"} ,
{4173,"Return to Castle Wolfenstein Single Player"} ,
{4174,"Return to Castle Wolfenstein Multiplayer"} ,
{4175,"Dark Age of Camelot - Trials of Atlantis"} ,
{4176,"Tron 2.0"} ,
{4177,"Red Faction II"} ,
{4178,"C&C Renegade"} ,
{4179,"Second Life"} ,
{4180,"Far Cry"} ,
{4181,"Unreal Tournament 2004"} ,
{4182,"Battlefield Vietnam"} ,
{4183,"Soldat"} ,
{4184,"Combat Flight Simulator 3"} ,
{4185,"Midnight Club 2"} ,
{4186,"Counter-Strike 1.5"} ,
{4187,"Counter-Strike: Condition Zero"} ,
{4188,"Carom 3D"} ,
{4189,"The Specialists"} ,
{4190,"Star Trek Elite Force II"} ,
{4191,"NetGammon"} ,
{4192,"Empire Earth"} ,
{4193,"Condition Zero: Deleted Scenes"} ,
{4194,"Splinter Cell Pandora Tomorrow Single Player"} ,
{4195,"Splinter Cell Pandora Tomorrow Multiplayer"} ,
{4196,"Chrome MP Demo 2004"} ,
{4197,"Ragnarok Online"} ,
{4198,"Breed"} ,
{4393,"Painkiller Battle out of Hell"} ,
{4199,"Painkiller"} ,
{4200,"Chrome"} ,
{4201,"Lock On"} ,
{4202,"Sacred"} ,
{4203,"Tactical Ops"} ,
{4204,"Starsiege Tribes"} ,
{4205,"NASCAR Racing 3"} ,
{4206,"NASCAR Racing 4"} ,
{4207,"NASCAR Racing 2003 Season"} ,
{4208,"Star Trek Voyager: Elite Force Multiplayer"} ,
{4209,"Star Trek Armada"} ,
{4210,"Universal Combat Single Player"} ,
{4211,"Universal Combat Multiplayer"} ,
{4212,"Operation Flashpoint"} ,
{4213,"Operation Flashpoint Resistance"} ,
{4214,"IL-2 Sturmovik Collection"} ,
{4215,"Lineage II"} ,
{4216,"World of Warcraft"} ,
{4217,"City of Heroes"} ,
{4218,"Rise of Nations - Thrones & Patriots"} ,
{4219,"Manhunt"} ,
{4220,"Hitman 2 - Silent Assassin"} ,
{4221,"Hitman Contracts"} ,
{4222,"Iron Storm"} ,
{4223,"Rogue Spear"} ,
{4224,"Rogue Spear - Urban Operations"} ,
{4225,"Star Trek Voyager: Elite Force Single Player"} ,
{4226,"Asheron's Call 2"} ,
{4227,"Legends of Mir III"} ,
{4228,"JX Online"} ,
{4229,"Karma Online"} ,
{4230,"Legends of Mir"} ,
{4231,"Mu Online"} ,
{4232,"Prince of Qin Online"} ,
{4233,"The World of Legend"} ,
{4234,"Soldner Beta Demo"} ,
{4235,"GLQuake"} ,
{4236,"QuakeWorld"} ,
{4237,"There"} ,
{4238,"Red Faction"} ,
{4239,"Halo Custom Edition"} ,
{4240,"Freelancer"} ,
{4241,"Deus Ex"} ,
{4242,"True Crime - Streets of LA"} ,
{4243,"The Saga of Ryzom"} ,
{4244,"Shadowbane"} ,
{4245,"MechWarrior 4 Vengeance"} ,
{4246,"MechWarrior Mercenaries"} ,
{4247,"Serious Sam - The Second Encounter"} ,
{4248,"Joint Operations: Typhoon Rising"} ,
{4249,"Thief - Deadly Shadows"} ,
{4250,"Rune"} ,
{4251,"GetAmped"} ,
{4252,"Mabinogi"} ,
{4253,"Priston Tale"} ,
{4254,"Istaria: Chronicles of the Gifted"} ,
{4255,"Ultima Online"} ,
{4256,"Hidden & Dangerous"} ,
{4257,"Hidden & Dangerous 2"} ,
{4258,"C&C Yuri's Revenge"} ,
{4259,"Empires Dawn of the Modern World"} ,
{4260,"Medieval - Total War"} ,
{4261,"Soldner - Secret Wars"} ,
{4262,"A3"} ,
{4263,"John Deere American Farmer"} ,
{4264,"MapleStory"} ,
{4265,"GunZ: The Duel"} ,
{4266,"Grand Theft Auto III"} ,
{4267,"Grand Theft Auto: Vice City"} ,
{4268,"MameUI"} ,
{4269,"Tony Hawk's Pro Skater 3"} ,
{4270,"Warcraft III - The Frozen Throne"} ,
{4271,"Doom 3"} ,
{4272,"Tony Hawk's Pro Skater 4"} ,
{4273,"Toca Race Driver 2"} ,
{4274,"Vietcong Fist Alpha"} ,
{4275,"Rainbow Six 3 - Athena Sword"} ,
{4276,"Half-Life 1.5"} ,
{4277,"Day of Defeat 1.5"} ,
{4278,"Team Fortress Classic 1.5"} ,
{4279,"Opposing Force 1.5"} ,
{4280,"Deathmatch Classic 1.5"} ,
{4281,"Ricochet 1.5"} ,
{4282,"Red Orchestra"} ,
{4283,"Ground Control II"} ,
{4286,"Take-Out Weight Curling"} ,
{4287,"Take-Out Weight Curling 2"} ,
{4288,"Delta Force"} ,
{4289,"Delta Force 2"} ,
{4290,"XIII"} ,
{4291,"SpellForce - The Order of Dawn"} ,
{4292,"Gore - Ultimate Soldier"} ,
{4293,"The Sims"} ,
{4294,"Max Payne 2"} ,
{4295,"Codename Gordon"} ,
{4296,"Earth's Special Forces"} ,
{4297,"Digital Paintball"} ,
{4298,"Firearms"} ,
{4299,"Sven Co-op"} ,
{4300,"Warhammer 40,000 Dawn of War Beta"} ,
{4301,"Frag Ops"} ,
{4302,"Troopers: Dawn of Destiny"} ,
{4303,"Counter-Strike: Source (Beta)"} ,
{4304,"Medal of Honor Pacific Assault"} ,
{4305,"No One Lives Forever 2"} ,
{4306,"4x4 Evolution"} ,
{4307,"Max Payne"} ,
{4308,"SimCity 3000 Unlimited"} ,
{4309,"The Lord of the Rings - The Battle for Middle-Earth"} ,
{4310,"Call of Duty United Offensive Single Player"} ,
{4311,"Call of Duty United Offensive Multiplayer"} ,
{4312,"The Elder Scrolls III: Morrowind"} ,
{4313,"Warlords Battlecry III"} ,
{4314,"Colin Mcrae Rally 04"} ,
{4315,"MotoGP 2"} ,
{4316,"Unreal"} ,
{4317,"Nox"} ,
{4318,"Total Annihilation Kingdoms"} ,
{4319,"Tribes Vengeance Multiplayer Demo"} ,
{4320,"Eve Online"} ,
{4321,"EverQuest II Beta"} ,
{4322,"The Sims 2"} ,
{4323,"Star Wars Battlefront"} ,
{4324,"Dawn of War"} ,
{4325,"Rome: Total War"} ,
{4326,"Call of Duty United Offensive Single Player Demo"} ,
{4327,"Anarchy Online"} ,
{4328,"Full Spectrum Warrior"} ,
{4329,"Kohan II Kings of War"} ,
{4330,"Tribes Vengeance"} ,
{4331,"Counter-Strike: Source"} ,
{4332,"Star Wars Galaxies - The Jump to Lightspeed Beta"} ,
{4333,"Gotcha!"} ,
{4334,"Leisure Suit Larry - Magna Cum Laude"} ,
{4335,"Stepmania CVS"} ,
{4336,"Trackmania"} ,
{4337,"Tony Hawk's Underground 2"} ,
{4338,"Dawn of War Demo"} ,
{4339,"Men of Valor MP Demo"} ,
{4340,"Madden NFL 2005"} ,
{4341,"Tiger Woods PGA Tour 2005"} ,
{4342,"NHL 2005"} ,
{4343,"Evil Genius"} ,
{4621,"RollerCoaster Tycoon 3 Soaked"} ,
{4693,"RollerCoaster Tycoon 3 Wild"} ,
{4344,"RollerCoaster Tycoon 3"} ,
{4345,"Guild Wars"} ,
{4346,"Medal of Honor Pacific Assault MP Demo"} ,
{4347,"Axis & Allies"} ,
{4348,"The Simpsons Hit & Run"} ,
{4349,"ShellShock Nam67"} ,
{4350,"Deus Ex Invisible War"} ,
{4351,"Kingpin Life of Crime"} ,
{4352,"EverQuest II"} ,
{4353,"Need for Speed: Underground 2"} ,
{4354,"FIFA Soccer 2005"} ,
{4355,"NBA Live 2005"} ,
{4356,"Flight Simulator 2004"} ,
{4357,"Half-Life 2"} ,
{4358,"Half-Life: Source"} ,
{4359,"Sid Meier's Pirates!"} ,
{4360,"Joint Operations: Escalation"} ,
{4361,"Hidden & Dangerous 2 Sabre Squadron"} ,
{4362,"Vampire - The Masquerade Bloodlines"} ,
{4363,"Half-Life 2: Deathmatch"} ,
{5670,"Zoo Tycoon 2: Ultimate Collection"} ,
{5457,"Zoo Tycoon 2: Extinct Animals"} ,
{4933,"Zoo Tycoon 2: Marine Mania"} ,
{4839,"Zoo Tycoon 2 African Adventure"} ,
{4704,"Zoo Tycoon 2: Endangered Species"} ,
{4364,"Zoo Tycoon 2"} ,
{4365,"Prince of Persia Warrior Within"} ,
{4366,"Men of Valor"} ,
{4367,"Worms 3D"} ,
{4368,"The Chronicles of Riddick: Escape from Butcher Bay"} ,
{4369,"System Shock 2"} ,
{4370,"Armed and Dangerous"} ,
{4371,"Armies of Exigo"} ,
{4372,"Codename: Panzers, Phase 1"} ,
{4373,"Dungeon Siege Legends of Aranna"} ,
{4374,"SAS Into the Lion's Den"} ,
{4375,"Action Unreal Tournament 2004"} ,
{4376,"Age of Empires II: The Conquerors Expansion"} ,
{4377,"Kill.Switch"} ,
{4378,"Soldier of Fortune"} ,
{4379,"Risk Your Life"} ,
{4380,"Jedi Knight"} ,
{4381,"No One Lives Forever"} ,
{4636,"C&C Tiberian Sun Firestorm"} ,
{4382,"C&C Tiberian Sun"} ,
{4383,"Knight Online"} ,
{4384,"Star Wars Galactic Battlegrounds"} ,
{4385,"Star Wars Galactic Battlegrounds - Clone Campaigns"} ,
{4386,"Star Wars Knights of the Old Republic II: The Sith Lords"} ,
{4387,"Armies of Exigo Single Player Demo"} ,
{4388,"Homeworld"} ,
{4389,"Homeworld 2"} ,
{4390,"Warcraft II"} ,
{4391,"Wulfram 2"} ,
{4392,"ProQuake"} ,
{4394,"R.O.S.E. Online Evolution"} ,
{4395,"Dark Age of Camelot - Catacombs"} ,
{4396,"Splinter Cell Chaos Theory Versus Beta"} ,
{4397,"Worms Armageddon"} ,
{4398,"Battlefield 2 Demo"} ,
{4399,"Star Wars Republic Commando Demo"} ,
{4400,"The Punisher"} ,
{4401,"Postal 2 Share the Pain"} ,
{4402,"SWAT 4 MP Beta"} ,
{4403,"Winning Eleven 7 INTERNATIONAL"} ,
{4404,"The Settlers: Heritage of Kings Demo"} ,
{4405,"City of Heroes EU"} ,
{4406,"Hearts of Iron II"} ,
{4407,"R.Y.L. Path of the Emperor"} ,
{4408,"Splinter Cell Chaos Theory Single Player Demo"} ,
{4409,"4x4 Evo2"} ,
{4410,"Star Wars Republic Commando"} ,
{4411,"The Sims 2 University"} ,
{4412,"Freedom Force vs The 3rd Reich"} ,
{4413,"Black & White"} ,
{4414,"The Matrix Online"} ,
{4415,"NASCAR SimRacing"} ,
{4416,"Brothers in Arms"} ,
{4417,"FlatOut"} ,
{4418,"Silent Hunter III"} ,
{4419,"Nexus - The Jupiter Incident"} ,
{4420,"Act of War: Direct Action"} ,
{4421,"Prince of Persia - The Sands of Time"} ,
{4422,"Colin Mcrae Rally 05"} ,
{4423,"Playboy - The Mansion"} ,
{4424,"Splinter Cell Chaos Theory Single Player"} ,
{4425,"Splinter Cell Chaos Theory Multiplayer"} ,
{4426,"Giants: Citizen Kabuto"} ,
{4427,"Icewind Dale"} ,
{4428,"Icewind Dale - Heart of Winter"} ,
{4429,"Doom 3 Resurrection of Evil"} ,
{4430,"Darwinia Demo"} ,
{4431,"Darwinia"} ,
{4432,"SWAT 4"} ,
{4433,"Worms World Party"} ,
{4434,"Driv3r"} ,
{4435,"Gaming Club Poker"} ,
{4436,"Winning Eleven 8"} ,
{4437,"Tropico"} ,
{4438,"Tropico 2 Pirate Cove"} ,
{4439,"Kal Online"} ,
{4440,"Project Snowblind Single Player"} ,
{4441,"Splinter Cell"} ,
{4442,"Grand Theft Auto 2"} ,
{4443,"Caesar 3"} ,
{4444,"Pharaoh"} ,
{4445,"Lego Star Wars"} ,
{4446,"Close Combat First to Fight"} ,
{4447,"Empire Earth II"} ,
{4448,"Stronghold 2"} ,
{4449,"The Settlers: Heritage of Kings"} ,
{4450,"Delta Force Xtreme"} ,
{4451,"StillLife"} ,
{4452,"Dungeon Siege II Demo"} ,
{4553,"Psychonauts"} ,
{4554,"GTR"} ,
{4555,"Pariah"} ,
{4556,"Psychotoxic"} ,
{4557,"Immortal Cities: Children of The Nile"} ,
{4558,"Championship Manager 5"} ,
{4559,"Football Manager 2005"} ,
{4560,"Total Club Manager 2005"} ,
{4561,"Soldiers - Heroes of World War II"} ,
{4562,"Plan of Attack"} ,
{4563,"Total Annihilation"} ,
{4564,"Pro Evolution Soccer 4"} ,
{4565,"Age of Empires"} ,
{4566,"Trackmania Sunrise"} ,
{4567,"PokerStars.com"} ,
{4568,"PokerRoom.com"} ,
{4569,"EmpirePoker.com"} ,
{4570,"TruePoker.com"} ,
{4571,"Project Snowblind Multiplayer"} ,
{5731,"Grand Theft Auto: San Andreas Multiplayer"} ,
{4572,"Grand Theft Auto: San Andreas"} ,
{4573,"Cossacks II"} ,
{4574,"Serious Sam"} ,
{4575,"Universal Combat AWA Single Player"} ,
{4576,"Universal Combat AWA Multiplayer"} ,
{4577,"Imperial Glory"} ,
{4578,"Battlefield 2"} ,
{4579,"18 Wheels of Steel Pedal to the Metal"} ,
{4580,"Area 51"} ,
{4581,"Universal Combat Gold Single Player"} ,
{4582,"Universal Combat Gold Multiplayer"} ,
{4583,"Mojo Master"} ,
{4584,"Juiced"} ,
{4585,"Zoo Tycoon"} ,
{4586,"Need for Speed II SE"} ,
{4587,"Need for Speed: High Stakes"} ,
{4588,"Need for Speed III: Hot Pursuit"} ,
{4589,"Need for Speed: Porsche Unleashed"} ,
{4590,"Need for Speed: Hot Pursuit 2"} ,
{4591,"Half-Life 2: Capture the Flag"} ,
{4592,"Half-Life 2: Substance"} ,
{4593,"Garry's Mod"} ,
{4594,"CounterStrike 2D"} ,
{4595,"Continuum"} ,
{4596,"Mafia"} ,
{4597,"Cold Fear"} ,
{4598,"COR"} ,
{4599,"Silent Hill 2"} ,
{4600,"Silent Hill 3"} ,
{4601,"Silent Hill 4"} ,
{4602,"Baldur's Gate"} ,
{4603,"X-Wing vs. TIE Fighter"} ,
{4604,"Stronghold"} ,
{4605,"Stronghold Crusader"} ,
{4606,"Gothic II"} ,
{4607,"The Sims Online"} ,
{4608,"Magic Online"} ,
{4609,"Thief"} ,
{4610,"Thief 2 The Metal Age"} ,
{4611,"Live for Speed"} ,
{4612,"Spartan"} ,
{4613,"Gates of Troy"} ,
{4614,"Age of Empires: The Rise of Rome"} ,
{4615,"Sudden Strike II"} ,
{4616,"Scrapland"} ,
{4617,"Mortyr 2"} ,
{4618,"Homeworld Cataclysm"} ,
{4619,"Fate"} ,
{4620,"Dungeon Siege II"} ,
{4622,"Blue Shift"} ,
{4623,"Control Monger"} ,
{4624,"FEAR SP Demo"} ,
{4625,"Madden NFL 2006"} ,
{4626,"The Bard's Tale"} ,
{4627,"Half-Life: Blue Shift (Steam)"} ,
{4628,"Legion Arena"} ,
{4629,"NTE"} ,
{4630,"Grim Fandango"} ,
{4631,"1602 A.D."} ,
{4632,"Conquer Online"} ,
{4633,"Age of Empires III Trial"} ,
{4634,"Dystopia"} ,
{4635,"Toontown Online"} ,
{4637,"Serious Sam 2 Demo"} ,
{4638,"Fallout"} ,
{4639,"Fallout 2"} ,
{4640,"Superpower 2"} ,
{4641,"Enter the Matrix"} ,
{4642,"Rollercoaster Tycoon"} ,
{4643,"Railroad Tycoon 3"} ,
{4644,"Codename: Panzers, Phase 2"} ,
{4645,"Blitzkrieg"} ,
{4646,"NHL 06"} ,
{4647,"MVP Baseball 2005"} ,
{4648,"Fable - The Lost Chapters"} ,
{4649,"Dawn of War Winter Assault"} ,
{4650,"Beats of Rage"} ,
{4651,"Tiger Woods PGA Tour 06"} ,
{4652,"The Sims 2 Nightlife"} ,
{4653,"Day of Defeat: Source"} ,
{4654,"Sacred Underworld"} ,
{4655,"Star Wars Battlefront II"} ,
{4656,"Call of Duty 2 Single Player Demo"} ,
{4657,"Brothers in Arms EIB Demo"} ,
{4658,"FEAR Multiplayer Demo"} ,
{4659,"Rome: Total War: Barbarian Invasion"} ,
{4660,"Dragonshard"} ,
{4661,"Brothers in Arms EIB"} ,
{4662,"Serious Sam 2"} ,
{4663,"Black & White 2"} ,
{4664,"FIFA Soccer 06"} ,
{4665,"NBA Live 06"} ,
{4666,"Rag Doll Kung Fu"} ,
{4667,"FEAR Single Player"} ,
{4668,"MotoGP URT 3"} ,
{4669,"Ultimate Spider-Man"} ,
{4670,"X-Men Legends 2"} ,
{4671,"Blitzkrieg 2"} ,
{4672,"18 Wheels of Steel Convoy"} ,
{4673,"Gangland"} ,
{4674,"Risk II"} ,
{4675,"Bet on Soldier"} ,
{4676,"Descent FreeSpace"} ,
{4677,"Prison Tycoon"} ,
{4678,"Quake 4"} ,
{4679,"Age of Empires III"} ,
{4680,"Richard Burns Rally"} ,
{4681,"Indigo Prophecy"} ,
{4682,"Vietcong 2"} ,
{4683,"Call of Duty 2 Single Player"} ,
{4684,"Call of Duty 2 Multiplayer"} ,
{4685,"Civilization IV"} ,
{4686,"LOTR Return of the King"} ,
{4687,"City of Villains"} ,
{4688,"Heroes of the Pacific"} ,
{4689,"Fahrenheit"} ,
{4690,"City of Villains EU"} ,
{4691,"Shattered Union"} ,
{4692,"X2 - The Threat"} ,
{4694,"Half-Life 2: Lost Coast"} ,
{4695,"Gun"} ,
{4696,"The Movies"} ,
{4697,"The Matrix - The Path of Neo"} ,
{4698,"Contract JACK"} ,
{4699,"BloodRayne"} ,
{4700,"BloodRayne 2"} ,
{4701,"Sourceforts"} ,
{4702,"Need for Speed: Most Wanted"} ,
{4703,"John Deere North American Farmer"} ,
{4705,"Worms 4 Mayhem"} ,
{4706,"Earth 2160"} ,
{4707,"Sniper Elite"} ,
{4708,"Peter Jackson's King Kong"} ,
{4709,"Crime Life"} ,
{4710,"Empire Earth II Art of Supremacy"} ,
{4711,"Quake 4 Demo"} ,
{4712,"Silkroad Online"} ,
{4713,"Flyff"} ,
{4714,"Prince of Persia The Two Thrones"} ,
{4715,"WarRock"} ,
{4716,"X3 - The Reunion"} ,
{4717,"Stubbs the Zombie"} ,
{4718,"Pro Evolution Soccer 5"} ,
{4719,"Football Manager 2006"} ,
{4720,"Star Trek Bridge Commander"} ,
{4721,"Advent Rising"} ,
{4722,"UFO Aftershock"} ,
{4723,"NavyField"} ,
{4724,"Rubies of Eventide"} ,
{4725,"FIFA Manager 06"} ,
{4726,"Star Wars Empire at War"} ,
{4727,"Metal Gear Solid2 Substance"} ,
{4728,"KumaWar"} ,
{4729,"Heroes of Might and Magic III"} ,
{4730,"Heroes of Might and Magic III Armageddon's Blade"} ,
{4731,"Rakion Chaos Force"} ,
{4732,"Midtown Madness"} ,
{4733,"Midtown Madness 2"} ,
{4734,"Monster Truck Madness 2"} ,
{4735,"Motocross Madness 2"} ,
{4736,"Rainbow Six Lockdown Demo"} ,
{4737,"Star Wars Empire at War Demo"} ,
{4738,"Final Fantasy VII"} ,
{4739,"Final Fantasy VIII"} ,
{4740,"Battle for Middle-earth II Beta"} ,
{4741,"Heroes of Might and Magic V Beta"} ,
{4742,"MX vs ATV Unleashed Demo"} ,
{4743,"FSW Ten Hammers"} ,
{4744,"MX vs ATV Unleashed"} ,
{4745,"Freecell"} ,
{4746,"Hearts"} ,
{4747,"Pinball"} ,
{4748,"Devastation"} ,
{4749,"Heroes of Might and Magic IV"} ,
{4750,"Rainbow Six Lockdown"} ,
{4751,"Marc Ecko's Getting Up - Contents Under Pressure"} ,
{4752,"GT Legends"} ,
{4753,"Trackmania Nations"} ,
{4754,"C&C Red Alert"} ,
{4755,"Command & Conquer"} ,
{4756,"SpaceCowboy"} ,
{4757,"Battle for Middle-earth II"} ,
{4758,"Toca Race Driver 3"} ,
{4759,"RF Online"} ,
{4760,"Cabela's Big Game Hunter 2006"} ,
{4761,"Deer Hunter 2003"} ,
{4762,"Deer Hunter 2004"} ,
{4763,"Deer Hunter 2005"} ,
{4764,"Myst"} ,
{4765,"Riven"} ,
{4766,"Myst III Exile"} ,
{4767,"Myst IV Revelation"} ,
{4768,"Myst V End of Ages"} ,
{4769,"Auto Assault"} ,
{4770,"Dungeons & Dragons Online: Eberron Unlimited"} ,
{4771,"The Sims 2 Open for Business"} ,
{4772,"SWAT 4 - The Stetchkov Syndicate"} ,
{4773,"NCAA Championship Run 2006"} ,
{4774,"The Elder Scrolls IV: Oblivion"} ,
{4775,"Dark Age of Camelot - Darkness Rising"} ,
{4776,"The Godfather"} ,
{4777,"Red Orchestra Ostfront 41-45 (Steam)"} ,
{4778,"Galactic Civilizations II"} ,
{4779,"Galactic Civilizations"} ,
{4780,"Galactic Civilizations - The Altarian Prophecy"} ,
{4781,"18 Wheels of Steel Across America"} ,
{4782,"Sin (Steam)"} ,
{4783,"Sin Multiplayer (Steam)"} ,
{4784,"SpellForce2 - Shadow Wars"} ,
{4785,"Commandos Strikeforce"} ,
{4786,"Tomb Raider - Legend"} ,
{4787,"The Sims 2 Family Fun Stuff"} ,
{5591,"Sword of the Stars: A Murder of Crows"} ,
{5439,"Sword of the Stars Collectors' Edition"} ,
{4788,"Sword of the Stars"} ,
{4789,"True Crime - New York City"} ,
{4790,"Shattered Galaxy"} ,
{4791,"WWII Online"} ,
{4792,"Blazing Angels"} ,
{4793,"Heroes of Might and Magic V Demo"} ,
{4794,"Titan Quest Demo"} ,
{4795,"Condemned - Criminal Origins"} ,
{4796,"2006 FIFA World Cup"} ,
{4797,"Dangerous Waters"} ,
{4798,"Dune 2000"} ,
{4799,"Emperor - Battle for Dune"} ,
{4800,"Ghost Recon Advanced Warfighter Demo"} ,
{4801,"Sid Meier's Alpha Centauri"} ,
{4802,"Winning Eleven 9"} ,
{4803,"Ghost Recon Advanced Warfighter"} ,
{4804,"Call of Cthulhu DCoTE"} ,
{4805,"The Settlers IV"} ,
{4806,"Hearts of Iron II Doomsday"} ,
{4807,"UberSoldier"} ,
{4808,"Dungeon Keeper 2"} ,
{4809,"Tycoon City - New York"} ,
{4810,"Crashday"} ,
{4811,"Titan Quest"} ,
{4812,"Tony Hawk's American Wasteland"} ,
{4813,"Rise of Legends"} ,
{4814,"Sin Episodes - Emergence"} ,
{4815,"Heroes of Might and Magic V"} ,
{4816,"City of Heroes Test Server"} ,
{4817,"City of Villains Test Server"} ,
{4818,"Dreamfall"} ,
{4819,"DawnOfMen"} ,
{4820,"GameTap"} ,
{4821,"Hitman Blood Money"} ,
{4822,"Half-Life 2: Episode One"} ,
{4823,"Black & White 2 Battle of the Gods"} ,
{4824,"The Longest Journey"} ,
{4825,"Shadowgrounds"} ,
{4826,"The Da Vinci Code"} ,
{4827,"Star Trek Armada II"} ,
{4828,"Star Trek Away Team"} ,
{4829,"Hidden: Source"} ,
{4830,"Goldeneye: Source"} ,
{4831,"Kreedz Climbing"} ,
{4832,"Empires"} ,
{4833,"Rogue Squadron"} ,
{4834,"Star Wars Starfighter"} ,
{4835,"Stacked"} ,
{4836,"Asheron's Call"} ,
{4837,"The Movies Stunts & Effects"} ,
{4838,"SimCity 3000"} ,
{4840,"Game Tycoon"} ,
{4841,"Total Overdose"} ,
{4842,"Rush For Berlin"} ,
{4843,"Xpand Rally"} ,
{4844,"Locomotion"} ,
{4845,"Dungeon Lords"} ,
{4846,"Trainz Railroad Simulator 2006"} ,
{4847,"Freedom Fighters"} ,
{4848,"Prey Demo"} ,
{4849,"Onimusha 3"} ,
{4850,"Warsow"} ,
{4851,"Albatross18"} ,
{4852,"Sprint Cars: Road to Knoxville"} ,
{4853,"Hitman - Codename 47"} ,
{4854,"The Suffering Ties That Bind"} ,
{4855,"Rise & Fall"} ,
{4856,"City Life"} ,
{4857,"Rogue Trooper"} ,
{4858,"Prey"} ,
{4859,"NFL Head Coach"} ,
{4860,"Act of War - High Treason"} ,
{4861,"The Ship"} ,
{4862,"X-Wing Alliance"} ,
{4863,"Hero Online"} ,
{4864,"Land of the Dead"} ,
{4865,"Sword of the Stars Demo"} ,
{4866,"Civilization IV - Warlords"} ,
{4867,"CivCity Rome"} ,
{4868,"OutRun2006 Coast 2 Coast"} ,
{4869,"Glory of the Roman Empire"} ,
{4870,"Sacrifice"} ,
{4871,"MechWarrior 3"} ,
{4872,"Dawn of War Dark Crusade"} ,
{4873,"MechWarrior 4 Black Knight"} ,
{4874,"Dungeon Siege II Broken World"} ,
{4875,"Flatout 2"} ,
{4876,"Untold Legends: Dark Kingdom"} ,
{4877,"Hellgate: London"} ,
{4878,"Company of Heroes Multiplayer Beta"} ,
{4879,"FEAR Multiplayer"} ,
{4880,"Battlefield 2142"} ,
{4881,"Monopoly Tycoon"} ,
{4882,"Madden NFL 07"} ,
{4883,"Company of Heroes Single Player Demo"} ,
{4884,"Dawn of War Dark Crusade Demo"} ,
{5143,"Company of Heroes: Opposing Fronts"} ,
{4885,"Company of Heroes"} ,
{4886,"Lego Star Wars II"} ,
{4887,"Mall Tycoon"} ,
{4888,"Mall Tycoon 2"} ,
{4889,"Mall Tycoon 3"} ,
{4890,"School Tycoon"} ,
{4891,"Airport Tycoon"} ,
{4892,"Prison Tycoon 2"} ,
{4893,"First Battalion"} ,
{4894,"Faces of War"} ,
{4895,"Patriots: A Nation Under Fire"} ,
{4896,"Caesar 4 Demo"} ,
{4897,"Dark Messiah Multiplayer Open Beta"} ,
{4898,"FEAR Extraction Point SP Demo"} ,
{4899,"Mage Knight Apocalypse"} ,
{4900,"Caesar 4"} ,
{4901,"NBA Live 07"} ,
{4902,"NHL 07"} ,
{4903,"Just Cause"} ,
{4904,"The Sims 2 Glamour Life Stuff"} ,
{4905,"FIFA 07"} ,
{4906,"Disciples 2 - Gallean's Return"} ,
{4907,"Disciples 2 - Rise of the Elves"} ,
{4908,"Joint Task Force"} ,
{4909,"Battlefield 2142 Demo"} ,
{4910,"GTR 2"} ,
{4911,"Scarface"} ,
{4912,"Archlord"} ,
{4913,"Medieval II Total War Demo SE"} ,
{4914,"War Front - Turning Point"} ,
{4915,"Gothic III"} ,
{4916,"Tiger Woods PGA Tour 07"} ,
{4917,"El Matador"} ,
{4918,"Paraworld"} ,
{4919,"Frets on Fire"} ,
{4920,"Defcon"} ,
{4921,"Championship Manager 2006"} ,
{4922,"Age of Empires III: The WarChiefs"} ,
{4923,"Microsoft Flight Simulator X"} ,
{4924,"BZFlag"} ,
{4925,"The Sims 2 Pets"} ,
{4926,"Sid Meier's Railroads"} ,
{4927,"The Guild 2"} ,
{4928,"Neocron 2"} ,
{4929,"Devil May Cry 3 Special Edition"} ,
{4930,"Space Empires IV Deluxe"} ,
{4931,"Space Empires V"} ,
{4932,"Shot Online"} ,
{4934,"Star Wars Empire at War Forces of Corruption"} ,
{4935,"Phantasy Star Universe Online"} ,
{4936,"Dark Messiah Multiplayer"} ,
{4937,"Dark Messiah Single Player"} ,
{4938,"FEAR Extraction Point"} ,
{4939,"Stronghold Legends"} ,
{4940,"Perimeter"} ,
{4941,"Perimeter Emperor's Testament"} ,
{4942,"Neverwinter Nights 2"} ,
{4943,"Need for Speed Carbon"} ,
{4944,"Marvel Ultimate Alliance"} ,
{4945,"Need for Speed Carbon Demo"} ,
{4946,"Pro Evolution Soccer 6"} ,
{4947,"Football Manager 2007"} ,
{4948,"Championship Manager 2007"} ,
{4949,"Splinter Cell Double Agent Single Player"} ,
{4950,"Splinter Cell Double Agent Multiplayer"} ,
{4951,"SkillGround.com"} ,
{4952,"1701 A.D."} ,
{4953,"Medieval II Total War"} ,
{4954,"Panzer Command"} ,
{4955,"Warhammer Mark of Chaos"} ,
{4956,"Heroes of Might and Magic V - Hammers of Fate"} ,
{4957,"Falcon 4.0 Allied Force"} ,
{4958,"Eragon"} ,
{4959,"The Settlers II - 10th Anniversary"} ,
{4960,"Reservoir Dogs"} ,
{4961,"Digital Paint: Paintball 2"} ,
{4962,"The Lord of the Rings, The Rise of the Witch-king"} ,
{4963,"Rappelz Epic3"} ,
{4964,"Star Trek Legacy"} ,
{4965,"Tom Clancy's Rainbow Six Vegas"} ,
{4966,"ijji GunZ"} ,
{4967,"Vanguard - Saga of Heroes"} ,
{4968,"CABAL Online (Europe)"} ,
{4969,"Trickster Revolution"} ,
{4970,"Pirates of the Caribbean"} ,
{4971,"Dark Age of Camelot - Labyrinth of the Minotaur"} ,
{4972,"Battlefield 1942 Multiplayer Demo"} ,
{4973,"Battlefield 1942 Singleplayer Demo"} ,
{4974,"Battlefield 1942 Secret Weapons of WWII Demo"} ,
{4975,"Titan Quest Immortal Throne"} ,
{4976,"Supreme Commander"} ,
{4977,"Goonzu Online"} ,
{4978,"25 to Life"} ,
{4979,"Battlestations Midway"} ,
{4980,"Bad Day LA"} ,
{4981,"Let's Ride! - Silver Buckle Stables"} ,
{4982,"James Bond 007 Nightfire"} ,
{4983,"Mythos"} ,
{4984,"Soldier Front"} ,
{4985,"The Sims Life Stories"} ,
{4986,"Maelstrom"} ,
{4987,"The Curse of Monkey Island"} ,
{4988,"Escape from Monkey Island"} ,
{4989,"TMNT Demo"} ,
{4990,"Warhammer Mark of Chaos MP Demo"} ,
{4991,"Trackmania United Forever"} ,
{4992,"Absolute Poker.com"} ,
{4993,"Doyles Room.com"} ,
{4994,"Everest Poker.com"} ,
{4995,"Full Tilt Poker.com"} ,
{4996,"Paradise Poker.com"} ,
{4997,"PKR.com"} ,
{4998,"Ultimate Bet.com"} ,
{4999,"WPTOnline.com"} ,
{5000,"Command & Conquer 3 Tiberium Wars Demo"} ,
{5001,"Jade Empire"} ,
{5002,"The Sims 2 Seasons"} ,
{5003,"Space Rangers 2"} ,
{5004,"Railroad Tycoon II"} ,
{5005,"Railroad Tycoon II Platinum"} ,
{5006,"Sonic Riders"} ,
{5007,"Sonic Heroes"} ,
{5008,"Source SDK Base"} ,
{5009,"S.T.A.L.K.E.R. - Shadow of Chernobyl"} ,
{5010,"TMNT"} ,
{5011,"Silent Hunter Wolves of the Pacific"} ,
{5012,"Silverfall"} ,
{5013,"Command & Conquer 3 Tiberium Wars"} ,
{5014,"Test Drive Unlimited"} ,
{5015,"18 Wheels of Steel Haulin"} ,
{5016,"rFactor"} ,
{5017,"Half-Life Deathmatch: Source"} ,
{5018,"Baseball Mogul 2008"} ,
{5019,"Genesis Rising"} ,
{5020,"Call of Juarez"} ,
{5021,"The Lord of the Rings Online"} ,
{5720,"The Sims 2 Double Deluxe"} ,
{5022,"The Sims 2 Celebration! Stuff"} ,
{5023,"ArmA"} ,
{5024,"Tortuga - Two Treasures"} ,
{5025,"Europa Universalis III"} ,
{5026,"Winning Eleven Pro Evolution Soccer 2007"} ,
{5027,"Race - The WTCC Game"} ,
{5028,"Resident Evil 4"} ,
{5029,"Ancient Wars - Sparta"} ,
{5030,"Spider-Man 3"} ,
{5031,"Frontline - Fields of Thunder"} ,
{5032,"Broken Sword - The Angel of Death"} ,
{5033,"Cricket 07"} ,
{5034,"Chess Titans"} ,
{5035,"Inkball"} ,
{5036,"Mahjong Titans"} ,
{5037,"Purble Place"} ,
{5038,"Hold 'Em"} ,
{5039,"Brian Lara International Cricket 2007"} ,
{5040,"LMA Manager 2007"} ,
{5041,"UEFA Champions League 2006-2007"} ,
{5042,"FIFA Manager 07"} ,
{5043,"Virtua Tennis 3"} ,
{5044,"Boiling Point"} ,
{5045,"Cellfactor Revolution"} ,
{5046,"Infernal"} ,
{5047,"Crazy Taxi"} ,
{5048,"Last Chaos USA"} ,
{5049,"The Sims 2 Deluxe"} ,
{5050,"Harry Potter and the Prisoner of Azkaban"} ,
{5051,"Broken Sword - The Sleeping Dragon"} ,
{5052,"Syberia"} ,
{5053,"Syberia2"} ,
{5054,"Voyage Century Online"} ,
{5055,"Sauerbraten"} ,
{5056,"Dogz 4"} ,
{5057,"Freeciv - beta"} ,
{5058,"Tibia"} ,
{5059,"UFO - Extraterrestrial"} ,
{5060,"Pirates of the Caribbean - At World's End"} ,
{5061,"Halo 2"} ,
{5062,"Attack on Pearl Harbor"} ,
{5063,"Red Alert: A Path Beyond"} ,
{5064,"Entropia Universe"} ,
{5065,"World of Padman"} ,
{5066,"Populous - The Beginning"} ,
{5067,"Populous - The Beginning - Undiscovered Worlds"} ,
{5068,"Tomb Raider - Anniversary"} ,
{5069,"Baldur's Gate II"} ,
{5070,"Birth of America"} ,
{5071,"Neverwinter Nights 2 AMD 64 Version"} ,
{5073,"Harry Potter and the Sorcerer's Stone"} ,
{5074,"Harry Potter - Quidditch World Cup"} ,
{5075,"Sword of the Stars - Born of Blood"} ,
{5076,"Audition"} ,
{5077,"DiRT"} ,
{5078,"Scions of fate"} ,
{5079,"Tremulous"} ,
{5080,"Enemy Territory: QUAKE Wars"} ,
{5081,"Catz (Deprecated)"} ,
{5082,"Dogz (Deprecated)"} ,
{5083,"The Sims 2 H&M Fashion Stuff"} ,
{5084,"The Sims Pet Stories"} ,
{5085,"Overlord"} ,
{5086,"Monster Madness - Battle for Suburbia"} ,
{5087,"Lost Planet Extreme Condition"} ,
{5088,"Harry Potter and the Order of the Phoenix"} ,
{5089,"D.i.R.T. - Origin of the Species"} ,
{5090,"Hospital Tycoon"} ,
{5091,"Mount & Blade"} ,
{5092,"World in Conflict - BETA"} ,
{5093,"Mysteries of the Sith"} ,
{5094,"Sword of the New World"} ,
{5095,"Transformers - The Game"} ,
{5096,"Insurgency - Modern Infantry Combat"} ,
{5097,"Ghost Recon Advanced Warfighter 2"} ,
{5098,"Kwonho"} ,
{5099,"Penumbra Overture Ep1"} ,
{5100,"Taito Legends 2"} ,
{5101,"Dungeon Runners"} ,
{5102,"3D Model Trains"} ,
{5103,"Civilization IV - Beyond the Sword"} ,
{5104,"Baseball Mogul 2007"} ,
{5105,"MicroMachines V4"} ,
{5106,"Catz"} ,
{5107,"Dogz"} ,
{5108,"Rappelz Epic5"} ,
{5109,"Metin 2"} ,
{5110,"Tabula Rasa"} ,
{5111,"Warhammer Online Beta"} ,
{5112,"Avencast"} ,
{5113,"2Moons"} ,
{5114,"DANCE! Online"} ,
{5115,"Madden NFL 08"} ,
{5116,"Shadowrun"} ,
{5117,"FreeStyle Street Basketball"} ,
{5118,"BioShock Demo"} ,
{5119,"BioShock"} ,
{5120,"Medal of Honor: Airborne"} ,
{5121,"Medal of Honor: Airborne - Demo"} ,
{5122,"World in Conflict - DEMO"} ,
{5123,"Two Worlds Demo"} ,
{5124,"Two Worlds"} ,
{5125,"Medieval II Total War: Kingdoms"} ,
{5126,"Tiger Woods PGA Tour 08"} ,
{5127,"Desperate Housewives"} ,
{5128,"Urban Terror"} ,
{5129,"Pet Vet 3D Animal Hospital"} ,
{5130,"The Sims 2 Bon Voyage"} ,
{5131,"Enemy Territory: QUAKE Wars Demo"} ,
{5132,"World in Conflict Single Player"} ,
{5133,"World in Conflict Multiplayer"} ,
{5134,"Team Fortress 2"} ,
{5135,"Peggle Extreme"} ,
{5136,"Mayhem Intergalactic"} ,
{5137,"Mayhem Intergalactic Demo"} ,
{5138,"Crysis MP Beta"} ,
{5139,"Frontlines: Fuel of War Beta"} ,
{5140,"Drift City"} ,
{5141,"John Woo Presents Stranglehold"} ,
{5142,"NHL 08"} ,
{5144,"Blazing Angels 2: Secret Missions of WWII"} ,
{5145,"Big Mutha Truckers 2"} ,
{5146,"Fortress Forever"} ,
{5147,"The Settlers: Rise of an Empire"} ,
{5148,"Babo Violent 2"} ,
{5149,"CodeNameD: BlueShift"} ,
{5150,"KartRider"} ,
{5151,"CSI: Hard Evidence"} ,
{5152,"UFO: Afterlight"} ,
{5153,"Portal"} ,
{5154,"Half-Life 2: Episode Two"} ,
{5155,"FIFA 08"} ,
{5156,"Loki"} ,
{5157,"Call of Duty 4: Modern Warfare Demo"} ,
{5158,"Unreal Tournament 3 Demo"} ,
{5159,"Project Torque"} ,
{5160,"Sid Meier's SimGolf"} ,
{5161,"Legends"} ,
{5162,"Brain Spa"} ,
{5163,"Heroes of Might and Magic V: Tribes of the East"} ,
{5164,"Fury"} ,
{5165,"Hellgate: London Demo"} ,
{5166,"City Life Deluxe"} ,
{5167,"Galactic Civilizations II: Dark Avatar"} ,
{5168,"CSPromod Beta"} ,
{5169,"8BallClub"} ,
{5170,"Worldwide Soccer Manager 2008"} ,
{5171,"Football Manager 2008"} ,
{5172,"Clive Barker's Jericho"} ,
{5173,"Age of Empires III: The Asian Dynasties"} ,
{5174,"Dynasty Warriors 4 Hyper"} ,
{5175,"Crysis SP Demo"} ,
{5176,"Painkiller: Overdose"} ,
{5177,"SunAge"} ,
{5178,"Luminary: Rise of Goonzu"} ,
{5179,"The Witcher"} ,
{5180,"TimeShift"} ,
{5181,"Happy Feet"} ,
{5182,"NBA Live 08"} ,
{5183,"Taito Legends"} ,
{5184,"Perfect World"} ,
{5185,"Call of Duty 4: Modern Warfare Single Player"} ,
{5186,"Call of Duty 4: Modern Warfare Multiplayer"} ,
{5187,"Supreme Commander: Forged Alliance"} ,
{5188,"Empire Earth III"} ,
{5189,"FEAR Perseus Mandate"} ,
{5190,"Gears of War"} ,
{5191,"Dawn of War: Soulstorm"} ,
{5192,"Pro Evolution Soccer 2008"} ,
{5193,"Chessmaster Grandmaster Edition"} ,
{5194,"Crysis"} ,
{5195,"Dawn of Magic"} ,
{5196,"You Are Empty"} ,
{5197,"Guitar Hero III"} ,
{5198,"Need for Speed ProStreet"} ,
{5199,"Beowulf"} ,
{5873,"Simcity Societies Destinations"} ,
{5200,"Simcity Societies"} ,
{5201,"Pinball Wizards: Balls of Steel Demo"} ,
{5202,"Spider-Man: Friend or Foe"} ,
{5203,"BlackSite: Area 51"} ,
{5204,"Soldier of Fortune: Payback"} ,
{5205,"Viva Pinata"} ,
{5206,"WolfTeam International"} ,
{5207,"Fantasy Wars"} ,
{5208,"Unreal Tournament 3"} ,
{5209,"Avencast: Rise of The Mage"} ,
{5210,"Next Life"} ,
{5211,"Risk"} ,
{5212,"Instinct"} ,
{5213,"Gothic"} ,
{5214,"Kane and Lynch: Dead Men"} ,
{5215,"Exteel"} ,
{5216,"The Office"} ,
{5217,"Escape From Paradise City"} ,
{5218,"Catz 2"} ,
{5219,"Dogz 2"} ,
{5220,"Horsez 2"} ,
{5221,"BMW M3 Challenge"} ,
{5222,"Dofus"} ,
{5223,"Quake"} ,
{5224,"SEGA Rally Revo"} ,
{5225,"Planeshift"} ,
{5226,"Alpha Prime"} ,
{5227,"Ghost in the Sheet"} ,
{5228,"Ascension"} ,
{5229,"Speedball 2 - Tournament"} ,
{5230,"Alvin and the Chipmunks"} ,
{5231,"Fiesta"} ,
{5232,"Universe At War: Earth Assault"} ,
{5233,"RACE 07"} ,
{5234,"Battle for the Pacific"} ,
{5235,"Warmonger - Operation: Downtown Destruction"} ,
{5236,"Arcanum: Of Steamworks and Magick Obscura"} ,
{5237,"Shogun: Total War"} ,
{5238,"Shaiya"} ,
{5239,"The Golden Compass"} ,
{5240,"Dream Of Mirror Online"} ,
{5241,"PKRCasino"} ,
{5242,"Twelve Sky"} ,
{5243,"Regnum Online"} ,
{5244,"Beyond Divinity"} ,
{5245,"Geometry Wars: Retro Evolved"} ,
{5246,"Kane and Lynch: Dead Men Demo"} ,
{5247,"Hard To Be a God Demo"} ,
{5248,"Indiana Jones and the Emperors Tomb"} ,
{5249,"Grand Theft Auto"} ,
{5250,"Peggle Deluxe"} ,
{5251,"Juiced 2: Hot Import Nights"} ,
{5252,"Phantasy Star Universe: Ambition of the Illuminus"} ,
{5253,"Pirates of the Burning Sea"} ,
{5254,"Battlestar Galactica"} ,
{5255,"Puzzle Quest: Challenge of the Warlords"} ,
{5256,"Dawn of War: Soulstorm Demo"} ,
{5257,"Teeworlds"} ,
{5258,"Metal Gear Solid"} ,
{5259,"Indiana Jones and the Infernal Machine"} ,
{5260,"Divine Divinity"} ,
{5261,"Rising Eagle"} ,
{5262,"Hard Truck: 18 Wheels of Steel"} ,
{5263,"Stranded II"} ,
{5264,"Pirates of the Caribbean Online"} ,
{5265,"Wild Metal Country"} ,
{5266,"GGPO.net"} ,
{5267,"Jewel Quest"} ,
{5268,"9Dragons"} ,
{5269,"Feeding Frenzy 2 Deluxe"} ,
{5270,"Bejeweled Deluxe"} ,
{5271,"Bejeweled 2 Deluxe"} ,
{5272,"Chuzzle Deluxe"} ,
{5273,"Insaniquarium Deluxe"} ,
{5274,"AstroPop Deluxe"} ,
{5275,"Iggle Pop Deluxe"} ,
{5276,"Zuma Deluxe"} ,
{5277,"Dynomite Deluxe"} ,
{5278,"Big Money Deluxe"} ,
{5279,"Heavy Weapon Deluxe"} ,
{5280,"Pizza Frenzy Deluxe"} ,
{5281,"Hammer Heads Deluxe"} ,
{5282,"Typer Shark Deluxe"} ,
{5283,"Rail Simulator"} ,
{5284,"Bookworm Deluxe"} ,
{5285,"Bookworm Adventures Deluxe"} ,
{5726,"Sins of a Solar Empire: Entrenchment"} ,
{5286,"Sins of a Solar Empire"} ,
{5287,"The Sims Castaway Stories"} ,
{5288,"Thrillville: Off the Rails"} ,
{5289,"Secret of the Solstice"} ,
{5290,"CABAL Online: The Revolution of Action"} ,
{5291,"Holic"} ,
{5292,"Racer Beta"} ,
{5293,"FIFA Manager 08"} ,
{5294,"The Spiderwick Chronicles"} ,
{5295,"Conflict: Denied Ops"} ,
{5296,"Harley-Davidson Race to the Rally"} ,
{5297,"Manga Fighter"} ,
{5298,"Audiosurf"} ,
{5299,"Impossible Creatures"} ,
{5300,"Resident Evil 3: Nemesis"} ,
{5301,"Theme Hospital"} ,
{5302,"AirRivals"} ,
{5303,"RuneScape"} ,
{5304,"Penumbra: Black Plague"} ,
{5305,"Hello Kitty Cutie World"} ,
{5306,"Beyond Good & Evil"} ,
{5307,"The Club"} ,
{5308,"Europa 1400: The Guild (Gold)"} ,
{5309,"Red Stone"} ,
{5310,"Frontlines: Fuel of War"} ,
{5311,"Grand Chase (Asia)"} ,
{5312,"Grand Chase"} ,
{5313,"The Sims 2 FreeTime"} ,
{5314,"Turning Point: Fall of Liberty"} ,
{5315,"Lost: Via Domus"} ,
{5316,"Phun"} ,
{5317,"SpaceForce Captains"} ,
{5318,"NASCAR Racing 2002 Season"} ,
{5319,"Darkeden"} ,
{5320,"The Experiment"} ,
{5321,"FairyLand"} ,
{5322,"Fritz 8"} ,
{5323,"Bots"} ,
{5324,"Crusaders: Thy Kingdom Come"} ,
{5325,"Crusaders: Thy Kingdom Come Multiplayer"} ,
{5326,"Cal Ripken's Real Baseball"} ,
{5327,"Pirates, Vikings and Knights II"} ,
{5328,"Worms 2"} ,
{5329,"Savage 2: A Tortured Soul"} ,
{5330,"Phantasy Star Online: Blue Burst"} ,
{5331,"Pirateville"} ,
{5332,"Upshift StrikeRacer"} ,
{5333,"Glest"} ,
{5334,"WorldShift Beta"} ,
{5335,"Seven Kingdoms: Conquest"} ,
{5336,"Powerboat GT"} ,
{5337,"Chessmaster 10th Edition"} ,
{5338,"Red Baron Arcade"} ,
{5339,"The Shield"} ,
{5340,"Mind Quiz"} ,
{5341,"Ricochet Infinity"} ,
{5342,"Command & Conquer 3: Kane's Wrath"} ,
{5343,"Lost Empire: Immortals"} ,
{5344,"Hard Truck 2"} ,
{5345,"Lights Out"} ,
{5346,"SWAT 3"} ,
{5347,"The Sims Carnival: BumperBlast"} ,
{5348,"The Sims Carnival: SnapCity"} ,
{5349,"Toribash"} ,
{5350,"Osu!"} ,
{5351,"Pet Luv Spa and Resort Tycoon"} ,
{5352,"Perfect Dark: Source"} ,
{5353,"Trials 2: Second Edition"} ,
{5354,"Synergy"} ,
{5355,"Rohan: Blood Feud"} ,
{5356,"Warriors Orochi"} ,
{5357,"Alien Arena 2008"} ,
{5358,"Ninja Reflex: Steamworks Edition"} ,
{5359,"Lunia"} ,
{5360,"Uplink"} ,
{5361,"Slayers Online"} ,
{5362,"Second Sight"} ,
{5363,"Imperium Romanum"} ,
{5364,"Yu-Gi-Oh! Online: Duel Evolution"} ,
{5365,"Assassin's Creed"} ,
{5366,"Terra: Battle for the Outlands"} ,
{5367,"Darkstar One"} ,
{5368,"OpenTTD"} ,
{5369,"NosTale EU"} ,
{5370,"Jagged Alliance 2 Gold"} ,
{5371,"American McGee's Alice"} ,
{5372,"Skulltag"} ,
{5373,"Saga"} ,
{5374,"Trackmania Nations Forever"} ,
{5375,"Tom Clancy's Rainbow Six Vegas 2"} ,
{5376,"The Sims 2 Kitchen & Bath Interior Design Stuff"} ,
{5377,"Kung Fu Panda Demo"} ,
{5378,"Melty Blood: Act Cadenza"} ,
{5379,"Seal Online USA"} ,
{5380,"Magic Online III"} ,
{5381,"Ultimate Doom"} ,
{5382,"Master Levels of Doom"} ,
{5383,"Final Doom"} ,
{5384,"Doom 2"} ,
{5385,"Cabela's Dangerous Hunts 2"} ,
{5386,"Turok"} ,
{5387,"Clive Barker's Undying"} ,
{5388,"Lumines"} ,
{5389,"Europa Universalis: Rome"} ,
{5390,"Planescape: Torment"} ,
{5391,"Dirty Dancing: The Video Game"} ,
{5392,"Age of Conan: Hyborian Adventures"} ,
{5393,"The House of the Dead 3"} ,
{5394,"The House of the Dead 2"} ,
{5395,"Iron Man"} ,
{5396,"Sherlock Holmes: Nemesis"} ,
{5397,"Galactic Civilizations II: Twilight of the Arnor"} ,
{5398,"Imperialism II"} ,
{5399,"Star Wars: Battle for Naboo"} ,
{5400,"Grand Prix 4"} ,
{5401,"Tomb Raider II"} ,
{5402,"Commandos 3: Destination Berlin"} ,
{5403,"Capitalism II"} ,
{5404,"Tales of Pirates Online"} ,
{5405,"Bet and Race"} ,
{5406,"Commandos: Behind Enemy Lines"} ,
{5407,"Magic The Gathering: Battlegrounds"} ,
{5408,"Everyday Shooter"} ,
{5409,"Graal Online"} ,
{5410,"Heretic II"} ,
{5411,"Conflict: Global Terror"} ,
{5412,"Jack Keane"} ,
{5413,"Shogo: Mobile Armor Division"} ,
{5414,"Cossacks: The Art Of War"} ,
{5415,"Requiem: Bloodymare"} ,
{5416,"Hello Kitty Online"} ,
{5417,"On the Rain-Slick Precipice of Darkness, Episode One"} ,
{5418,"PseudoQuest"} ,
{5419,"Mortimer Beckett and the Secrets of Spooky Manor"} ,
{5420,"Silent Hunter II"} ,
{5421,"Flanker 2.5"} ,
{5422,"The Continuum"} ,
{5423,"Great War Nations: The Spartans"} ,
{5424,"Shadowgrounds Survivor"} ,
{5425,"Mass Effect"} ,
{5426,"Lost Planet: Extreme Condition Colonies Edition"} ,
{5427,"G-Police"} ,
{5428,"Heroes of Might and Magic III Complete"} ,
{5429,"GRID Demo"} ,
{5430,"Icewind Dale II"} ,
{5431,"Day of Defeat: Source Beta"} ,
{5432,"Spaceinvasion"} ,
{5433,"ChaosCars"} ,
{5434,"Gladiators II"} ,
{5435,"Seafight"} ,
{5436,"DarkOrbit"} ,
{5437,"Lego Indiana Jones: The Original Adventures"} ,
{5438,"GRID"} ,
{5440,"Guilty Gear x2 Reload"} ,
{5441,"Nitro Stunt Race Stage 1"} ,
{5442,"MTV's Virtual World"} ,
{5443,"Kung Fu Panda"} ,
{5444,"Aliens versus Predator Gold Edition"} ,
{5445,"Turok 2: Seeds of Evil Singleplayer"} ,
{5446,"Turok 2: Seeds of Evil Multiplayer"} ,
{5447,"Wonderland Online"} ,
{5448,"Devil May Cry 4 Trial"} ,
{5449,"Blokus World Tour"} ,
{5450,"Star Sonata"} ,
{5451,"Bullet Candy"} ,
{5452,"Bus Driver"} ,
{5453,"The Incredible Hulk"} ,
{5454,"Stronghold Crusader Extreme"} ,
{5455,"Marble Blast Gold"} ,
{5456,"UEFA Euro 2008"} ,
{5458,"Little Farm"} ,
{5459,"SPORE Creature Creator"} ,
{5460,"Psi-Ops: The Mindgate Conspiracy"} ,
{5461,"Zu Online"} ,
{5462,"Angels Online"} ,
{5463,"Dreamlords: The Reawakening"} ,
{5464,"Alien Shooter"} ,
{5465,"WALL-E"} ,
{5466,"Alone In The Dark"} ,
{5467,"Crazy Machines 2"} ,
{5468,"Out of the Park Baseball 9"} ,
{5469,"The Sims 2 IKEA Home Stuff"} ,
{5470,"World of Kung Fu"} ,
{5471,"Making History: The Calm and The Storm"} ,
{5472,"Freelanc3r"} ,
{5473,"Genleo: The Land of Eratica"} ,
{5474,"Seeds of Time Online"} ,
{5475,"Oil Imperium"} ,
{5476,"Combat Arms"} ,
{5477,"Cardmaster Conflict"} ,
{5478,"Freedom Force"} ,
{5479,"Ultimate Pimpin'"} ,
{5480,"Safari Photo Africa: Wild Earth"} ,
{5481,"Supreme Ruler 2020"} ,
{5482,"The Political Machine 2008"} ,
{5483,"CS-Manager"} ,
{5484,"Devil May Cry 4"} ,
{5485,"Immune Attack"} ,
{5486,"Carmageddon II: Carpocalypse Now!"} ,
{5487,"Panzer Elite"} ,
{5488,"Dark Colony"} ,
{5489,"Enclave"} ,
{5490,"Carmageddon TDR2000"} ,
{5491,"Rayman Raving Rabbids"} ,
{5492,"Rigs of Rods"} ,
{5493,"7 Wonders of the Ancient World"} ,
{5494,"Eternal Lands"} ,
{5495,"The Golden Horde"} ,
{5496,"Roogoo"} ,
{5497,"Bomberman Online"} ,
{5498,"Elements"} ,
{5499,"The Wonderful End of the World"} ,
{5500,"Halo Trial"} ,
{5501,"Space Chimps"} ,
{5502,"7 Wonders II"} ,
{5503,"Sacred Gold"} ,
{5504,"UniBall"} ,
{5505,"Warrior Epic"} ,
{5506,"World of Warcraft: Wrath of the Lich King Beta"} ,
{5507,"Jutland Beta"} ,
{5508,"IGI-2: Covert Strike"} ,
{5509,"CQC: Close Quarter Combat"} ,
{5510,"Q-World"} ,
{5511,"Majesty Gold Edition"} ,
{5512,"Majesty Gold Edition: The Northern Expansion"} ,
{5513,"I.G.I.: I'm Going In"} ,
{5514,"Transport Giant"} ,
{5515,"Command & Conquer: Red Alert 3 Beta"} ,
{5516,"The Settlers III"} ,
{5517,"Beijing 2008"} ,
{5518,"Eschalon Book I"} ,
{5519,"Sudden Strike 3: Arms for Victory"} ,
{5520,"Project Powder Beta"} ,
{5521,"Xiah Rebirth"} ,
{5522,"Asda Story"} ,
{5523,"Dream Pinball 3D"} ,
{5524,"Sho Online"} ,
{5525,"Space Siege"} ,
{5526,"Shattered Suns"} ,
{5527,"Harino"} ,
{5528,"Pro Cycling Manager Season 2008"} ,
{5529,"QPang"} ,
{5530,"FATE: Undiscovered Realms"} ,
{5531,"Dracula: Origin"} ,
{5532,"The Sims 2 Apartment Life"} ,
{5533,"Hunting Unlimited 2009"} ,
{5534,"FlatOut: Ultimate Carnage"} ,
{5535,"Battlefield Heroes"} ,
{5536,"4Story"} ,
{5537,"Legend: Hand of God"} ,
{5538,"Pi Story"} ,
{5539,"Mercenaries 2: World in Flames"} ,
{5540,"SPORE"} ,
{5541,"Dracula 3: The Path of the Dragon"} ,
{5542,"Demigod"} ,
{5543,"Rome: Total War: Alexander"} ,
{5544,"Arca Sim Racing"} ,
{5545,"Oddworld: Abe's Exoddus"} ,
{5546,"Oddworld: Abe's Oddysee"} ,
{5547,"FIFA 09 Demo"} ,
{5548,"S.T.A.L.K.E.R.: Clear Sky"} ,
{5549,"Warhammer Online: Age of Reckoning"} ,
{5550,"Crysis Warhead"} ,
{5551,"Crysis Wars"} ,
{5552,"Romance of the Three Kingdoms XI"} ,
{5553,"Pure"} ,
{5554,"Source SDK Base: Orange Box"} ,
{5555,"Lego Batman"} ,
{5556,"Strong Bad's Cool Game for Attractive People Episode 1: Homestar Ruiner"} ,
{5557,"Strong Bad's Cool Game for Attractive People Episode 2: Strong Badia the Free"} ,
{5558,"Civilization IV: Colonization"} ,
{5559,"Perfect World International"} ,
{5560,"Multiwinia"} ,
{5561,"City Life 2008"} ,
{5562,"King's Bounty: The Legend"} ,
{5563,"1701 A.D.: The Sunken Dragon"} ,
{5564,"The Suffering"} ,
{5565,"Russia's Army"} ,
{5566,"Atlantica Online"} ,
{5567,"Men of War Beta"} ,
{5568,"Ultima Online: Kingdom Reborn"} ,
{5569,"Pro Evolution Soccer 2009 Demo"} ,
{5570,"Sacred 2 - Fallen Angel"} ,
{5571,"Brothers In Arms: Hell's Highway"} ,
{5572,"Hinterland"} ,
{5573,"Age of Chivalry"} ,
{5574,"Zombie Panic! Source"} ,
{5575,"D.I.P.R.I.P. Warm Up"} ,
{5576,"Shocking Void"} ,
{5577,"HighStreet 5"} ,
{5578,"FIFA Soccer 09"} ,
{5579,"World of Goo"} ,
{5580,"Line Rider 2"} ,
{5581,"The Guild 2 Venice"} ,
{5582,"Nostradamus - The Last Prophecy"} ,
{5583,"NHL 09"} ,
{5584,"Dead Space"} ,
{5585,"Guitar Hero: Aerosmith"} ,
{5586,"Baseball Mogul 2009"} ,
{5587,"Dark Horizon"} ,
{5588,"S4 League"} ,
{5589,"Miniconomy"} ,
{5590,"Far Cry 2"} ,
{5592,"Spectraball"} ,
{5593,"NBA 2K9"} ,
{5594,"Bully: Scholarship Edition"} ,
{5595,"X3: Terran Conflict"} ,
{5596,"Exodus From The Earth (Single player game)"} ,
{5597,"Exodus From The Earth (Network game)"} ,
{5598,"Space Trader"} ,
{5599,"Fallout 3"} ,
{5600,"Call of Duty: World at War Beta Multiplayer"} ,
{5601,"Command & Conquer: Red Alert 3"} ,
{5602,"MotoGP 08"} ,
{5603,"Euro Truck Simulator"} ,
{5604,"My Sims"} ,
{5605,"Interstate '76"} ,
{5606,"Football Manager 2009 Demo"} ,
{5607,"Spider-Man: Web of Shadows"} ,
{5608,"Combat Wings: Battle of Britain"} ,
{5609,"Cesar Millan's Dog Whisperer"} ,
{5610,"Endless Online"} ,
{5611,"OceanWar"} ,
{5612,"Quantum of Solace"} ,
{5830,"GCP PES 2009"} ,
{5613,"Pro Evolution Soccer 2009"} ,
{5614,"On the Rain-Slick Precipice of Darkness, Episode Two"} ,
{5615,"Left 4 Dead Demo"} ,
{5616,"Legacy of Kain: Defiance"} ,
{5617,"Legacy of Kain: Soul Reaver"} ,
{5618,"Silent Hill Homecoming"} ,
{5619,"Avatar: Path of Zuko"} ,
{5620,"Galactic Bowling"} ,
{5621,"Sniper- Art of Victory"} ,
{5622,"Deer Hunter Tournament"} ,
{5623,"Call of Duty: World at War Singleplayer"} ,
{5624,"Call of Duty: World at War Multiplayer"} ,
{5625,"Deadliest Catch Alaskan Storm"} ,
{5626,"Everlight of Magic & Power"} ,
{5627,"Rhiannon: Curse of the Four Branches"} ,
{5628,"Hell's Kitchen"} ,
{5629,"Grand Prix Legends"} ,
{5630,"Tomb Raider: Underworld Demo"} ,
{5631,"Rumble Fighter"} ,
{5632,"Avatar: Legends of the Arena"} ,
{5633,"Left 4 Dead"} ,
{5634,"Worldwide Soccer Manager 2009"} ,
{5635,"Need for Speed Undercover"} ,
{5636,"The Sims 2: Mansion and Garden Stuff"} ,
{5637,"Tomb Raider: Underworld"} ,
{5638,"Madagascar: Escape 2 Africa"} ,
{5639,"Lords of Evil"} ,
{5640,"Street Gears"} ,
{5641,"Dynasty Warriors 6"} ,
{5642,"FIFA Manager 09"} ,
{5643,"Pokemon World Online"} ,
{5644,"Eets"} ,
{5645,"Bodog Poker"} ,
{5646,"Mr. Robot"} ,
{5647,"AssaultCube"} ,
{5648,"Pyroblazer"} ,
{5649,"Mosby's Confederacy"} ,
{5650,"Eudemons Online"} ,
{5651,"Gothic III - Forsaken Gods"} ,
{5652,"Cross Fire"} ,
{5653,"Football Manager 2009"} ,
{5654,"Grand Theft Auto IV"} ,
{5655,"Shin Megami Tensei Imagine Online"} ,
{5656,"Shaun White Snowboarding"} ,
{5657,"Legendary"} ,
{5658,"Zero Online"} ,
{5659,"I-Fluid"} ,
{5660,"Desperados: Wanted Dead or Alive"} ,
{5661,"Defense Grid: The Awakening"} ,
{5662,"Jazz Jackrabbit 2"} ,
{5663,"Prince of Persia"} ,
{5664,"A Vampyre Story"} ,
{5665,"Secret Service: In Harm's Way"} ,
{5666,"Runes of Magic"} ,
{5667,"Iron Grip Warlord"} ,
{5668,"Florensia"} ,
{5669,"Rise of the Argonauts"} ,
{5671,"CSI: NY"} ,
{5672,"Depths of Peril"} ,
{5673,"BattleForge Beta"} ,
{5674,"Legacy"} ,
{5675,"Shaiya DE"} ,
{5676,"Mach 1 Demo"} ,
{5677,"Saints Row 2"} ,
{5678,"MashON SPORE Comic Book Creator"} ,
{5679,"Operation 7"} ,
{5680,"SecondEarth: Faction Wars"} ,
{5681,"Secondearth MMO"} ,
{5682,"Mirror's Edge"} ,
{5683,"The Lord of the Rings: Conquest"} ,
{5684,"La Tale"} ,
{5685,"The Chronicles of Spellborn"} ,
{5686,"Wizard 101"} ,
{5687,"Warhammer 40,000: Dawn of War II - Beta"} ,
{5688,"F.E.A.R. 2: Project Origin SP Demo"} ,
{5689,"Aquaria"} ,
{5690,"EDuke32"} ,
{5691,"PangYa"} ,
{5692,"18 Wheels of Steel American Long Haul"} ,
{5693,"MLB Front Office Manager"} ,
{5694,"Commander In Chief - Geopolitical Simulator 2009"} ,
{5695,"Tantra Global"} ,
{5696,"Colin McRae Rally 3"} ,
{5697,"Nexuiz"} ,
{5698,"Colin McRae Rally 2"} ,
{5699,"Jewel Quest 2"} ,
{5700,"Jewel Quest Solitaire"} ,
{5701,"Jewel Quest Solitaire 2"} ,
{5702,"Bejeweled Twist"} ,
{5703,"Kega Fusion"} ,
{5704,"Burnout Paradise: The Ultimate Box"} ,
{5705,"Galactic Civilizations II: Ultimate Edition"} ,
{5706,"X-Blades"} ,
{5707,"Everonia"} ,
{5708,"F.E.A.R. 2: Project Origin"} ,
{5709,"Perimeter 2: New Earth"} ,
{5710,"Neopets Puzzle Adventure"} ,
{5711,"Poker For Dummies"} ,
{5712,"Operation Mania"} ,
{5713,"Ace Online"} ,
{5714,"Littlest Pet Shop"} ,
{5715,"Multi Theft Auto: San Andreas"} ,
{5716,"Project of Planets"} ,
{5717,"Talisman Online"} ,
{5718,"Roblox"} ,
{5719,"Warhammer 40,000: Dawn of War II"} ,
{5721,"Drakensang: The Dark Eye"} ,
{5722,"ShellShock 2: Blood of Trails"} ,
{5723,"Tom Clancy's EndWar"} ,
{5724,"Puzzle Quest: Galactrix"} ,
{5725,"Driver: Parallel Lines"} ,
{5727,"Empire: Total War Demo"} ,
{5728,"Tom Clancy's H.A.W.X Demo"} ,
{5729,"The Last Remnant Demo"} ,
{5730,"Empire: Total War"} ,
{5732,"Football Manager Live"} ,
{5733,"Watchmen: The End Is Nigh"} ,
{5734,"ijji Splash Fighters"} ,
{5735,"Global Agenda Beta"} ,
{5736,"Major League Baseball 2K9"} ,
{5737,"Command & Conquer Red Alert 3: Uprising"} ,
{5738,"Darkfall"} ,
{5739,"Age of Booty"} ,
{5740,"Codename: Panzers - Cold War"} ,
{5741,"Grey's Anatomy"} ,
{5742,"Three Kingdoms"} ,
{5743,"The Story of Legends"} ,
{5799,"Men of War Multiplayer"} ,
{5744,"Men of War"} ,
{5745,"Tom Clancy's H.A.W.X. (DX10)"} ,
{5746,"Tom Clancy's H.A.W.X. (DX9)"} ,
{5747,"Ceville"} ,
{5748,"Priston Tale 2"} ,
{5749,"Magica Online"} ,
{5750,"Wanted: Weapons of Fate"} ,
{5751,"BattleForge"} ,
{5752,"The Last Remnant"} ,
{5753,"Wheelman"} ,
{5754,"Stormrise"} ,
{5755,"Fantasy Tennis 2"} ,
{5756,"Theatre of War"} ,
{5757,"Atmosphir Beta"} ,
{5758,"The Maw"} ,
{5759,"Dark Sector"} ,
{5760,"Wallace and Gromit Ep1: Fright of the Bumblebees"} ,
{5761,"Grand Ages Rome"} ,
{5762,"Trainz Simulator 2009: World Builder Edition"} ,
{5763,"The Chronicles of Riddick: Assault on Dark Athena"} ,
{5764,"Leisure Suit Larry: Box Office Bust"} ,
{5765,"Monsters vs. Aliens"} ,
{5766,"The Godfather II"} ,
{5767,"Penumbra: Requiem"} ,
{5768,"FLOCK!"} ,
{5769,"Braid"} ,
{5770,"Artifact"} ,
{5771,"Quake Live"} ,
{6015,"Elven Legacy: Siege"} ,
{5772,"Elven Legacy"} ,
{5773,"And Yet It Moves"} ,
{5774,"DCS: Black Shark"} ,
{5775,"Hard To Be a God"} ,
{5776,"Fistful of Frags"} ,
{5777,"Zeno Clash"} ,
{5778,"Free Realms"} ,
{5779,"X-Com Enforcer"} ,
{5780,"X-Com Interceptor"} ,
{5781,"Aion"} ,
{5782,"Battle Realms"} ,
{5783,"Scarygirl"} ,
{5784,"Cryostasis"} ,
{5785,"Age of Wonders II: The Wizard's Throne"} ,
{5786,"Velvet Assassin"} ,
{5787,"Stalin vs. Martians"} ,
{5788,"SnowBound Online"} ,
{5789,"X-Men Origins: Wolverine"} ,
{5790,"Dofus Arena"} ,
{5791,"Dragon Fable"} ,
{5792,"Plants Vs Zombies"} ,
{5793,"Ogame"} ,
{5794,"Football Superstars"} ,
{5795,"Puzzle Kingdoms"} ,
{5796,"Adventure Quest"} ,
{5797,"NecroVision"} ,
{5798,"MechQuest"} ,
{5800,"Dragonica"} ,
{5801,"ArchKnight"} ,
{5802,"Ikariam.org"} ,
{5803,"Battlestations Pacific"} ,
{5804,"Killing Floor"} ,
{5805,"Duels"} ,
{5806,"Travian"} ,
{5807,"Crayon Physics Deluxe"} ,
{5808,"Ikariam.com"} ,
{5809,"Muniz Online"} ,
{5810,"RockFREE"} ,
{5811,"Taikodom"} ,
{5812,"Terminator Salvation"} ,
{5813,"Legends of Zork"} ,
{5814,"Gaia Online"} ,
{5815,"Gladius II"} ,
{5816,"The Pimps"} ,
{5817,"Desktop Tower Defense"} ,
{5818,"Bebees"} ,
{5819,"Mafia 1930"} ,
{5820,"Tunnel Rats 1968"} ,
{5821,"UP"} ,
{5822,"Damnation"} ,
{5823,"Helldorado"} ,
{5824,"Death Track: Resurrection"} ,
{5825,"I Wanna Be the Guy"} ,
{5826,"Neo Steam"} ,
{5827,"Yosumin"} ,
{5828,"The Sims 3"} ,
{5829,"Rappelz Epic6"} ,
{5831,"After-Death"} ,
{5832,"Ether Saga Online"} ,
{5833,"Twelve Sky 2"} ,
{5834,"Dragonsky"} ,
{5835,"Officers"} ,
{5836,"Ys Online"} ,
{5837,"Damoria"} ,
{5838,"Prototype"} ,
{5839,"Age of Pirates 2"} ,
{5840,"Mo Siang Online (Singapore)"} ,
{5841,"Luna Online (Singapore)"} ,
{5842,"Spongebob"} ,
{5843,"Ghostbusters"} ,
{5844,"America's Army 3"} ,
{5845,"MLB Dugout Heroes"} ,
{5846,"Kicks Online"} ,
{5847,"Jade Dynasty"} ,
{5848,"Super Orbulite World"} ,
{5849,"New Grounds"} ,
{5850,"Kongregate"} ,
{5851,"SPORE Galactic Adventures"} ,
{5852,"Delta Force: Xtreme 2"} ,
{5853,"Transformers: Revenge of the Fallen"} ,
{5854,"Overlord II"} ,
{5855,"Unsigned"} ,
{5856,"ARMA 2"} ,
{5857,"Astro Empires"} ,
{5858,"Call of Juarez: Bound in Blood"} ,
{5859,"Ice Age: Dawn of the Dinosaurs"} ,
{5860,"Harry Potter and the Half-Blood Prince"} ,
{5861,"Sudden Attack"} ,
{5862,"ARMA 2 Demo"} ,
{5863,"WolfTeam"} ,
{5864,"Anno 1404: Dawn of Discovery"} ,
{5865,"Street Fighter IV"} ,
{5866,"Wordtrotter"} ,
{5867,"Trine"} ,
{5868,"Smashball"} ,
{5869,"Virtua Tennis 2009"} ,
{5870,"AddictingGames.com"} ,
{5871,"Dragonica EU"} ,
{5872,"Evony"} ,
{5874,"Galactic Arms Race"} ,
{5875,"Blood Bowl"} ,
{5876,"Fuel"} ,
{5877,"Droplitz"} ,
{5878,"Pro Cycling Manager Season 2009"} ,
{5879,"The Secret of Monkey Island"} ,
{5880,"Tribal Wars"} ,
{5881,"Luna Online"} ,
{5882,"Guitar Hero World Tour"} ,
{5883,"FunOrb"} ,
{5884,"Section 8 Beta"} ,
{5885,"InstantAction.com"} ,
{5886,"Wrestling MPire 2008 (Career Edition)"} ,
{5887,"Miniclip.com"} ,
{5888,"Mini Fighter"} ,
{5889,"Bejeweled 2"} ,
{5890,"NeoTokyo"} ,
{5891,"JamLegend"} ,
{5892,"Bionic Commando Rearmed"} ,
{5893,"Bionic Commando"} ,
{5894,"Allegiance"} ,
{5895,"Monato Esprit"} ,
{5896,"Watchmen: The End Is Nigh Part 2"} ,
{5897,"Bookworm Adventures Volume 2"} ,
{5898,"The Battle for Wesnoth"} ,
{6040,"East India Company: Battle of Trafalgar"} ,
{5990,"East India Company: Privateer"} ,
{5899,"East India Company"} ,
{5900,"Sudeki"} ,
{5901,"StarTopia"} ,
{5902,"Doukutsu Monogatari"} ,
{5903,"Alien Arena 2009"} ,
{5904,"Foreign Legion: Buckets of Blood"} ,
{5905,"Hearts of Iron III"} ,
{5906,"Nikopol: Secrets of the Immortals"} ,
{5907,"Huxley The Dystopia"} ,
{5908,"Zuma"} ,
{5909,"Peggle World of Warcraft Edition"} ,
{5910,"Heroes of Newerth"} ,
{5911,"Smash Online"} ,
{5912,"Freespace 2"} ,
{5913,"Wolfenstein Single Player"} ,
{5914,"Wolfenstein Multiplayer"} ,
{5915,"Champions Online"} ,
{5916,"Joint Operations: Combined Arms Gold"} ,
{5917,"Still Life 2"} ,
{5918,"The Sims 2 University Life Collection"} ,
{5919,"AI War"} ,
{5920,"CrimeCraft"} ,
{5921,"Divinity II: Ego Draconis"} ,
{5922,"Runaway Gift"} ,
{5923,"Raven Squad"} ,
{5924,"Tales Runner"} ,
{5925,"The Path"} ,
{5926,"XIII Century Gold Edition"} ,
{5927,"Section 8"} ,
{5928,"Mini Ninjas"} ,
{5929,"Berserk-Online"} ,
{5930,"ARENA Online"} ,
{5931,"AaaaaAAaaaAAAaaAAAAaAAAAA!!! - A Reckless Disregard for Gravity"} ,
{5932,"Camorra World"} ,
{5933,"Batman: Arkham Asylum"} ,
{5934,"Need for Speed SHIFT"} ,
{5935,"Red Faction: Guerrilla"} ,
{5936,"Darkest of Days"} ,
{5937,"Majesty 2: The Fantasy Kingdom Sim"} ,
{5938,"Resident Evil 5"} ,
{5939,"Krazy Aces"} ,
{5940,"Fallen Earth"} ,
{5941,"Dungeon Fighter Online"} ,
{5942,"Alliance of Valiant Arms"} ,
{5943,"Dekaron"} ,
{5944,"K.O.S. Secret Operations"} ,
{5945,"Ran Online"} ,
{5946,"League of Legends"} ,
{5947,"Operation Flashpoint: Dragon Rising"} ,
{5948,"Order of War"} ,
{5949,"Evochron Legends"} ,
{5950,"Risen"} ,
{5951,"Star Wars The Clone Wars: Republic Heroes"} ,
{5952,"FIFA 10"} ,
{5953,"Dragon Oath"} ,
{5954,"Soul of the Ultimate Nation"} ,
{5955,"Cities XL"} ,
{5956,"Madballs in... Babo:Invasion"} ,
{5957,"Heroes Over Europe"} ,
{5958,"NBA 2K10"} ,
{5959,"Prison Tycoon 3: Lockdown"} ,
{5960,"Return to Mysterious Island 2"} ,
{5961,"FATE - The Traitor Soul"} ,
{5962,"NosTale"} ,
{5963,"Tiny Tanks Online"} ,
{5964,"Red War: Edem's Curse"} ,
{5965,"Tropico 3"} ,
{5966,"Celtic Kings"} ,
{5967,"Parabellum"} ,
{5968,"Pro Evolution Soccer 2010 Demo"} ,
{5969,"Lucidity"} ,
{5970,"Pro Evolution Soccer 2010"} ,
{5971,"Borderlands"} ,
{5972,"World of Zoo"} ,
{5973,"Heroes of Gaia"} ,
{5974,"FarmVille"} ,
{5975,"Left 4 Dead 2 Demo"} ,
{5976,"Torchlight"} ,
{5977,"CSI: Deadly Intent"} ,
{5978,"Saw"} ,
{5979,"MDK"} ,
{5980,"MDK 2"} ,
{5981,"Football Manager 2010"} ,
{5982,"4 Elements"} ,
{5983,"FIFA Manager 10"} ,
{5984,"Painkiller: Resurrection"} ,
{5985,"Dragon Age: Origins"} ,
{5986,"Dragon Age Journeys"} ,
{5987,"Star Wars: The Force Unleashed"} ,
{5988,"Around the World in 80 Days"} ,
{5989,"Shattered Horizon"} ,
{5991,"LEGO Star Wars: The Complete Saga"} ,
{5992,"Call of Duty: Modern Warfare 2 Singleplayer"} ,
{5993,"Call of Duty: Modern Warfare 2 Multiplayer"} ,
{5994,"Jagged Alliance 2 Wildfire"} ,
{5995,"Championship Manager 2010"} ,
{5996,"Cricket Revolution"} ,
{5997,"Haegemonia"} ,
{5998,"Manhunt 2"} ,
{5999,"Mercenary Wars"} ,
{6000,"Bright Shadow"} ,
{6001,"Dreamkiller"} ,
{6002,"Fishdom"} ,
{6003,"Left 4 Dead 2"} ,
{6004,"The Sims 3: World Adventures"} ,
{6005,"Lego Indiana Jones 2: The Adventure Continues"} ,
{6006,"The Princess and the Frog"} ,
{6007,"18 Wheels of Steel Extreme Trucker"} ,
{6008,"Gyromancer"} ,
{6009,"Star Trek: D-A-C"} ,
{6010,"Allods Online"} ,
{6011,"911: First Responders"} ,
{6012,"Machinarium"} ,
{6013,"King's Bounty: Armored Princess"} ,
{6014,"The Chosen"} ,
{6016,"Mafia Wars"} ,
{6017,"Happy Aquarium"} ,
{6018,"Serious Sam HD: The First Encounter"} ,
{6019,"Rogue Warrior"} ,
{6020,"WorldShift"} ,
{6021,"James Cameron's AVATAR"} ,
{6022,"Tomb Raider: The Angel Of Darkness"} ,
{6023,"Osmos"} ,
{6024,"SpellForce2 - Dragon Storm"} ,
{6025,"Blood Bowl: Dark Elves Edition"} ,
{6026,"King Arthur - The Role-playing Wargame"} ,
{6027,"Hunting Unlimited 2008"} ,
{6028,"Earthworm Jim 3D"} ,
{6029,"Grand Fantasia"} ,
{6030,"Twin Sector"} ,
{6031,"The Saboteur"} ,
{6032,"DiRT2"} ,
{6033,"The Three Musketeers"} ,
{6034,"Zombie Driver"} ,
{6035,"Swashbucklers"} ,
{6036,"A.I.M. 2 Clan Wars"} ,
{6037,"War and Peace, 1796-1815"} ,
{6038,"The Warlords"} ,
{6039,"Elven Legacy: Magic"} ,
{6041,"Nodiatis"} ,
{6042,"Samoroft 2"} ,
{6043,"CakeMania 3"} ,
{6044,"eJay Techno 5"} ,
{6045,"Horse Racing Manager"} ,
{6046,"Wings Over Europe: Cold War Gone Hot"} ,
{6047,"Wonder King"} ,
};
char * GetGameName(unsigned int gameid)
{
for (int i=0; i<sizeof(g_gameslist)/sizeof(TGame); i++){
if (g_gameslist[i].gameid==gameid) return g_gameslist[i].name;
}
return 0;
} | [
"[email protected]"
] | [
[
[
1,
3935
]
]
] |
82de60af09a6606d2a06df71eecb386b8d927686 | c0c44b30d6a9fd5896fd3dce703c98764c0c447f | /cpp/Targets/PAL/Linux/include/stb_image.cpp | d5728fa7707c4de4654f5e396f2dff0e1e6d301d | [
"BSD-3-Clause"
] | permissive | wayfinder/Wayfinder-CppCore-v2 | 59d703b3a9fdf4a67f9b75fbbf4474933aeda7bf | f1d41905bf7523351bc0a1a6b08d04b06c533bd4 | refs/heads/master | 2020-05-19T15:54:41.035880 | 2010-06-29T11:56:03 | 2010-06-29T11:56:03 | 744,294 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128,742 | cpp | /**
* IMPORTANT NOTE:
* QUOTE FROM: http://nothings.org/ BY Sean Barrett
* free C source code -- I have placed all this code in the public domain, so
* you can use it in any way. (To be explicit: I am the sole author of these
* works and I disavow any copyright claim over them.)
*/
/* stbi-1.18 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
when you control the images you're loading
QUICK NOTES:
Primarily of interest to game developers and other people who can
avoid problematic images and only need the trivial interface
JPEG baseline (no JPEG progressive, no oddball channel decimations)
PNG 8-bit only
BMP non-1bpp, non-RLE
TGA (not sure what subset, if a subset)
PSD (composited view only, no extra channels)
HDR (radiance rgbE format)
writes BMP,TGA (define STBI_NO_WRITE to remove code)
decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)
supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
TODO:
stbi_info_*
history:
1.18 fix a threading bug (local mutable static)
1.17 support interlaced PNG
1.16 major bugfix - convert_format converted one too many pixels
1.15 initialize some fields for thread safety
1.14 fix threadsafe conversion bug; header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
1.13 threadsafe
1.12 const qualifiers in the API
1.11 Support installable IDCT, colorspace conversion routines
1.10 Fixes for 64-bit (don't use "unsigned long")
optimized upsampling by Fabian "ryg" Giesen
1.09 Fix format-conversion for PSD code (bad global variables!)
1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
1.07 attempt to fix C++ warning/errors again
1.06 attempt to fix C++ warning/errors again
1.05 fix TGA loading to return correct *comp and use good luminance calc
1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
1.02 support for (subset of) HDR files, float interface for preferred access to them
1.01 fix bug: possible bug in handling right-side up bmps... not sure
fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all
1.00 interface to zlib that skips zlib header
0.99 correct handling of alpha in palette
0.98 TGA loader by lonesock; dynamically add loaders (untested)
0.97 jpeg errors on too large a file; also catch another malloc failure
0.96 fix detection of invalid v value - particleman@mollyrocket forum
0.95 during header scan, seek to markers in case of padding
0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
0.93 handle jpegtran output; verbose errors
0.92 read 4,8,16,24,32-bit BMP files of several formats
0.91 output 24-bit Windows 3.0 BMP files
0.90 fix a few more warnings; bump version number to approach 1.0
0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
0.60 fix compiling as c++
0.59 fix warnings: merge Dave Moore's -Wall fixes
0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less
than 16 available
0.56 fix bug: zlib uncompressed mode len vs. nlen
0.55 fix bug: restart_interval not initialized to 0
0.54 allow NULL for 'int *comp'
0.53 fix bug in png 3->4; speedup png decoding
0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
0.51 obey req_comp requests, 1-component jpegs return as 1-component,
on 'test' only check type, not whether we support this variant
*/
#ifndef STBI_INCLUDE_STB_IMAGE_H
#define STBI_INCLUDE_STB_IMAGE_H
//// begin header file ////////////////////////////////////////////////////
//
// Limitations:
// - no progressive/interlaced support (jpeg, png)
// - 8-bit samples only (jpeg, png)
// - not threadsafe
// - channel subsampling of at most 2 in each dimension (jpeg)
// - no delayed line count (jpeg) -- IJG doesn't support either
//
// Basic usage (see HDR discussion below):
// int x,y,n;
// unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
// // ... process data if not NULL ...
// // ... x = width, y = height, n = # 8-bit components per pixel ...
// // ... replace '0' with '1'..'4' to force that many components per pixel
// stbi_image_free(data)
//
// Standard parameters:
// int *x -- outputs image width in pixels
// int *y -- outputs image height in pixels
// int *comp -- outputs # of image components in image file
// int req_comp -- if non-zero, # of image components requested in result
//
// The return value from an image loader is an 'unsigned char *' which points
// to the pixel data. The pixel data consists of *y scanlines of *x pixels,
// with each pixel consisting of N interleaved 8-bit components; the first
// pixel pointed to is top-left-most in the image. There is no padding between
// image scanlines or between pixels, regardless of format. The number of
// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
// If req_comp is non-zero, *comp has the number of components that _would_
// have been output otherwise. E.g. if you set req_comp to 4, you will always
// get RGBA output, but you can check *comp to easily see if it's opaque.
//
// An output image with N components has the following components interleaved
// in this order in each pixel:
//
// N=#comp components
// 1 grey
// 2 grey, alpha
// 3 red, green, blue
// 4 red, green, blue, alpha
//
// If image loading fails for any reason, the return value will be NULL,
// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
// can be queried for an extremely brief, end-user unfriendly explanation
// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
// more user-friendly ones.
//
// Paletted PNG and BMP images are automatically depalettized.
//
//
// ===========================================================================
//
// HDR image support (disable by defining STBI_NO_HDR)
//
// stb_image now supports loading HDR images in general, and currently
// the Radiance .HDR file format, although the support is provided
// generically. You can still load any file through the existing interface;
// if you attempt to load an HDR file, it will be automatically remapped to
// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
// both of these constants can be reconfigured through this interface:
//
// stbi_hdr_to_ldr_gamma(2.2f);
// stbi_hdr_to_ldr_scale(1.0f);
//
// (note, do not use _inverse_ constants; stbi_image will invert them
// appropriately).
//
// Additionally, there is a new, parallel interface for loading files as
// (linear) floats to preserve the full dynamic range:
//
// float *data = stbi_loadf(filename, &x, &y, &n, 0);
//
// If you load LDR images through this interface, those images will
// be promoted to floating point values, run through the inverse of
// constants corresponding to the above:
//
// stbi_ldr_to_hdr_scale(1.0f);
// stbi_ldr_to_hdr_gamma(2.2f);
//
// Finally, given a filename (or an open file or memory block--see header
// file for details) containing image data, you can query for the "most
// appropriate" interface to use (that is, whether the image is HDR or
// not), using:
//
// stbi_is_hdr(char *filename);
#ifndef STBI_NO_STDIO
#include <stdio.h>
#endif
#define STBI_VERSION 1
enum
{
STBI_default = 0, // only used for req_comp
STBI_grey = 1,
STBI_grey_alpha = 2,
STBI_rgb = 3,
STBI_rgb_alpha = 4,
};
typedef unsigned char stbi_uc;
#ifdef __cplusplus
extern "C" {
#endif
// WRITING API
#if !defined(STBI_NO_WRITE) && !defined(STBI_NO_STDIO)
// write a BMP/TGA file given tightly packed 'comp' channels (no padding, nor bmp-stride-padding)
// (you must include the appropriate extension in the filename).
// returns TRUE on success, FALSE if couldn't open file, error writing file
extern int stbi_write_bmp (char const *filename, int x, int y, int comp, void *data);
extern int stbi_write_tga (char const *filename, int x, int y, int comp, void *data);
#endif
// PRIMARY API - works on images of any type
// load image by filename, open file, or memory buffer
#ifndef STBI_NO_STDIO
extern stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
// for stbi_load_from_file, file pointer is left pointing immediately after image
#ifndef STBI_NO_HDR
#ifndef STBI_NO_STDIO
extern float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);
extern float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
extern void stbi_hdr_to_ldr_gamma(float gamma);
extern void stbi_hdr_to_ldr_scale(float scale);
extern void stbi_ldr_to_hdr_gamma(float gamma);
extern void stbi_ldr_to_hdr_scale(float scale);
#endif // STBI_NO_HDR
// get a VERY brief reason for failure
// NOT THREADSAFE
extern char *stbi_failure_reason (void);
// free the loaded image -- this is just free()
extern void stbi_image_free (void *retval_from_stbi_load);
// get image dimensions & components without fully decoding
extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
extern int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
#ifndef STBI_NO_STDIO
extern int stbi_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_is_hdr (char const *filename);
extern int stbi_is_hdr_from_file(FILE *f);
#endif
// ZLIB client - used by PNG, available for other purposes
extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
extern int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
extern int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
// TYPE-SPECIFIC ACCESS
// is it a jpeg?
extern int stbi_jpeg_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
extern int stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
#ifndef STBI_NO_STDIO
extern stbi_uc *stbi_jpeg_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern int stbi_jpeg_test_file (FILE *f);
extern stbi_uc *stbi_jpeg_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
extern int stbi_jpeg_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_jpeg_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
// is it a png?
extern int stbi_png_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_png_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
extern int stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);
#ifndef STBI_NO_STDIO
extern stbi_uc *stbi_png_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern int stbi_png_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_png_test_file (FILE *f);
extern stbi_uc *stbi_png_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
extern int stbi_png_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
// is it a bmp?
extern int stbi_bmp_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_bmp_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
extern int stbi_bmp_test_file (FILE *f);
extern stbi_uc *stbi_bmp_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
// is it a tga?
extern int stbi_tga_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_tga_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
extern int stbi_tga_test_file (FILE *f);
extern stbi_uc *stbi_tga_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
// is it a psd?
extern int stbi_psd_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_psd_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
extern int stbi_psd_test_file (FILE *f);
extern stbi_uc *stbi_psd_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
// is it an hdr?
extern int stbi_hdr_test_memory (stbi_uc const *buffer, int len);
extern float * stbi_hdr_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern float * stbi_hdr_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
extern int stbi_hdr_test_file (FILE *f);
extern float * stbi_hdr_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
// define new loaders
typedef struct
{
int (*test_memory)(stbi_uc const *buffer, int len);
stbi_uc * (*load_from_memory)(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
int (*test_file)(FILE *f);
stbi_uc * (*load_from_file)(FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
} stbi_loader;
// register a loader by filling out the above structure (you must defined ALL functions)
// returns 1 if added or already added, 0 if not added (too many loaders)
// NOT THREADSAFE
extern int stbi_register_loader(stbi_loader *loader);
// define faster low-level operations (typically SIMD support)
#if STBI_SIMD
typedef void (*stbi_idct_8x8)(uint8 *out, int out_stride, short data[64], unsigned short *dequantize);
// compute an integer IDCT on "input"
// input[x] = data[x] * dequantize[x]
// write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'
// CLAMP results to 0..255
typedef void (*stbi_YCbCr_to_RGB_run)(uint8 *output, uint8 const *y, uint8 const *cb, uint8 const *cr, int count, int step);
// compute a conversion from YCbCr to RGB
// 'count' pixels
// write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B
// y: Y input channel
// cb: Cb input channel; scale/biased to be 0..255
// cr: Cr input channel; scale/biased to be 0..255
extern void stbi_install_idct(stbi_idct_8x8 func);
extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);
#endif // STBI_SIMD
#ifdef __cplusplus
}
#endif
//
//
//// end header file /////////////////////////////////////////////////////
#endif // STBI_INCLUDE_STB_IMAGE_H
#ifndef STBI_HEADER_FILE_ONLY
#ifndef STBI_NO_HDR
#include <math.h> // ldexp
#include <string.h> // strcmp
#endif
#ifndef STBI_NO_STDIO
#include <stdio.h>
#endif
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
#include <stdarg.h>
#ifndef _MSC_VER
#ifdef __cplusplus
#define __forceinline inline
#else
#define __forceinline
#endif
#endif
// implementation:
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
typedef unsigned int uint;
// should produce compiler error if size is wrong
typedef unsigned char validate_uint32[sizeof(uint32)==4];
#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
#define STBI_NO_WRITE
#endif
//////////////////////////////////////////////////////////////////////////////
//
// Generic API that works on all image types
//
// this is not threadsafe
static char *failure_reason;
char *stbi_failure_reason(void)
{
return failure_reason;
}
static int e(char *str)
{
failure_reason = str;
return 0;
}
#ifdef STBI_NO_FAILURE_STRINGS
#define e(x,y) 0
#elif defined(STBI_FAILURE_USERMSG)
#define e(x,y) e(y)
#else
#define e(x,y) e(x)
#endif
#define epf(x,y) ((float *) (e(x,y)?NULL:NULL))
#define epuc(x,y) ((unsigned char *) (e(x,y)?NULL:NULL))
void stbi_image_free(void *retval_from_stbi_load)
{
free(retval_from_stbi_load);
}
#define MAX_LOADERS 32
stbi_loader *loaders[MAX_LOADERS];
static int max_loaders = 0;
int stbi_register_loader(stbi_loader *loader)
{
int i;
for (i=0; i < MAX_LOADERS; ++i) {
// already present?
if (loaders[i] == loader)
return 1;
// end of the list?
if (loaders[i] == NULL) {
loaders[i] = loader;
max_loaders = i+1;
return 1;
}
}
// no room for it
return 0;
}
#ifndef STBI_NO_HDR
static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp);
#endif
#ifndef STBI_NO_STDIO
unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
{
FILE *f = fopen(filename, "rb");
unsigned char *result;
if (!f) return epuc("can't fopen", "Unable to open file");
result = stbi_load_from_file(f,x,y,comp,req_comp);
fclose(f);
return result;
}
unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
int i;
if (stbi_jpeg_test_file(f))
return stbi_jpeg_load_from_file(f,x,y,comp,req_comp);
if (stbi_png_test_file(f))
return stbi_png_load_from_file(f,x,y,comp,req_comp);
if (stbi_bmp_test_file(f))
return stbi_bmp_load_from_file(f,x,y,comp,req_comp);
if (stbi_psd_test_file(f))
return stbi_psd_load_from_file(f,x,y,comp,req_comp);
#ifndef STBI_NO_HDR
if (stbi_hdr_test_file(f)) {
float *hdr = stbi_hdr_load_from_file(f, x,y,comp,req_comp);
return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
}
#endif
for (i=0; i < max_loaders; ++i)
if (loaders[i]->test_file(f))
return loaders[i]->load_from_file(f,x,y,comp,req_comp);
// test tga last because otherwist the test will not work
if (stbi_tga_test_file(f))
return stbi_tga_load_from_file(f,x,y,comp,req_comp);
return epuc("unknown image type", "Image not of any known type, or corrupt");
}
#endif
unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
int i;
if (stbi_jpeg_test_memory(buffer,len))
return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp);
if (stbi_png_test_memory(buffer,len))
return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp);
if (stbi_bmp_test_memory(buffer,len))
return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp);
if (stbi_psd_test_memory(buffer,len))
return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp);
#ifndef STBI_NO_HDR
if (stbi_hdr_test_memory(buffer, len)) {
float *hdr = stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
}
#endif
for (i=0; i < max_loaders; ++i)
if (loaders[i]->test_memory(buffer,len))
return loaders[i]->load_from_memory(buffer,len,x,y,comp,req_comp);
// test tga last because the test will not work otherwise
if (stbi_tga_test_memory(buffer,len))
return stbi_tga_load_from_memory(buffer,len,x,y,comp,req_comp);
return epuc("unknown image type", "Image not of any known type, or corrupt");
}
#ifndef STBI_NO_HDR
#ifndef STBI_NO_STDIO
float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
{
FILE *f = fopen(filename, "rb");
float *result;
if (!f) return epf("can't fopen", "Unable to open file");
result = stbi_loadf_from_file(f,x,y,comp,req_comp);
fclose(f);
return result;
}
float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
unsigned char *data;
#ifndef STBI_NO_HDR
if (stbi_hdr_test_file(f))
return stbi_hdr_load_from_file(f,x,y,comp,req_comp);
#endif
data = stbi_load_from_file(f, x, y, comp, req_comp);
if (data)
return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
return epf("unknown image type", "Image not of any known type, or corrupt");
}
#endif
float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi_uc *data;
#ifndef STBI_NO_HDR
if (stbi_hdr_test_memory(buffer, len))
return stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
#endif
data = stbi_load_from_memory(buffer, len, x, y, comp, req_comp);
if (data)
return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
return epf("unknown image type", "Image not of any known type, or corrupt");
}
#endif
// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
// defined, for API simplicity; if STBI_NO_HDR is defined, it always
// reports false!
int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
{
#ifndef STBI_NO_HDR
return stbi_hdr_test_memory(buffer, len);
#else
return 0;
#endif
}
#ifndef STBI_NO_STDIO
extern int stbi_is_hdr (char const *filename)
{
FILE *f = fopen(filename, "rb");
int result=0;
if (f) {
result = stbi_is_hdr_from_file(f);
fclose(f);
}
return result;
}
extern int stbi_is_hdr_from_file(FILE *f)
{
#ifndef STBI_NO_HDR
return stbi_hdr_test_file(f);
#else
return 0;
#endif
}
#endif
// @TODO: get image dimensions & components without fully decoding
#ifndef STBI_NO_STDIO
extern int stbi_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
#ifndef STBI_NO_HDR
static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
static float l2h_gamma=2.2f, l2h_scale=1.0f;
void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
#endif
//////////////////////////////////////////////////////////////////////////////
//
// Common code used by all image loaders
//
enum
{
SCAN_load=0,
SCAN_type,
SCAN_header,
};
typedef struct
{
uint32 img_x, img_y;
int img_n, img_out_n;
#ifndef STBI_NO_STDIO
FILE *img_file;
#endif
uint8 *img_buffer, *img_buffer_end;
} stbi;
#ifndef STBI_NO_STDIO
static void start_file(stbi *s, FILE *f)
{
s->img_file = f;
}
#endif
static void start_mem(stbi *s, uint8 const *buffer, int len)
{
#ifndef STBI_NO_STDIO
s->img_file = NULL;
#endif
s->img_buffer = (uint8 *) buffer;
s->img_buffer_end = (uint8 *) buffer+len;
}
__forceinline static int get8(stbi *s)
{
#ifndef STBI_NO_STDIO
if (s->img_file) {
int c = fgetc(s->img_file);
return c == EOF ? 0 : c;
}
#endif
if (s->img_buffer < s->img_buffer_end)
return *s->img_buffer++;
return 0;
}
__forceinline static int at_eof(stbi *s)
{
#ifndef STBI_NO_STDIO
if (s->img_file)
return feof(s->img_file);
#endif
return s->img_buffer >= s->img_buffer_end;
}
__forceinline static uint8 get8u(stbi *s)
{
return (uint8) get8(s);
}
static void skip(stbi *s, int n)
{
#ifndef STBI_NO_STDIO
if (s->img_file)
fseek(s->img_file, n, SEEK_CUR);
else
#endif
s->img_buffer += n;
}
static int get16(stbi *s)
{
int z = get8(s);
return (z << 8) + get8(s);
}
static uint32 get32(stbi *s)
{
uint32 z = get16(s);
return (z << 16) + get16(s);
}
static int get16le(stbi *s)
{
int z = get8(s);
return z + (get8(s) << 8);
}
static uint32 get32le(stbi *s)
{
uint32 z = get16le(s);
return z + (get16le(s) << 16);
}
static void getn(stbi *s, stbi_uc *buffer, int n)
{
#ifndef STBI_NO_STDIO
if (s->img_file) {
fread(buffer, 1, n, s->img_file);
return;
}
#endif
memcpy(buffer, s->img_buffer, n);
s->img_buffer += n;
}
//////////////////////////////////////////////////////////////////////////////
//
// generic converter from built-in img_n to req_comp
// individual types do this automatically as much as possible (e.g. jpeg
// does all cases internally since it needs to colorspace convert anyway,
// and it never has alpha, so very few cases ). png can automatically
// interleave an alpha=255 channel, but falls back to this for other cases
//
// assume data buffer is malloced, so malloc a new one and free that one
// only failure mode is malloc failing
static uint8 compute_y(int r, int g, int b)
{
return (uint8) (((r*77) + (g*150) + (29*b)) >> 8);
}
static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)
{
int i,j;
unsigned char *good;
if (req_comp == img_n) return data;
assert(req_comp >= 1 && req_comp <= 4);
good = (unsigned char *) malloc(req_comp * x * y);
if (good == NULL) {
free(data);
return epuc("outofmem", "Out of memory");
}
for (j=0; j < (int) y; ++j) {
unsigned char *src = data + j * x * img_n ;
unsigned char *dest = good + j * x * req_comp;
#define COMBO(a,b) ((a)*8+(b))
#define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
// convert source image with img_n components to one with req_comp components;
// avoid switch per pixel, so use switch per scanline and massive macros
switch(COMBO(img_n, req_comp)) {
CASE(1,2) dest[0]=src[0], dest[1]=255; break;
CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
CASE(2,1) dest[0]=src[0]; break;
CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
default: assert(0);
}
#undef CASE
}
free(data);
return good;
}
#ifndef STBI_NO_HDR
static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
{
int i,k,n;
float *output = (float *) malloc(x * y * comp * sizeof(float));
if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }
// compute number of non-alpha components
if (comp & 1) n = comp; else n = comp-1;
for (i=0; i < x*y; ++i) {
for (k=0; k < n; ++k) {
output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;
}
if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
}
free(data);
return output;
}
#define float2int(x) ((int) (x))
static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp)
{
int i,k,n;
stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }
// compute number of non-alpha components
if (comp & 1) n = comp; else n = comp-1;
for (i=0; i < x*y; ++i) {
for (k=0; k < n; ++k) {
float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
if (z < 0) z = 0;
if (z > 255) z = 255;
output[i*comp + k] = float2int(z);
}
if (k < comp) {
float z = data[i*comp+k] * 255 + 0.5f;
if (z < 0) z = 0;
if (z > 255) z = 255;
output[i*comp + k] = float2int(z);
}
}
free(data);
return output;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//
// "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
//
// simple implementation
// - channel subsampling of at most 2 in each dimension
// - doesn't support delayed output of y-dimension
// - simple interface (only one output format: 8-bit interleaved RGB)
// - doesn't try to recover corrupt jpegs
// - doesn't allow partial loading, loading multiple at once
// - still fast on x86 (copying globals into locals doesn't help x86)
// - allocates lots of intermediate memory (full size of all components)
// - non-interleaved case requires this anyway
// - allows good upsampling (see next)
// high-quality
// - upsampled channels are bilinearly interpolated, even across blocks
// - quality integer IDCT derived from IJG's 'slow'
// performance
// - fast huffman; reasonable integer IDCT
// - uses a lot of intermediate memory, could cache poorly
// - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
// stb_jpeg: 1.34 seconds (MSVC6, default release build)
// stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)
// IJL11.dll: 1.08 seconds (compiled by intel)
// IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)
// IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)
// huffman decoding acceleration
#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
typedef struct
{
uint8 fast[1 << FAST_BITS];
// weirdly, repacking this into AoS is a 10% speed loss, instead of a win
uint16 code[256];
uint8 values[256];
uint8 size[257];
unsigned int maxcode[18];
int delta[17]; // old 'firstsymbol' - old 'firstcode'
} huffman;
typedef struct
{
#if STBI_SIMD
unsigned short dequant2[4][64];
#endif
stbi s;
huffman huff_dc[4];
huffman huff_ac[4];
uint8 dequant[4][64];
// sizes for components, interleaved MCUs
int img_h_max, img_v_max;
int img_mcu_x, img_mcu_y;
int img_mcu_w, img_mcu_h;
// definition of jpeg image component
struct
{
int id;
int h,v;
int tq;
int hd,ha;
int dc_pred;
int x,y,w2,h2;
uint8 *data;
void *raw_data;
uint8 *linebuf;
} img_comp[4];
uint32 code_buffer; // jpeg entropy-coded buffer
int code_bits; // number of valid bits
unsigned char marker; // marker seen while filling entropy buffer
int nomore; // flag if we saw a marker so must stop
int scan_n, order[4];
int restart_interval, todo;
} jpeg;
static int build_huffman(huffman *h, int *count)
{
int i,j,k=0,code;
// build size list for each symbol (from JPEG spec)
for (i=0; i < 16; ++i)
for (j=0; j < count[i]; ++j)
h->size[k++] = (uint8) (i+1);
h->size[k] = 0;
// compute actual symbols (from jpeg spec)
code = 0;
k = 0;
for(j=1; j <= 16; ++j) {
// compute delta to add to code to compute symbol id
h->delta[j] = k - code;
if (h->size[k] == j) {
while (h->size[k] == j)
h->code[k++] = (uint16) (code++);
if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");
}
// compute largest code + 1 for this size, preshifted as needed later
h->maxcode[j] = code << (16-j);
code <<= 1;
}
h->maxcode[j] = 0xffffffff;
// build non-spec acceleration table; 255 is flag for not-accelerated
memset(h->fast, 255, 1 << FAST_BITS);
for (i=0; i < k; ++i) {
int s = h->size[i];
if (s <= FAST_BITS) {
int c = h->code[i] << (FAST_BITS-s);
int m = 1 << (FAST_BITS-s);
for (j=0; j < m; ++j) {
h->fast[c+j] = (uint8) i;
}
}
}
return 1;
}
static void grow_buffer_unsafe(jpeg *j)
{
do {
int b = j->nomore ? 0 : get8(&j->s);
if (b == 0xff) {
int c = get8(&j->s);
if (c != 0) {
j->marker = (unsigned char) c;
j->nomore = 1;
return;
}
}
j->code_buffer = (j->code_buffer << 8) | b;
j->code_bits += 8;
} while (j->code_bits <= 24);
}
// (1 << n) - 1
static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
// decode a jpeg huffman value from the bitstream
__forceinline static int decode(jpeg *j, huffman *h)
{
unsigned int temp;
int c,k;
if (j->code_bits < 16) grow_buffer_unsafe(j);
// look at the top FAST_BITS and determine what symbol ID it is,
// if the code is <= FAST_BITS
c = (j->code_buffer >> (j->code_bits - FAST_BITS)) & ((1 << FAST_BITS)-1);
k = h->fast[c];
if (k < 255) {
if (h->size[k] > j->code_bits)
return -1;
j->code_bits -= h->size[k];
return h->values[k];
}
// naive test is to shift the code_buffer down so k bits are
// valid, then test against maxcode. To speed this up, we've
// preshifted maxcode left so that it has (16-k) 0s at the
// end; in other words, regardless of the number of bits, it
// wants to be compared against something shifted to have 16;
// that way we don't need to shift inside the loop.
if (j->code_bits < 16)
temp = (j->code_buffer << (16 - j->code_bits)) & 0xffff;
else
temp = (j->code_buffer >> (j->code_bits - 16)) & 0xffff;
for (k=FAST_BITS+1 ; ; ++k)
if (temp < h->maxcode[k])
break;
if (k == 17) {
// error! code not found
j->code_bits -= 16;
return -1;
}
if (k > j->code_bits)
return -1;
// convert the huffman code to the symbol id
c = ((j->code_buffer >> (j->code_bits - k)) & bmask[k]) + h->delta[k];
assert((((j->code_buffer) >> (j->code_bits - h->size[c])) & bmask[h->size[c]]) == h->code[c]);
// convert the id to a symbol
j->code_bits -= k;
return h->values[c];
}
// combined JPEG 'receive' and JPEG 'extend', since baseline
// always extends everything it receives.
__forceinline static int extend_receive(jpeg *j, int n)
{
unsigned int m = 1 << (n-1);
unsigned int k;
if (j->code_bits < n) grow_buffer_unsafe(j);
k = (j->code_buffer >> (j->code_bits - n)) & bmask[n];
j->code_bits -= n;
// the following test is probably a random branch that won't
// predict well. I tried to table accelerate it but failed.
// maybe it's compiling as a conditional move?
if (k < m)
return (-1 << n) + k + 1;
else
return k;
}
// given a value that's at position X in the zigzag stream,
// where does it appear in the 8x8 matrix coded as row-major?
static uint8 dezigzag[64+15] =
{
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63,
// let corrupt input sample past end
63, 63, 63, 63, 63, 63, 63, 63,
63, 63, 63, 63, 63, 63, 63
};
// decode one 64-entry block--
static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)
{
int diff,dc,k;
int t = decode(j, hdc);
if (t < 0) return e("bad huffman code","Corrupt JPEG");
// 0 all the ac values now so we can do it 32-bits at a time
memset(data,0,64*sizeof(data[0]));
diff = t ? extend_receive(j, t) : 0;
dc = j->img_comp[b].dc_pred + diff;
j->img_comp[b].dc_pred = dc;
data[0] = (short) dc;
// decode AC components, see JPEG spec
k = 1;
do {
int r,s;
int rs = decode(j, hac);
if (rs < 0) return e("bad huffman code","Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0) {
if (rs != 0xf0) break; // end block
k += 16;
} else {
k += r;
// decode into unzigzag'd location
data[dezigzag[k++]] = (short) extend_receive(j,s);
}
} while (k < 64);
return 1;
}
// take a -128..127 value and clamp it and convert to 0..255
__forceinline static uint8 clamp(int x)
{
x += 128;
// trick to use a single test to catch both cases
if ((unsigned int) x > 255) {
if (x < 0) return 0;
if (x > 255) return 255;
}
return (uint8) x;
}
#define f2f(x) (int) (((x) * 4096 + 0.5))
#define fsh(x) ((x) << 12)
// derived from jidctint -- DCT_ISLOW
#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
p2 = s2; \
p3 = s6; \
p1 = (p2+p3) * f2f(0.5411961f); \
t2 = p1 + p3*f2f(-1.847759065f); \
t3 = p1 + p2*f2f( 0.765366865f); \
p2 = s0; \
p3 = s4; \
t0 = fsh(p2+p3); \
t1 = fsh(p2-p3); \
x0 = t0+t3; \
x3 = t0-t3; \
x1 = t1+t2; \
x2 = t1-t2; \
t0 = s7; \
t1 = s5; \
t2 = s3; \
t3 = s1; \
p3 = t0+t2; \
p4 = t1+t3; \
p1 = t0+t3; \
p2 = t1+t2; \
p5 = (p3+p4)*f2f( 1.175875602f); \
t0 = t0*f2f( 0.298631336f); \
t1 = t1*f2f( 2.053119869f); \
t2 = t2*f2f( 3.072711026f); \
t3 = t3*f2f( 1.501321110f); \
p1 = p5 + p1*f2f(-0.899976223f); \
p2 = p5 + p2*f2f(-2.562915447f); \
p3 = p3*f2f(-1.961570560f); \
p4 = p4*f2f(-0.390180644f); \
t3 += p1+p4; \
t2 += p2+p3; \
t1 += p2+p4; \
t0 += p1+p3;
#if !STBI_SIMD
// .344 seconds on 3*anemones.jpg
static void idct_block(uint8 *out, int out_stride, short data[64], uint8 *dequantize)
{
int i,val[64],*v=val;
uint8 *o,*dq = dequantize;
short *d = data;
// columns
for (i=0; i < 8; ++i,++d,++dq, ++v) {
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
&& d[40]==0 && d[48]==0 && d[56]==0) {
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * dq[0] << 2;
v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
} else {
IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
// constants scaled things up by 1<<12; let's bring them back
// down, but keep 2 extra bits of precision
x0 += 512; x1 += 512; x2 += 512; x3 += 512;
v[ 0] = (x0+t3) >> 10;
v[56] = (x0-t3) >> 10;
v[ 8] = (x1+t2) >> 10;
v[48] = (x1-t2) >> 10;
v[16] = (x2+t1) >> 10;
v[40] = (x2-t1) >> 10;
v[24] = (x3+t0) >> 10;
v[32] = (x3-t0) >> 10;
}
}
for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
// no fast case since the first 1D IDCT spread components out
IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
// constants scaled things up by 1<<12, plus we had 1<<2 from first
// loop, plus horizontal and vertical each scale by sqrt(8) so together
// we've got an extra 1<<3, so 1<<17 total we need to remove.
x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;
o[0] = clamp((x0+t3) >> 17);
o[7] = clamp((x0-t3) >> 17);
o[1] = clamp((x1+t2) >> 17);
o[6] = clamp((x1-t2) >> 17);
o[2] = clamp((x2+t1) >> 17);
o[5] = clamp((x2-t1) >> 17);
o[3] = clamp((x3+t0) >> 17);
o[4] = clamp((x3-t0) >> 17);
}
}
#else
static void idct_block(uint8 *out, int out_stride, short data[64], unsigned short *dequantize)
{
int i,val[64],*v=val;
uint8 *o;
unsigned short *dq = dequantize;
short *d = data;
// columns
for (i=0; i < 8; ++i,++d,++dq, ++v) {
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
&& d[40]==0 && d[48]==0 && d[56]==0) {
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * dq[0] << 2;
v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
} else {
IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
// constants scaled things up by 1<<12; let's bring them back
// down, but keep 2 extra bits of precision
x0 += 512; x1 += 512; x2 += 512; x3 += 512;
v[ 0] = (x0+t3) >> 10;
v[56] = (x0-t3) >> 10;
v[ 8] = (x1+t2) >> 10;
v[48] = (x1-t2) >> 10;
v[16] = (x2+t1) >> 10;
v[40] = (x2-t1) >> 10;
v[24] = (x3+t0) >> 10;
v[32] = (x3-t0) >> 10;
}
}
for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
// no fast case since the first 1D IDCT spread components out
IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
// constants scaled things up by 1<<12, plus we had 1<<2 from first
// loop, plus horizontal and vertical each scale by sqrt(8) so together
// we've got an extra 1<<3, so 1<<17 total we need to remove.
x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;
o[0] = clamp((x0+t3) >> 17);
o[7] = clamp((x0-t3) >> 17);
o[1] = clamp((x1+t2) >> 17);
o[6] = clamp((x1-t2) >> 17);
o[2] = clamp((x2+t1) >> 17);
o[5] = clamp((x2-t1) >> 17);
o[3] = clamp((x3+t0) >> 17);
o[4] = clamp((x3-t0) >> 17);
}
}
static stbi_idct_8x8 stbi_idct_installed = idct_block;
extern void stbi_install_idct(stbi_idct_8x8 func)
{
stbi_idct_installed = func;
}
#endif
#define MARKER_none 0xff
// if there's a pending marker from the entropy stream, return that
// otherwise, fetch from the stream and get a marker. if there's no
// marker, return 0xff, which is never a valid marker value
static uint8 get_marker(jpeg *j)
{
uint8 x;
if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }
x = get8u(&j->s);
if (x != 0xff) return MARKER_none;
while (x == 0xff)
x = get8u(&j->s);
return x;
}
// in each scan, we'll have scan_n components, and the order
// of the components is specified by order[]
#define RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
// after a restart interval, reset the entropy decoder and
// the dc prediction
static void reset(jpeg *j)
{
j->code_bits = 0;
j->code_buffer = 0;
j->nomore = 0;
j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
j->marker = MARKER_none;
j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
// no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
// since we don't even allow 1<<30 pixels
}
static int parse_entropy_coded_data(jpeg *z)
{
reset(z);
if (z->scan_n == 1) {
int i,j;
#if STBI_SIMD
__declspec(align(16))
#endif
short data[64];
int n = z->order[0];
// non-interleaved data, we just need to process one block at a time,
// in trivial scanline order
// number of blocks to do just depends on how many actual "pixels" this
// component has, independent of interleaved MCU blocking and such
int w = (z->img_comp[n].x+7) >> 3;
int h = (z->img_comp[n].y+7) >> 3;
for (j=0; j < h; ++j) {
for (i=0; i < w; ++i) {
if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
#if STBI_SIMD
stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
#else
idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
#endif
// every data block is an MCU, so countdown the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) grow_buffer_unsafe(z);
// if it's NOT a restart, then just bail, so we get corrupt data
// rather than no data
if (!RESTART(z->marker)) return 1;
reset(z);
}
}
}
} else { // interleaved!
int i,j,k,x,y;
short data[64];
for (j=0; j < z->img_mcu_y; ++j) {
for (i=0; i < z->img_mcu_x; ++i) {
// scan an interleaved mcu... process scan_n components in order
for (k=0; k < z->scan_n; ++k) {
int n = z->order[k];
// scan out an mcu's worth of this component; that's just determined
// by the basic H and V specified for the component
for (y=0; y < z->img_comp[n].v; ++y) {
for (x=0; x < z->img_comp[n].h; ++x) {
int x2 = (i*z->img_comp[n].h + x)*8;
int y2 = (j*z->img_comp[n].v + y)*8;
if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
#if STBI_SIMD
stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
#else
idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
#endif
}
}
}
// after all interleaved components, that's an interleaved MCU,
// so now count down the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) grow_buffer_unsafe(z);
// if it's NOT a restart, then just bail, so we get corrupt data
// rather than no data
if (!RESTART(z->marker)) return 1;
reset(z);
}
}
}
}
return 1;
}
static int process_marker(jpeg *z, int m)
{
int L;
switch (m) {
case MARKER_none: // no marker found
return e("expected marker","Corrupt JPEG");
case 0xC2: // SOF - progressive
return e("progressive jpeg","JPEG format not supported (progressive)");
case 0xDD: // DRI - specify restart interval
if (get16(&z->s) != 4) return e("bad DRI len","Corrupt JPEG");
z->restart_interval = get16(&z->s);
return 1;
case 0xDB: // DQT - define quantization table
L = get16(&z->s)-2;
while (L > 0) {
int q = get8(&z->s);
int p = q >> 4;
int t = q & 15,i;
if (p != 0) return e("bad DQT type","Corrupt JPEG");
if (t > 3) return e("bad DQT table","Corrupt JPEG");
for (i=0; i < 64; ++i)
z->dequant[t][dezigzag[i]] = get8u(&z->s);
#if STBI_SIMD
for (i=0; i < 64; ++i)
z->dequant2[t][i] = z->dequant[t][i];
#endif
L -= 65;
}
return L==0;
case 0xC4: // DHT - define huffman table
L = get16(&z->s)-2;
while (L > 0) {
uint8 *v;
int sizes[16],i,m=0;
int q = get8(&z->s);
int tc = q >> 4;
int th = q & 15;
if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");
for (i=0; i < 16; ++i) {
sizes[i] = get8(&z->s);
m += sizes[i];
}
L -= 17;
if (tc == 0) {
if (!build_huffman(z->huff_dc+th, sizes)) return 0;
v = z->huff_dc[th].values;
} else {
if (!build_huffman(z->huff_ac+th, sizes)) return 0;
v = z->huff_ac[th].values;
}
for (i=0; i < m; ++i)
v[i] = get8u(&z->s);
L -= m;
}
return L==0;
}
// check for comment block or APP blocks
if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
skip(&z->s, get16(&z->s)-2);
return 1;
}
return 0;
}
// after we see SOS
static int process_scan_header(jpeg *z)
{
int i;
int Ls = get16(&z->s);
z->scan_n = get8(&z->s);
if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s.img_n) return e("bad SOS component count","Corrupt JPEG");
if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG");
for (i=0; i < z->scan_n; ++i) {
int id = get8(&z->s), which;
int q = get8(&z->s);
for (which = 0; which < z->s.img_n; ++which)
if (z->img_comp[which].id == id)
break;
if (which == z->s.img_n) return 0;
z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");
z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");
z->order[i] = which;
}
if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG");
get8(&z->s); // should be 63, but might be 0
if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG");
return 1;
}
static int process_frame_header(jpeg *z, int scan)
{
stbi *s = &z->s;
int Lf,p,i,q, h_max=1,v_max=1,c;
Lf = get16(s); if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG
p = get8(s); if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
s->img_y = get16(s); if (s->img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
s->img_x = get16(s); if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires
c = get8(s);
if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG"); // JFIF requires
s->img_n = c;
for (i=0; i < c; ++i) {
z->img_comp[i].data = NULL;
z->img_comp[i].linebuf = NULL;
}
if (Lf != 8+3*s->img_n) return e("bad SOF len","Corrupt JPEG");
for (i=0; i < s->img_n; ++i) {
z->img_comp[i].id = get8(s);
if (z->img_comp[i].id != i+1) // JFIF requires
if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files!
return e("bad component ID","Corrupt JPEG");
q = get8(s);
z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e("bad H","Corrupt JPEG");
z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e("bad V","Corrupt JPEG");
z->img_comp[i].tq = get8(s); if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");
}
if (scan != SCAN_load) return 1;
if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");
for (i=0; i < s->img_n; ++i) {
if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
}
// compute interleaved mcu info
z->img_h_max = h_max;
z->img_v_max = v_max;
z->img_mcu_w = h_max * 8;
z->img_mcu_h = v_max * 8;
z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
for (i=0; i < s->img_n; ++i) {
// number of effective pixels (e.g. for non-interleaved MCU)
z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
// to simplify generation, we'll allocate enough memory to decode
// the bogus oversized data from using interleaved MCUs and their
// big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
// discard the extra data until colorspace conversion
z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
if (z->img_comp[i].raw_data == NULL) {
for(--i; i >= 0; --i) {
free(z->img_comp[i].raw_data);
z->img_comp[i].data = NULL;
}
return e("outofmem", "Out of memory");
}
// align blocks for installable-idct using mmx/sse
z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
z->img_comp[i].linebuf = NULL;
}
return 1;
}
// use comparisons since in some cases we handle more than one case (e.g. SOF)
#define DNL(x) ((x) == 0xdc)
#define SOI(x) ((x) == 0xd8)
#define EOI(x) ((x) == 0xd9)
#define SOF(x) ((x) == 0xc0 || (x) == 0xc1)
#define SOS(x) ((x) == 0xda)
static int decode_jpeg_header(jpeg *z, int scan)
{
int m;
z->marker = MARKER_none; // initialize cached marker to empty
m = get_marker(z);
if (!SOI(m)) return e("no SOI","Corrupt JPEG");
if (scan == SCAN_type) return 1;
m = get_marker(z);
while (!SOF(m)) {
if (!process_marker(z,m)) return 0;
m = get_marker(z);
while (m == MARKER_none) {
// some files have extra padding after their blocks, so ok, we'll scan
if (at_eof(&z->s)) return e("no SOF", "Corrupt JPEG");
m = get_marker(z);
}
}
if (!process_frame_header(z, scan)) return 0;
return 1;
}
static int decode_jpeg_image(jpeg *j)
{
int m;
j->restart_interval = 0;
if (!decode_jpeg_header(j, SCAN_load)) return 0;
m = get_marker(j);
while (!EOI(m)) {
if (SOS(m)) {
if (!process_scan_header(j)) return 0;
if (!parse_entropy_coded_data(j)) return 0;
} else {
if (!process_marker(j, m)) return 0;
}
m = get_marker(j);
}
return 1;
}
// static jfif-centered resampling (across block boundaries)
typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1,
int w, int hs);
#define div4(x) ((uint8) ((x) >> 2))
static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
return in_near;
}
static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
// need to generate two samples vertically for every one in input
int i;
for (i=0; i < w; ++i)
out[i] = div4(3*in_near[i] + in_far[i] + 2);
return out;
}
static uint8* resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
// need to generate two samples horizontally for every one in input
int i;
uint8 *input = in_near;
if (w == 1) {
// if only one sample, can't do any interpolation
out[0] = out[1] = input[0];
return out;
}
out[0] = input[0];
out[1] = div4(input[0]*3 + input[1] + 2);
for (i=1; i < w-1; ++i) {
int n = 3*input[i]+2;
out[i*2+0] = div4(n+input[i-1]);
out[i*2+1] = div4(n+input[i+1]);
}
out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2);
out[i*2+1] = input[w-1];
return out;
}
#define div16(x) ((uint8) ((x) >> 4))
static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
// need to generate 2x2 samples for every one in input
int i,t0,t1;
if (w == 1) {
out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2);
return out;
}
t1 = 3*in_near[0] + in_far[0];
out[0] = div4(t1+2);
for (i=1; i < w; ++i) {
t0 = t1;
t1 = 3*in_near[i]+in_far[i];
out[i*2-1] = div16(3*t0 + t1 + 8);
out[i*2 ] = div16(3*t1 + t0 + 8);
}
out[w*2-1] = div4(t1+2);
return out;
}
static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
// resample with nearest-neighbor
int i,j;
for (i=0; i < w; ++i)
for (j=0; j < hs; ++j)
out[i*hs+j] = in_near[i];
return out;
}
#define float2fixed(x) ((int) ((x) * 65536 + 0.5))
// 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro)
// VC6 without processor=Pro is generating multiple LEAs per multiply!
static void YCbCr_to_RGB_row(uint8 *out, const uint8 *y, const uint8 *pcb, const uint8 *pcr, int count, int step)
{
int i;
for (i=0; i < count; ++i) {
int y_fixed = (y[i] << 16) + 32768; // rounding
int r,g,b;
int cr = pcr[i] - 128;
int cb = pcb[i] - 128;
r = y_fixed + cr*float2fixed(1.40200f);
g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
b = y_fixed + cb*float2fixed(1.77200f);
r >>= 16;
g >>= 16;
b >>= 16;
if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
out[0] = (uint8)r;
out[1] = (uint8)g;
out[2] = (uint8)b;
out[3] = 255;
out += step;
}
}
#if STBI_SIMD
static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;
void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)
{
stbi_YCbCr_installed = func;
}
#endif
// clean up the temporary component buffers
static void cleanup_jpeg(jpeg *j)
{
int i;
for (i=0; i < j->s.img_n; ++i) {
if (j->img_comp[i].data) {
free(j->img_comp[i].raw_data);
j->img_comp[i].data = NULL;
}
if (j->img_comp[i].linebuf) {
free(j->img_comp[i].linebuf);
j->img_comp[i].linebuf = NULL;
}
}
}
typedef struct
{
resample_row_func resample;
uint8 *line0,*line1;
int hs,vs; // expansion factor in each axis
int w_lores; // horizontal pixels pre-expansion
int ystep; // how far through vertical expansion we are
int ypos; // which pre-expansion row we're on
} stbi_resample;
static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
{
int n, decode_n;
// validate req_comp
if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
z->s.img_n = 0;
// load a jpeg image from whichever source
if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }
// determine actual number of components to generate
n = req_comp ? req_comp : z->s.img_n;
if (z->s.img_n == 3 && n < 3)
decode_n = 1;
else
decode_n = z->s.img_n;
// resample and color-convert
{
int k;
uint i,j;
uint8 *output;
uint8 *coutput[4];
stbi_resample res_comp[4];
for (k=0; k < decode_n; ++k) {
stbi_resample *r = &res_comp[k];
// allocate line buffer big enough for upsampling off the edges
// with upsample factor of 4
z->img_comp[k].linebuf = (uint8 *) malloc(z->s.img_x + 3);
if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }
r->hs = z->img_h_max / z->img_comp[k].h;
r->vs = z->img_v_max / z->img_comp[k].v;
r->ystep = r->vs >> 1;
r->w_lores = (z->s.img_x + r->hs-1) / r->hs;
r->ypos = 0;
r->line0 = r->line1 = z->img_comp[k].data;
if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2;
else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;
else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;
else r->resample = resample_row_generic;
}
// can't error after this so, this is safe
output = (uint8 *) malloc(n * z->s.img_x * z->s.img_y + 1);
if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }
// now go ahead and resample
for (j=0; j < z->s.img_y; ++j) {
uint8 *out = output + n * z->s.img_x * j;
for (k=0; k < decode_n; ++k) {
stbi_resample *r = &res_comp[k];
int y_bot = r->ystep >= (r->vs >> 1);
coutput[k] = r->resample(z->img_comp[k].linebuf,
y_bot ? r->line1 : r->line0,
y_bot ? r->line0 : r->line1,
r->w_lores, r->hs);
if (++r->ystep >= r->vs) {
r->ystep = 0;
r->line0 = r->line1;
if (++r->ypos < z->img_comp[k].y)
r->line1 += z->img_comp[k].w2;
}
}
if (n >= 3) {
uint8 *y = coutput[0];
if (z->s.img_n == 3) {
#if STBI_SIMD
stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n);
#else
YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s.img_x, n);
#endif
} else
for (i=0; i < z->s.img_x; ++i) {
out[0] = out[1] = out[2] = y[i];
out[3] = 255; // not used if n==3
out += n;
}
} else {
uint8 *y = coutput[0];
if (n == 1)
for (i=0; i < z->s.img_x; ++i) out[i] = y[i];
else
for (i=0; i < z->s.img_x; ++i) *out++ = y[i], *out++ = 255;
}
}
cleanup_jpeg(z);
*out_x = z->s.img_x;
*out_y = z->s.img_y;
if (comp) *comp = z->s.img_n; // report original components, not output
return output;
}
}
#ifndef STBI_NO_STDIO
unsigned char *stbi_jpeg_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
jpeg j;
start_file(&j.s, f);
return load_jpeg_image(&j, x,y,comp,req_comp);
}
unsigned char *stbi_jpeg_load(char const *filename, int *x, int *y, int *comp, int req_comp)
{
unsigned char *data;
FILE *f = fopen(filename, "rb");
if (!f) return NULL;
data = stbi_jpeg_load_from_file(f,x,y,comp,req_comp);
fclose(f);
return data;
}
#endif
unsigned char *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
jpeg j;
start_mem(&j.s, buffer,len);
return load_jpeg_image(&j, x,y,comp,req_comp);
}
#ifndef STBI_NO_STDIO
int stbi_jpeg_test_file(FILE *f)
{
int n,r;
jpeg j;
n = ftell(f);
start_file(&j.s, f);
r = decode_jpeg_header(&j, SCAN_type);
fseek(f,n,SEEK_SET);
return r;
}
#endif
int stbi_jpeg_test_memory(stbi_uc const *buffer, int len)
{
jpeg j;
start_mem(&j.s, buffer,len);
return decode_jpeg_header(&j, SCAN_type);
}
// @TODO:
#ifndef STBI_NO_STDIO
extern int stbi_jpeg_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_jpeg_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
extern int stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
// public domain zlib decode v0.2 Sean Barrett 2006-11-18
// simple implementation
// - all input must be provided in an upfront buffer
// - all output is written to a single output buffer (can malloc/realloc)
// performance
// - fast huffman
// fast-way is faster to check than jpeg huffman, but slow way is slower
#define ZFAST_BITS 9 // accelerate all cases in default tables
#define ZFAST_MASK ((1 << ZFAST_BITS) - 1)
// zlib-style huffman encoding
// (jpegs packs from left, zlib from right, so can't share code)
typedef struct
{
uint16 fast[1 << ZFAST_BITS];
uint16 firstcode[16];
int maxcode[17];
uint16 firstsymbol[16];
uint8 size[288];
uint16 value[288];
} zhuffman;
__forceinline static int bitreverse16(int n)
{
n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
return n;
}
__forceinline static int bit_reverse(int v, int bits)
{
assert(bits <= 16);
// to bit reverse n bits, reverse 16 and shift
// e.g. 11 bits, bit reverse and shift away 5
return bitreverse16(v) >> (16-bits);
}
static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)
{
int i,k=0;
int code, next_code[16], sizes[17];
// DEFLATE spec for generating codes
memset(sizes, 0, sizeof(sizes));
memset(z->fast, 255, sizeof(z->fast));
for (i=0; i < num; ++i)
++sizes[sizelist[i]];
sizes[0] = 0;
for (i=1; i < 16; ++i)
assert(sizes[i] <= (1 << i));
code = 0;
for (i=1; i < 16; ++i) {
next_code[i] = code;
z->firstcode[i] = (uint16) code;
z->firstsymbol[i] = (uint16) k;
code = (code + sizes[i]);
if (sizes[i])
if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");
z->maxcode[i] = code << (16-i); // preshift for inner loop
code <<= 1;
k += sizes[i];
}
z->maxcode[16] = 0x10000; // sentinel
for (i=0; i < num; ++i) {
int s = sizelist[i];
if (s) {
int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
z->size[c] = (uint8)s;
z->value[c] = (uint16)i;
if (s <= ZFAST_BITS) {
int k = bit_reverse(next_code[s],s);
while (k < (1 << ZFAST_BITS)) {
z->fast[k] = (uint16) c;
k += (1 << s);
}
}
++next_code[s];
}
}
return 1;
}
// zlib-from-memory implementation for PNG reading
// because PNG allows splitting the zlib stream arbitrarily,
// and it's annoying structurally to have PNG call ZLIB call PNG,
// we require PNG read all the IDATs and combine them into a single
// memory buffer
typedef struct
{
uint8 *zbuffer, *zbuffer_end;
int num_bits;
uint32 code_buffer;
char *zout;
char *zout_start;
char *zout_end;
int z_expandable;
zhuffman z_length, z_distance;
} zbuf;
__forceinline static int zget8(zbuf *z)
{
if (z->zbuffer >= z->zbuffer_end) return 0;
return *z->zbuffer++;
}
static void fill_bits(zbuf *z)
{
do {
assert(z->code_buffer < (1U << z->num_bits));
z->code_buffer |= zget8(z) << z->num_bits;
z->num_bits += 8;
} while (z->num_bits <= 24);
}
__forceinline static unsigned int zreceive(zbuf *z, int n)
{
unsigned int k;
if (z->num_bits < n) fill_bits(z);
k = z->code_buffer & ((1 << n) - 1);
z->code_buffer >>= n;
z->num_bits -= n;
return k;
}
__forceinline static int zhuffman_decode(zbuf *a, zhuffman *z)
{
int b,s,k;
if (a->num_bits < 16) fill_bits(a);
b = z->fast[a->code_buffer & ZFAST_MASK];
if (b < 0xffff) {
s = z->size[b];
a->code_buffer >>= s;
a->num_bits -= s;
return z->value[b];
}
// not resolved by fast table, so compute it the slow way
// use jpeg approach, which requires MSbits at top
k = bit_reverse(a->code_buffer, 16);
for (s=ZFAST_BITS+1; ; ++s)
if (k < z->maxcode[s])
break;
if (s == 16) return -1; // invalid code!
// code size is s, so:
b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
assert(z->size[b] == s);
a->code_buffer >>= s;
a->num_bits -= s;
return z->value[b];
}
static int expand(zbuf *z, int n) // need to make room for n bytes
{
char *q;
int cur, limit;
if (!z->z_expandable) return e("output buffer limit","Corrupt PNG");
cur = (int) (z->zout - z->zout_start);
limit = (int) (z->zout_end - z->zout_start);
while (cur + n > limit)
limit *= 2;
q = (char *) realloc(z->zout_start, limit);
if (q == NULL) return e("outofmem", "Out of memory");
z->zout_start = q;
z->zout = q + cur;
z->zout_end = q + limit;
return 1;
}
static int length_base[31] = {
3,4,5,6,7,8,9,10,11,13,
15,17,19,23,27,31,35,43,51,59,
67,83,99,115,131,163,195,227,258,0,0 };
static int length_extra[31]=
{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
static int dist_extra[32] =
{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
static int parse_huffman_block(zbuf *a)
{
for(;;) {
int z = zhuffman_decode(a, &a->z_length);
if (z < 256) {
if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes
if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;
*a->zout++ = (char) z;
} else {
uint8 *p;
int len,dist;
if (z == 256) return 1;
z -= 257;
len = length_base[z];
if (length_extra[z]) len += zreceive(a, length_extra[z]);
z = zhuffman_decode(a, &a->z_distance);
if (z < 0) return e("bad huffman code","Corrupt PNG");
dist = dist_base[z];
if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);
if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG");
if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;
p = (uint8 *) (a->zout - dist);
while (len--)
*a->zout++ = *p++;
}
}
}
static int compute_huffman_codes(zbuf *a)
{
static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
zhuffman z_codelength;
uint8 lencodes[286+32+137];//padding for maximum single op
uint8 codelength_sizes[19];
int i,n;
int hlit = zreceive(a,5) + 257;
int hdist = zreceive(a,5) + 1;
int hclen = zreceive(a,4) + 4;
memset(codelength_sizes, 0, sizeof(codelength_sizes));
for (i=0; i < hclen; ++i) {
int s = zreceive(a,3);
codelength_sizes[length_dezigzag[i]] = (uint8) s;
}
if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
n = 0;
while (n < hlit + hdist) {
int c = zhuffman_decode(a, &z_codelength);
assert(c >= 0 && c < 19);
if (c < 16)
lencodes[n++] = (uint8) c;
else if (c == 16) {
c = zreceive(a,2)+3;
memset(lencodes+n, lencodes[n-1], c);
n += c;
} else if (c == 17) {
c = zreceive(a,3)+3;
memset(lencodes+n, 0, c);
n += c;
} else {
assert(c == 18);
c = zreceive(a,7)+11;
memset(lencodes+n, 0, c);
n += c;
}
}
if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");
if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
return 1;
}
static int parse_uncompressed_block(zbuf *a)
{
uint8 header[4];
int len,nlen,k;
if (a->num_bits & 7)
zreceive(a, a->num_bits & 7); // discard
// drain the bit-packed data into header
k = 0;
while (a->num_bits > 0) {
header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns?
a->code_buffer >>= 8;
a->num_bits -= 8;
}
assert(a->num_bits == 0);
// now fill header the normal way
while (k < 4)
header[k++] = (uint8) zget8(a);
len = header[1] * 256 + header[0];
nlen = header[3] * 256 + header[2];
if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");
if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG");
if (a->zout + len > a->zout_end)
if (!expand(a, len)) return 0;
memcpy(a->zout, a->zbuffer, len);
a->zbuffer += len;
a->zout += len;
return 1;
}
static int parse_zlib_header(zbuf *a)
{
int cmf = zget8(a);
int cm = cmf & 15;
/* int cinfo = cmf >> 4; */
int flg = zget8(a);
if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec
if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png
// window = 1 << (8 + cinfo)... but who cares, we fully buffer output
return 1;
}
// @TODO: should statically initialize these for optimal thread safety
static uint8 default_length[288], default_distance[32];
static void init_defaults(void)
{
int i; // use <= to match clearly with spec
for (i=0; i <= 143; ++i) default_length[i] = 8;
for ( ; i <= 255; ++i) default_length[i] = 9;
for ( ; i <= 279; ++i) default_length[i] = 7;
for ( ; i <= 287; ++i) default_length[i] = 8;
for (i=0; i <= 31; ++i) default_distance[i] = 5;
}
int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead
static int parse_zlib(zbuf *a, int parse_header)
{
int final, type;
if (parse_header)
if (!parse_zlib_header(a)) return 0;
a->num_bits = 0;
a->code_buffer = 0;
do {
final = zreceive(a,1);
type = zreceive(a,2);
if (type == 0) {
if (!parse_uncompressed_block(a)) return 0;
} else if (type == 3) {
return 0;
} else {
if (type == 1) {
// use fixed code lengths
if (!default_distance[31]) init_defaults();
if (!zbuild_huffman(&a->z_length , default_length , 288)) return 0;
if (!zbuild_huffman(&a->z_distance, default_distance, 32)) return 0;
} else {
if (!compute_huffman_codes(a)) return 0;
}
if (!parse_huffman_block(a)) return 0;
}
if (stbi_png_partial && a->zout - a->zout_start > 65536)
break;
} while (!final);
return 1;
}
static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)
{
a->zout_start = obuf;
a->zout = obuf;
a->zout_end = obuf + olen;
a->z_expandable = exp;
return parse_zlib(a, parse_header);
}
char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
{
zbuf a;
char *p = (char *) malloc(initial_size);
if (p == NULL) return NULL;
a.zbuffer = (uint8 *) buffer;
a.zbuffer_end = (uint8 *) buffer + len;
if (do_zlib(&a, p, initial_size, 1, 1)) {
if (outlen) *outlen = (int) (a.zout - a.zout_start);
return a.zout_start;
} else {
free(a.zout_start);
return NULL;
}
}
char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
{
return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
}
int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
{
zbuf a;
a.zbuffer = (uint8 *) ibuffer;
a.zbuffer_end = (uint8 *) ibuffer + ilen;
if (do_zlib(&a, obuffer, olen, 0, 1))
return (int) (a.zout - a.zout_start);
else
return -1;
}
char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
{
zbuf a;
char *p = (char *) malloc(16384);
if (p == NULL) return NULL;
a.zbuffer = (uint8 *) buffer;
a.zbuffer_end = (uint8 *) buffer+len;
if (do_zlib(&a, p, 16384, 1, 0)) {
if (outlen) *outlen = (int) (a.zout - a.zout_start);
return a.zout_start;
} else {
free(a.zout_start);
return NULL;
}
}
int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
{
zbuf a;
a.zbuffer = (uint8 *) ibuffer;
a.zbuffer_end = (uint8 *) ibuffer + ilen;
if (do_zlib(&a, obuffer, olen, 0, 0))
return (int) (a.zout - a.zout_start);
else
return -1;
}
// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
// simple implementation
// - only 8-bit samples
// - no CRC checking
// - allocates lots of intermediate memory
// - avoids problem of streaming data between subsystems
// - avoids explicit window management
// performance
// - uses stb_zlib, a PD zlib implementation with fast huffman decoding
typedef struct
{
uint32 length;
uint32 type;
} chunk;
#define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
static chunk get_chunk_header(stbi *s)
{
chunk c;
c.length = get32(s);
c.type = get32(s);
return c;
}
static int check_png_header(stbi *s)
{
static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };
int i;
for (i=0; i < 8; ++i)
if (get8(s) != png_sig[i]) return e("bad png sig","Not a PNG");
return 1;
}
typedef struct
{
stbi s;
uint8 *idata, *expanded, *out;
} png;
enum {
F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,
F_avg_first, F_paeth_first,
};
static uint8 first_row_filter[5] =
{
F_none, F_sub, F_none, F_avg_first, F_paeth_first
};
static int paeth(int a, int b, int c)
{
int p = a + b - c;
int pa = abs(p-a);
int pb = abs(p-b);
int pc = abs(p-c);
if (pa <= pb && pa <= pc) return a;
if (pb <= pc) return b;
return c;
}
// create the png data from post-deflated data
static int create_png_image_raw(png *a, uint8 *raw, uint32 raw_len, int out_n, uint32 x, uint32 y)
{
stbi *s = &a->s;
uint32 i,j,stride = x*out_n;
int k;
int img_n = s->img_n; // copy it into a local for later
assert(out_n == s->img_n || out_n == s->img_n+1);
if (stbi_png_partial) y = 1;
a->out = (uint8 *) malloc(x * y * out_n);
if (!a->out) return e("outofmem", "Out of memory");
if (!stbi_png_partial) {
if (s->img_x == x && s->img_y == y)
if (raw_len != (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
else // interlaced:
if (raw_len < (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
}
for (j=0; j < y; ++j) {
uint8 *cur = a->out + stride*j;
uint8 *prior = cur - stride;
int filter = *raw++;
if (filter > 4) return e("invalid filter","Corrupt PNG");
// if first row, use special filter that doesn't sample previous row
if (j == 0) filter = first_row_filter[filter];
// handle first pixel explicitly
for (k=0; k < img_n; ++k) {
switch(filter) {
case F_none : cur[k] = raw[k]; break;
case F_sub : cur[k] = raw[k]; break;
case F_up : cur[k] = raw[k] + prior[k]; break;
case F_avg : cur[k] = raw[k] + (prior[k]>>1); break;
case F_paeth : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;
case F_avg_first : cur[k] = raw[k]; break;
case F_paeth_first: cur[k] = raw[k]; break;
}
}
if (img_n != out_n) cur[img_n] = 255;
raw += img_n;
cur += out_n;
prior += out_n;
// this is a little gross, so that we don't switch per-pixel or per-component
if (img_n == out_n) {
#define CASE(f) \
case f: \
for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \
for (k=0; k < img_n; ++k)
switch(filter) {
CASE(F_none) cur[k] = raw[k]; break;
CASE(F_sub) cur[k] = raw[k] + cur[k-img_n]; break;
CASE(F_up) cur[k] = raw[k] + prior[k]; break;
CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;
CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;
CASE(F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break;
CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;
}
#undef CASE
} else {
assert(img_n+1 == out_n);
#define CASE(f) \
case f: \
for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \
for (k=0; k < img_n; ++k)
switch(filter) {
CASE(F_none) cur[k] = raw[k]; break;
CASE(F_sub) cur[k] = raw[k] + cur[k-out_n]; break;
CASE(F_up) cur[k] = raw[k] + prior[k]; break;
CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;
CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
CASE(F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break;
CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;
}
#undef CASE
}
}
return 1;
}
static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n, int interlaced)
{
uint8 *final;
int p;
int save;
if (!interlaced)
return create_png_image_raw(a, raw, raw_len, out_n, a->s.img_x, a->s.img_y);
save = stbi_png_partial;
stbi_png_partial = 0;
// de-interlacing
final = (uint8 *) malloc(a->s.img_x * a->s.img_y * out_n);
for (p=0; p < 7; ++p) {
int xorig[] = { 0,4,0,2,0,1,0 };
int yorig[] = { 0,0,4,0,2,0,1 };
int xspc[] = { 8,8,4,4,2,2,1 };
int yspc[] = { 8,8,8,4,4,2,2 };
int i,j,x,y;
// pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
x = (a->s.img_x - xorig[p] + xspc[p]-1) / xspc[p];
y = (a->s.img_y - yorig[p] + yspc[p]-1) / yspc[p];
if (x && y) {
if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {
free(final);
return 0;
}
for (j=0; j < y; ++j)
for (i=0; i < x; ++i)
memcpy(final + (j*yspc[p]+yorig[p])*a->s.img_x*out_n + (i*xspc[p]+xorig[p])*out_n,
a->out + (j*x+i)*out_n, out_n);
free(a->out);
raw += (x*out_n+1)*y;
raw_len -= (x*out_n+1)*y;
}
}
a->out = final;
stbi_png_partial = save;
return 1;
}
static int compute_transparency(png *z, uint8 tc[3], int out_n)
{
stbi *s = &z->s;
uint32 i, pixel_count = s->img_x * s->img_y;
uint8 *p = z->out;
// compute color-based transparency, assuming we've
// already got 255 as the alpha value in the output
assert(out_n == 2 || out_n == 4);
if (out_n == 2) {
for (i=0; i < pixel_count; ++i) {
p[1] = (p[0] == tc[0] ? 0 : 255);
p += 2;
}
} else {
for (i=0; i < pixel_count; ++i) {
if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
p[3] = 0;
p += 4;
}
}
return 1;
}
static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n)
{
uint32 i, pixel_count = a->s.img_x * a->s.img_y;
uint8 *p, *temp_out, *orig = a->out;
p = (uint8 *) malloc(pixel_count * pal_img_n);
if (p == NULL) return e("outofmem", "Out of memory");
// between here and free(out) below, exitting would leak
temp_out = p;
if (pal_img_n == 3) {
for (i=0; i < pixel_count; ++i) {
int n = orig[i]*4;
p[0] = palette[n ];
p[1] = palette[n+1];
p[2] = palette[n+2];
p += 3;
}
} else {
for (i=0; i < pixel_count; ++i) {
int n = orig[i]*4;
p[0] = palette[n ];
p[1] = palette[n+1];
p[2] = palette[n+2];
p[3] = palette[n+3];
p += 4;
}
}
free(a->out);
a->out = temp_out;
return 1;
}
static int parse_png_file(png *z, int scan, int req_comp)
{
uint8 palette[1024], pal_img_n=0;
uint8 has_trans=0, tc[3];
uint32 ioff=0, idata_limit=0, i, pal_len=0;
int first=1,k,interlace=0;
stbi *s = &z->s;
if (!check_png_header(s)) return 0;
if (scan == SCAN_type) return 1;
for(;;first=0) {
chunk c = get_chunk_header(s);
if (first && c.type != PNG_TYPE('I','H','D','R'))
return e("first not IHDR","Corrupt PNG");
switch (c.type) {
case PNG_TYPE('I','H','D','R'): {
int depth,color,comp,filter;
if (!first) return e("multiple IHDR","Corrupt PNG");
if (c.length != 13) return e("bad IHDR len","Corrupt PNG");
s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");
s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");
depth = get8(s); if (depth != 8) return e("8bit only","PNG not supported: 8-bit only");
color = get8(s); if (color > 6) return e("bad ctype","Corrupt PNG");
if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");
comp = get8(s); if (comp) return e("bad comp method","Corrupt PNG");
filter= get8(s); if (filter) return e("bad filter method","Corrupt PNG");
interlace = get8(s); if (interlace>1) return e("bad interlace method","Corrupt PNG");
if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG");
if (!pal_img_n) {
s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");
if (scan == SCAN_header) return 1;
} else {
// if paletted, then pal_n is our final components, and
// img_n is # components to decompress/filter.
s->img_n = 1;
if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG");
// if SCAN_header, have to scan to see if we have a tRNS
}
break;
}
case PNG_TYPE('P','L','T','E'): {
if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");
pal_len = c.length / 3;
if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");
for (i=0; i < pal_len; ++i) {
palette[i*4+0] = get8u(s);
palette[i*4+1] = get8u(s);
palette[i*4+2] = get8u(s);
palette[i*4+3] = 255;
}
break;
}
case PNG_TYPE('t','R','N','S'): {
if (z->idata) return e("tRNS after IDAT","Corrupt PNG");
if (pal_img_n) {
if (scan == SCAN_header) { s->img_n = 4; return 1; }
if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");
if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");
pal_img_n = 4;
for (i=0; i < c.length; ++i)
palette[i*4+3] = get8u(s);
} else {
if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG");
if (c.length != (uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG");
has_trans = 1;
for (k=0; k < s->img_n; ++k)
tc[k] = (uint8) get16(s); // non 8-bit images will be larger
}
break;
}
case PNG_TYPE('I','D','A','T'): {
if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");
if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }
if (ioff + c.length > idata_limit) {
uint8 *p;
if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
while (ioff + c.length > idata_limit)
idata_limit *= 2;
p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");
z->idata = p;
}
#ifndef STBI_NO_STDIO
if (s->img_file)
{
if (fread(z->idata+ioff,1,c.length,s->img_file) != c.length) return e("outofdata","Corrupt PNG");
}
else
#endif
{
memcpy(z->idata+ioff, s->img_buffer, c.length);
s->img_buffer += c.length;
}
ioff += c.length;
break;
}
case PNG_TYPE('I','E','N','D'): {
uint32 raw_len;
if (scan != SCAN_load) return 1;
if (z->idata == NULL) return e("no IDAT","Corrupt PNG");
z->expanded = (uint8 *) stbi_zlib_decode_malloc((char *) z->idata, ioff, (int *) &raw_len);
if (z->expanded == NULL) return 0; // zlib should set error
free(z->idata); z->idata = NULL;
if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
s->img_out_n = s->img_n+1;
else
s->img_out_n = s->img_n;
if (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;
if (has_trans)
if (!compute_transparency(z, tc, s->img_out_n)) return 0;
if (pal_img_n) {
// pal_img_n == 3 or 4
s->img_n = pal_img_n; // record the actual colors we had
s->img_out_n = pal_img_n;
if (req_comp >= 3) s->img_out_n = req_comp;
if (!expand_palette(z, palette, pal_len, s->img_out_n))
return 0;
}
free(z->expanded); z->expanded = NULL;
return 1;
}
default:
// if critical, fail
if ((c.type & (1 << 29)) == 0) {
#ifndef STBI_NO_FAILURE_STRINGS
// not threadsafe
static char invalid_chunk[] = "XXXX chunk not known";
invalid_chunk[0] = (uint8) (c.type >> 24);
invalid_chunk[1] = (uint8) (c.type >> 16);
invalid_chunk[2] = (uint8) (c.type >> 8);
invalid_chunk[3] = (uint8) (c.type >> 0);
#endif
return e(invalid_chunk, "PNG not supported: unknown chunk type");
}
skip(s, c.length);
break;
}
// end of chunk, read and skip CRC
get32(s);
}
}
static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)
{
unsigned char *result=NULL;
p->expanded = NULL;
p->idata = NULL;
p->out = NULL;
if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
if (parse_png_file(p, SCAN_load, req_comp)) {
result = p->out;
p->out = NULL;
if (req_comp && req_comp != p->s.img_out_n) {
result = convert_format(result, p->s.img_out_n, req_comp, p->s.img_x, p->s.img_y);
p->s.img_out_n = req_comp;
if (result == NULL) return result;
}
*x = p->s.img_x;
*y = p->s.img_y;
if (n) *n = p->s.img_n;
}
free(p->out); p->out = NULL;
free(p->expanded); p->expanded = NULL;
free(p->idata); p->idata = NULL;
return result;
}
#ifndef STBI_NO_STDIO
unsigned char *stbi_png_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
png p;
start_file(&p.s, f);
return do_png(&p, x,y,comp,req_comp);
}
unsigned char *stbi_png_load(char const *filename, int *x, int *y, int *comp, int req_comp)
{
unsigned char *data;
FILE *f = fopen(filename, "rb");
if (!f) return NULL;
data = stbi_png_load_from_file(f,x,y,comp,req_comp);
fclose(f);
return data;
}
#endif
unsigned char *stbi_png_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
png p;
start_mem(&p.s, buffer,len);
return do_png(&p, x,y,comp,req_comp);
}
#ifndef STBI_NO_STDIO
int stbi_png_test_file(FILE *f)
{
png p;
int n,r;
n = ftell(f);
start_file(&p.s, f);
r = parse_png_file(&p, SCAN_type,STBI_default);
fseek(f,n,SEEK_SET);
return r;
}
#endif
int stbi_png_test_memory(stbi_uc const *buffer, int len)
{
png p;
start_mem(&p.s, buffer, len);
return parse_png_file(&p, SCAN_type,STBI_default);
}
// TODO: load header from png
#ifndef STBI_NO_STDIO
int stbi_png_info (char const *filename, int *x, int *y, int *comp)
{
png p;
FILE *f = fopen(filename, "rb");
if (!f) return 0;
start_file(&p.s, f);
if (parse_png_file(&p, SCAN_header, 0)) {
if(x) *x = p.s.img_x;
if(y) *y = p.s.img_y;
if (comp) *comp = p.s.img_n;
fclose(f);
return 1;
}
fclose(f);
return 0;
}
extern int stbi_png_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
extern int stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);
// Microsoft/Windows BMP image
static int bmp_test(stbi *s)
{
int sz;
if (get8(s) != 'B') return 0;
if (get8(s) != 'M') return 0;
get32le(s); // discard filesize
get16le(s); // discard reserved
get16le(s); // discard reserved
get32le(s); // discard data offset
sz = get32le(s);
if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;
return 0;
}
#ifndef STBI_NO_STDIO
int stbi_bmp_test_file (FILE *f)
{
stbi s;
int r,n = ftell(f);
start_file(&s,f);
r = bmp_test(&s);
fseek(f,n,SEEK_SET);
return r;
}
#endif
int stbi_bmp_test_memory (stbi_uc const *buffer, int len)
{
stbi s;
start_mem(&s, buffer, len);
return bmp_test(&s);
}
// returns 0..31 for the highest set bit
static int high_bit(unsigned int z)
{
int n=0;
if (z == 0) return -1;
if (z >= 0x10000) n += 16, z >>= 16;
if (z >= 0x00100) n += 8, z >>= 8;
if (z >= 0x00010) n += 4, z >>= 4;
if (z >= 0x00004) n += 2, z >>= 2;
if (z >= 0x00002) n += 1, z >>= 1;
return n;
}
static int bitcount(unsigned int a)
{
a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
a = (a + (a >> 8)); // max 16 per 8 bits
a = (a + (a >> 16)); // max 32 per 8 bits
return a & 0xff;
}
static int shiftsigned(int v, int shift, int bits)
{
int result;
int z=0;
if (shift < 0) v <<= -shift;
else v >>= shift;
result = v;
z = bits;
while (z < 8) {
result += v >> z;
z += bits;
}
return result;
}
static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
uint8 *out;
unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;
stbi_uc pal[256][4];
int psize=0,i,j,compress=0,width;
int bpp, flip_vertically, pad, target, offset, hsz;
if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP");
get32le(s); // discard filesize
get16le(s); // discard reserved
get16le(s); // discard reserved
offset = get32le(s);
hsz = get32le(s);
if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");
failure_reason = "bad BMP";
if (hsz == 12) {
s->img_x = get16le(s);
s->img_y = get16le(s);
} else {
s->img_x = get32le(s);
s->img_y = get32le(s);
}
if (get16le(s) != 1) return 0;
bpp = get16le(s);
if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");
flip_vertically = ((int) s->img_y) > 0;
s->img_y = abs((int) s->img_y);
if (hsz == 12) {
if (bpp < 24)
psize = (offset - 14 - 24) / 3;
} else {
compress = get32le(s);
if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");
get32le(s); // discard sizeof
get32le(s); // discard hres
get32le(s); // discard vres
get32le(s); // discard colorsused
get32le(s); // discard max important
if (hsz == 40 || hsz == 56) {
if (hsz == 56) {
get32le(s);
get32le(s);
get32le(s);
get32le(s);
}
if (bpp == 16 || bpp == 32) {
mr = mg = mb = 0;
if (compress == 0) {
if (bpp == 32) {
mr = 0xff << 16;
mg = 0xff << 8;
mb = 0xff << 0;
ma = 0xff << 24;
fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
} else {
mr = 31 << 10;
mg = 31 << 5;
mb = 31 << 0;
}
} else if (compress == 3) {
mr = get32le(s);
mg = get32le(s);
mb = get32le(s);
// not documented, but generated by photoshop and handled by mspaint
if (mr == mg && mg == mb) {
// ?!?!?
return NULL;
}
} else
return NULL;
}
} else {
assert(hsz == 108);
mr = get32le(s);
mg = get32le(s);
mb = get32le(s);
ma = get32le(s);
get32le(s); // discard color space
for (i=0; i < 12; ++i)
get32le(s); // discard color space parameters
}
if (bpp < 16)
psize = (offset - 14 - hsz) >> 2;
}
s->img_n = ma ? 4 : 3;
if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
target = req_comp;
else
target = s->img_n; // if they want monochrome, we'll post-convert
out = (stbi_uc *) malloc(target * s->img_x * s->img_y);
if (!out) return epuc("outofmem", "Out of memory");
if (bpp < 16) {
int z=0;
if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); }
for (i=0; i < psize; ++i) {
pal[i][2] = get8(s);
pal[i][1] = get8(s);
pal[i][0] = get8(s);
if (hsz != 12) get8(s);
pal[i][3] = 255;
}
skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));
if (bpp == 4) width = (s->img_x + 1) >> 1;
else if (bpp == 8) width = s->img_x;
else { free(out); return epuc("bad bpp", "Corrupt BMP"); }
pad = (-width)&3;
for (j=0; j < (int) s->img_y; ++j) {
for (i=0; i < (int) s->img_x; i += 2) {
int v=get8(s),v2=0;
if (bpp == 4) {
v2 = v & 15;
v >>= 4;
}
out[z++] = pal[v][0];
out[z++] = pal[v][1];
out[z++] = pal[v][2];
if (target == 4) out[z++] = 255;
if (i+1 == (int) s->img_x) break;
v = (bpp == 8) ? get8(s) : v2;
out[z++] = pal[v][0];
out[z++] = pal[v][1];
out[z++] = pal[v][2];
if (target == 4) out[z++] = 255;
}
skip(s, pad);
}
} else {
int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
int z = 0;
int easy=0;
skip(s, offset - 14 - hsz);
if (bpp == 24) width = 3 * s->img_x;
else if (bpp == 16) width = 2*s->img_x;
else /* bpp = 32 and pad = 0 */ width=0;
pad = (-width) & 3;
if (bpp == 24) {
easy = 1;
} else if (bpp == 32) {
if (mb == 0xff && mg == 0xff00 && mr == 0xff000000 && ma == 0xff000000)
easy = 2;
}
if (!easy) {
if (!mr || !mg || !mb) return epuc("bad masks", "Corrupt BMP");
// right shift amt to put high bit in position #7
rshift = high_bit(mr)-7; rcount = bitcount(mr);
gshift = high_bit(mg)-7; gcount = bitcount(mr);
bshift = high_bit(mb)-7; bcount = bitcount(mr);
ashift = high_bit(ma)-7; acount = bitcount(mr);
}
for (j=0; j < (int) s->img_y; ++j) {
if (easy) {
for (i=0; i < (int) s->img_x; ++i) {
int a;
out[z+2] = get8(s);
out[z+1] = get8(s);
out[z+0] = get8(s);
z += 3;
a = (easy == 2 ? get8(s) : 255);
if (target == 4) out[z++] = a;
}
} else {
for (i=0; i < (int) s->img_x; ++i) {
uint32 v = (bpp == 16 ? get16le(s) : get32le(s));
int a;
out[z++] = shiftsigned(v & mr, rshift, rcount);
out[z++] = shiftsigned(v & mg, gshift, gcount);
out[z++] = shiftsigned(v & mb, bshift, bcount);
a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);
if (target == 4) out[z++] = a;
}
}
skip(s, pad);
}
}
if (flip_vertically) {
stbi_uc t;
for (j=0; j < (int) s->img_y>>1; ++j) {
stbi_uc *p1 = out + j *s->img_x*target;
stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
for (i=0; i < (int) s->img_x*target; ++i) {
t = p1[i], p1[i] = p2[i], p2[i] = t;
}
}
}
if (req_comp && req_comp != target) {
out = convert_format(out, target, req_comp, s->img_x, s->img_y);
if (out == NULL) return out; // convert_format frees input on failure
}
*x = s->img_x;
*y = s->img_y;
if (comp) *comp = target;
return out;
}
#ifndef STBI_NO_STDIO
stbi_uc *stbi_bmp_load (char const *filename, int *x, int *y, int *comp, int req_comp)
{
stbi_uc *data;
FILE *f = fopen(filename, "rb");
if (!f) return NULL;
data = stbi_bmp_load_from_file(f, x,y,comp,req_comp);
fclose(f);
return data;
}
stbi_uc *stbi_bmp_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_file(&s, f);
return bmp_load(&s, x,y,comp,req_comp);
}
#endif
stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_mem(&s, buffer, len);
return bmp_load(&s, x,y,comp,req_comp);
}
// Targa Truevision - TGA
// by Jonathan Dummer
static int tga_test(stbi *s)
{
int sz;
get8u(s); // discard Offset
sz = get8u(s); // color type
if( sz > 1 ) return 0; // only RGB or indexed allowed
sz = get8u(s); // image type
if( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE
get16(s); // discard palette start
get16(s); // discard palette length
get8(s); // discard bits per palette color entry
get16(s); // discard x origin
get16(s); // discard y origin
if( get16(s) < 1 ) return 0; // test width
if( get16(s) < 1 ) return 0; // test height
sz = get8(s); // bits per pixel
if( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0; // only RGB or RGBA or grey allowed
return 1; // seems to have passed everything
}
#ifndef STBI_NO_STDIO
int stbi_tga_test_file (FILE *f)
{
stbi s;
int r,n = ftell(f);
start_file(&s, f);
r = tga_test(&s);
fseek(f,n,SEEK_SET);
return r;
}
#endif
int stbi_tga_test_memory (stbi_uc const *buffer, int len)
{
stbi s;
start_mem(&s, buffer, len);
return tga_test(&s);
}
static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
// read in the TGA header stuff
int tga_offset = get8u(s);
int tga_indexed = get8u(s);
int tga_image_type = get8u(s);
int tga_is_RLE = 0;
int tga_palette_start = get16le(s);
int tga_palette_len = get16le(s);
int tga_palette_bits = get8u(s);
int tga_x_origin = get16le(s);
int tga_y_origin = get16le(s);
int tga_width = get16le(s);
int tga_height = get16le(s);
int tga_bits_per_pixel = get8u(s);
int tga_inverted = get8u(s);
// image data
unsigned char *tga_data;
unsigned char *tga_palette = NULL;
int i, j;
unsigned char raw_data[4];
unsigned char trans_data[4];
int RLE_count = 0;
int RLE_repeating = 0;
int read_next_pixel = 1;
// do a tiny bit of precessing
if( tga_image_type >= 8 )
{
tga_image_type -= 8;
tga_is_RLE = 1;
}
/* int tga_alpha_bits = tga_inverted & 15; */
tga_inverted = 1 - ((tga_inverted >> 5) & 1);
// error check
if( //(tga_indexed) ||
(tga_width < 1) || (tga_height < 1) ||
(tga_image_type < 1) || (tga_image_type > 3) ||
((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&
(tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))
)
{
return NULL;
}
// If I'm paletted, then I'll use the number of bits from the palette
if( tga_indexed )
{
tga_bits_per_pixel = tga_palette_bits;
}
// tga info
*x = tga_width;
*y = tga_height;
if( (req_comp < 1) || (req_comp > 4) )
{
// just use whatever the file was
req_comp = tga_bits_per_pixel / 8;
*comp = req_comp;
} else
{
// force a new number of components
*comp = tga_bits_per_pixel/8;
}
tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );
// skip to the data's starting position (offset usually = 0)
skip(s, tga_offset );
// do I need to load a palette?
if( tga_indexed )
{
// any data to skip? (offset usually = 0)
skip(s, tga_palette_start );
// load the palette
tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );
getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 );
}
// load the data
for( i = 0; i < tga_width * tga_height; ++i )
{
// if I'm in RLE mode, do I need to get a RLE chunk?
if( tga_is_RLE )
{
if( RLE_count == 0 )
{
// yep, get the next byte as a RLE command
int RLE_cmd = get8u(s);
RLE_count = 1 + (RLE_cmd & 127);
RLE_repeating = RLE_cmd >> 7;
read_next_pixel = 1;
} else if( !RLE_repeating )
{
read_next_pixel = 1;
}
} else
{
read_next_pixel = 1;
}
// OK, if I need to read a pixel, do it now
if( read_next_pixel )
{
// load however much data we did have
if( tga_indexed )
{
// read in 1 byte, then perform the lookup
int pal_idx = get8u(s);
if( pal_idx >= tga_palette_len )
{
// invalid index
pal_idx = 0;
}
pal_idx *= tga_bits_per_pixel / 8;
for( j = 0; j*8 < tga_bits_per_pixel; ++j )
{
raw_data[j] = tga_palette[pal_idx+j];
}
} else
{
// read in the data raw
for( j = 0; j*8 < tga_bits_per_pixel; ++j )
{
raw_data[j] = get8u(s);
}
}
// convert raw to the intermediate format
switch( tga_bits_per_pixel )
{
case 8:
// Luminous => RGBA
trans_data[0] = raw_data[0];
trans_data[1] = raw_data[0];
trans_data[2] = raw_data[0];
trans_data[3] = 255;
break;
case 16:
// Luminous,Alpha => RGBA
trans_data[0] = raw_data[0];
trans_data[1] = raw_data[0];
trans_data[2] = raw_data[0];
trans_data[3] = raw_data[1];
break;
case 24:
// BGR => RGBA
trans_data[0] = raw_data[2];
trans_data[1] = raw_data[1];
trans_data[2] = raw_data[0];
trans_data[3] = 255;
break;
case 32:
// BGRA => RGBA
trans_data[0] = raw_data[2];
trans_data[1] = raw_data[1];
trans_data[2] = raw_data[0];
trans_data[3] = raw_data[3];
break;
}
// clear the reading flag for the next pixel
read_next_pixel = 0;
} // end of reading a pixel
// convert to final format
switch( req_comp )
{
case 1:
// RGBA => Luminance
tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
break;
case 2:
// RGBA => Luminance,Alpha
tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
tga_data[i*req_comp+1] = trans_data[3];
break;
case 3:
// RGBA => RGB
tga_data[i*req_comp+0] = trans_data[0];
tga_data[i*req_comp+1] = trans_data[1];
tga_data[i*req_comp+2] = trans_data[2];
break;
case 4:
// RGBA => RGBA
tga_data[i*req_comp+0] = trans_data[0];
tga_data[i*req_comp+1] = trans_data[1];
tga_data[i*req_comp+2] = trans_data[2];
tga_data[i*req_comp+3] = trans_data[3];
break;
}
// in case we're in RLE mode, keep counting down
--RLE_count;
}
// do I need to invert the image?
if( tga_inverted )
{
for( j = 0; j*2 < tga_height; ++j )
{
int index1 = j * tga_width * req_comp;
int index2 = (tga_height - 1 - j) * tga_width * req_comp;
for( i = tga_width * req_comp; i > 0; --i )
{
unsigned char temp = tga_data[index1];
tga_data[index1] = tga_data[index2];
tga_data[index2] = temp;
++index1;
++index2;
}
}
}
// clear my palette, if I had one
if( tga_palette != NULL )
{
free( tga_palette );
}
// Done to avoid an error message, and yet keep
// Microsoft's C compilers happy...
tga_palette_start = tga_palette_len = tga_palette_bits =
tga_x_origin = tga_y_origin = 0;
// OK, done
return tga_data;
}
#ifndef STBI_NO_STDIO
stbi_uc *stbi_tga_load (char const *filename, int *x, int *y, int *comp, int req_comp)
{
stbi_uc *data;
FILE *f = fopen(filename, "rb");
if (!f) return NULL;
data = stbi_tga_load_from_file(f, x,y,comp,req_comp);
fclose(f);
return data;
}
stbi_uc *stbi_tga_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_file(&s, f);
return tga_load(&s, x,y,comp,req_comp);
}
#endif
stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_mem(&s, buffer, len);
return tga_load(&s, x,y,comp,req_comp);
}
// *************************************************************************************************
// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicholas Schulz, tweaked by STB
static int psd_test(stbi *s)
{
if (get32(s) != 0x38425053) return 0; // "8BPS"
else return 1;
}
#ifndef STBI_NO_STDIO
int stbi_psd_test_file(FILE *f)
{
stbi s;
int r,n = ftell(f);
start_file(&s, f);
r = psd_test(&s);
fseek(f,n,SEEK_SET);
return r;
}
#endif
int stbi_psd_test_memory(stbi_uc const *buffer, int len)
{
stbi s;
start_mem(&s, buffer, len);
return psd_test(&s);
}
static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
int pixelCount;
int channelCount, compression;
int channel, i, count, len;
int w,h;
uint8 *out;
// Check identifier
if (get32(s) != 0x38425053) // "8BPS"
return epuc("not PSD", "Corrupt PSD image");
// Check file type version.
if (get16(s) != 1)
return epuc("wrong version", "Unsupported version of PSD image");
// Skip 6 reserved bytes.
skip(s, 6 );
// Read the number of channels (R, G, B, A, etc).
channelCount = get16(s);
if (channelCount < 0 || channelCount > 16)
return epuc("wrong channel count", "Unsupported number of channels in PSD image");
// Read the rows and columns of the image.
h = get32(s);
w = get32(s);
// Make sure the depth is 8 bits.
if (get16(s) != 8)
return epuc("unsupported bit depth", "PSD bit depth is not 8 bit");
// Make sure the color mode is RGB.
// Valid options are:
// 0: Bitmap
// 1: Grayscale
// 2: Indexed color
// 3: RGB color
// 4: CMYK color
// 7: Multichannel
// 8: Duotone
// 9: Lab color
if (get16(s) != 3)
return epuc("wrong color format", "PSD is not in RGB color format");
// Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
skip(s,get32(s) );
// Skip the image resources. (resolution, pen tool paths, etc)
skip(s, get32(s) );
// Skip the reserved data.
skip(s, get32(s) );
// Find out if the data is compressed.
// Known values:
// 0: no compression
// 1: RLE compressed
compression = get16(s);
if (compression > 1)
return epuc("bad compression", "PSD has an unknown compression format");
// Create the destination image.
out = (stbi_uc *) malloc(4 * w*h);
if (!out) return epuc("outofmem", "Out of memory");
pixelCount = w*h;
// Initialize the data to zero.
//memset( out, 0, pixelCount * 4 );
// Finally, the image data.
if (compression) {
// RLE as used by .PSD and .TIFF
// Loop until you get the number of unpacked bytes you are expecting:
// Read the next source byte into n.
// If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
// Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
// Else if n is 128, noop.
// Endloop
// The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,
// which we're going to just skip.
skip(s, h * channelCount * 2 );
// Read the RLE data by channel.
for (channel = 0; channel < 4; channel++) {
uint8 *p;
p = out+channel;
if (channel >= channelCount) {
// Fill this channel with default data.
for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;
} else {
// Read the RLE data.
count = 0;
while (count < pixelCount) {
len = get8(s);
if (len == 128) {
// No-op.
} else if (len < 128) {
// Copy next len+1 bytes literally.
len++;
count += len;
while (len) {
*p = get8(s);
p += 4;
len--;
}
} else if (len > 128) {
uint32 val;
// Next -len+1 bytes in the dest are replicated from next source byte.
// (Interpret len as a negative 8-bit int.)
len ^= 0x0FF;
len += 2;
val = get8(s);
count += len;
while (len) {
*p = val;
p += 4;
len--;
}
}
}
}
}
} else {
// We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
// where each channel consists of an 8-bit value for each pixel in the image.
// Read the data by channel.
for (channel = 0; channel < 4; channel++) {
uint8 *p;
p = out + channel;
if (channel > channelCount) {
// Fill this channel with default data.
for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;
} else {
// Read the data.
count = 0;
for (i = 0; i < pixelCount; i++)
*p = get8(s), p += 4;
}
}
}
if (req_comp && req_comp != 4) {
out = convert_format(out, 4, req_comp, w, h);
if (out == NULL) return out; // convert_format frees input on failure
}
if (comp) *comp = channelCount;
*y = h;
*x = w;
return out;
}
#ifndef STBI_NO_STDIO
stbi_uc *stbi_psd_load(char const *filename, int *x, int *y, int *comp, int req_comp)
{
stbi_uc *data;
FILE *f = fopen(filename, "rb");
if (!f) return NULL;
data = stbi_psd_load_from_file(f, x,y,comp,req_comp);
fclose(f);
return data;
}
stbi_uc *stbi_psd_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_file(&s, f);
return psd_load(&s, x,y,comp,req_comp);
}
#endif
stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_mem(&s, buffer, len);
return psd_load(&s, x,y,comp,req_comp);
}
// *************************************************************************************************
// Radiance RGBE HDR loader
// originally by Nicolas Schulz
#ifndef STBI_NO_HDR
static int hdr_test(stbi *s)
{
char *signature = "#?RADIANCE\n";
int i;
for (i=0; signature[i]; ++i)
if (get8(s) != signature[i])
return 0;
return 1;
}
int stbi_hdr_test_memory(stbi_uc const *buffer, int len)
{
stbi s;
start_mem(&s, buffer, len);
return hdr_test(&s);
}
#ifndef STBI_NO_STDIO
int stbi_hdr_test_file(FILE *f)
{
stbi s;
int r,n = ftell(f);
start_file(&s, f);
r = hdr_test(&s);
fseek(f,n,SEEK_SET);
return r;
}
#endif
#define HDR_BUFLEN 1024
static char *hdr_gettoken(stbi *z, char *buffer)
{
int len=0;
char *s = buffer, c = '\0';
c = get8(z);
while (!at_eof(z) && c != '\n') {
buffer[len++] = c;
if (len == HDR_BUFLEN-1) {
// flush to end of line
while (!at_eof(z) && get8(z) != '\n')
;
break;
}
c = get8(z);
}
buffer[len] = 0;
return buffer;
}
static void hdr_convert(float *output, stbi_uc *input, int req_comp)
{
if( input[3] != 0 ) {
float f1;
// Exponent
f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
if (req_comp <= 2)
output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
else {
output[0] = input[0] * f1;
output[1] = input[1] * f1;
output[2] = input[2] * f1;
}
if (req_comp == 2) output[1] = 1;
if (req_comp == 4) output[3] = 1;
} else {
switch (req_comp) {
case 4: output[3] = 1; /* fallthrough */
case 3: output[0] = output[1] = output[2] = 0;
break;
case 2: output[1] = 1; /* fallthrough */
case 1: output[0] = 0;
break;
}
}
}
static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
char buffer[HDR_BUFLEN];
char *token;
int valid = 0;
int width, height;
stbi_uc *scanline;
float *hdr_data;
int len;
unsigned char count, value;
int i, j, k, c1,c2, z;
// Check identifier
if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
return epf("not HDR", "Corrupt HDR image");
// Parse header
while(1) {
token = hdr_gettoken(s,buffer);
if (token[0] == 0) break;
if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
}
if (!valid) return epf("unsupported format", "Unsupported HDR format");
// Parse width and height
// can't use sscanf() if we're not using stdio!
token = hdr_gettoken(s,buffer);
if (strncmp(token, "-Y ", 3)) return epf("unsupported data layout", "Unsupported HDR format");
token += 3;
height = strtol(token, &token, 10);
while (*token == ' ') ++token;
if (strncmp(token, "+X ", 3)) return epf("unsupported data layout", "Unsupported HDR format");
token += 3;
width = strtol(token, NULL, 10);
*x = width;
*y = height;
*comp = 3;
if (req_comp == 0) req_comp = 3;
// Read data
hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));
// Load image data
// image data is stored as some number of sca
if( width < 8 || width >= 32768) {
// Read flat data
for (j=0; j < height; ++j) {
for (i=0; i < width; ++i) {
stbi_uc rgbe[4];
main_decode_loop:
getn(s, rgbe, 4);
hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
}
}
} else {
// Read RLE-encoded data
scanline = NULL;
for (j = 0; j < height; ++j) {
c1 = get8(s);
c2 = get8(s);
len = get8(s);
if (c1 != 2 || c2 != 2 || (len & 0x80)) {
// not run-length encoded, so we have to actually use THIS data as a decoded
// pixel (note this can't be a valid pixel--one of RGB must be >= 128)
stbi_uc rgbe[4] = { c1,c2,len, get8(s) };
hdr_convert(hdr_data, rgbe, req_comp);
i = 1;
j = 0;
free(scanline);
goto main_decode_loop; // yes, this is not nice, but it is due to the insane format
}
len <<= 8;
len |= get8(s);
if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }
if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);
for (k = 0; k < 4; ++k) {
i = 0;
while (i < width) {
count = get8(s);
if (count > 128) {
// Run
value = get8(s);
count -= 128;
for (z = 0; z < count; ++z)
scanline[i++ * 4 + k] = value;
} else {
// Dump
for (z = 0; z < count; ++z)
scanline[i++ * 4 + k] = get8(s);
}
}
}
for (i=0; i < width; ++i)
hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
}
free(scanline);
}
return hdr_data;
}
#ifndef STBI_NO_STDIO
float *stbi_hdr_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_file(&s,f);
return hdr_load(&s,x,y,comp,req_comp);
}
#endif
float *stbi_hdr_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_mem(&s,buffer, len);
return hdr_load(&s,x,y,comp,req_comp);
}
#endif // STBI_NO_HDR
/////////////////////// write image ///////////////////////
#ifndef STBI_NO_WRITE
static void write8(FILE *f, int x) { uint8 z = (uint8) x; fwrite(&z,1,1,f); }
static void writefv(FILE *f, char *fmt, va_list v)
{
while (*fmt) {
switch (*fmt++) {
case ' ': break;
case '1': { uint8 x = va_arg(v, int); write8(f,x); break; }
case '2': { int16 x = va_arg(v, int); write8(f,x); write8(f,x>>8); break; }
case '4': { int32 x = va_arg(v, int); write8(f,x); write8(f,x>>8); write8(f,x>>16); write8(f,x>>24); break; }
default:
assert(0);
va_end(v);
return;
}
}
}
static void writef(FILE *f, char *fmt, ...)
{
va_list v;
va_start(v, fmt);
writefv(f,fmt,v);
va_end(v);
}
static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad)
{
uint8 bg[3] = { 255, 0, 255}, px[3];
uint32 zero = 0;
int i,j,k, j_end;
if (vdir < 0)
j_end = -1, j = y-1;
else
j_end = y, j = 0;
for (; j != j_end; j += vdir) {
for (i=0; i < x; ++i) {
uint8 *d = (uint8 *) data + (j*x+i)*comp;
if (write_alpha < 0)
fwrite(&d[comp-1], 1, 1, f);
switch (comp) {
case 1:
case 2: writef(f, "111", d[0],d[0],d[0]);
break;
case 4:
if (!write_alpha) {
for (k=0; k < 3; ++k)
px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;
writef(f, "111", px[1-rgb_dir],px[1],px[1+rgb_dir]);
break;
}
/* FALLTHROUGH */
case 3:
writef(f, "111", d[1-rgb_dir],d[1],d[1+rgb_dir]);
break;
}
if (write_alpha > 0)
fwrite(&d[comp-1], 1, 1, f);
}
fwrite(&zero,scanline_pad,1,f);
}
}
static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, void *data, int alpha, int pad, char *fmt, ...)
{
FILE *f = fopen(filename, "wb");
if (f) {
va_list v;
va_start(v, fmt);
writefv(f, fmt, v);
va_end(v);
write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad);
fclose(f);
}
return f != NULL;
}
int stbi_write_bmp(char const *filename, int x, int y, int comp, void *data)
{
int pad = (-x*3) & 3;
return outfile(filename,-1,-1,x,y,comp,data,0,pad,
"11 4 22 4" "4 44 22 444444",
'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header
40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header
}
int stbi_write_tga(char const *filename, int x, int y, int comp, void *data)
{
int has_alpha = !(comp & 1);
return outfile(filename, -1,-1, x, y, comp, data, has_alpha, 0,
"111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);
}
// any other image formats that do interleaved rgb data?
// PNG: requires adler32,crc32 -- significant amount of code
// PSD: no, channels output separately
// TIFF: no, stripwise-interleaved... i think
#endif // STBI_NO_WRITE
#endif // STBI_HEADER_FILE_ONLY
| [
"[email protected]"
] | [
[
[
1,
3899
]
]
] |
87f06659473a386fef5f922bf74d0e2aa6f39661 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/pymuscle/rs/pymrsrender.cpp | 01da5326f7f7893153090560cd987b3301797b92 | [] | no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43,534 | cpp | #include "PymRsPch.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "PrsGraphCapi.h"
#include "PymStruct.h"
#include "PymBiped.h"
#include "RigidBody.h"
#include "MuscleFiber.h"
#include "ConvexHullCapi.h"
#include "PymuscleConfig.h"
#include "StateDependents.h"
#include "Config.h"
#include "DebugPrintDef.h"
#include "Optimize.h"
#include "PymJointAnchor.h"
#include "PymDebugMessageFlags.h"
#include "TrajParser.h"
#include "PhysicsThreadMain.h"
#include "PymCmdLineParser.h"
#include "MathUtil.h"
#include "pymrscore.h"
#include "pymrsrender.h"
#include "LinearR3.h"
#include "QuaternionEOM.h"
#include "pymdrawingoption.h"
#ifndef M_PI
#define M_PI 3.14
#endif
GLuint m_vaoID[5]; /* two vertex array objects,
one for each drawn object */
GLuint m_vboID[3]; // three VBOs
GLuint gndTex;
// Z values will be rendered to this texture when using fboId framebuffer
GLuint depthTextureId;
// Hold id of the framebuffer for light POV rendering
GLuint fboId;
// Use to activate/disable shadowShader
GLhandleARB shadowShaderId;
GLint shadowMapUniform;
GLint projMatUniform;
GLint modelViewMatUniform;
GLint normalMatUniform;
const int n_face = 45; // Circle shaped ground face number
static inline double Norm3(const double *const v) {
return sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
}
static void pym_strict_checK_gl() {
GLenum gl_error = glGetError();
if( gl_error != GL_NO_ERROR ) {
fprintf( stderr, "ARAN: OpenGL error: %s\n",
gluErrorString(gl_error) );
abort();
}
}
GLuint InitTriangleVao() {
// First simple object
float vert[9]; // vertex array
float col[9]; // color array
vert[0] =-0.3; vert[1] = 0.5; vert[2] =-1.0;
vert[3] =-0.8; vert[4] =-0.5; vert[5] =-1.0;
vert[6] = 0.2; vert[7] =-0.5; vert[8]= -1.0;
col[0] = 1.0; col[1] = 1.0; col[2] = 1.0;
col[3] = 0.0; col[4] = 1.0; col[5] = 0.0;
col[6] = 0.0; col[7] = 0.0; col[8] = 1.0;
GLuint vaoId = 0;
assert(glGenVertexArrays);
glGenVertexArrays(1, &vaoId);
// First VAO setup
glBindVertexArray(vaoId);
// 2 VBOs (Vertex Buffer Object) for the first VAO
GLuint vboId[2] = {0,};
glGenBuffers(2, vboId);
glBindBuffer(GL_ARRAY_BUFFER, vboId[0]);
glBufferData(GL_ARRAY_BUFFER, 9*sizeof(GLfloat), vert, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vboId[1]);
glBufferData(GL_ARRAY_BUFFER, 9*sizeof(GLfloat), col, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
return vaoId;
}
GLuint InitQuadVao() {
float vert2[9]; // vertex array
vert2[0] =-0.2; vert2[1] = 0.5; vert2[2] =-1.0;
vert2[3] = 0.3; vert2[4] =-0.5; vert2[5] =-1.0;
vert2[6] = 0.8; vert2[7] = 0.5; vert2[8]= -1.0;
GLuint vaoId = 0;
glGenVertexArrays(1, &vaoId);
glBindVertexArray(vaoId);
// 1 VBO for the second VAO
GLuint vboId = 0;
glGenBuffers(1, &vboId);
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBufferData(GL_ARRAY_BUFFER, 9*sizeof(GLfloat), vert2, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
return vaoId;
}
GLuint InitQuad2Vao() {
GLuint vaoId = 0;
glGenVertexArrays(1, &vaoId);
glBindVertexArray(vaoId);
// Third simple object
GLfloat vert3[] = { 15.3f, 5.3f, 0.0f,
-5.3f, 5.3f, 0.0f,
-5.3f, -5.3f, 0.0f,
5.3f, -5.3f, 0.0f };
// 1 VBO for the third VAO
GLuint vboId = 0;
glGenBuffers(1, &vboId);
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBufferData(GL_ARRAY_BUFFER, 12*sizeof(GLfloat), vert3, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
return vaoId;
}
GLuint InitUnitBoxVao() {
GLuint vaoId = 0;
glGenVertexArrays(1, &vaoId);
glBindVertexArray(vaoId);
GLfloat vert4[] = { /* Face which has +X normals (x= 0.5) */
0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
/* Face which has -X normals (x=-0.5) */
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
/* Face which has +Y normals (y= 0.5) */
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, 0.5f,
/* Face which has -Y normals (y=-0.5) */
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, -0.5f,-0.5f,
0.5f, -0.5f,-0.5f,
/* Face which has +Z normals (z= 0.5) */
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
/* Face which has -Z normals (z=-0.5) */
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f };
GLfloat nor4[] = {
1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,
0,0,1,0,0,1,0,0,1,0,0,1,
0,0,-1,0,0,-1,0,0,-1,0,0,-1,
};
GLfloat col4[3*4*6];
int i;
FOR_0(i, 3*4*6) {
if (i%3 == 0)
col4[i] = 1;
}
GLuint vboId[3] = {0,};
glGenBuffers(3, vboId);
glBindBuffer(GL_ARRAY_BUFFER, vboId[0]);
glBufferData(GL_ARRAY_BUFFER, 3*4*6*sizeof(GLfloat), vert4, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vboId[1]);
glBufferData(GL_ARRAY_BUFFER, 3*4*6*sizeof(GLfloat), col4, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, vboId[2]);
glBufferData(GL_ARRAY_BUFFER, 3*4*6*sizeof(GLfloat), nor4, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)2, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(2);
return vaoId;
}
GLuint InitCircleVao() {
GLuint vaoId = 0;
glGenVertexArrays(1, &vaoId);
glBindVertexArray(vaoId);
/* center point(1) + vertices around circumference(n_face) + final point(1) */
const int n_vert_circle = (1+n_face+1)*3;
GLfloat vert5[n_vert_circle];
memset(vert5, 0, sizeof(vert5));
float circle_radius = 10;
int i;
for (i=0;i<=n_face;++i) { /* note that '<=' for final point */
const double rad = 2*M_PI/n_face*i;
vert5[3 + i*3 + 0] = circle_radius*cos(rad);
vert5[3 + i*3 + 1] = circle_radius*sin(rad);
}
// 1 VBO for the third VAO
GLuint vboId = 0;
glGenBuffers(1, &vboId);
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBufferData(GL_ARRAY_BUFFER, n_vert_circle*sizeof(GLfloat),
vert5, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
return vaoId;
}
void InitVertexArrayObjects(GLuint *m_vaoID)
{
m_vaoID[0] = InitTriangleVao();
m_vaoID[1] = InitQuadVao();
m_vaoID[2] = InitQuad2Vao();
m_vaoID[3] = InitUnitBoxVao();
m_vaoID[4] = InitCircleVao();
glBindVertexArray(0);
}
// Loading shader function
GLhandleARB loadShader(char* filename, unsigned int type)
{
FILE *pfile;
GLhandleARB handle;
const GLcharARB* files[1];
// shader Compilation variable
GLint result; // Compilation code result
GLint errorLoglength ;
char* errorLogText;
GLsizei actualErrorLogLength;
char buffer[400000];
memset(buffer,0,400000);
// This will raise a warning on MS compiler
printf("Loading shader %s...\n", filename);
pfile = fopen(filename, "rb");
if(!pfile)
{
printf("Sorry, can't open file: '%s'.\n", filename);
exit(-1);
}
fread(buffer,sizeof(char),400000,pfile);
//printf("%s\n",buffer);
fclose(pfile);
handle = glCreateShaderObjectARB(type);
if (!handle)
{
//We have failed creating the vertex shader object.
printf("Failed creating vertex shader object from file: %s.",filename);
exit(-1);
}
files[0] = (const GLcharARB*)buffer;
glShaderSourceARB(
handle, //The handle to our shader
1, //The number of files.
files, //An array of const char * data, which represents the source code of theshaders
NULL);
glCompileShaderARB(handle);
//Compilation checking.
glGetObjectParameterivARB(handle, GL_OBJECT_COMPILE_STATUS_ARB, &result);
//Attempt to get the length of our error and warning log.
glGetObjectParameterivARB(handle, GL_OBJECT_INFO_LOG_LENGTH_ARB, &errorLoglength);
if (errorLoglength) {
//Create a buffer to read compilation error message
errorLogText = (char *)malloc(sizeof(char) * errorLoglength);
//Used to get the final length of the log.
glGetInfoLogARB(handle, errorLoglength, &actualErrorLogLength, errorLogText);
// Display errors.
printf("%s\n",errorLogText);
// Free the buffer malloced earlier
free(errorLogText);
// In case of error occurred:
if (!result) {
//We failed to compile.
printf("WARN - Shader '%s' failed compilation.\n", filename);
return 0;
}
}
return handle;
}
void CheckLinkError(GLhandleARB obj)
{
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
GLint result;
glGetObjectParameterivARB(obj, GL_OBJECT_LINK_STATUS_ARB, &result);
if (!result) {
glGetObjectParameterivARB(obj, GL_OBJECT_INFO_LOG_LENGTH_ARB,
&infologLength);
if (infologLength > 0) {
infoLog = (char *)malloc(infologLength);
glGetInfoLogARB(obj, infologLength, &charsWritten, infoLog);
printf("%s\n",infoLog);
free(infoLog);
}
exit(-2);
}
}
void loadShadowShader()
{
GLhandleARB vertexShaderHandle;
GLhandleARB fragmentShaderHandle;
vertexShaderHandle = loadShader("Shadow.vert", GL_VERTEX_SHADER_ARB);
printf("Vertex shader handle : %d\n", vertexShaderHandle);
fragmentShaderHandle = loadShader("Shadow.frag", GL_FRAGMENT_SHADER_ARB);
printf("Fragment shader handle : %d\n", fragmentShaderHandle);
shadowShaderId = glCreateProgramObjectARB();
printf("Program handle : %d\n", shadowShaderId);
glAttachObjectARB(shadowShaderId, vertexShaderHandle);
glAttachObjectARB(shadowShaderId, fragmentShaderHandle);
glBindAttribLocationARB(shadowShaderId, 0, "in_Position");
glBindAttribLocationARB(shadowShaderId, 1, "in_Color");
glBindAttribLocationARB(shadowShaderId, 2, "in_Normal");
glLinkProgramARB(shadowShaderId);
CheckLinkError(shadowShaderId);
glUseProgram(shadowShaderId);
printf("Shadow shader loaded successfully.\n");
shadowMapUniform = glGetUniformLocation(shadowShaderId,
"ShadowMap");
projMatUniform = glGetUniformLocation(shadowShaderId,
"projection_matrix");
modelViewMatUniform = glGetUniformLocation(shadowShaderId,
"modelview_matrix");
normalMatUniform = glGetUniformLocation(shadowShaderId,
"normal_matrix");
assert(shadowMapUniform >= 0);
assert(projMatUniform >= 0);
assert(modelViewMatUniform >= 0);
//assert(normalMatUniform >= 0);
}
void generateShadowFBO() {
/*
int shadowMapWidth = RENDER_WIDTH * SHADOW_MAP_RATIO;
int shadowMapHeight = RENDER_HEIGHT * SHADOW_MAP_RATIO;
*/
int shadowMapWidth = 1024;
int shadowMapHeight = 1024;
//GLfloat borderColor[4] = {0,0,0,0};
GLenum FBOstatus;
// Try to use a texture depth component
glGenTextures(1, &depthTextureId);
glBindTexture(GL_TEXTURE_2D, depthTextureId);
// GL_LINEAR does not make sense for depth texture. However, next tutorial shows usage of GL_LINEAR and PCF
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Remove artefact on the edges of the shadowmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
//glTexParameterfv( GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor );
// No need to force GL_DEPTH_COMPONENT24, drivers usually give you the max precision if available
glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadowMapWidth, shadowMapHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, 0);
// create a framebuffer object
glGenFramebuffersEXT(1, &fboId);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fboId);
// Instruct openGL that we won't bind a color texture with the currently binded FBO
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
// attach the texture to FBO depth attachment point
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,GL_TEXTURE_2D, depthTextureId, 0);
// check FBO status
FBOstatus = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if(FBOstatus != GL_FRAMEBUFFER_COMPLETE_EXT)
printf("GL_FRAMEBUFFER_COMPLETE_EXT failed, CANNOT use FBO\n");
// switch back to window-system-provided framebuffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
void setupMatrices(float position_x, float position_y, float position_z,
float lookAt_x, float lookAt_y, float lookAt_z) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//gluPerspective(45, (double)RENDER_WIDTH/RENDER_HEIGHT, 1, 100);
glOrtho(-3, 3, -3, 3, 1e-2, 1e5);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(position_x, position_y, position_z,
lookAt_x, lookAt_y, lookAt_z,
0,0,1);
GLfloat mat[16];
glGetFloatv(GL_PROJECTION_MATRIX, mat);
glUniformMatrix4fvARB(projMatUniform, 1, 0, mat);
glGetFloatv(GL_MODELVIEW_MATRIX, mat);
glUniformMatrix4fvARB(modelViewMatUniform, 1, 0, mat);
}
void setTextureMatrix(void) {
static double modelView[16];
static double projection[16];
// This is matrix transform every coordinate x,y,z
// x = x* 0.5 + 0.5
// y = y* 0.5 + 0.5
// z = z* 0.5 + 0.5
// Moving from unit cube [-1,1] to [0,1]
const GLdouble bias[16] = {
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0};
// Grab modelview and transformation matrices
glGetDoublev(GL_MODELVIEW_MATRIX, modelView);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glMatrixMode(GL_TEXTURE);
glActiveTextureARB(GL_TEXTURE7);
glLoadIdentity();
glLoadMatrixd(bias);
// concatating all matrice into one.
glMultMatrixd (projection);
glMultMatrixd (modelView);
// Go back to normal matrix mode
glMatrixMode(GL_MODELVIEW);
}
void startXform(double W[4][4]) {
glPushAttrib(GL_TEXTURE_BIT);
const GLdouble *const Wa = (const GLdouble *const)W;
glPushMatrix();
glMultTransposeMatrixd(Wa);
glMatrixMode(GL_TEXTURE);
glActiveTextureARB(GL_TEXTURE7);
glPushMatrix();
glMultTransposeMatrixd(Wa);
}
void endXform() {
glMatrixMode(GL_TEXTURE);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
}
void startTranslate(float x, float y, float z) {
glPushAttrib(GL_TEXTURE_BIT);
glPushMatrix();
glTranslatef(x,y,z);
glMatrixMode(GL_TEXTURE);
glActiveTextureARB(GL_TEXTURE7);
glPushMatrix();
glTranslatef(x,y,z);
}
void endTranslate() {
endXform();
}
void SetUniforms() {
GLfloat mat44[4][4];
/* Projection matrix to vertex shader */
glGetFloatv(GL_PROJECTION_MATRIX, (GLfloat *)mat44);
glUniformMatrix4fvARB(projMatUniform, 1, GL_FALSE, (GLfloat *)mat44);
/* Modelview matrix to vertex shader */
glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat *)mat44);
glUniformMatrix4fvARB(modelViewMatUniform, 1, GL_FALSE, (GLfloat *)mat44);
/* Normal matrix (transpose of inverse of modelview matrix)
* to vertex shader */
float mat33[3][3];
int i, j;
FOR_0(i, 3) {
FOR_0(j, 3) {
mat33[i][j] = mat44[i][j];
}
}
float mat33Inv[3][3];
Invert3x3Matrixf(mat33Inv, mat33);
glUniformMatrix3fvARB(normalMatUniform, 1, GL_TRUE, (GLfloat *)mat33Inv);
}
void DrawBox_chi(const double *chi,
const double *const boxSize, int wf) {
double W[4][4];
GetWFrom6Dof(W, chi); /* chi only has translation and rotation */
int j, k;
/* Scaling added w.r.t. boxSize */
FOR_0(j, 4)
FOR_0(k, 3)
W[j][k] *= boxSize[k];
/* TODO: Remove scaling factor from the transform matrix W */
startXform(W);
glPushAttrib(GL_POLYGON_BIT | GL_ENABLE_BIT);
if (wf == 1) {
glDisable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
} else if (wf == 0) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
} else {
assert("What the...");
}
if (glBindVertexArray) {
glBindVertexArray(m_vaoID[3]); // select second VAO
glDrawArrays(GL_QUADS, 0, 4*6); // draw second object
glBindVertexArray(0);
} else {
static GLfloat vert4[] = { /* Face which has +X normals (x= 0.5) */
0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
/* Face which has -X normals (x=-0.5) */
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
/* Face which has +Y normals (y= 0.5) */
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, 0.5f,
/* Face which has -Y normals (y=-0.5) */
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, -0.5f,-0.5f,
0.5f, -0.5f,-0.5f,
/* Face which has +Z normals (z= 0.5) */
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
/* Face which has -Z normals (z=-0.5) */
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f };
static GLfloat nor4[] = {
1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,
0,0,1,0,0,1,0,0,1,0,0,1,
0,0,-1,0,0,-1,0,0,-1,0,0,-1,
};
glBegin(GL_QUADS);
for (int j = 0; j < 6; ++j) {
/* One quad(rectangle) face */
for (int i = 0; i < 4; ++i) {
glNormal3fv(nor4 + 3*4*j + 3*i);
glVertex3fv(vert4 + 3*4*j + 3*i);
}
}
glEnd();
}
glPopAttrib();
endXform();
}
void DrawBox_pq(const double *p, const double *q,
const double *const boxSize, int wf) {
double chi[6];
assert(p);
memcpy(chi + 0, p, sizeof(double)*3);
if (q)
memcpy(chi + 3, q, sizeof(double)*3);
else {
chi[3] = 0;
chi[4] = 0;
chi[5] = 0;
}
DrawBox_chi(chi, boxSize, wf);
}
static void pym_draw_square_ground() {
float colorBlue[] = { 0.2f, 0.5f, 1.0f, 1.0f };
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colorBlue);
glBegin(GL_QUADS);
int i, j;
const int tile_count = 100;
const double tile_size = 10.0;
const double tile_unit_size = tile_size/tile_count;
for (i=-tile_count/2; i<tile_count/2; ++i) {
for (j=-tile_count/2; j<tile_count/2; ++j) {
const double tx = tile_unit_size*i;
const double ty = tile_unit_size*j;
glVertex3d(tx, ty, 0);
glVertex3d(tx+tile_unit_size, ty, 0);
glVertex3d(tx+tile_unit_size, ty+tile_unit_size, 0);
glVertex3d(tx, ty+tile_unit_size, 0);
}
}
glEnd();
}
void DrawRb(const pym_rb_named_t *rbn,
const double *const boxSize, int wf) {
const double *const p = rbn->p;
const double *const q = rbn->q;
glColor3f(0.3,0.75,0.3);
DrawBox_pq(p, q, boxSize, wf);
/* Draw external force (disturbance) if exists */
if (rbn->extForce[0] || rbn->extForce[1] || rbn->extForce[2]) {
const double norm = Norm3(rbn->extForce);
double chi[6] = { rbn->p[0],
rbn->p[1],
rbn->p[2],
rbn->q[0],
rbn->q[1],
rbn->q[2] };
double W[4][4];
GetWFrom6Dof(W, chi);
double extForcePos[3];
TransformPoint(extForcePos, W, rbn->extForcePos);
glLineWidth(6.0);
glDisable(GL_LIGHTING);
glColor3f(1,0,0);
glBegin(GL_LINES);
glVertex3dv(extForcePos);
glVertex3d(extForcePos[0]-rbn->extForce[0]/1000,
extForcePos[1]-rbn->extForce[1]/1000,
extForcePos[2]-rbn->extForce[2]/1000);
glEnd();
glLineWidth(1.0);
glEnable(GL_LIGHTING);
}
}
void DrawRbRef(const pym_rb_named_t *rbn,
const double *const boxSize, int wf) {
const double *const chi = rbn->chi_ref;
assert(chi);
glColor3f(1, 0, 0);
//printf("%p -- %lf\n", &chi[0], chi[0]);
DrawBox_chi(chi, boxSize, wf);
}
void DrawRbContacts(const pym_rb_named_t *rbn) {
int j;
FOR_0(j, rbn->nContacts_1) {
const double *conPos = rbn->contactsPoints_1[j];
const double *conForce = rbn->contactsForce_2[j];
glColor3f(0,1,0);
startTranslate(conPos[0], conPos[1], conPos[2]);
/* TODO: No draw call */
endTranslate();
static const double scale = 0.1;
glBegin(GL_LINES);
glVertex3f(conPos[0], conPos[1], conPos[2]);
glVertex3f(conPos[0]+conForce[0]*scale,
conPos[1]+conForce[1]*scale,
conPos[2]+conForce[2]*scale);
glEnd();
}
}
void DrawAxisOnWorldOrigin() {
glBegin(GL_LINES);
glColor3f(1,0,0); glVertex3f(0,0,0); glVertex3f(1,0,0);
glColor3f(0,1,0); glVertex3f(0,0,0); glVertex3f(0,1,0);
glColor3f(0,0,1); glVertex3f(0,0,0); glVertex3f(0,0,1);
glEnd();
}
void DrawGround(pym_ground_type_t gndType, const GLuint *const m_vaoID) {
if (gndType == PYM_TRANSPARENT_GRID) {
glPushAttrib(GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
glColor3f(0.2, 0.2, 0.2);
glBegin(GL_LINES);
for (int i = -10; i <= 10; ++i) {
glVertex3f(i, -10, 0);
glVertex3f(i, 10, 0);
glVertex3f(-10, i, 0);
glVertex3f(10, i, 0);
}
for (int i = -10; i <= 10; ++i) {
for (int j = -10; j <= 10; ++j) {
glVertex3f(i, j, 0);
glVertex3f(i, j, -0.1);
}
}
glEnd();
glPopAttrib();
return;
}
assert(glBindVertexArray);
if (gndType == PYM_SQUARE_GROUND)
glBindVertexArray(m_vaoID[2]);
else if (gndType == PYM_CIRCLE_GROUND)
glBindVertexArray(m_vaoID[4]);
else
return;
glPushAttrib(GL_POLYGON_BIT);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// in_Color (vertex shader)
glVertexAttrib3f((GLuint)1, 0.3, 0.3, 0.3);
// in_Normal (vertex shader)
glVertexAttrib3f((GLuint)2, 0.0, 0.0, 1.0);
pym_strict_checK_gl();
//SetUniforms();
pym_strict_checK_gl();
if (gndType == PYM_SQUARE_GROUND)
// draw second object
glDrawArrays(GL_QUADS, 0, 4);
else if (gndType == PYM_CIRCLE_GROUND)
// draw second object
glDrawArrays(GL_TRIANGLE_FAN, 0, (1+n_face+1)*3);
glPopAttrib();
pym_strict_checK_gl();
}
void XRotPoint(float pr[3], float p[3], float th) {
pr[0] = p[0];
pr[1] = cos(th)*p[1] - sin(th)*p[2];
pr[2] = sin(th)*p[1] + cos(th)*p[2];
}
void YRotPoint(float pr[3], float p[3], float th) {
pr[0] = cos(th)*p[0] + sin(th)*p[2];
pr[1] = p[1];
pr[2] = -sin(th)*p[0] + cos(th)*p[2];
}
void RenderFootContactStatus
(const pym_physics_thread_context_t *const phyCon) {
static const double pointBoxSize[3] = { 3e-2, 3e-2, 3e-2 };
static const double pzero[3] = {0,};
//static const double q1[3] = {1,1,1};
int i, j, k;
FOR_0(i, phyCon->pymCfg->nBody) {
/* Access data from renderer-accessable area of phyCon */
const pym_rb_named_t *rbn = &phyCon->pymCfg->body[i].b;
const char *footParts[] = { "soleL", "soleR", "toeL", "toeR" };
const double pos[4][2] = { { -0.7, 0 },
{0.7, 0},
{-0.7, 0.2},
{0.7, 0.2} };
FOR_0(k, 4) {
if (strcmp(rbn->name, footParts[k]) == 0) {
const double *const boxSize = rbn->boxSize;
glPushMatrix(); /* Stack A */
glTranslated(pos[k][0], pos[k][1], 0);
glRotatef(30, 1, 0, 0);
glRotatef(45, 0, 1, 0);
glColor3f(1,1,1);
DrawBox_pq(pzero, 0, boxSize, 1);
glColor3f(1,0,0);
FOR_0(j, phyCon->sd[i].nContacts_1) {
const int ci = phyCon->sd[i].contactIndices_1[j];
glColor3f(1,0,0);
DrawBox_pq(rbn->corners[ ci ], 0, pointBoxSize, 0);
}
glPopMatrix(); /* Stack A */
break;
}
}
}
}
void RenderFootContactFixPosition
(const pym_physics_thread_context_t *const phyCon) {
static const double pointBoxSize[3] = { 5e-2, 5e-2, 5e-2 };
int i, j, k;
FOR_0(i, phyCon->pymCfg->nBody) {
/* Access data from renderer-accessable area of phyCon */
const pym_rb_named_t *rbn = &phyCon->pymCfg->body[i].b;
const char *footParts[] = { "soleL", "soleR", "toeL", "toeR" };
FOR_0(k, 4) {
if (strcmp(rbn->name, footParts[k]) == 0) {
glColor3f(1, 0, 0);
//printf("nContacts_2 = %d\n", phyCon->sd[i].nContacts_2);
assert(phyCon->sd[i].nContacts_1 >= 0);
FOR_0(j, phyCon->sd[i].nContacts_1) {
DrawBox_pq(phyCon->sd[i].contactsFix_1[j], 0, pointBoxSize, 1);
}
}
}
}
}
void pym_sphere_to_cartesian(double *c, double r,
double phi, double theta) {
c[0] = r*sin(theta)*sin(phi);
c[1] = -r*sin(theta)*cos(phi);
c[2] = r*cos(theta);
}
static void pym_cross3(double *u, const double *const a,
const double *const b) {
u[0] = a[1]*b[2] - a[2]*b[1];
u[1] = a[2]*b[0] - a[0]*b[2];
u[2] = a[0]*b[1] - a[1]*b[0];
}
void pym_up_dir_from_sphere(double *u,
const double *const cam_car,
double r, double phi, double theta) {
const double left[3] = { -cos(phi), -sin(phi), 0 };
const double look_dir[3] = { -cam_car[0]/r,
-cam_car[1]/r,
-cam_car[2]/r };
pym_cross3(u, look_dir, left);
}
void PymLookUpLeft(double *look, double *up, double *left,
double r, double phi, double theta) {
double cam_car[3];
pym_sphere_to_cartesian(cam_car, r, phi, theta);
left[0] = -cos(phi);
left[1] = -sin(phi);
left[2] = 0;
look[0] = -cam_car[0]/r;
look[1] = -cam_car[1]/r;
look[2] = -cam_car[2]/r;
pym_cross3(up, look, left);
}
void pym_configure_light() {
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
const float cutoff = 90;
glLightfv(GL_LIGHT0, GL_SPOT_CUTOFF, &cutoff);
const float noAmbient[] = {0.5f, 0.5f, 0.5f, 1.0f};
const float whiteDiffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
float lightVector[4] = { 0, 0, 10, 1 };
float spot_direction[4] = {0, 0, -1};
glLightfv(GL_LIGHT0, GL_AMBIENT, noAmbient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, whiteDiffuse);
glLightfv(GL_LIGHT0, GL_POSITION, lightVector);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_direction);
}
static void render_fibers(const pym_config_t *const pymCfg) {
glPushAttrib(GL_LINE_BIT | GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
int i;
const int nf = pymCfg->nFiber;
FOR_0(i, nf) {
const pym_mf_named_t *mfn = &pymCfg->fiber[i].b;
double W_org[4][4], W_ins[4][4];
const pym_rb_named_t *rbn_org = &pymCfg->body[mfn->org].b;
const pym_rb_named_t *rbn_ins = &pymCfg->body[mfn->ins].b;
double chi_org[6] = { rbn_org->p[0],
rbn_org->p[1],
rbn_org->p[2],
rbn_org->q[0],
rbn_org->q[1],
rbn_org->q[2] };
double chi_ins[6] = { rbn_ins->p[0],
rbn_ins->p[1],
rbn_ins->p[2],
rbn_ins->q[0],
rbn_ins->q[1],
rbn_ins->q[2] };
GetWFrom6Dof(W_org, chi_org);
GetWFrom6Dof(W_ins, chi_ins);
//mfn->fibb_org
double org[3], ins[3];
TransformPoint(org, W_org, mfn->fibb_org);
TransformPoint(ins, W_ins, mfn->fibb_ins);
glLineWidth(6.0);
if (mfn->mType == PMT_ACTUATED_MUSCLE) {
if (mfn->T * mfn->A < 0) {
glLineWidth(8.0);
glColor3f(1.0, 0, 0);
} else {
glColor3f(0.8, 0.6, 0.6);
}
} else {
glColor3f(0.5, 0.5, 0.5);
}
glBegin(GL_LINES);
glVertex3dv(org);
glVertex3dv(ins);
glEnd();
}
glPopAttrib();
}
static void pym_draw_all(pym_rs_t *rs, int forShadow, GLuint *m_vaoID) {
pym_physics_thread_context_t *phyCon = &rs->phyCon;
glPushMatrix();
if (!forShadow)
DrawAxisOnWorldOrigin();
pym_strict_checK_gl();
if (glBindVertexArray)
DrawGround(PYM_TRANSPARENT_GRID, m_vaoID);
pym_strict_checK_gl();
//pym_draw_square_ground();
pym_strict_checK_gl();
pym_config_t *pymCfg = phyCon->pymCfg;
const int nb = pymCfg->nBody;
int i;
// Rendering position offset value of a twin biped for visual analysis.
const double twin_offset_x = -1.5;
FOR_0(i, nb) {
/* Access data from renderer-accessable area of phyCon */
const pym_rb_named_t *rbn = &phyCon->pymCfg->body[i].b;
const double *const boxSize = rbn->boxSize;
pym_strict_checK_gl();
if (strcmp(rbn->name, "uarmL") == 0 ||
strcmp(rbn->name, "uarmR") == 0 ||
strcmp(rbn->name, "larmL") == 0 ||
strcmp(rbn->name, "larmR") == 0 ||
strcmp(rbn->name, "head") == 0) {
} else {
DrawRb(rbn, boxSize, rs->drawing_options[pym_do_wireframe] ? 1 : 0);
DrawRbRef(rbn, boxSize, 1);
}
glPushMatrix();
glTranslated(twin_offset_x, 0, 0);
//DrawRb(rbn, boxSize, 1);
//DrawRbRef(rbn, boxSize, 1);
glPopMatrix();
pym_strict_checK_gl();
DrawRbContacts(rbn);
}
if (pymCfg->renderFibers) {
render_fibers(pymCfg);
}
static const double pointBoxSize[3] = { 5e-2, 5e-2, 5e-2 };
glColor3f(1,1,1);
pym_strict_checK_gl();
glPushMatrix();
glTranslated(twin_offset_x, 0, 0);
glPushAttrib(GL_CURRENT_BIT);
glColor3f(0,1,0);
DrawBox_pq(pymCfg->bipCom, 0, pointBoxSize, 0);
glColor3f(1,0,0);
DrawBox_pq(phyCon->pymCfg->bipRefCom, 0, pointBoxSize, 0);
const double *const trajData = phyCon->pymTraj->trajData;
/* render COM of reference */
if (trajData && 0) {
glBegin(GL_LINE_STRIP);
for (int i = 0; i < rs->pymTraj.nBlenderFrame; ++i) {
glVertex3dv(phyCon->pymTraj->comTrajData + 3*i);
/*printf("comref %lf %lf %lf\n", phyCon->pymTraj->comTrajData[3*i],
phyCon->pymTraj->comTrajData[3*i+1],
phyCon->pymTraj->comTrajData[3*i+2]);*/
}
glEnd();
}
glPopAttrib();
glPopMatrix();
const int nj = phyCon->pymCfg->nJoint;
for (int j = 0; j < nj; ++j) {
const int ajBodyAIdx = pymCfg->anchoredJoints[j].aIdx;
const int bjBodyAIdx = pymCfg->anchoredJoints[j].bIdx;
const int aancIdx = pymCfg->anchoredJoints[j].aAnchorIdx;
const int bancIdx = pymCfg->anchoredJoints[j].bAnchorIdx;
const pym_rb_named_t *ajBodyA = &pymCfg->body[ ajBodyAIdx ].b;
const pym_rb_named_t *ajBodyB = &pymCfg->body[ bjBodyAIdx ].b;
const char *aAncName = ajBodyA->jointAnchorNames[ aancIdx ];
const char *bAncName = ajBodyA->jointAnchorNames[ bancIdx ];
char aiden[128], biden[128];
ExtractAnchorIdentifier(aiden, aAncName);
ExtractAnchorIdentifier(biden, bAncName);
//std::cout << "Joint anchor - " << aiden << " (" << ajBodyA->name << " == " << ajBodyB->name << ")" << std::endl;
assert(aancIdx < ajBodyA->nAnchor);
assert(bancIdx < ajBodyB->nAnchor);
const double *aanc = ajBodyA->jointAnchors[aancIdx];
const double *banc = ajBodyB->jointAnchors[bancIdx];
double achi[6] = { ajBodyA->p[0],
ajBodyA->p[1],
ajBodyA->p[2],
ajBodyA->q[0],
ajBodyA->q[1],
ajBodyA->q[2] };
double bchi[6] = { ajBodyB->p[0],
ajBodyB->p[1],
ajBodyB->p[2],
ajBodyB->q[0],
ajBodyB->q[1],
ajBodyB->q[2] };
double aW[4][4], bW[4][4];
GetWFrom6Dof(aW, achi);
GetWFrom6Dof(bW, bchi);
double aaj[3], baj[3];
TransformPoint(aaj, aW, aanc);
TransformPoint(baj, bW, banc);
glPushMatrix();
glTranslated(aaj[0], aaj[1], aaj[2]);
ArnRenderSphereGl(0.03);
glPopMatrix();
glPushMatrix();
glTranslated(baj[0], baj[1], baj[2]);
ArnRenderSphereGl(0.03);
glPopMatrix();
glPushAttrib(GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
glColor3f(1,0,0);
// Body A's anchored joint position line
glBegin(GL_LINES);
glVertex3dv(ajBodyA->p);
glVertex3dv(aaj);
glEnd();
// Body B's anchored joint position line
glBegin(GL_LINES);
glVertex3dv(ajBodyB->p);
glVertex3dv(baj);
glEnd();
glColor3f(0,1,0);
// A line connecting two anchored joints
glBegin(GL_LINES);
glVertex3dv(aaj);
glVertex3dv(baj);
glEnd();
glPopAttrib();
}
//printf("pymCfg address2 = %p\n", phyCon->pymCfg);
if (strcmp(phyCon->pymCfg->trajName, "Walk1") == 0) {
static const double s[3][3] = { { 1.557, 0.580, 0.210 },
{ 1.557, 0.580, 0.413 },
{ 1.557, 0.580, 0.630 } };
static const double p[3][3] = { { 0.973, 0.298, 0.104 },
{ 0.973, 0.891, 0.207 },
{ 0.973, 1.478, 0.316 } };
glColor3f(1,1,1);
pym_strict_checK_gl();
FOR_0(i, 3) {
DrawBox_pq(p[i], 0, s[i], 0);
}
}
glPopMatrix();
}
static int CreateGridPatternGroundTexture(void) {
GLuint gndTex;
glGenTextures(1, &gndTex);
assert(gndTex > 0);
glBindTexture( GL_TEXTURE_2D, gndTex );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR );
// when texture area is large, bilinear filter the original
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// the texture wraps over at the edges (repeat)
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
// allocate buffer
int gndTexSize = 512;
unsigned char *data = (unsigned char *)malloc( gndTexSize * gndTexSize * 3 );
memset(data, 0, gndTexSize * gndTexSize * 3);
unsigned char xAxisColor[] = { 120, 200, 220 };
unsigned char yAxisColor[] = { 120, 200, 220 };
int i, j;
FOR_0(i, gndTexSize) {
for (j=-1; j<=1; ++j) {
data[3*(gndTexSize*(gndTexSize/2+j) + i) + 0] = xAxisColor[0];
data[3*(gndTexSize*(gndTexSize/2+j) + i) + 1] = xAxisColor[1];
data[3*(gndTexSize*(gndTexSize/2+j) + i) + 2] = xAxisColor[2];
data[3*(gndTexSize*i + (gndTexSize/2+j)) + 0] = yAxisColor[0];
data[3*(gndTexSize*i + (gndTexSize/2+j)) + 1] = yAxisColor[1];
data[3*(gndTexSize*i + (gndTexSize/2+j)) + 2] = yAxisColor[2];
}
for (j=-gndTexSize/2; j<gndTexSize/2-1; j+=32) {
data[3*(gndTexSize*(gndTexSize/2+j) + i) + 0] = xAxisColor[0];
data[3*(gndTexSize*(gndTexSize/2+j) + i) + 1] = xAxisColor[1];
data[3*(gndTexSize*(gndTexSize/2+j) + i) + 2] = xAxisColor[2];
// data[3*(gndTexSize*(gndTexSize/2+j+1) + i) + 0] = xAxisColor[0];
// data[3*(gndTexSize*(gndTexSize/2+j+1) + i) + 1] = xAxisColor[1];
// data[3*(gndTexSize*(gndTexSize/2+j+1) + i) + 2] = xAxisColor[2];
}
for (j=-gndTexSize/2; j<gndTexSize/2-1; j+=32) {
data[3*(gndTexSize*i + (gndTexSize/2+j)) + 0] = yAxisColor[0];
data[3*(gndTexSize*i + (gndTexSize/2+j)) + 1] = yAxisColor[1];
data[3*(gndTexSize*i + (gndTexSize/2+j)) + 2] = yAxisColor[2];
// data[3*(gndTexSize*i + (gndTexSize/2+j+1)) + 0] = yAxisColor[0];
// data[3*(gndTexSize*i + (gndTexSize/2+j+1)) + 1] = yAxisColor[1];
// data[3*(gndTexSize*i + (gndTexSize/2+j+1)) + 2] = yAxisColor[2];
}
}
// open and read texture data
// build our texture mipmaps
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, gndTexSize, gndTexSize,
GL_RGB, GL_UNSIGNED_BYTE, data );
glBindTexture(GL_TEXTURE_2D, 0);
free(data);
return gndTex;
}
static void RenderGraph(PRSGRAPH g, int slotid, pym_render_config_t *rc) {
glPushMatrix(); /* stack A */
const double margin = 0.05;
double graphW, graphH;
double graphGapX, graphGapY;
const int width = rc->vpw;
const int height = rc->vph;
if (width > height) {
graphGapX = margin*height/width;
graphGapY = margin;
graphW = 0.12*height/width;
graphH = 0.3;
} else {
graphGapX = margin;
graphGapY = margin*width/height;
graphW = 0.12;
graphH = 0.3*width/height;
}
const double graphX = -1 + graphGapX + slotid*(graphW + graphGapX);
const double graphY = -1 + graphGapY;
glTranslated(graphX, graphY, 0);
glScaled(graphW, graphH, 1);
glPushAttrib(GL_LIST_BIT | GL_DEPTH_BUFFER_BIT); /* stack B */
glDisable(GL_DEPTH_TEST);
PrsGraphRender(g);
/* Graph title */
/* glColor3f(1.0f, 1.0f, 1.0f); */
/* glListBase(fps_font - ' '); */
/* static const double fontHeight = 14.0; */
/* glWindowPos2d((graphX + 1)*width/2, */
/* (graphY + 1)*height/2 - fontHeight); */
/* const char *test = PrsGraphTitle(g); */
/* glCallLists(strlen(test), GL_UNSIGNED_BYTE, test); */
glPopAttrib(); /* stack B */
glPopMatrix(); /* stack A */
}
static void RenderSupportPolygon
(const pym_physics_thread_context_t *const phyCon,
pym_render_config_t *rc,
const int chInputLen, const Point_C *const chInput,
const int chOutputLen, const Point_C *const chOutput, const double *const col) {
int i;
//const int chInputLen = phyCon->pymCfg->chInputLen;
//const int chOutputLen = phyCon->pymCfg->chOutputLen;
const int width = rc->vpw;
const int height = rc->vph;
if (chInputLen+1 < chOutputLen) {
printf("ERROR - chInputLen = %d, chOutputLen = %d\n",
chInputLen, chOutputLen);
//abort();
}
/* PAIR A */
glPushAttrib(GL_LINE_BIT | GL_CURRENT_BIT | GL_POINT_BIT);
glPushMatrix(); /* PAIR B */
const double margin = 0.05;
/* size on normalized coordinates */
const double sizeW = 0.5, sizeH = 0.5;
double graphW, graphH;
double graphGapX, graphGapY;
if (width > height) {
graphGapX = margin*height/width;
graphGapY = margin;
graphW = sizeW*height/width;
graphH = sizeH;
} else {
graphGapX = margin;
graphGapY = margin*width/height;
graphW = sizeW;
graphH = sizeH*width/height;
}
const int slotid = 0;
const double graphX = -1 + graphW/2 + graphGapX
+ slotid*(graphW/2 + graphGapX);
const double graphY = 1 - graphGapY - graphH/2;
glTranslated(graphX, graphY, 0);
glScaled(graphW, graphH, 1);
double chSumX = 0, chSumY = 0;
double chMeanX = 0;
double chMeanY = 0;
if (chOutputLen > 0) {
FOR_0(i, chOutputLen-1) {
chSumX += chOutput[i].x;
chSumY += chOutput[i].y;
}
chMeanX = chSumX / (chOutputLen-1);
chMeanY = chSumY / (chOutputLen-1);
} else if (chInputLen > 0) {
FOR_0(i, chInputLen) {
chSumX += chInput[i].x;
chSumY += chInput[i].y;
}
chMeanX = chSumX / chInputLen;
chMeanY = chSumY / chInputLen;
}
glColor3dv(col);
glPushMatrix(); // PUSH ABC
glBegin(GL_LINE_LOOP);
if (chOutputLen) {
FOR_0(i, chOutputLen) {
glVertex2d(chOutput[i].x, chOutput[i].y);
}
} else if (chInputLen) {
FOR_0(i, chInputLen) {
glVertex2d(chInput[i].x, chInput[i].y);
}
glVertex2d(chInput[0].x, chInput[0].y);
}
glEnd();
glPointSize(3);
glColor3dv(col);
glBegin(GL_POINTS);
FOR_0(i, chInputLen) {
glVertex2d(chInput[i].x, chInput[i].y);
}
glEnd();
glPopMatrix(); // POP ABC
glPushMatrix(); // PUSH KKK
glPointSize(5);
glColor3d(1, 0, 0);
glTranslated(phyCon->pymCfg->bipCom[0], phyCon->pymCfg->bipCom[1], 0);
glScaled(0.015,0.015,1);
glBegin(GL_LINE_LOOP);
glVertex3d(1,1,0);
glVertex3d(-1,1,0);
glVertex3d(-1,-1,0);
glVertex3d(1,-1,0);
glEnd();
glPopMatrix(); // POP KKK
glPushMatrix(); // PUSH KKK
glPointSize(5);
glColor3dv(col);
glTranslated(chMeanX, chMeanY, 0);
glScaled(0.025,0.025,1);
glBegin(GL_LINES);
glVertex2d(-1, 0);
glVertex2d(+1, 0);
glVertex2d(0, -1);
glVertex2d(0, +1);
glEnd();
glPopMatrix(); // POP KKK
glPopMatrix(); /* PAIR B */
glPopAttrib(); /* PAIR A */
}
void PymRsInitRender() {
gndTex = CreateGridPatternGroundTexture();
if (glGenVertexArrays && glBindVertexArray)
InitVertexArrayObjects(m_vaoID);
//preparedata();
//generateShadowFBO();
//loadShadowShader();
}
void PymRsDestroyRender() {
glDeleteTextures(1, &gndTex);
}
/*
* Precondition: Projection, modelview matrices are already set up.
*/
void PymRsRender(pym_rs_t *rs, pym_render_config_t *rc) {
pym_strict_checK_gl();
if (glUseProgramObjectARB)
glUseProgramObjectARB(0);
pym_configure_light();
pym_strict_checK_gl();
pym_draw_all(rs, 0, m_vaoID);
pym_strict_checK_gl();
//RenderFootContactFixPosition(&rs->phyCon);
/* Head-up Display
* --------------------------
* Turn off shader and use fixed pipeline.
* Also make sure we have identities
* on projection and modelview matrix.
*/
if (rs->pymCfg.render_hud) {
glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
RenderGraph(rs->phyCon.comZGraph, 0, rc);
RenderGraph(rs->phyCon.comDevGraph, 1, rc);
RenderGraph(rs->phyCon.actGraph, 2, rc);
RenderGraph(rs->phyCon.ligGraph, 3, rc);
for (int i = 0; i < rs->pymCfg.nBody; ++i)
RenderGraph(rs->phyCon.exprotGraph[i], 4 + i, rc);
pym_strict_checK_gl();
static const double PHY_CP_COLOR[3] = { 0, 1, 0 };
static const double VIR_CP_COLOR[3] = { 0.8, 0.75, 0.2 };
RenderSupportPolygon(&rs->phyCon, rc,
rs->phyCon.pymCfg->chVInputLen, rs->phyCon.pymCfg->chVInput,
rs->phyCon.pymCfg->chVOutputLen, rs->phyCon.pymCfg->chVOutput, VIR_CP_COLOR);
RenderSupportPolygon(&rs->phyCon, rc,
rs->phyCon.pymCfg->chInputLen, rs->phyCon.pymCfg->chInput,
rs->phyCon.pymCfg->chOutputLen, rs->phyCon.pymCfg->chOutput, PHY_CP_COLOR);
RenderFootContactStatus(&rs->phyCon);
pym_strict_checK_gl();
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopAttrib();
}
}
| [
"Dan@Dan-PC.(none)",
"[email protected]"
] | [
[
[
1,
1
],
[
8,
8
]
],
[
[
2,
7
],
[
9,
1418
]
]
] |
e5f0bf9b96a855f8f85fc882afa31d2d23e450cc | 9340e21ef492eec9f19d1e4ef2ef33a19354ca6e | /cing/src/video/MediaPlayerGS.cpp | 256552b5ff06daec83b8534e327d66ccb8da2036 | [] | no_license | jamessqr/Cing | e236c38fe729fd9d49ccd1584358eaad475f7686 | c46045d9d0c2b4d9e569466971bbff1662be4e7a | refs/heads/master | 2021-01-17T22:55:17.935520 | 2011-05-14T18:35:30 | 2011-05-14T18:35:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,741 | cpp | /*
This source file is part of the Cing project
For the latest info, see http://www.cing.cc
Copyright (c) 2008-2010 Julio Obelleiro and Jorge Cano
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 im_mediaPlayerlied 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 Tem_mediaPlayerle Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Precompiled headers
#include "Cing-Precompiled.h"
#include "MediaPlayerGS.h"
#include "GStreamerManager.h"
// GStreamer
#include <gst/video/video.h>
// Common
#include "common/CommonUtilsIncludes.h"
#include "common/XMLElement.h"
#include "common/LogManager.h"
// Framework
#include "framework/UserAppGlobals.h"
// Graphics
#include "graphics/Color.h"
namespace Cing
{
// GStreamer Callback functions
/**
* @internal
* Called from GStreamer when there is new decoded frame from the playing video
* @param sink GStremaer Sink that is giving us the new frame
* @param userData Is the pointer to the MediaPlayerGS instance
*/
static GstFlowReturn onNewBufferHandler(GstAppSink *sink, gpointer userData)
{
MediaPlayerGS* mediaPlayer = reinterpret_cast<MediaPlayerGS*>(userData);
if ( mediaPlayer == NULL )
{
LOG_ERROR( "MediaPlayerGS::onNewBufferHandler error. MediaPlayerGS is NULL. Cannot store new frame" );
return GST_FLOW_OK;
}
// Get appSink state
GstState currentState;
GstStateChangeReturn ret = gst_element_get_state(GST_ELEMENT(mediaPlayer->getPlayBin()), ¤tState, NULL, 0);
// Get the new buffer (or the preroll if the stream is paused, as there should be no new buffer in this case)
GstBuffer* buffer = NULL;
if ( currentState == GST_STATE_PAUSED )
buffer = gst_app_sink_pull_preroll(sink );
else
buffer = gst_app_sink_pull_buffer( sink );
// Check new buffer
if ( buffer == NULL )
{
LOG_ERROR( "GStreamer reported new buffer, but the new buffer is NULL" );
return GST_FLOW_OK;
}
// Buffer is ok -> notify
mediaPlayer->onNewBuffer( buffer );
// All good
return GST_FLOW_OK;
}
/**
* @internal
* Called from GStreamer when there is a new message comming from the Bus (like End of Stream)
* @param bus GStremaer Bus that is giving us the message
* @param message The GStreamer message itself
* @param userData The Gstreamer player that initiated the playback
*/
static GstBusSyncReply onSyncBusMessageHandler(GstBus * bus, GstMessage * message, gpointer userData)
{
// Get pointer to the player
MediaPlayerGS* player = reinterpret_cast<MediaPlayerGS*>(userData);
if ( !player )
{
LOG_ERROR( "onSyncBusMessage Error: NULL player. Cannot process the GStreamer message" );
return GST_BUS_PASS;
}
// Decode message
switch (GST_MESSAGE_TYPE(message))
{
case GST_MESSAGE_EOS:
//LOG_TRIVIAL( "End of stream" );
player->onEndOfStream();
break;
case GST_MESSAGE_ERROR:
player->stop();
// Get error info
GError* error;
gchar* debugInfo;
gst_message_parse_error(message, &error, &debugInfo);
// Report it
LOG_ERROR( "Gstreamer Error (%s): %s", GST_OBJECT_NAME (message->src), error->message );
// Free error resources
g_error_free(error);
g_free(debugInfo);
// Stop the media player
player->stop();
break;
default:
break;
}
return GST_BUS_PASS;
}
/**
* Default constructor.
*/
MediaPlayerGS::MediaPlayerGS():
m_pipeline ( NULL ),
m_appSink ( NULL ),
m_appBin ( NULL ),
m_internalBuffer( NULL ),
m_bufferSizeInBytes(0),
m_videoWidth ( 0 ),
m_videoHeight ( 0 ),
m_videoFps ( 0 ),
m_videoDuration ( 0 ),
m_loop ( false ),
m_loopPending ( false ),
m_newBufferReady( false ),
m_bIsValid ( false ),
m_pixelFormat ( RGB ),
m_mute ( false ),
m_volume ( 1.0f ),
m_endOfFileReached (false),
m_paused (false),
m_playing (false)
{
}
/**
* Constructor to load a movie file.
* @param filename Name of the movie to load (it can be a local path relative to the data folder, or a network path)
* @param fps Desired Frames per Second for the playback. -1 means to use the fps of the movie file.
*/
MediaPlayerGS::MediaPlayerGS( const char* filename, float fps /*= -1*/ ):
m_pipeline ( NULL ),
m_appSink ( NULL ),
m_appBin ( NULL ),
m_internalBuffer( NULL ),
m_bufferSizeInBytes(0),
m_videoWidth ( 0 ),
m_videoHeight ( 0 ),
m_videoFps ( 0 ),
m_videoDuration ( 0 ),
m_loop ( false ),
m_loopPending ( false ),
m_newBufferReady( false ),
m_bIsValid ( false ),
m_pixelFormat ( RGB ),
m_mute ( false ),
m_volume ( 1.0f ),
m_endOfFileReached (false),
m_paused (false),
m_playing (false)
{
// Load the movie
load( filename, RGB, fps );
}
/**
* Default destructor.
*/
MediaPlayerGS::~MediaPlayerGS()
{
end();
}
/**
* Inits the object to make it valid.
*/
bool MediaPlayerGS::init()
{
LOG_ENTER_FUNCTION;
// GStreamer Init
return GStreamerManager::initGStreamer();
LOG_EXIT_FUNCTION;
}
/**
* Loads a movie file
* @param filename Name of the movie to load (it can be a local path relative to the data folder, or a network path)
* @param requestedVideoFormat Format in which the frames of the movie will be stored. Default RGB, which means that the
* movie file video format will be used (regarding alpha channel: RGB vs RGBA)
* @param fps Desired Frames per Second for the playback. -1 means to use the fps of the movie file.
* @return true if the video was succesfully loaded
*/
bool MediaPlayerGS::load( const char* fileName, GraphicsType requestedVideoFormat /*= RGB*/, float fps /*= -1*/ )
{
LOG_ENTER_FUNCTION;
// Init the player (to make sure GStreamer is initialized)
bool result = init();
if ( !result )
{
LOG_ERROR( "MediaPlayerGS::load. Error loading %s, GStreamer could not load it correctly.", fileName );
end();
return false;
}
// Build path to file
result = buildPathToFile( fileName );
if ( !result )
{
LOG_ERROR( "MediaPlayerGS::load. File %s Not Found", fileName );
end();
return false;
}
// Create the Gstreamer Pipeline
result = createPipeline();
if ( !result )
{
LOG_ERROR( "MediaPlayerGS::load. Error loading %s, GStreamer could create the pipeline to play it.", fileName );
end();
return false;
}
// By default, playbin creates its own window to which it streams
// video output. We create an appsink element to allow video to be
// streamed to our own Cing Image
result = createVideoSink();
if ( !result )
{
LOG_ERROR( "MediaPlayerGS::load. Error loading %s, GStreamer could create the sink to play it.", fileName );
end();
return false;
}
// Configure the output video format
result = configureVideoFormat( requestedVideoFormat );
if ( !result )
{
LOG_ERROR( "MediaPlayerGS::load. Error loading %s, Image format could not be configured.", fileName );
end();
return false;
}
// Init the frame container to the video size
m_frameImg.init( m_videoWidth, m_videoHeight, m_pixelFormat );
m_bufferSizeInBytes = m_videoWidth * m_videoHeight * m_frameImg.getNChannels();
m_internalBuffer = new unsigned char[m_bufferSizeInBytes];
// Query video duration
GstFormat format = GST_FORMAT_TIME;
gint64 duration;
gboolean res = gst_element_query_duration( GST_ELEMENT(m_pipeline), &format, &duration );
if ( res != 1 )
{
LOG_ERROR( "MediaPlayerGS::time() Error getting video duration" );
end();
return false;
}
m_videoDuration = duration / 1000000000.0;
// Also store the number of frames
m_nFrames = m_videoFps * m_videoDuration;
// Check if the requested fps is different than the actual video fps -> if so, change it
if ( (fps > 0) && (equal(fps, m_videoFps) == false) )
{
float newSpeed = fps/m_videoFps;
speed( newSpeed );
}
LOG( "MediaPlayer: File %s correctly loaded", m_fileName.c_str() );
// Init other vars
m_endOfFileReached = false;
m_loopPending = false;
m_paused = false;
m_playing = false;
// The object is valid when the file is loaded
m_bIsValid = true;
LOG_EXIT_FUNCTION;
return true;
}
/**
* Releases the object's resources
*/
void MediaPlayerGS::end()
{
LOG_ENTER_FUNCTION;
// Check if already released
if ( !isValid() )
return;
// Clean Gstreamer stuff
gst_element_set_state (m_pipeline, GST_STATE_NULL);
gst_object_unref (GST_OBJECT (m_pipeline));
// Clear pointers
delete []m_internalBuffer;
m_internalBuffer = NULL;
m_pipeline = NULL;
m_appSink = NULL;
m_appBin = NULL;
// Clear flags
m_bIsValid = false;
m_newBufferReady = false;
m_loopPending = false;
m_paused = false;
m_playing = false;
LOG_EXIT_FUNCTION;
}
/**
* Updates media playback state
*/
void MediaPlayerGS::update()
{
LOG_ENTER_FUNCTION;
// Check if we have to loop
if ( m_loopPending )
{
jump(0);
m_loopPending = false;
}
LOG_EXIT_FUNCTION;
}
/**
* Returns the internal Image (that contains the last buffer coming from the stream)
*/
Image& MediaPlayerGS::getImage()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR_NTIMES( 1, "MediaPlayerGS not corretly initialized. No new frame will be returned" );
return m_frameImg;
}
// Update, just in case there are pending operations
update();
// Check if we have a new buffer to copy
if ( m_newBufferReady )
copyBufferIntoImage();
LOG_EXIT_FUNCTION;
return m_frameImg;
}
/**
* Returns true if the media is playing, false otherwise
**/
bool MediaPlayerGS::isPlaying()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized" );
return false;
}
LOG_EXIT_FUNCTION;
return m_playing;
}
/**
* Returns true if the media is paused, false otherwise
**/
bool MediaPlayerGS::isPaused()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized" );
return false;
}
LOG_EXIT_FUNCTION;
return m_paused;
}
/**
* Returns the location of the play head in seconds (that is, the time it has played)
**/
float MediaPlayerGS::time()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized. Time cannot be obtained" );
return 0;
}
GstFormat format = GST_FORMAT_TIME;
gint64 currentPosition;
gboolean result = gst_element_query_position( GST_ELEMENT(m_pipeline), &format, ¤tPosition );
if ( result != 1 )
{
LOG_ERROR( "MediaPlayerGS::time() Error getting curret position" );
return 0;
}
LOG_EXIT_FUNCTION;
return currentPosition / 1000000000.0f;
}
/**
* Plays the media with no loop
**/
void MediaPlayerGS::play()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized. File will not play" );
return;
}
// Clean bus to avoid accumulation of messages
flushBusMsg();
// If the end of the file was reached, reset the playhead to the beginning
if ( m_endOfFileReached )
{
jump(0);
m_endOfFileReached = false;
}
// no loop mode
m_loop = false;
m_paused = false;
m_playing = true;
// Play Stream
setPipelineState(GST_STATE_PLAYING);
LOG_EXIT_FUNCTION;
}
/**
* Plays the media with no loop
**/
void MediaPlayerGS::loop()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized. File will not loop" );
return;
}
// Clean bus to avoid accumulation of messages
flushBusMsg();
// If the end of the file was reached, reset the playhead to the beginning
if ( m_endOfFileReached )
{
jump(0);
m_endOfFileReached = false;
}
// loop mode
m_loop = true;
m_paused = false;
m_playing = true;
// Play Stream
setPipelineState(GST_STATE_PLAYING);
LOG_EXIT_FUNCTION;
}
/**
* Plays the media with no loop
**/
void MediaPlayerGS::stop()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized. File will not stop (as it is not playing)" );
return;
}
// Reset playhead and pause
jump(0);
setPipelineState(GST_STATE_PAUSED);
m_paused = false;
m_playing = false;
LOG_EXIT_FUNCTION;
}
/**
* Plays the media with no loop
**/
void MediaPlayerGS::pause()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized. File will not pause (as it is not playing)" );
return;
}
// pause the media
setPipelineState(GST_STATE_PAUSED);
m_paused = true;
m_playing = false;
LOG_EXIT_FUNCTION;
}
/**
* Jumps to a specific location within a movie (specified in seconds)
* @param whereInSecs Where to jump in the movie (in seconds)
**/
void MediaPlayerGS::jump( float whereInSecs )
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized. File will not jump" );
return;
}
// Clamp time position
whereInSecs = constrain( whereInSecs, 0, duration() );
// Clean bus to avoid accumulation of messages
flushBusMsg();
// If we have a new buffer available, clear the flag, we don't want it anymore after the seek
m_newBufferReady = false;
// Perform the seek
GstSeekFlags flags = (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE);
gint64 currentPos = whereInSecs * GST_SECOND; /// Time in Gstreamer is in nano seconds
double speed = 1.0;
GstFormat format = GST_FORMAT_TIME;
gboolean ret = gst_element_seek(GST_ELEMENT(m_pipeline), speed, format, flags, GST_SEEK_TYPE_SET, currentPos, GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE);
if ( ret != 1 )
{
LOG_ERROR( "MediaPlayerGS::jump. Error performing GStreamer seek" );
}
// Get Current state
GstState currentState, pendingState;
GstStateChangeReturn currentRet = gst_element_get_state(GST_ELEMENT(m_pipeline), ¤tState, &pendingState, 2000 * GST_MSECOND );
// Play the pipeline (to get the new frame after the seek), but tell it to return to pause if it's not currently playing
if ( currentState == GST_STATE_PAUSED )
{
setPipelineState(GST_STATE_PLAYING);
setPipelineState(GST_STATE_PAUSED);
}
LOG_EXIT_FUNCTION;
}
/**
* Jumps to a specific location within a movie (specified in frame number)
* @param whereInSecs Where to jump in the movie (in seconds)
**/
void MediaPlayerGS::jumpToFrame ( unsigned int frameNumber )
{
LOG_ENTER_FUNCTION;
// Clamp time position
frameNumber = constrain( frameNumber, 0, numberOfFrames()-1 );
// Calculate time in seconds for this frame
double whereInSecs = (double)frameNumber / fps();
// Jump to that second
jump( whereInSecs );
LOG_EXIT_FUNCTION;
}
/**
* Sets the relative playback speed of the movie (
* Examples: 1.0 = normal speed, 2.0 = 2x speed, 0.5 = half speed
* @param rate Speed rate to play the movie
**/
void MediaPlayerGS::speed( float rate )
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized" );
return;
}
// Perform the seek
GstSeekFlags flags = (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_SKIP | GST_SEEK_FLAG_ACCURATE);
int currentPos = 0;
GstFormat format = GST_FORMAT_TIME;
gboolean ret = gst_element_seek(GST_ELEMENT(m_pipeline), rate, format, flags, GST_SEEK_TYPE_NONE, currentPos, GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE);
if ( ret != 1 )
{
LOG_ERROR( "MediaPlayerGS::speed. Error performing GStreamer seek" );
}
LOG_EXIT_FUNCTION;
}
/**
* Toggles the audio mute
**/
void MediaPlayerGS::toggleMute()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized" );
return;
}
// Toggle mute
m_mute = !m_mute;
// if mute -> set volume to 0
if ( m_mute )
setVolume( 0 );
// otherwise -> reset previous volume
else
setVolume( m_volume );
LOG_EXIT_FUNCTION;
}
/**
* Sets audio volume (0..1)
* @param volume new volume
**/
void MediaPlayerGS::setVolume( float volume )
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized. File will not play" );
return;
}
g_object_set (G_OBJECT(m_pipeline), "volume", volume, (const char*)NULL);
LOG_EXIT_FUNCTION;
}
/**
* Returns the current audio volume (0..1)
* @return current volume
**/
float MediaPlayerGS::getVolume() const
{
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS not corretly initialized. File will not play" );
return 0;
}
float volume;
g_object_get (G_OBJECT(m_pipeline), "volume", &volume, (const char*)NULL);
LOG_EXIT_FUNCTION;
return volume;
}
/**
* Notifies about a new buffer ready from the stream.
* The buffer is released (unreffed) when it has been copied, which happens when the image is requested from the user)
* @param newBuffer New GStreamer buffer ready to be copied
*/
void MediaPlayerGS::onNewBuffer( GstBuffer* newBuffer )
{
LOG_ENTER_FUNCTION;
// Check buffer
if ( newBuffer == NULL )
return;
// Set new buffer flag (so that it's copied into the image when it is required)
m_newBufferReady = true;
// Obtain the dimensions of the video.
GstCaps* caps = gst_buffer_get_caps(newBuffer);
GstVideoFormat currentVideoFormat;
int width = 0;
int height = 0;
int ratioNum = 0;
int ratioDen = 0;
float pixelRatio = 1.0;
for (size_t i = 0; i < gst_caps_get_size(caps); ++i)
{
GstStructure* structure = gst_caps_get_structure(caps, i);
// Get current video format and dimensions
gst_video_format_parse_caps( caps, ¤tVideoFormat, &width, &height );
// Aspect Ratio (even if it's not used for now)
if (gst_structure_get_fraction(structure, "pixel-aspect-ratio",&ratioNum, &ratioDen))
{
pixelRatio = ratioNum / static_cast<float>(ratioDen);
}
}
// Check buffer dimensions (to make sure they match with the Image before copying)
if ( (m_videoWidth != width) || (m_videoHeight != height) )
{
LOG_ERROR( "MediaPlayerGS::copyBufferIntoImage. New frame's dimensions do not match with stored dimensions. New frame will not be loaded" );
return;
}
// Copy Gstreamer buffer into our internal temporary buffer
// We do this instead of keeping gstreamer buffer reference, as doing so, gstreamer crashes (or throws errors)
m_bufferMutex.lock();
memcpy( m_internalBuffer, (char*)GST_BUFFER_DATA(newBuffer), m_bufferSizeInBytes );
// We have the image -> the buffer is ready to be reused by GStreamer
gst_buffer_unref(newBuffer);
// operation done
m_bufferMutex.unlock();
LOG_EXIT_FUNCTION;
}
/**
* Notifies that the stream that is being player has reached its end
*/
void MediaPlayerGS::onEndOfStream()
{
LOG_ENTER_FUNCTION;
// Check if we need to loop
if ( m_loop )
{
m_loopPending = true;
}
// End of playback
else
{
// Flag the end of the stream
m_endOfFileReached = true;
m_paused = false;
m_playing = false;
}
LOG_EXIT_FUNCTION;
}
/**
* Builds an absolute path to the file that will be loaded into the player
* @return true if there was no problem
*/
bool MediaPlayerGS::buildPathToFile( const String& path )
{
LOG_ENTER_FUNCTION;
// Store incomming path as the filename (if it's a local file, the use would have passed the file path
// relative to the data folder)
m_fileName = path;
// Check if it is a network path
if ( m_fileName.find( "://" ) != std::string::npos )
m_filePath = m_fileName;
// It looks like a local path -> check if it exists
else
{
m_filePath = dataFolder + path;
if ( !fileExists( m_filePath ) )
{
LOG_ERROR( "MediaPlayer: File %s not found in data folder.", path.c_str() );
LOG_ERROR( "Absolute path to file: %s", m_filePath.c_str() );
return false;
}
// Build uri in the formtat tha GStreamer expects it
m_filePath = "file:///" + m_filePath;
}
LOG_EXIT_FUNCTION;
return true;
}
/**
* Creates and configues the GStreamer pipeline that will allow the media playback and control
* @return true if there was no problem
*/
bool MediaPlayerGS::createPipeline()
{
LOG_ENTER_FUNCTION;
// Create the GStreamer pipeline (playbin2 is an all-in-one audio and video player)
m_pipeline = gst_element_factory_make ("playbin2", NULL);
if ( m_pipeline == NULL )
{
LOG_ERROR( "GStreamer Error: Could not create pipeline playbin2" );
return false;
}
// Set the location of the file to load
g_object_set (G_OBJECT (m_pipeline), "uri", m_filePath.c_str(), NULL);
// Listen for messages on the playbin pipeline bus (to detect events like end of stream)
GstElement *bus = (GstElement *)gst_pipeline_get_bus(GST_PIPELINE(m_pipeline));
gst_bus_set_sync_handler (GST_BUS(bus), (GstBusSyncHandler)onSyncBusMessageHandler, this);
gst_object_unref(bus);
LOG_EXIT_FUNCTION;
return true;
}
/**
* Sets a specific state to the pipeline
* @state state to be set. The state change might not syncrhonous.
*/
void MediaPlayerGS::setPipelineState( GstState state )
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() )
{
LOG_ERROR( "MediaPlayerGS is not valid yet. Cannot change the pipeline state. Did you call load()?" );
return;
}
// Change the state
GstStateChangeReturn ret = gst_element_set_state(GST_ELEMENT(m_pipeline), state);
if ( (ret != GST_STATE_CHANGE_SUCCESS) && (ret != GST_STATE_CHANGE_ASYNC) )
LOG_ERROR( "GStreamer Error, State could not be changed in the pipeline. Error Code %d", ret );
LOG_EXIT_FUNCTION;
}
/**
* Creates and configues the GStreamer video sink that will allow our app to get the decoded video frames
* @return true if there was no problem
*/
bool MediaPlayerGS::createVideoSink()
{
LOG_ENTER_FUNCTION;
// Create our video sink
m_appSink = gst_element_factory_make("appsink", NULL);
if ( m_appSink == NULL )
{
LOG_ERROR( "GStreamer Error: Could not create the video app sync" );
return false;
}
// Set the new sink as the pipeline video sink
g_object_set (G_OBJECT(m_pipeline), "video-sink", m_appSink, (const char*)NULL);
// Configure the video sink
// Make it play the media in real time
gst_base_sink_set_sync(GST_BASE_SINK(m_appSink), true);
g_object_set(G_OBJECT(m_appSink), "drop", true, NULL);
//< NOTE: this should be set to one (as we only want 1 buffer), but the performance is better disabling it
//-> check memory hit
//g_object_set(G_OBJECT(m_appSink), "max-buffers", 1, NULL);
//Listen for new-buffer signals
g_object_set(G_OBJECT(m_appSink), "emit-signals", true, NULL);
g_signal_connect(G_OBJECT(m_appSink), "new-buffer", G_CALLBACK(onNewBufferHandler), this);
LOG_EXIT_FUNCTION;
// all fine
return true;
}
/**
* Detects and set the most suitable video format trying to match the requested video format, and the movie video format
* @param requestedVideoFormat Requested video format for the Image video frames
* @param movieVideoFormat Movie file video format
*/
bool MediaPlayerGS::configureVideoFormat( GraphicsType requestedVideoFormat )
{
LOG_ENTER_FUNCTION;
// Define the video format in GStreamer terms (according to the requested Cing video format)
m_outputGstVideoFormat = cingToGstPixelFormat( requestedVideoFormat );
// Create custom caps, to force a certain video output format
GstCaps* caps = gst_caps_from_string(m_outputGstVideoFormat.c_str());
if ( caps == NULL )
{
LOG_ERROR( "GStreamer Error: Could not create the simple caps" );
return false ;
}
gst_app_sink_set_caps(GST_APP_SINK(m_appSink), caps);
gst_caps_unref(caps);
// Store the image cing pixel format in which the frames will be stored
m_pixelFormat = gstToCingPixelFormat(m_outputGstVideoFormat);
// Pause Stream (this will allow us to start getting frames as soon as the user plays the video)
GstState currentState, pendingState;
gst_element_set_state (GST_ELEMENT(m_pipeline), GST_STATE_PAUSED);
GstStateChangeReturn ret = gst_element_get_state(GST_ELEMENT(m_pipeline), ¤tState, &pendingState, 2000 * GST_MSECOND );
if ( ret == GST_STATE_CHANGE_FAILURE )
{
LOG_ERROR( "MediaPlayerGS: Error setting GST_STATE_PAUSED state. The video dimensions might not be retrieved correctly." );
}
// Security check: check that video format was set succesfully
// Get the player buffer to retrieve its caps (to get info about the video format)
GstBuffer* buffer = NULL;
g_object_get( GST_ELEMENT(m_pipeline), "frame", &buffer, NULL);
// Get caps from buffer
caps = gst_buffer_get_caps(buffer);
gst_buffer_unref(buffer);
// Get current video format and dimensions
GstVideoFormat currentVideoFormat;
gst_video_format_parse_caps( caps, ¤tVideoFormat, &m_videoWidth, &m_videoHeight );
// Get current fps
gint fps_n, fps_d;
gboolean res = gst_video_parse_caps_framerate( caps, &fps_n, &fps_d );
m_videoFps = (float)fps_n / (float)fps_d;
gst_caps_unref(caps);
// Check format
if ( checkVideoFormatMatch( currentVideoFormat, requestedVideoFormat ) == false )
{
LOG_ERROR( "MediaPlayerGS: Error: Video format could not be set correctly to the requested format" );
return false;
}
LOG_EXIT_FUNCTION;
// all good
return true;
}
/**
* Copies the last buffer that came from the stream into the Image (drawable)
*/
void MediaPlayerGS::copyBufferIntoImage()
{
LOG_ENTER_FUNCTION;
// Check if video is ok
if ( !isValid() || !m_newBufferReady)
return;
// Set image data (and upload it to the texture)
m_frameImg.setData( m_internalBuffer, m_videoWidth, m_videoHeight, m_frameImg.getFormat() );
m_frameImg.updateTexture();
// Clear new buffer flag
m_newBufferReady = false;
LOG_EXIT_FUNCTION;
}
/**
* Flushes the pending messages on the bus
*/
void MediaPlayerGS::flushBusMsg()
{
LOG_ENTER_FUNCTION;
// Flush messages on the bus
GstBus *bus = gst_element_get_bus(GST_ELEMENT(m_pipeline));
if(bus)
{
GstMessage *msg;
while((msg=gst_bus_pop(bus)) != NULL)
gst_message_unref(msg);
gst_object_unref(bus);
bus = NULL;
}
LOG_EXIT_FUNCTION;
}
/**
* Helper to convert Cing pixel format into Gstreamer video format
* @note: it only converts formats supported by Cing Images
* @param cingPixelFormat Cing Pixel format to be translated into Gstreamer pixel format
* @return Gstreamer video format
*/
const char* MediaPlayerGS::cingToGstPixelFormat( GraphicsType cingPixelFormat )
{
LOG_ENTER_FUNCTION;
switch( cingPixelFormat )
{
case RGB:
return GST_VIDEO_CAPS_RGB;
break;
case RGBA:
return GST_VIDEO_CAPS_RGBA;
break;
case BGR:
return GST_VIDEO_CAPS_BGR;
break;
case BGRA:
return GST_VIDEO_CAPS_BGRA;
break;
};
LOG_EXIT_FUNCTION;
// Not recognized -> default to RGB
return GST_VIDEO_CAPS_RGB;
}
/**
* Helper to convert GStreamer video format into Cing pixel format.
* @note: it only converts formats supported by Cing Images
* @param cingPixelFormat Cing Pixel format to be translated into Gstreamer pixel format
* @return Gstreamer pixel format
*/
GraphicsType MediaPlayerGS::gstToCingPixelFormat( const String& gstVideoFormat )
{
LOG_ENTER_FUNCTION;
if ( gstVideoFormat == GST_VIDEO_CAPS_RGB ) return RGB;
if ( gstVideoFormat == GST_VIDEO_CAPS_RGBA ) return RGBA;
if ( gstVideoFormat == GST_VIDEO_CAPS_BGR ) return BGR;
if ( gstVideoFormat == GST_VIDEO_CAPS_BGRA ) return BGRA;
LOG_EXIT_FUNCTION;
// Format not supported by Cing Images -> default to RGB
return RGB;
}
/**
* Helper to check if a GStreamer video format matches with a Cing pixel format.
* @note: it only compares formats supported by Cing Images
* @param gstVideoFormat GStreamer video format
* @param cingVideoFormat Cing video (image) format
* @return true if both formats match. false otherwise
*/
bool MediaPlayerGS::checkVideoFormatMatch( GstVideoFormat gstVideoFormat, GraphicsType cingVideoFormat )
{
LOG_ENTER_FUNCTION;
if ( (gstVideoFormat == GST_VIDEO_FORMAT_RGB) && ( cingVideoFormat == RGB ) ) return true;
if ( (gstVideoFormat == GST_VIDEO_FORMAT_RGBA) && ( cingVideoFormat == RGBA ) ) return true;
if ( (gstVideoFormat == GST_VIDEO_FORMAT_BGR) && ( cingVideoFormat == BGR ) ) return true;
if ( (gstVideoFormat == GST_VIDEO_FORMAT_BGRA) && ( cingVideoFormat == BGRA ) ) return true;
LOG_EXIT_FUNCTION;
// Formats do not match
return false;
}
} // namespace
| [
"[email protected]"
] | [
[
[
1,
1155
]
]
] |
3bf961aee452f748ca76f843858848f7824f8de5 | 3c22e8879c8060942ad1ba4a28835d7963e10bce | /trunk/scintilla/win32/ScintillaWin.cxx | 8c8d9ca6dd17c9c6ea4f2c99087eb8df01318fcf | [
"LicenseRef-scancode-scintilla"
] | permissive | svn2github/NotepadPlusPlus | b17f159f9fe6d8d650969b0555824d259d775d45 | 35b5304f02aaacfc156269c4b894159de53222ef | refs/heads/master | 2021-01-22T09:05:19.267064 | 2011-01-31T01:46:36 | 2011-01-31T01:46:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 82,411 | cxx | // Scintilla source code edit control
/** @file ScintillaWin.cxx
** Windows specific subclass of ScintillaBase.
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <new>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <limits.h>
#include <string>
#include <vector>
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <commctrl.h>
#include <richedit.h>
#include <windowsx.h>
#include "Platform.h"
#include "ILexer.h"
#include "Scintilla.h"
#ifdef SCI_LEXER
#include "SciLexer.h"
#include "LexerModule.h"
#endif
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "CallTip.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "XPM.h"
#include "LineMarker.h"
#include "Style.h"
#include "AutoComplete.h"
#include "ViewStyle.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "Document.h"
#include "Selection.h"
#include "PositionCache.h"
#include "Editor.h"
#include "ScintillaBase.h"
#include "UniConversion.h"
#ifdef SCI_LEXER
#include "ExternalLexer.h"
#endif
#ifndef SPI_GETWHEELSCROLLLINES
#define SPI_GETWHEELSCROLLLINES 104
#endif
#ifndef WM_UNICHAR
#define WM_UNICHAR 0x0109
#endif
#ifndef UNICODE_NOCHAR
#define UNICODE_NOCHAR 0xFFFF
#endif
#ifndef WM_IME_STARTCOMPOSITION
#include <imm.h>
#endif
#include <commctrl.h>
#ifndef __BORLANDC__
#ifndef __DMC__
#include <zmouse.h>
#endif
#endif
#include <ole2.h>
#ifndef MK_ALT
#define MK_ALT 32
#endif
#define SC_WIN_IDLE 5001
// Functions imported from PlatWin
extern bool IsNT();
extern void Platform_Initialise(void *hInstance);
extern void Platform_Finalise();
typedef BOOL (WINAPI *TrackMouseEventSig)(LPTRACKMOUSEEVENT);
// GCC has trouble with the standard COM ABI so do it the old C way with explicit vtables.
const TCHAR scintillaClassName[] = TEXT("Scintilla");
const TCHAR callClassName[] = TEXT("CallTip");
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
class ScintillaWin; // Forward declaration for COM interface subobjects
typedef void VFunction(void);
/**
*/
class FormatEnumerator {
public:
VFunction **vtbl;
int ref;
int pos;
CLIPFORMAT formats[2];
int formatsLen;
FormatEnumerator(int pos_, CLIPFORMAT formats_[], int formatsLen_);
};
/**
*/
class DropSource {
public:
VFunction **vtbl;
ScintillaWin *sci;
DropSource();
};
/**
*/
class DataObject {
public:
VFunction **vtbl;
ScintillaWin *sci;
DataObject();
};
/**
*/
class DropTarget {
public:
VFunction **vtbl;
ScintillaWin *sci;
DropTarget();
};
/**
*/
class ScintillaWin :
public ScintillaBase {
bool lastKeyDownConsumed;
bool capturedMouse;
bool trackedMouseLeave;
TrackMouseEventSig TrackMouseEventFn;
unsigned int linesPerScroll; ///< Intellimouse support
int wheelDelta; ///< Wheel delta from roll
HRGN hRgnUpdate;
bool hasOKText;
CLIPFORMAT cfColumnSelect;
CLIPFORMAT cfLineSelect;
HRESULT hrOle;
DropSource ds;
DataObject dob;
DropTarget dt;
static HINSTANCE hInstance;
ScintillaWin(HWND hwnd);
ScintillaWin(const ScintillaWin &);
virtual ~ScintillaWin();
ScintillaWin &operator=(const ScintillaWin &);
virtual void Initialise();
virtual void Finalise();
HWND MainHWND();
static sptr_t DirectFunction(
ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam);
static sptr_t PASCAL SWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam);
static sptr_t PASCAL CTWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam);
enum { invalidTimerID, standardTimerID, idleTimerID };
virtual bool DragThreshold(Point ptStart, Point ptNow);
virtual void StartDrag();
sptr_t WndPaint(uptr_t wParam);
sptr_t HandleComposition(uptr_t wParam, sptr_t lParam);
UINT CodePageOfDocument();
virtual bool ValidCodePage(int codePage) const;
virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
virtual bool SetIdle(bool on);
virtual void SetTicking(bool on);
virtual void SetMouseCapture(bool on);
virtual bool HaveMouseCapture();
virtual void SetTrackMouseLeaveEvent(bool on);
virtual bool PaintContains(PRectangle rc);
virtual void ScrollText(int linesToMove);
virtual void UpdateSystemCaret();
virtual void SetVerticalScrollPos();
virtual void SetHorizontalScrollPos();
virtual bool ModifyScrollBars(int nMax, int nPage);
virtual void NotifyChange();
virtual void NotifyFocus(bool focus);
virtual int GetCtrlID();
virtual void NotifyParent(SCNotification scn);
virtual void NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt);
virtual CaseFolder *CaseFolderForEncoding();
virtual std::string CaseMapString(const std::string &s, int caseMapping);
virtual void Copy();
virtual void CopyAllowLine();
virtual bool CanPaste();
virtual void Paste();
virtual void CreateCallTipWindow(PRectangle rc);
virtual void AddToPopUp(const char *label, int cmd = 0, bool enabled = true);
virtual void ClaimSelection();
// DBCS
void ImeStartComposition();
void ImeEndComposition();
void AddCharBytes(char b0, char b1);
void GetIntelliMouseParameters();
virtual void CopyToClipboard(const SelectionText &selectedText);
void ScrollMessage(WPARAM wParam);
void HorizontalScrollMessage(WPARAM wParam);
void RealizeWindowPalette(bool inBackGround);
void FullPaint();
void FullPaintDC(HDC dc);
bool IsCompatibleDC(HDC dc);
DWORD EffectFromState(DWORD grfKeyState);
virtual int SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw);
virtual bool GetScrollInfo(int nBar, LPSCROLLINFO lpsi);
void ChangeScrollPos(int barType, int pos);
void InsertPasteText(const char *text, int len, SelectionPosition selStart, bool isRectangular, bool isLine);
public:
// Public for benefit of Scintilla_DirectFunction
virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
/// Implement IUnknown
STDMETHODIMP QueryInterface(REFIID riid, PVOID *ppv);
STDMETHODIMP_(ULONG)AddRef();
STDMETHODIMP_(ULONG)Release();
/// Implement IDropTarget
STDMETHODIMP DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect);
STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect);
STDMETHODIMP DragLeave();
STDMETHODIMP Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect);
/// Implement important part of IDataObject
STDMETHODIMP GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM);
static bool Register(HINSTANCE hInstance_);
static bool Unregister();
friend class DropSource;
friend class DataObject;
friend class DropTarget;
bool DragIsRectangularOK(CLIPFORMAT fmt) {
return drag.rectangular && (fmt == cfColumnSelect);
}
private:
// For use in creating a system caret
bool HasCaretSizeChanged();
BOOL CreateSystemCaret();
BOOL DestroySystemCaret();
HBITMAP sysCaretBitmap;
int sysCaretWidth;
int sysCaretHeight;
bool keysAlwaysUnicode;
};
HINSTANCE ScintillaWin::hInstance = 0;
ScintillaWin::ScintillaWin(HWND hwnd) {
lastKeyDownConsumed = false;
capturedMouse = false;
trackedMouseLeave = false;
TrackMouseEventFn = 0;
linesPerScroll = 0;
wheelDelta = 0; // Wheel delta from roll
hRgnUpdate = 0;
hasOKText = false;
// There does not seem to be a real standard for indicating that the clipboard
// contains a rectangular selection, so copy Developer Studio.
cfColumnSelect = static_cast<CLIPFORMAT>(
::RegisterClipboardFormat(TEXT("MSDEVColumnSelect")));
// Likewise for line-copy (copies a full line when no text is selected)
cfLineSelect = static_cast<CLIPFORMAT>(
::RegisterClipboardFormat(TEXT("MSDEVLineSelect")));
hrOle = E_FAIL;
wMain = hwnd;
dob.sci = this;
ds.sci = this;
dt.sci = this;
sysCaretBitmap = 0;
sysCaretWidth = 0;
sysCaretHeight = 0;
keysAlwaysUnicode = false;
Initialise();
}
ScintillaWin::~ScintillaWin() {}
void ScintillaWin::Initialise() {
// Initialize COM. If the app has already done this it will have
// no effect. If the app hasnt, we really shouldnt ask them to call
// it just so this internal feature works.
hrOle = ::OleInitialize(NULL);
// Find TrackMouseEvent which is available on Windows > 95
HMODULE user32 = ::GetModuleHandle(TEXT("user32.dll"));
TrackMouseEventFn = (TrackMouseEventSig)::GetProcAddress(user32, "TrackMouseEvent");
if (TrackMouseEventFn == NULL) {
// Windows 95 has an emulation in comctl32.dll:_TrackMouseEvent
HMODULE commctrl32 = ::LoadLibrary(TEXT("comctl32.dll"));
if (commctrl32 != NULL) {
TrackMouseEventFn = (TrackMouseEventSig)
::GetProcAddress(commctrl32, "_TrackMouseEvent");
}
}
}
void ScintillaWin::Finalise() {
ScintillaBase::Finalise();
SetTicking(false);
SetIdle(false);
::RevokeDragDrop(MainHWND());
if (SUCCEEDED(hrOle)) {
::OleUninitialize();
}
}
HWND ScintillaWin::MainHWND() {
return reinterpret_cast<HWND>(wMain.GetID());
}
bool ScintillaWin::DragThreshold(Point ptStart, Point ptNow) {
int xMove = abs(ptStart.x - ptNow.x);
int yMove = abs(ptStart.y - ptNow.y);
return (xMove > ::GetSystemMetrics(SM_CXDRAG)) ||
(yMove > ::GetSystemMetrics(SM_CYDRAG));
}
void ScintillaWin::StartDrag() {
inDragDrop = ddDragging;
DWORD dwEffect = 0;
dropWentOutside = true;
IDataObject *pDataObject = reinterpret_cast<IDataObject *>(&dob);
IDropSource *pDropSource = reinterpret_cast<IDropSource *>(&ds);
//Platform::DebugPrintf("About to DoDragDrop %x %x\n", pDataObject, pDropSource);
HRESULT hr = ::DoDragDrop(
pDataObject,
pDropSource,
DROPEFFECT_COPY | DROPEFFECT_MOVE, &dwEffect);
//Platform::DebugPrintf("DoDragDrop = %x\n", hr);
if (SUCCEEDED(hr)) {
if ((hr == DRAGDROP_S_DROP) && (dwEffect == DROPEFFECT_MOVE) && dropWentOutside) {
// Remove dragged out text
ClearSelection();
}
}
inDragDrop = ddNone;
SetDragPosition(SelectionPosition(invalidPosition));
}
// Avoid warnings everywhere for old style casts by concentrating them here
static WORD LoWord(DWORD l) {
return LOWORD(l);
}
static WORD HiWord(DWORD l) {
return HIWORD(l);
}
static int InputCodePage() {
HKL inputLocale = ::GetKeyboardLayout(0);
LANGID inputLang = LOWORD(inputLocale);
char sCodePage[10];
int res = ::GetLocaleInfoA(MAKELCID(inputLang, SORT_DEFAULT),
LOCALE_IDEFAULTANSICODEPAGE, sCodePage, sizeof(sCodePage));
if (!res)
return 0;
return atoi(sCodePage);
}
#ifndef VK_OEM_2
static const int VK_OEM_2=0xbf;
static const int VK_OEM_3=0xc0;
static const int VK_OEM_4=0xdb;
static const int VK_OEM_5=0xdc;
static const int VK_OEM_6=0xdd;
#endif
/** Map the key codes to their equivalent SCK_ form. */
static int KeyTranslate(int keyIn) {
//PLATFORM_ASSERT(!keyIn);
switch (keyIn) {
case VK_DOWN: return SCK_DOWN;
case VK_UP: return SCK_UP;
case VK_LEFT: return SCK_LEFT;
case VK_RIGHT: return SCK_RIGHT;
case VK_HOME: return SCK_HOME;
case VK_END: return SCK_END;
case VK_PRIOR: return SCK_PRIOR;
case VK_NEXT: return SCK_NEXT;
case VK_DELETE: return SCK_DELETE;
case VK_INSERT: return SCK_INSERT;
case VK_ESCAPE: return SCK_ESCAPE;
case VK_BACK: return SCK_BACK;
case VK_TAB: return SCK_TAB;
case VK_RETURN: return SCK_RETURN;
case VK_ADD: return SCK_ADD;
case VK_SUBTRACT: return SCK_SUBTRACT;
case VK_DIVIDE: return SCK_DIVIDE;
case VK_LWIN: return SCK_WIN;
case VK_RWIN: return SCK_RWIN;
case VK_APPS: return SCK_MENU;
case VK_OEM_2: return '/';
case VK_OEM_3: return '`';
case VK_OEM_4: return '[';
case VK_OEM_5: return '\\';
case VK_OEM_6: return ']';
default: return keyIn;
}
}
LRESULT ScintillaWin::WndPaint(uptr_t wParam) {
//ElapsedTime et;
// Redirect assertions to debug output and save current state
bool assertsPopup = Platform::ShowAssertionPopUps(false);
paintState = painting;
PAINTSTRUCT ps;
PAINTSTRUCT *pps;
bool IsOcxCtrl = (wParam != 0); // if wParam != 0, it contains
// a PAINSTRUCT* from the OCX
// Removed since this interferes with reporting other assertions as it occurs repeatedly
//PLATFORM_ASSERT(hRgnUpdate == NULL);
hRgnUpdate = ::CreateRectRgn(0, 0, 0, 0);
if (IsOcxCtrl) {
pps = reinterpret_cast<PAINTSTRUCT*>(wParam);
} else {
::GetUpdateRgn(MainHWND(), hRgnUpdate, FALSE);
pps = &ps;
::BeginPaint(MainHWND(), pps);
}
AutoSurface surfaceWindow(pps->hdc, this);
if (surfaceWindow) {
rcPaint = PRectangle(pps->rcPaint.left, pps->rcPaint.top, pps->rcPaint.right, pps->rcPaint.bottom);
PRectangle rcClient = GetClientRectangle();
paintingAllText = rcPaint.Contains(rcClient);
if (paintingAllText) {
//Platform::DebugPrintf("Performing full text paint\n");
} else {
//Platform::DebugPrintf("Performing partial paint %d .. %d\n", rcPaint.top, rcPaint.bottom);
}
Paint(surfaceWindow, rcPaint);
surfaceWindow->Release();
}
if (hRgnUpdate) {
::DeleteRgn(hRgnUpdate);
hRgnUpdate = 0;
}
if (!IsOcxCtrl)
::EndPaint(MainHWND(), pps);
if (paintState == paintAbandoned) {
// Painting area was insufficient to cover new styling or brace highlight positions
FullPaint();
}
paintState = notPainting;
// Restore debug output state
Platform::ShowAssertionPopUps(assertsPopup);
//Platform::DebugPrintf("Paint took %g\n", et.Duration());
return 0l;
}
sptr_t ScintillaWin::HandleComposition(uptr_t wParam, sptr_t lParam) {
#ifdef __DMC__
// Digital Mars compiler does not include Imm library
return 0;
#else
if (lParam & GCS_RESULTSTR) {
HIMC hIMC = ::ImmGetContext(MainHWND());
if (hIMC) {
const int maxLenInputIME = 200;
wchar_t wcs[maxLenInputIME];
LONG bytes = ::ImmGetCompositionStringW(hIMC,
GCS_RESULTSTR, wcs, (maxLenInputIME-1)*2);
int wides = bytes / 2;
if (IsUnicodeMode()) {
char utfval[maxLenInputIME * 3];
unsigned int len = UTF8Length(wcs, wides);
UTF8FromUTF16(wcs, wides, utfval, len);
utfval[len] = '\0';
AddCharUTF(utfval, len);
} else {
char dbcsval[maxLenInputIME * 2];
int size = ::WideCharToMultiByte(InputCodePage(),
0, wcs, wides, dbcsval, sizeof(dbcsval) - 1, 0, 0);
for (int i=0; i<size; i++) {
AddChar(dbcsval[i]);
}
}
// Set new position after converted
Point pos = PointMainCaret();
COMPOSITIONFORM CompForm;
CompForm.dwStyle = CFS_POINT;
CompForm.ptCurrentPos.x = pos.x;
CompForm.ptCurrentPos.y = pos.y;
::ImmSetCompositionWindow(hIMC, &CompForm);
::ImmReleaseContext(MainHWND(), hIMC);
}
return 0;
}
return ::DefWindowProc(MainHWND(), WM_IME_COMPOSITION, wParam, lParam);
#endif
}
// Translate message IDs from WM_* and EM_* to SCI_* so can partly emulate Windows Edit control
static unsigned int SciMessageFromEM(unsigned int iMessage) {
switch (iMessage) {
case EM_CANPASTE: return SCI_CANPASTE;
case EM_CANUNDO: return SCI_CANUNDO;
case EM_EMPTYUNDOBUFFER: return SCI_EMPTYUNDOBUFFER;
case EM_FINDTEXTEX: return SCI_FINDTEXT;
case EM_FORMATRANGE: return SCI_FORMATRANGE;
case EM_GETFIRSTVISIBLELINE: return SCI_GETFIRSTVISIBLELINE;
case EM_GETLINECOUNT: return SCI_GETLINECOUNT;
case EM_GETSELTEXT: return SCI_GETSELTEXT;
case EM_GETTEXTRANGE: return SCI_GETTEXTRANGE;
case EM_HIDESELECTION: return SCI_HIDESELECTION;
case EM_LINEINDEX: return SCI_POSITIONFROMLINE;
case EM_LINESCROLL: return SCI_LINESCROLL;
case EM_REPLACESEL: return SCI_REPLACESEL;
case EM_SCROLLCARET: return SCI_SCROLLCARET;
case EM_SETREADONLY: return SCI_SETREADONLY;
case WM_CLEAR: return SCI_CLEAR;
case WM_COPY: return SCI_COPY;
case WM_CUT: return SCI_CUT;
case WM_GETTEXT: return SCI_GETTEXT;
case WM_SETTEXT: return SCI_SETTEXT;
case WM_GETTEXTLENGTH: return SCI_GETTEXTLENGTH;
case WM_PASTE: return SCI_PASTE;
case WM_UNDO: return SCI_UNDO;
}
return iMessage;
}
static UINT CodePageFromCharSet(DWORD characterSet, UINT documentCodePage) {
if (documentCodePage == SC_CP_UTF8) {
// The system calls here are a little slow so avoid if known case.
return SC_CP_UTF8;
}
CHARSETINFO ci = { 0, 0, { { 0, 0, 0, 0 }, { 0, 0 } } };
BOOL bci = ::TranslateCharsetInfo((DWORD*)characterSet,
&ci, TCI_SRCCHARSET);
UINT cp;
if (bci)
cp = ci.ciACP;
else
cp = documentCodePage;
CPINFO cpi;
if (!IsValidCodePage(cp) && !GetCPInfo(cp, &cpi))
cp = CP_ACP;
return cp;
}
UINT ScintillaWin::CodePageOfDocument() {
return CodePageFromCharSet(vs.styles[STYLE_DEFAULT].characterSet, pdoc->dbcsCodePage);
}
sptr_t ScintillaWin::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
try {
//Platform::DebugPrintf("S M:%x WP:%x L:%x\n", iMessage, wParam, lParam);
iMessage = SciMessageFromEM(iMessage);
switch (iMessage) {
case WM_CREATE:
ctrlID = ::GetDlgCtrlID(reinterpret_cast<HWND>(wMain.GetID()));
// Get Intellimouse scroll line parameters
GetIntelliMouseParameters();
::RegisterDragDrop(MainHWND(), reinterpret_cast<IDropTarget *>(&dt));
break;
case WM_COMMAND:
Command(LoWord(wParam));
break;
case WM_PAINT:
return WndPaint(wParam);
case WM_PRINTCLIENT: {
HDC hdc = reinterpret_cast<HDC>(wParam);
if (!IsCompatibleDC(hdc)) {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
FullPaintDC(hdc);
}
break;
case WM_VSCROLL:
ScrollMessage(wParam);
break;
case WM_HSCROLL:
HorizontalScrollMessage(wParam);
break;
case WM_SIZE: {
//Platform::DebugPrintf("Scintilla WM_SIZE %d %d\n", LoWord(lParam), HiWord(lParam));
ChangeSize();
}
break;
case WM_MOUSEWHEEL:
// Don't handle datazoom.
// (A good idea for datazoom would be to "fold" or "unfold" details.
// i.e. if datazoomed out only class structures are visible, when datazooming in the control
// structures appear, then eventually the individual statements...)
if (wParam & MK_SHIFT) {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
// Either SCROLL or ZOOM. We handle the wheel steppings calculation
wheelDelta -= static_cast<short>(HiWord(wParam));
if (abs(wheelDelta) >= WHEEL_DELTA && linesPerScroll > 0) {
int linesToScroll = linesPerScroll;
if (linesPerScroll == WHEEL_PAGESCROLL)
linesToScroll = LinesOnScreen() - 1;
if (linesToScroll == 0) {
linesToScroll = 1;
}
linesToScroll *= (wheelDelta / WHEEL_DELTA);
if (wheelDelta >= 0)
wheelDelta = wheelDelta % WHEEL_DELTA;
else
wheelDelta = - (-wheelDelta % WHEEL_DELTA);
if (wParam & MK_CONTROL) {
// Zoom! We play with the font sizes in the styles.
// Number of steps/line is ignored, we just care if sizing up or down
if (linesToScroll < 0) {
KeyCommand(SCI_ZOOMIN);
} else {
KeyCommand(SCI_ZOOMOUT);
}
} else {
// Scroll
ScrollTo(topLine + linesToScroll);
}
}
return 0;
case WM_TIMER:
if (wParam == standardTimerID && timer.ticking) {
Tick();
} else if (wParam == idleTimerID && idler.state) {
SendMessage(MainHWND(), SC_WIN_IDLE, 0, 1);
} else {
return 1;
}
break;
case SC_WIN_IDLE:
// wParam=dwTickCountInitial, or 0 to initialize. lParam=bSkipUserInputTest
if (idler.state) {
if (lParam || (WAIT_TIMEOUT == MsgWaitForMultipleObjects(0, 0, 0, 0, QS_INPUT|QS_HOTKEY))) {
if (Idle()) {
// User input was given priority above, but all events do get a turn. Other
// messages, notifications, etc. will get interleaved with the idle messages.
// However, some things like WM_PAINT are a lower priority, and will not fire
// when there's a message posted. So, several times a second, we stop and let
// the low priority events have a turn (after which the timer will fire again).
DWORD dwCurrent = GetTickCount();
DWORD dwStart = wParam ? wParam : dwCurrent;
if (dwCurrent >= dwStart && dwCurrent > 200 && dwCurrent - 200 < dwStart)
PostMessage(MainHWND(), SC_WIN_IDLE, dwStart, 0);
} else {
SetIdle(false);
}
}
}
break;
case WM_GETMINMAXINFO:
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_LBUTTONDOWN: {
#ifndef __DMC__
// Digital Mars compiler does not include Imm library
// For IME, set the composition string as the result string.
HIMC hIMC = ::ImmGetContext(MainHWND());
::ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
::ImmReleaseContext(MainHWND(), hIMC);
#endif
//
//Platform::DebugPrintf("Buttdown %d %x %x %x %x %x\n",iMessage, wParam, lParam,
// Platform::IsKeyDown(VK_SHIFT),
// Platform::IsKeyDown(VK_CONTROL),
// Platform::IsKeyDown(VK_MENU));
::SetFocus(MainHWND());
ButtonDown(Point::FromLong(lParam), ::GetMessageTime(),
(wParam & MK_SHIFT) != 0,
(wParam & MK_CONTROL) != 0,
Platform::IsKeyDown(VK_MENU));
}
break;
case WM_MBUTTONDOWN:
::SetFocus(MainHWND());
break;
case WM_MOUSEMOVE:
SetTrackMouseLeaveEvent(true);
ButtonMove(Point::FromLong(lParam));
break;
case WM_MOUSELEAVE:
SetTrackMouseLeaveEvent(false);
MouseLeave();
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_LBUTTONUP:
ButtonUp(Point::FromLong(lParam),
::GetMessageTime(),
(wParam & MK_CONTROL) != 0);
break;
case WM_RBUTTONDOWN:
if (!PointInSelection(Point::FromLong(lParam)))
SetEmptySelection(PositionFromLocation(Point::FromLong(lParam)));
break;
case WM_SETCURSOR:
if (LoWord(lParam) == HTCLIENT) {
if (inDragDrop == ddDragging) {
DisplayCursor(Window::cursorUp);
} else {
// Display regular (drag) cursor over selection
POINT pt;
::GetCursorPos(&pt);
::ScreenToClient(MainHWND(), &pt);
if (PointInSelMargin(Point(pt.x, pt.y))) {
DisplayCursor(Window::cursorReverseArrow);
} else if (PointInSelection(Point(pt.x, pt.y)) && !SelectionEmpty()) {
DisplayCursor(Window::cursorArrow);
} else if (PointIsHotspot(Point(pt.x, pt.y))) {
DisplayCursor(Window::cursorHand);
} else {
DisplayCursor(Window::cursorText);
}
}
return TRUE;
} else {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
case WM_CHAR:
if (((wParam >= 128) || !iscntrl(wParam)) || !lastKeyDownConsumed) {
if (::IsWindowUnicode(MainHWND()) || keysAlwaysUnicode) {
wchar_t wcs[2] = {wParam, 0};
if (IsUnicodeMode()) {
// For a wide character version of the window:
char utfval[4];
unsigned int len = UTF8Length(wcs, 1);
UTF8FromUTF16(wcs, 1, utfval, len);
AddCharUTF(utfval, len);
} else {
UINT cpDest = CodePageOfDocument();
char inBufferCP[20];
int size = ::WideCharToMultiByte(cpDest,
0, wcs, 1, inBufferCP, sizeof(inBufferCP) - 1, 0, 0);
AddCharUTF(inBufferCP, size);
}
} else {
if (IsUnicodeMode()) {
AddCharBytes('\0', LOBYTE(wParam));
} else {
AddChar(LOBYTE(wParam));
}
}
}
return 0;
case WM_UNICHAR:
if (wParam == UNICODE_NOCHAR) {
return IsUnicodeMode() ? 1 : 0;
} else if (lastKeyDownConsumed) {
return 1;
} else {
if (IsUnicodeMode()) {
char utfval[4];
wchar_t wcs[2] = {static_cast<wchar_t>(wParam), 0};
unsigned int len = UTF8Length(wcs, 1);
UTF8FromUTF16(wcs, 1, utfval, len);
AddCharUTF(utfval, len);
return 1;
} else {
return 0;
}
}
case WM_SYSKEYDOWN:
case WM_KEYDOWN: {
//Platform::DebugPrintf("S keydown %d %x %x %x %x\n",iMessage, wParam, lParam, ::IsKeyDown(VK_SHIFT), ::IsKeyDown(VK_CONTROL));
lastKeyDownConsumed = false;
int ret = KeyDown(KeyTranslate(wParam),
Platform::IsKeyDown(VK_SHIFT),
Platform::IsKeyDown(VK_CONTROL),
Platform::IsKeyDown(VK_MENU),
&lastKeyDownConsumed);
if (!ret && !lastKeyDownConsumed) {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
break;
}
case WM_IME_KEYDOWN:
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_KEYUP:
//Platform::DebugPrintf("S keyup %d %x %x\n",iMessage, wParam, lParam);
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_SETTINGCHANGE:
//Platform::DebugPrintf("Setting Changed\n");
InvalidateStyleData();
// Get Intellimouse scroll line parameters
GetIntelliMouseParameters();
break;
case WM_GETDLGCODE:
return DLGC_HASSETSEL | DLGC_WANTALLKEYS;
case WM_KILLFOCUS: {
HWND wOther = reinterpret_cast<HWND>(wParam);
HWND wThis = MainHWND();
HWND wCT = reinterpret_cast<HWND>(ct.wCallTip.GetID());
if (!wParam ||
!(::IsChild(wThis, wOther) || (wOther == wCT))) {
SetFocusState(false);
DestroySystemCaret();
}
}
//RealizeWindowPalette(true);
break;
case WM_SETFOCUS:
SetFocusState(true);
RealizeWindowPalette(false);
DestroySystemCaret();
CreateSystemCaret();
break;
case WM_SYSCOLORCHANGE:
//Platform::DebugPrintf("Setting Changed\n");
InvalidateStyleData();
break;
case WM_PALETTECHANGED:
if (wParam != reinterpret_cast<uptr_t>(MainHWND())) {
//Platform::DebugPrintf("** Palette Changed\n");
RealizeWindowPalette(true);
}
break;
case WM_QUERYNEWPALETTE:
//Platform::DebugPrintf("** Query palette\n");
RealizeWindowPalette(false);
break;
case WM_IME_STARTCOMPOSITION: // dbcs
ImeStartComposition();
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_IME_ENDCOMPOSITION: // dbcs
ImeEndComposition();
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_IME_COMPOSITION:
return HandleComposition(wParam, lParam);
case WM_IME_CHAR: {
AddCharBytes(HIBYTE(wParam), LOBYTE(wParam));
return 0;
}
case WM_CONTEXTMENU:
if (displayPopupMenu) {
Point pt = Point::FromLong(lParam);
if ((pt.x == -1) && (pt.y == -1)) {
// Caused by keyboard so display menu near caret
pt = PointMainCaret();
POINT spt = {pt.x, pt.y};
::ClientToScreen(MainHWND(), &spt);
pt = Point(spt.x, spt.y);
}
ContextMenu(pt);
return 0;
}
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_INPUTLANGCHANGE:
//::SetThreadLocale(LOWORD(lParam));
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_INPUTLANGCHANGEREQUEST:
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_ERASEBKGND:
return 1; // Avoid any background erasure as whole window painted.
case WM_CAPTURECHANGED:
capturedMouse = false;
return 0;
// These are not handled in Scintilla and its faster to dispatch them here.
// Also moves time out to here so profile doesn't count lots of empty message calls.
case WM_MOVE:
case WM_MOUSEACTIVATE:
case WM_NCHITTEST:
case WM_NCCALCSIZE:
case WM_NCPAINT:
case WM_NCMOUSEMOVE:
case WM_NCLBUTTONDOWN:
case WM_IME_SETCONTEXT:
case WM_IME_NOTIFY:
case WM_SYSCOMMAND:
case WM_WINDOWPOSCHANGING:
case WM_WINDOWPOSCHANGED:
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case EM_LINEFROMCHAR:
if (static_cast<int>(wParam) < 0) {
wParam = SelectionStart().Position();
}
return pdoc->LineFromPosition(wParam);
case EM_EXLINEFROMCHAR:
return pdoc->LineFromPosition(lParam);
case EM_GETSEL:
if (wParam) {
*reinterpret_cast<int *>(wParam) = SelectionStart().Position();
}
if (lParam) {
*reinterpret_cast<int *>(lParam) = SelectionEnd().Position();
}
return MAKELONG(SelectionStart().Position(), SelectionEnd().Position());
case EM_EXGETSEL: {
if (lParam == 0) {
return 0;
}
Sci_CharacterRange *pCR = reinterpret_cast<Sci_CharacterRange *>(lParam);
pCR->cpMin = SelectionStart().Position();
pCR->cpMax = SelectionEnd().Position();
}
break;
case EM_SETSEL: {
int nStart = static_cast<int>(wParam);
int nEnd = static_cast<int>(lParam);
if (nStart == 0 && nEnd == -1) {
nEnd = pdoc->Length();
}
if (nStart == -1) {
nStart = nEnd; // Remove selection
}
if (nStart > nEnd) {
SetSelection(nEnd, nStart);
} else {
SetSelection(nStart, nEnd);
}
EnsureCaretVisible();
}
break;
case EM_EXSETSEL: {
if (lParam == 0) {
return 0;
}
Sci_CharacterRange *pCR = reinterpret_cast<Sci_CharacterRange *>(lParam);
sel.selType = Selection::selStream;
if (pCR->cpMin == 0 && pCR->cpMax == -1) {
SetSelection(pCR->cpMin, pdoc->Length());
} else {
SetSelection(pCR->cpMin, pCR->cpMax);
}
EnsureCaretVisible();
return pdoc->LineFromPosition(SelectionStart().Position());
}
case SCI_GETDIRECTFUNCTION:
return reinterpret_cast<sptr_t>(DirectFunction);
case SCI_GETDIRECTPOINTER:
return reinterpret_cast<sptr_t>(this);
case SCI_GRABFOCUS:
::SetFocus(MainHWND());
break;
case SCI_SETKEYSUNICODE:
keysAlwaysUnicode = wParam != 0;
break;
case SCI_GETKEYSUNICODE:
return keysAlwaysUnicode;
#ifdef SCI_LEXER
case SCI_LOADLEXERLIBRARY:
LexerManager::GetInstance()->Load(reinterpret_cast<const char *>(lParam));
break;
#endif
default:
return ScintillaBase::WndProc(iMessage, wParam, lParam);
}
} catch (std::bad_alloc &) {
errorStatus = SC_STATUS_BADALLOC;
} catch (...) {
errorStatus = SC_STATUS_FAILURE;
}
return 0l;
}
bool ScintillaWin::ValidCodePage(int codePage) const {
return codePage == 0 || codePage == SC_CP_UTF8 ||
codePage == 932 || codePage == 936 || codePage == 949 ||
codePage == 950 || codePage == 1361;
}
sptr_t ScintillaWin::DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
void ScintillaWin::SetTicking(bool on) {
if (timer.ticking != on) {
timer.ticking = on;
if (timer.ticking) {
timer.tickerID = ::SetTimer(MainHWND(), standardTimerID, timer.tickSize, NULL)
? reinterpret_cast<TickerID>(standardTimerID) : 0;
} else {
::KillTimer(MainHWND(), reinterpret_cast<uptr_t>(timer.tickerID));
timer.tickerID = 0;
}
}
timer.ticksToWait = caret.period;
}
bool ScintillaWin::SetIdle(bool on) {
// On Win32 the Idler is implemented as a Timer on the Scintilla window. This
// takes advantage of the fact that WM_TIMER messages are very low priority,
// and are only posted when the message queue is empty, i.e. during idle time.
if (idler.state != on) {
if (on) {
idler.idlerID = ::SetTimer(MainHWND(), idleTimerID, 10, NULL)
? reinterpret_cast<IdlerID>(idleTimerID) : 0;
} else {
::KillTimer(MainHWND(), reinterpret_cast<uptr_t>(idler.idlerID));
idler.idlerID = 0;
}
idler.state = idler.idlerID != 0;
}
return idler.state;
}
void ScintillaWin::SetMouseCapture(bool on) {
if (mouseDownCaptures) {
if (on) {
::SetCapture(MainHWND());
} else {
::ReleaseCapture();
}
}
capturedMouse = on;
}
bool ScintillaWin::HaveMouseCapture() {
// Cannot just see if GetCapture is this window as the scroll bar also sets capture for the window
return capturedMouse;
//return capturedMouse && (::GetCapture() == MainHWND());
}
void ScintillaWin::SetTrackMouseLeaveEvent(bool on) {
if (on && TrackMouseEventFn && !trackedMouseLeave) {
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(tme);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = MainHWND();
TrackMouseEventFn(&tme);
}
trackedMouseLeave = on;
}
bool ScintillaWin::PaintContains(PRectangle rc) {
bool contains = true;
if ((paintState == painting) && (!rc.Empty())) {
if (!rcPaint.Contains(rc)) {
contains = false;
} else {
// In bounding rectangle so check more accurately using region
HRGN hRgnRange = ::CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
if (hRgnRange) {
HRGN hRgnDest = ::CreateRectRgn(0, 0, 0, 0);
if (hRgnDest) {
int combination = ::CombineRgn(hRgnDest, hRgnRange, hRgnUpdate, RGN_DIFF);
if (combination != NULLREGION) {
contains = false;
}
::DeleteRgn(hRgnDest);
}
::DeleteRgn(hRgnRange);
}
}
}
return contains;
}
void ScintillaWin::ScrollText(int linesToMove) {
//Platform::DebugPrintf("ScintillaWin::ScrollText %d\n", linesToMove);
::ScrollWindow(MainHWND(), 0,
vs.lineHeight * linesToMove, 0, 0);
::UpdateWindow(MainHWND());
}
void ScintillaWin::UpdateSystemCaret() {
if (hasFocus) {
if (HasCaretSizeChanged()) {
DestroySystemCaret();
CreateSystemCaret();
}
Point pos = PointMainCaret();
::SetCaretPos(pos.x, pos.y);
}
}
int ScintillaWin::SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw) {
return ::SetScrollInfo(MainHWND(), nBar, lpsi, bRedraw);
}
bool ScintillaWin::GetScrollInfo(int nBar, LPSCROLLINFO lpsi) {
return ::GetScrollInfo(MainHWND(), nBar, lpsi) ? true : false;
}
// Change the scroll position but avoid repaint if changing to same value
void ScintillaWin::ChangeScrollPos(int barType, int pos) {
SCROLLINFO sci = {
sizeof(sci), 0, 0, 0, 0, 0, 0
};
sci.fMask = SIF_POS;
GetScrollInfo(barType, &sci);
if (sci.nPos != pos) {
DwellEnd(true);
sci.nPos = pos;
SetScrollInfo(barType, &sci, TRUE);
}
}
void ScintillaWin::SetVerticalScrollPos() {
ChangeScrollPos(SB_VERT, topLine);
}
void ScintillaWin::SetHorizontalScrollPos() {
ChangeScrollPos(SB_HORZ, xOffset);
}
bool ScintillaWin::ModifyScrollBars(int nMax, int nPage) {
bool modified = false;
SCROLLINFO sci = {
sizeof(sci), 0, 0, 0, 0, 0, 0
};
sci.fMask = SIF_PAGE | SIF_RANGE;
GetScrollInfo(SB_VERT, &sci);
int vertEndPreferred = nMax;
if (!verticalScrollBarVisible)
vertEndPreferred = 0;
if ((sci.nMin != 0) ||
(sci.nMax != vertEndPreferred) ||
(sci.nPage != static_cast<unsigned int>(nPage)) ||
(sci.nPos != 0)) {
//Platform::DebugPrintf("Scroll info changed %d %d %d %d %d\n",
// sci.nMin, sci.nMax, sci.nPage, sci.nPos, sci.nTrackPos);
sci.fMask = SIF_PAGE | SIF_RANGE;
sci.nMin = 0;
sci.nMax = vertEndPreferred;
sci.nPage = nPage;
sci.nPos = 0;
sci.nTrackPos = 1;
SetScrollInfo(SB_VERT, &sci, TRUE);
modified = true;
}
PRectangle rcText = GetTextRectangle();
int horizEndPreferred = scrollWidth;
if (horizEndPreferred < 0)
horizEndPreferred = 0;
if (!horizontalScrollBarVisible || (wrapState != eWrapNone))
horizEndPreferred = 0;
unsigned int pageWidth = rcText.Width();
sci.fMask = SIF_PAGE | SIF_RANGE;
GetScrollInfo(SB_HORZ, &sci);
if ((sci.nMin != 0) ||
(sci.nMax != horizEndPreferred) ||
(sci.nPage != pageWidth) ||
(sci.nPos != 0)) {
sci.fMask = SIF_PAGE | SIF_RANGE;
sci.nMin = 0;
sci.nMax = horizEndPreferred;
sci.nPage = pageWidth;
sci.nPos = 0;
sci.nTrackPos = 1;
SetScrollInfo(SB_HORZ, &sci, TRUE);
modified = true;
if (scrollWidth < static_cast<int>(pageWidth)) {
HorizontalScrollTo(0);
}
}
return modified;
}
void ScintillaWin::NotifyChange() {
::SendMessage(::GetParent(MainHWND()), WM_COMMAND,
MAKELONG(GetCtrlID(), SCEN_CHANGE),
reinterpret_cast<LPARAM>(MainHWND()));
}
void ScintillaWin::NotifyFocus(bool focus) {
::SendMessage(::GetParent(MainHWND()), WM_COMMAND,
MAKELONG(GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS),
reinterpret_cast<LPARAM>(MainHWND()));
}
int ScintillaWin::GetCtrlID() {
return ::GetDlgCtrlID(reinterpret_cast<HWND>(wMain.GetID()));
}
void ScintillaWin::NotifyParent(SCNotification scn) {
scn.nmhdr.hwndFrom = MainHWND();
scn.nmhdr.idFrom = GetCtrlID();
::SendMessage(::GetParent(MainHWND()), WM_NOTIFY,
GetCtrlID(), reinterpret_cast<LPARAM>(&scn));
}
void ScintillaWin::NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt) {
//Platform::DebugPrintf("ScintillaWin Double click 0\n");
ScintillaBase::NotifyDoubleClick(pt, shift, ctrl, alt);
// Send myself a WM_LBUTTONDBLCLK, so the container can handle it too.
::SendMessage(MainHWND(),
WM_LBUTTONDBLCLK,
shift ? MK_SHIFT : 0,
MAKELPARAM(pt.x, pt.y));
}
class CaseFolderUTF8 : public CaseFolderTable {
// Allocate the expandable storage here so that it does not need to be reallocated
// for each call to Fold.
std::vector<wchar_t> utf16Mixed;
std::vector<wchar_t> utf16Folded;
public:
CaseFolderUTF8() {
StandardASCII();
}
virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
if ((lenMixed == 1) && (sizeFolded > 0)) {
folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
return 1;
} else {
if (lenMixed > utf16Mixed.size()) {
utf16Mixed.resize(lenMixed + 8);
}
size_t nUtf16Mixed = ::MultiByteToWideChar(65001, 0, mixed, lenMixed,
&utf16Mixed[0], utf16Mixed.size());
if (nUtf16Mixed == 0) {
// Failed to convert -> bad UTF-8
folded[0] = '\0';
return 1;
}
if (nUtf16Mixed * 4 > utf16Folded.size()) { // Maximum folding expansion factor of 4
utf16Folded.resize(nUtf16Mixed * 4 + 8);
}
int lenFlat = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT,
LCMAP_LINGUISTIC_CASING | LCMAP_LOWERCASE,
&utf16Mixed[0], nUtf16Mixed, &utf16Folded[0], utf16Folded.size());
size_t lenOut = UTF8Length(&utf16Folded[0], lenFlat);
if (lenOut < sizeFolded) {
UTF8FromUTF16(&utf16Folded[0], lenFlat, folded, lenOut);
return lenOut;
} else {
return 0;
}
}
}
};
class CaseFolderDBCS : public CaseFolderTable {
// Allocate the expandable storage here so that it does not need to be reallocated
// for each call to Fold.
std::vector<wchar_t> utf16Mixed;
std::vector<wchar_t> utf16Folded;
UINT cp;
public:
CaseFolderDBCS(UINT cp_) : cp(cp_) {
StandardASCII();
}
virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
if ((lenMixed == 1) && (sizeFolded > 0)) {
folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
return 1;
} else {
if (lenMixed > utf16Mixed.size()) {
utf16Mixed.resize(lenMixed + 8);
}
size_t nUtf16Mixed = ::MultiByteToWideChar(cp, 0, mixed, lenMixed,
&utf16Mixed[0], utf16Mixed.size());
if (nUtf16Mixed == 0) {
// Failed to convert -> bad input
folded[0] = '\0';
return 1;
}
if (nUtf16Mixed * 4 > utf16Folded.size()) { // Maximum folding expansion factor of 4
utf16Folded.resize(nUtf16Mixed * 4 + 8);
}
int lenFlat = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT,
LCMAP_LINGUISTIC_CASING | LCMAP_LOWERCASE,
&utf16Mixed[0], nUtf16Mixed, &utf16Folded[0], utf16Folded.size());
size_t lenOut = ::WideCharToMultiByte(cp, 0,
&utf16Folded[0], lenFlat,
NULL, 0, NULL, 0);
if (lenOut < sizeFolded) {
::WideCharToMultiByte(cp, 0,
&utf16Folded[0], lenFlat,
folded, lenOut, NULL, 0);
return lenOut;
} else {
return 0;
}
}
}
};
CaseFolder *ScintillaWin::CaseFolderForEncoding() {
UINT cpDest = CodePageOfDocument();
if (cpDest == SC_CP_UTF8) {
return new CaseFolderUTF8();
} else {
if (pdoc->dbcsCodePage == 0) {
CaseFolderTable *pcf = new CaseFolderTable();
pcf->StandardASCII();
// Only for single byte encodings
UINT cpDoc = CodePageOfDocument();
for (int i=0x80; i<0x100; i++) {
char sCharacter[2] = "A";
sCharacter[0] = static_cast<char>(i);
wchar_t wCharacter[20];
unsigned int lengthUTF16 = ::MultiByteToWideChar(cpDoc, 0, sCharacter, 1,
wCharacter, sizeof(wCharacter)/sizeof(wCharacter[0]));
if (lengthUTF16 == 1) {
wchar_t wLower[20];
int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT,
LCMAP_LINGUISTIC_CASING | LCMAP_LOWERCASE,
wCharacter, lengthUTF16, wLower, sizeof(wLower)/sizeof(wLower[0]));
char sCharacterLowered[20];
unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
wLower, charsConverted,
sCharacterLowered, sizeof(sCharacterLowered), NULL, 0);
if ((lengthConverted == 1) && (sCharacter[0] != sCharacterLowered[0])) {
pcf->SetTranslation(sCharacter[0], sCharacterLowered[0]);
}
}
}
return pcf;
} else {
return new CaseFolderDBCS(cpDest);
}
}
}
std::string ScintillaWin::CaseMapString(const std::string &s, int caseMapping) {
if (s.size() == 0)
return std::string();
if (caseMapping == cmSame)
return s;
UINT cpDoc = CodePageOfDocument();
unsigned int lengthUTF16 = ::MultiByteToWideChar(cpDoc, 0, s.c_str(), s.size(), NULL, 0);
if (lengthUTF16 == 0) // Failed to convert
return s;
DWORD mapFlags = LCMAP_LINGUISTIC_CASING |
((caseMapping == cmUpper) ? LCMAP_UPPERCASE : LCMAP_LOWERCASE);
// Many conversions performed by search function are short so optimize this case.
enum { shortSize=20 };
if (s.size() > shortSize) {
// Use dynamic allocations for long strings
// Change text to UTF-16
std::vector<wchar_t> vwcText(lengthUTF16);
::MultiByteToWideChar(cpDoc, 0, s.c_str(), s.size(), &vwcText[0], lengthUTF16);
// Change case
int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
&vwcText[0], lengthUTF16, NULL, 0);
std::vector<wchar_t> vwcConverted(charsConverted);
::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
&vwcText[0], lengthUTF16, &vwcConverted[0], charsConverted);
// Change back to document encoding
unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
&vwcConverted[0], vwcConverted.size(),
NULL, 0, NULL, 0);
std::vector<char> vcConverted(lengthConverted);
::WideCharToMultiByte(cpDoc, 0,
&vwcConverted[0], vwcConverted.size(),
&vcConverted[0], vcConverted.size(), NULL, 0);
return std::string(&vcConverted[0], vcConverted.size());
} else {
// Use static allocations for short strings as much faster
// A factor of 15 for single character strings
// Change text to UTF-16
wchar_t vwcText[shortSize];
::MultiByteToWideChar(cpDoc, 0, s.c_str(), s.size(), vwcText, lengthUTF16);
// Change case
int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
vwcText, lengthUTF16, NULL, 0);
// Full mapping may produce up to 3 characters per input character
wchar_t vwcConverted[shortSize*3];
::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags, vwcText, lengthUTF16,
vwcConverted, charsConverted);
// Change back to document encoding
unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
vwcConverted, charsConverted,
NULL, 0, NULL, 0);
// Each UTF-16 code unit may need up to 3 bytes in UTF-8
char vcConverted[shortSize * 3 * 3];
::WideCharToMultiByte(cpDoc, 0,
vwcConverted, charsConverted,
vcConverted, lengthConverted, NULL, 0);
return std::string(vcConverted, lengthConverted);
}
}
void ScintillaWin::Copy() {
//Platform::DebugPrintf("Copy\n");
if (!sel.Empty()) {
SelectionText selectedText;
CopySelectionRange(&selectedText);
CopyToClipboard(selectedText);
}
}
void ScintillaWin::CopyAllowLine() {
SelectionText selectedText;
CopySelectionRange(&selectedText, true);
CopyToClipboard(selectedText);
}
bool ScintillaWin::CanPaste() {
if (!Editor::CanPaste())
return false;
if (::IsClipboardFormatAvailable(CF_TEXT))
return true;
if (IsUnicodeMode())
return ::IsClipboardFormatAvailable(CF_UNICODETEXT) != 0;
return false;
}
class GlobalMemory {
HGLOBAL hand;
public:
void *ptr;
GlobalMemory() : hand(0), ptr(0) {
}
GlobalMemory(HGLOBAL hand_) : hand(hand_), ptr(0) {
if (hand) {
ptr = ::GlobalLock(hand);
}
}
~GlobalMemory() {
PLATFORM_ASSERT(!ptr);
}
void Allocate(size_t bytes) {
hand = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, bytes);
if (hand) {
ptr = ::GlobalLock(hand);
}
}
HGLOBAL Unlock() {
PLATFORM_ASSERT(ptr);
HGLOBAL handCopy = hand;
::GlobalUnlock(hand);
ptr = 0;
hand = 0;
return handCopy;
}
void SetClip(UINT uFormat) {
::SetClipboardData(uFormat, Unlock());
}
operator bool() const {
return ptr != 0;
}
SIZE_T Size() {
return ::GlobalSize(hand);
}
};
void ScintillaWin::InsertPasteText(const char *text, int len, SelectionPosition selStart, bool isRectangular, bool isLine) {
if (isRectangular) {
PasteRectangular(selStart, text, len);
} else {
char *convertedText = 0;
if (convertPastes) {
// Convert line endings of the paste into our local line-endings mode
convertedText = Document::TransformLineEnds(&len, text, len, pdoc->eolMode);
text = convertedText;
}
if (isLine) {
int insertPos = pdoc->LineStart(pdoc->LineFromPosition(sel.MainCaret()));
pdoc->InsertString(insertPos, text, len);
// add the newline if necessary
if ((len > 0) && (text[len-1] != '\n' && text[len-1] != '\r')) {
const char *endline = StringFromEOLMode(pdoc->eolMode);
pdoc->InsertString(insertPos + len, endline, strlen(endline));
len += strlen(endline);
}
if (sel.MainCaret() == insertPos) {
SetEmptySelection(sel.MainCaret() + len);
}
} else {
InsertPaste(selStart, text, len);
}
delete []convertedText;
}
}
void ScintillaWin::Paste() {
if (!::OpenClipboard(MainHWND()))
return;
UndoGroup ug(pdoc);
bool isLine = SelectionEmpty() && (::IsClipboardFormatAvailable(cfLineSelect) != 0);
ClearSelection();
SelectionPosition selStart = sel.IsRectangular() ?
sel.Rectangular().Start() :
sel.Range(sel.Main()).Start();
bool isRectangular = ::IsClipboardFormatAvailable(cfColumnSelect) != 0;
// Always use CF_UNICODETEXT if available
GlobalMemory memUSelection(::GetClipboardData(CF_UNICODETEXT));
if (memUSelection) {
wchar_t *uptr = static_cast<wchar_t *>(memUSelection.ptr);
if (uptr) {
unsigned int len;
char *putf;
// Default Scintilla behaviour in Unicode mode
if (IsUnicodeMode()) {
unsigned int bytes = memUSelection.Size();
len = UTF8Length(uptr, bytes / 2);
putf = new char[len + 1];
UTF8FromUTF16(uptr, bytes / 2, putf, len);
} else {
// CF_UNICODETEXT available, but not in Unicode mode
// Convert from Unicode to current Scintilla code page
UINT cpDest = CodePageOfDocument();
len = ::WideCharToMultiByte(cpDest, 0, uptr, -1,
NULL, 0, NULL, NULL) - 1; // subtract 0 terminator
putf = new char[len + 1];
::WideCharToMultiByte(cpDest, 0, uptr, -1,
putf, len + 1, NULL, NULL);
}
InsertPasteText(putf, len, selStart, isRectangular, isLine);
delete []putf;
}
memUSelection.Unlock();
} else {
// CF_UNICODETEXT not available, paste ANSI text
GlobalMemory memSelection(::GetClipboardData(CF_TEXT));
if (memSelection) {
char *ptr = static_cast<char *>(memSelection.ptr);
if (ptr) {
unsigned int bytes = memSelection.Size();
unsigned int len = bytes;
for (unsigned int i = 0; i < bytes; i++) {
if ((len == bytes) && (0 == ptr[i]))
len = i;
}
// In Unicode mode, convert clipboard text to UTF-8
if (IsUnicodeMode()) {
wchar_t *uptr = new wchar_t[len+1];
unsigned int ulen = ::MultiByteToWideChar(CP_ACP, 0,
ptr, len, uptr, len+1);
unsigned int mlen = UTF8Length(uptr, ulen);
char *putf = new char[mlen + 1];
if (putf) {
// CP_UTF8 not available on Windows 95, so use UTF8FromUTF16()
UTF8FromUTF16(uptr, ulen, putf, mlen);
}
delete []uptr;
if (putf) {
InsertPasteText(putf, mlen, selStart, isRectangular, isLine);
delete []putf;
}
} else {
InsertPasteText(ptr, len, selStart, isRectangular, isLine);
}
}
memSelection.Unlock();
}
}
::CloseClipboard();
Redraw();
}
void ScintillaWin::CreateCallTipWindow(PRectangle) {
if (!ct.wCallTip.Created()) {
ct.wCallTip = ::CreateWindow(callClassName, TEXT("ACallTip"),
WS_POPUP, 100, 100, 150, 20,
MainHWND(), 0,
GetWindowInstance(MainHWND()),
this);
ct.wDraw = ct.wCallTip;
}
}
void ScintillaWin::AddToPopUp(const char *label, int cmd, bool enabled) {
HMENU hmenuPopup = reinterpret_cast<HMENU>(popup.GetID());
if (!label[0])
::AppendMenuA(hmenuPopup, MF_SEPARATOR, 0, "");
else if (enabled)
::AppendMenuA(hmenuPopup, MF_STRING, cmd, label);
else
::AppendMenuA(hmenuPopup, MF_STRING | MF_DISABLED | MF_GRAYED, cmd, label);
}
void ScintillaWin::ClaimSelection() {
// Windows does not have a primary selection
}
/// Implement IUnknown
STDMETHODIMP_(ULONG)FormatEnumerator_AddRef(FormatEnumerator *fe);
STDMETHODIMP FormatEnumerator_QueryInterface(FormatEnumerator *fe, REFIID riid, PVOID *ppv) {
//Platform::DebugPrintf("EFE QI");
*ppv = NULL;
if (riid == IID_IUnknown)
*ppv = reinterpret_cast<IEnumFORMATETC *>(fe);
if (riid == IID_IEnumFORMATETC)
*ppv = reinterpret_cast<IEnumFORMATETC *>(fe);
if (!*ppv)
return E_NOINTERFACE;
FormatEnumerator_AddRef(fe);
return S_OK;
}
STDMETHODIMP_(ULONG)FormatEnumerator_AddRef(FormatEnumerator *fe) {
return ++fe->ref;
}
STDMETHODIMP_(ULONG)FormatEnumerator_Release(FormatEnumerator *fe) {
fe->ref--;
if (fe->ref > 0)
return fe->ref;
delete fe;
return 0;
}
/// Implement IEnumFORMATETC
STDMETHODIMP FormatEnumerator_Next(FormatEnumerator *fe, ULONG celt, FORMATETC *rgelt, ULONG *pceltFetched) {
//Platform::DebugPrintf("EFE Next %d %d", fe->pos, celt);
if (rgelt == NULL) return E_POINTER;
// We only support one format, so this is simple.
unsigned int putPos = 0;
while ((fe->pos < fe->formatsLen) && (putPos < celt)) {
rgelt->cfFormat = fe->formats[fe->pos];
rgelt->ptd = 0;
rgelt->dwAspect = DVASPECT_CONTENT;
rgelt->lindex = -1;
rgelt->tymed = TYMED_HGLOBAL;
fe->pos++;
putPos++;
}
if (pceltFetched)
*pceltFetched = putPos;
return putPos ? S_OK : S_FALSE;
}
STDMETHODIMP FormatEnumerator_Skip(FormatEnumerator *fe, ULONG celt) {
fe->pos += celt;
return S_OK;
}
STDMETHODIMP FormatEnumerator_Reset(FormatEnumerator *fe) {
fe->pos = 0;
return S_OK;
}
STDMETHODIMP FormatEnumerator_Clone(FormatEnumerator *fe, IEnumFORMATETC **ppenum) {
FormatEnumerator *pfe;
try {
pfe = new FormatEnumerator(fe->pos, fe->formats, fe->formatsLen);
} catch (...) {
return E_OUTOFMEMORY;
}
return FormatEnumerator_QueryInterface(pfe, IID_IEnumFORMATETC,
reinterpret_cast<void **>(ppenum));
}
static VFunction *vtFormatEnumerator[] = {
(VFunction *)(FormatEnumerator_QueryInterface),
(VFunction *)(FormatEnumerator_AddRef),
(VFunction *)(FormatEnumerator_Release),
(VFunction *)(FormatEnumerator_Next),
(VFunction *)(FormatEnumerator_Skip),
(VFunction *)(FormatEnumerator_Reset),
(VFunction *)(FormatEnumerator_Clone)
};
FormatEnumerator::FormatEnumerator(int pos_, CLIPFORMAT formats_[], int formatsLen_) {
vtbl = vtFormatEnumerator;
ref = 0; // First QI adds first reference...
pos = pos_;
formatsLen = formatsLen_;
for (int i=0; i<formatsLen; i++)
formats[i] = formats_[i];
}
/// Implement IUnknown
STDMETHODIMP DropSource_QueryInterface(DropSource *ds, REFIID riid, PVOID *ppv) {
return ds->sci->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG)DropSource_AddRef(DropSource *ds) {
return ds->sci->AddRef();
}
STDMETHODIMP_(ULONG)DropSource_Release(DropSource *ds) {
return ds->sci->Release();
}
/// Implement IDropSource
STDMETHODIMP DropSource_QueryContinueDrag(DropSource *, BOOL fEsc, DWORD grfKeyState) {
if (fEsc)
return DRAGDROP_S_CANCEL;
if (!(grfKeyState & MK_LBUTTON))
return DRAGDROP_S_DROP;
return S_OK;
}
STDMETHODIMP DropSource_GiveFeedback(DropSource *, DWORD) {
return DRAGDROP_S_USEDEFAULTCURSORS;
}
static VFunction *vtDropSource[] = {
(VFunction *)(DropSource_QueryInterface),
(VFunction *)(DropSource_AddRef),
(VFunction *)(DropSource_Release),
(VFunction *)(DropSource_QueryContinueDrag),
(VFunction *)(DropSource_GiveFeedback)
};
DropSource::DropSource() {
vtbl = vtDropSource;
sci = 0;
}
/// Implement IUnkown
STDMETHODIMP DataObject_QueryInterface(DataObject *pd, REFIID riid, PVOID *ppv) {
//Platform::DebugPrintf("DO QI %x\n", pd);
return pd->sci->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG)DataObject_AddRef(DataObject *pd) {
return pd->sci->AddRef();
}
STDMETHODIMP_(ULONG)DataObject_Release(DataObject *pd) {
return pd->sci->Release();
}
/// Implement IDataObject
STDMETHODIMP DataObject_GetData(DataObject *pd, FORMATETC *pFEIn, STGMEDIUM *pSTM) {
return pd->sci->GetData(pFEIn, pSTM);
}
STDMETHODIMP DataObject_GetDataHere(DataObject *, FORMATETC *, STGMEDIUM *) {
//Platform::DebugPrintf("DOB GetDataHere\n");
return E_NOTIMPL;
}
STDMETHODIMP DataObject_QueryGetData(DataObject *pd, FORMATETC *pFE) {
if (pd->sci->DragIsRectangularOK(pFE->cfFormat) &&
pFE->ptd == 0 &&
(pFE->dwAspect & DVASPECT_CONTENT) != 0 &&
pFE->lindex == -1 &&
(pFE->tymed & TYMED_HGLOBAL) != 0
) {
return S_OK;
}
bool formatOK = (pFE->cfFormat == CF_TEXT) ||
((pFE->cfFormat == CF_UNICODETEXT) && pd->sci->IsUnicodeMode());
if (!formatOK ||
pFE->ptd != 0 ||
(pFE->dwAspect & DVASPECT_CONTENT) == 0 ||
pFE->lindex != -1 ||
(pFE->tymed & TYMED_HGLOBAL) == 0
) {
//Platform::DebugPrintf("DOB QueryGetData No %x\n",pFE->cfFormat);
//return DATA_E_FORMATETC;
return S_FALSE;
}
//Platform::DebugPrintf("DOB QueryGetData OK %x\n",pFE->cfFormat);
return S_OK;
}
STDMETHODIMP DataObject_GetCanonicalFormatEtc(DataObject *pd, FORMATETC *, FORMATETC *pFEOut) {
//Platform::DebugPrintf("DOB GetCanon\n");
if (pd->sci->IsUnicodeMode())
pFEOut->cfFormat = CF_UNICODETEXT;
else
pFEOut->cfFormat = CF_TEXT;
pFEOut->ptd = 0;
pFEOut->dwAspect = DVASPECT_CONTENT;
pFEOut->lindex = -1;
pFEOut->tymed = TYMED_HGLOBAL;
return S_OK;
}
STDMETHODIMP DataObject_SetData(DataObject *, FORMATETC *, STGMEDIUM *, BOOL) {
//Platform::DebugPrintf("DOB SetData\n");
return E_FAIL;
}
STDMETHODIMP DataObject_EnumFormatEtc(DataObject *pd, DWORD dwDirection, IEnumFORMATETC **ppEnum) {
try {
//Platform::DebugPrintf("DOB EnumFormatEtc %d\n", dwDirection);
if (dwDirection != DATADIR_GET) {
*ppEnum = 0;
return E_FAIL;
}
FormatEnumerator *pfe;
if (pd->sci->IsUnicodeMode()) {
CLIPFORMAT formats[] = {CF_UNICODETEXT, CF_TEXT};
pfe = new FormatEnumerator(0, formats, 2);
} else {
CLIPFORMAT formats[] = {CF_TEXT};
pfe = new FormatEnumerator(0, formats, 1);
}
return FormatEnumerator_QueryInterface(pfe, IID_IEnumFORMATETC,
reinterpret_cast<void **>(ppEnum));
} catch (std::bad_alloc &) {
pd->sci->errorStatus = SC_STATUS_BADALLOC;
return E_OUTOFMEMORY;
} catch (...) {
pd->sci->errorStatus = SC_STATUS_FAILURE;
return E_FAIL;
}
}
STDMETHODIMP DataObject_DAdvise(DataObject *, FORMATETC *, DWORD, IAdviseSink *, PDWORD) {
//Platform::DebugPrintf("DOB DAdvise\n");
return E_FAIL;
}
STDMETHODIMP DataObject_DUnadvise(DataObject *, DWORD) {
//Platform::DebugPrintf("DOB DUnadvise\n");
return E_FAIL;
}
STDMETHODIMP DataObject_EnumDAdvise(DataObject *, IEnumSTATDATA **) {
//Platform::DebugPrintf("DOB EnumDAdvise\n");
return E_FAIL;
}
static VFunction *vtDataObject[] = {
(VFunction *)(DataObject_QueryInterface),
(VFunction *)(DataObject_AddRef),
(VFunction *)(DataObject_Release),
(VFunction *)(DataObject_GetData),
(VFunction *)(DataObject_GetDataHere),
(VFunction *)(DataObject_QueryGetData),
(VFunction *)(DataObject_GetCanonicalFormatEtc),
(VFunction *)(DataObject_SetData),
(VFunction *)(DataObject_EnumFormatEtc),
(VFunction *)(DataObject_DAdvise),
(VFunction *)(DataObject_DUnadvise),
(VFunction *)(DataObject_EnumDAdvise)
};
DataObject::DataObject() {
vtbl = vtDataObject;
sci = 0;
}
/// Implement IUnknown
STDMETHODIMP DropTarget_QueryInterface(DropTarget *dt, REFIID riid, PVOID *ppv) {
//Platform::DebugPrintf("DT QI %x\n", dt);
return dt->sci->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG)DropTarget_AddRef(DropTarget *dt) {
return dt->sci->AddRef();
}
STDMETHODIMP_(ULONG)DropTarget_Release(DropTarget *dt) {
return dt->sci->Release();
}
/// Implement IDropTarget by forwarding to Scintilla
STDMETHODIMP DropTarget_DragEnter(DropTarget *dt, LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect) {
try {
return dt->sci->DragEnter(pIDataSource, grfKeyState, pt, pdwEffect);
} catch (...) {
dt->sci->errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP DropTarget_DragOver(DropTarget *dt, DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) {
try {
return dt->sci->DragOver(grfKeyState, pt, pdwEffect);
} catch (...) {
dt->sci->errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP DropTarget_DragLeave(DropTarget *dt) {
try {
return dt->sci->DragLeave();
} catch (...) {
dt->sci->errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP DropTarget_Drop(DropTarget *dt, LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect) {
try {
return dt->sci->Drop(pIDataSource, grfKeyState, pt, pdwEffect);
} catch (...) {
dt->sci->errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
static VFunction *vtDropTarget[] = {
(VFunction *)(DropTarget_QueryInterface),
(VFunction *)(DropTarget_AddRef),
(VFunction *)(DropTarget_Release),
(VFunction *)(DropTarget_DragEnter),
(VFunction *)(DropTarget_DragOver),
(VFunction *)(DropTarget_DragLeave),
(VFunction *)(DropTarget_Drop)
};
DropTarget::DropTarget() {
vtbl = vtDropTarget;
sci = 0;
}
/**
* DBCS: support Input Method Editor (IME).
* Called when IME Window opened.
*/
void ScintillaWin::ImeStartComposition() {
#ifndef __DMC__
// Digital Mars compiler does not include Imm library
if (caret.active) {
// Move IME Window to current caret position
HIMC hIMC = ::ImmGetContext(MainHWND());
Point pos = PointMainCaret();
COMPOSITIONFORM CompForm;
CompForm.dwStyle = CFS_POINT;
CompForm.ptCurrentPos.x = pos.x;
CompForm.ptCurrentPos.y = pos.y;
::ImmSetCompositionWindow(hIMC, &CompForm);
// Set font of IME window to same as surrounded text.
if (stylesValid) {
// Since the style creation code has been made platform independent,
// The logfont for the IME is recreated here.
int styleHere = (pdoc->StyleAt(sel.MainCaret())) & 31;
LOGFONTA lf = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ""};
int sizeZoomed = vs.styles[styleHere].size + vs.zoomLevel;
if (sizeZoomed <= 2) // Hangs if sizeZoomed <= 1
sizeZoomed = 2;
AutoSurface surface(this);
int deviceHeight = sizeZoomed;
if (surface) {
deviceHeight = (sizeZoomed * surface->LogPixelsY()) / 72;
}
// The negative is to allow for leading
lf.lfHeight = -(abs(deviceHeight));
lf.lfWeight = vs.styles[styleHere].bold ? FW_BOLD : FW_NORMAL;
lf.lfItalic = static_cast<BYTE>(vs.styles[styleHere].italic ? 1 : 0);
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfFaceName[0] = '\0';
if (vs.styles[styleHere].fontName)
strcpy(lf.lfFaceName, vs.styles[styleHere].fontName);
::ImmSetCompositionFontA(hIMC, &lf);
}
::ImmReleaseContext(MainHWND(), hIMC);
// Caret is displayed in IME window. So, caret in Scintilla is useless.
DropCaret();
}
#endif
}
/** Called when IME Window closed. */
void ScintillaWin::ImeEndComposition() {
ShowCaretAtCurrentPosition();
}
void ScintillaWin::AddCharBytes(char b0, char b1) {
int inputCodePage = InputCodePage();
if (inputCodePage && IsUnicodeMode()) {
char utfval[4] = "\0\0\0";
char ansiChars[3];
wchar_t wcs[2];
if (b0) { // Two bytes from IME
ansiChars[0] = b0;
ansiChars[1] = b1;
ansiChars[2] = '\0';
::MultiByteToWideChar(inputCodePage, 0, ansiChars, 2, wcs, 1);
} else {
ansiChars[0] = b1;
ansiChars[1] = '\0';
::MultiByteToWideChar(inputCodePage, 0, ansiChars, 1, wcs, 1);
}
unsigned int len = UTF8Length(wcs, 1);
UTF8FromUTF16(wcs, 1, utfval, len);
utfval[len] = '\0';
AddCharUTF(utfval, len ? len : 1);
} else if (b0) {
char dbcsChars[3];
dbcsChars[0] = b0;
dbcsChars[1] = b1;
dbcsChars[2] = '\0';
AddCharUTF(dbcsChars, 2, true);
} else {
AddChar(b1);
}
}
void ScintillaWin::GetIntelliMouseParameters() {
// This retrieves the number of lines per scroll as configured inthe Mouse Properties sheet in Control Panel
::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &linesPerScroll, 0);
}
void ScintillaWin::CopyToClipboard(const SelectionText &selectedText) {
if (!::OpenClipboard(MainHWND()))
return;
::EmptyClipboard();
GlobalMemory uniText;
// Default Scintilla behaviour in Unicode mode
if (IsUnicodeMode()) {
int uchars = UTF16Length(selectedText.s, selectedText.len);
uniText.Allocate(2 * uchars);
if (uniText) {
UTF16FromUTF8(selectedText.s, selectedText.len, static_cast<wchar_t *>(uniText.ptr), uchars);
}
} else {
// Not Unicode mode
// Convert to Unicode using the current Scintilla code page
UINT cpSrc = CodePageFromCharSet(
selectedText.characterSet, selectedText.codePage);
int uLen = ::MultiByteToWideChar(cpSrc, 0, selectedText.s, selectedText.len, 0, 0);
uniText.Allocate(2 * uLen);
if (uniText) {
::MultiByteToWideChar(cpSrc, 0, selectedText.s, selectedText.len,
static_cast<wchar_t *>(uniText.ptr), uLen);
}
}
if (uniText) {
if (!IsNT()) {
// Copy ANSI text to clipboard on Windows 9x
// Convert from Unicode text, so other ANSI programs can
// paste the text
// Windows NT, 2k, XP automatically generates CF_TEXT
GlobalMemory ansiText;
ansiText.Allocate(selectedText.len);
if (ansiText) {
::WideCharToMultiByte(CP_ACP, 0, static_cast<wchar_t *>(uniText.ptr), -1,
static_cast<char *>(ansiText.ptr), selectedText.len, NULL, NULL);
ansiText.SetClip(CF_TEXT);
}
}
uniText.SetClip(CF_UNICODETEXT);
} else {
// There was a failure - try to copy at least ANSI text
GlobalMemory ansiText;
ansiText.Allocate(selectedText.len);
if (ansiText) {
memcpy(static_cast<char *>(ansiText.ptr), selectedText.s, selectedText.len);
ansiText.SetClip(CF_TEXT);
}
}
if (selectedText.rectangular) {
::SetClipboardData(cfColumnSelect, 0);
}
if (selectedText.lineCopy) {
::SetClipboardData(cfLineSelect, 0);
}
::CloseClipboard();
}
void ScintillaWin::ScrollMessage(WPARAM wParam) {
//DWORD dwStart = timeGetTime();
//Platform::DebugPrintf("Scroll %x %d\n", wParam, lParam);
SCROLLINFO sci;
memset(&sci, 0, sizeof(sci));
sci.cbSize = sizeof(sci);
sci.fMask = SIF_ALL;
GetScrollInfo(SB_VERT, &sci);
//Platform::DebugPrintf("ScrollInfo %d mask=%x min=%d max=%d page=%d pos=%d track=%d\n", b,sci.fMask,
//sci.nMin, sci.nMax, sci.nPage, sci.nPos, sci.nTrackPos);
int topLineNew = topLine;
switch (LoWord(wParam)) {
case SB_LINEUP:
topLineNew -= 1;
break;
case SB_LINEDOWN:
topLineNew += 1;
break;
case SB_PAGEUP:
topLineNew -= LinesToScroll(); break;
case SB_PAGEDOWN: topLineNew += LinesToScroll(); break;
case SB_TOP: topLineNew = 0; break;
case SB_BOTTOM: topLineNew = MaxScrollPos(); break;
case SB_THUMBPOSITION: topLineNew = sci.nTrackPos; break;
case SB_THUMBTRACK: topLineNew = sci.nTrackPos; break;
}
ScrollTo(topLineNew);
}
void ScintillaWin::HorizontalScrollMessage(WPARAM wParam) {
int xPos = xOffset;
PRectangle rcText = GetTextRectangle();
int pageWidth = rcText.Width() * 2 / 3;
switch (LoWord(wParam)) {
case SB_LINEUP:
xPos -= 20;
break;
case SB_LINEDOWN: // May move past the logical end
xPos += 20;
break;
case SB_PAGEUP:
xPos -= pageWidth;
break;
case SB_PAGEDOWN:
xPos += pageWidth;
if (xPos > scrollWidth - rcText.Width()) { // Hit the end exactly
xPos = scrollWidth - rcText.Width();
}
break;
case SB_TOP:
xPos = 0;
break;
case SB_BOTTOM:
xPos = scrollWidth;
break;
case SB_THUMBPOSITION:
case SB_THUMBTRACK: {
// Do NOT use wParam, its 16 bit and not enough for very long lines. Its still possible to overflow the 32 bit but you have to try harder =]
SCROLLINFO si;
si.cbSize = sizeof(si);
si.fMask = SIF_TRACKPOS;
if (GetScrollInfo(SB_HORZ, &si)) {
xPos = si.nTrackPos;
}
}
break;
}
HorizontalScrollTo(xPos);
}
void ScintillaWin::RealizeWindowPalette(bool inBackGround) {
RefreshStyleData();
HDC hdc = ::GetDC(MainHWND());
// Select a stock font to prevent warnings from BoundsChecker
::SelectObject(hdc, GetStockFont(DEFAULT_GUI_FONT));
AutoSurface surfaceWindow(hdc, this);
if (surfaceWindow) {
int changes = surfaceWindow->SetPalette(&palette, inBackGround);
if (changes > 0)
Redraw();
surfaceWindow->Release();
}
::ReleaseDC(MainHWND(), hdc);
}
/**
* Redraw all of text area.
* This paint will not be abandoned.
*/
void ScintillaWin::FullPaint() {
HDC hdc = ::GetDC(MainHWND());
FullPaintDC(hdc);
::ReleaseDC(MainHWND(), hdc);
}
/**
* Redraw all of text area on the specified DC.
* This paint will not be abandoned.
*/
void ScintillaWin::FullPaintDC(HDC hdc) {
paintState = painting;
rcPaint = GetClientRectangle();
paintingAllText = true;
AutoSurface surfaceWindow(hdc, this);
if (surfaceWindow) {
Paint(surfaceWindow, rcPaint);
surfaceWindow->Release();
}
paintState = notPainting;
}
static bool CompareDevCap(HDC hdc, HDC hOtherDC, int nIndex) {
return ::GetDeviceCaps(hdc, nIndex) == ::GetDeviceCaps(hOtherDC, nIndex);
}
bool ScintillaWin::IsCompatibleDC(HDC hOtherDC) {
HDC hdc = ::GetDC(MainHWND());
bool isCompatible =
CompareDevCap(hdc, hOtherDC, TECHNOLOGY) &&
CompareDevCap(hdc, hOtherDC, LOGPIXELSY) &&
CompareDevCap(hdc, hOtherDC, LOGPIXELSX) &&
CompareDevCap(hdc, hOtherDC, BITSPIXEL) &&
CompareDevCap(hdc, hOtherDC, PLANES);
::ReleaseDC(MainHWND(), hdc);
return isCompatible;
}
DWORD ScintillaWin::EffectFromState(DWORD grfKeyState) {
// These are the Wordpad semantics.
DWORD dwEffect;
if (inDragDrop == ddDragging) // Internal defaults to move
dwEffect = DROPEFFECT_MOVE;
else
dwEffect = DROPEFFECT_COPY;
if (grfKeyState & MK_ALT)
dwEffect = DROPEFFECT_MOVE;
if (grfKeyState & MK_CONTROL)
dwEffect = DROPEFFECT_COPY;
return dwEffect;
}
/// Implement IUnknown
STDMETHODIMP ScintillaWin::QueryInterface(REFIID riid, PVOID *ppv) {
*ppv = NULL;
if (riid == IID_IUnknown)
*ppv = reinterpret_cast<IDropTarget *>(&dt);
if (riid == IID_IDropSource)
*ppv = reinterpret_cast<IDropSource *>(&ds);
if (riid == IID_IDropTarget)
*ppv = reinterpret_cast<IDropTarget *>(&dt);
if (riid == IID_IDataObject)
*ppv = reinterpret_cast<IDataObject *>(&dob);
if (!*ppv)
return E_NOINTERFACE;
return S_OK;
}
STDMETHODIMP_(ULONG) ScintillaWin::AddRef() {
return 1;
}
STDMETHODIMP_(ULONG) ScintillaWin::Release() {
return 1;
}
/// Implement IDropTarget
STDMETHODIMP ScintillaWin::DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL, PDWORD pdwEffect) {
if (pIDataSource == NULL)
return E_POINTER;
FORMATETC fmtu = {CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
HRESULT hrHasUText = pIDataSource->QueryGetData(&fmtu);
hasOKText = (hrHasUText == S_OK);
if (!hasOKText) {
FORMATETC fmte = {CF_TEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
HRESULT hrHasText = pIDataSource->QueryGetData(&fmte);
hasOKText = (hrHasText == S_OK);
}
if (!hasOKText) {
*pdwEffect = DROPEFFECT_NONE;
return S_OK;
}
*pdwEffect = EffectFromState(grfKeyState);
return S_OK;
}
STDMETHODIMP ScintillaWin::DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) {
try {
if (!hasOKText || pdoc->IsReadOnly()) {
*pdwEffect = DROPEFFECT_NONE;
return S_OK;
}
*pdwEffect = EffectFromState(grfKeyState);
// Update the cursor.
POINT rpt = {pt.x, pt.y};
::ScreenToClient(MainHWND(), &rpt);
SetDragPosition(SPositionFromLocation(Point(rpt.x, rpt.y), false, false, UserVirtualSpace()));
return S_OK;
} catch (...) {
errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP ScintillaWin::DragLeave() {
try {
SetDragPosition(SelectionPosition(invalidPosition));
return S_OK;
} catch (...) {
errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP ScintillaWin::Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect) {
try {
*pdwEffect = EffectFromState(grfKeyState);
if (pIDataSource == NULL)
return E_POINTER;
SetDragPosition(SelectionPosition(invalidPosition));
STGMEDIUM medium = {0, {0}, 0};
char *data = 0;
bool dataAllocated = false;
FORMATETC fmtu = {CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
HRESULT hr = pIDataSource->GetData(&fmtu, &medium);
if (SUCCEEDED(hr) && medium.hGlobal) {
wchar_t *udata = static_cast<wchar_t *>(::GlobalLock(medium.hGlobal));
if (IsUnicodeMode()) {
int tlen = ::GlobalSize(medium.hGlobal);
// Convert UTF-16 to UTF-8
int dataLen = UTF8Length(udata, tlen/2);
data = new char[dataLen+1];
UTF8FromUTF16(udata, tlen/2, data, dataLen);
dataAllocated = true;
} else {
// Convert UTF-16 to ANSI
//
// Default Scintilla behavior in Unicode mode
// CF_UNICODETEXT available, but not in Unicode mode
// Convert from Unicode to current Scintilla code page
UINT cpDest = CodePageOfDocument();
int tlen = ::WideCharToMultiByte(cpDest, 0, udata, -1,
NULL, 0, NULL, NULL) - 1; // subtract 0 terminator
data = new char[tlen + 1];
memset(data, 0, (tlen+1));
::WideCharToMultiByte(cpDest, 0, udata, -1,
data, tlen + 1, NULL, NULL);
dataAllocated = true;
}
}
if (!data) {
FORMATETC fmte = {CF_TEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
hr = pIDataSource->GetData(&fmte, &medium);
if (SUCCEEDED(hr) && medium.hGlobal) {
data = static_cast<char *>(::GlobalLock(medium.hGlobal));
}
}
if (data && convertPastes) {
// Convert line endings of the drop into our local line-endings mode
int len = strlen(data);
char *convertedText = Document::TransformLineEnds(&len, data, len, pdoc->eolMode);
if (dataAllocated)
delete []data;
data = convertedText;
dataAllocated = true;
}
if (!data) {
//Platform::DebugPrintf("Bad data format: 0x%x\n", hres);
return hr;
}
FORMATETC fmtr = {cfColumnSelect, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
HRESULT hrRectangular = pIDataSource->QueryGetData(&fmtr);
POINT rpt = {pt.x, pt.y};
::ScreenToClient(MainHWND(), &rpt);
SelectionPosition movePos = SPositionFromLocation(Point(rpt.x, rpt.y), false, false, UserVirtualSpace());
DropAt(movePos, data, *pdwEffect == DROPEFFECT_MOVE, hrRectangular == S_OK);
::GlobalUnlock(medium.hGlobal);
// Free data
if (medium.pUnkForRelease != NULL)
medium.pUnkForRelease->Release();
else
::GlobalFree(medium.hGlobal);
if (dataAllocated)
delete []data;
return S_OK;
} catch (...) {
errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
/// Implement important part of IDataObject
STDMETHODIMP ScintillaWin::GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM) {
bool formatOK = (pFEIn->cfFormat == CF_TEXT) ||
((pFEIn->cfFormat == CF_UNICODETEXT) && IsUnicodeMode());
if (!formatOK ||
pFEIn->ptd != 0 ||
(pFEIn->dwAspect & DVASPECT_CONTENT) == 0 ||
pFEIn->lindex != -1 ||
(pFEIn->tymed & TYMED_HGLOBAL) == 0
) {
//Platform::DebugPrintf("DOB GetData No %d %x %x fmt=%x\n", lenDrag, pFEIn, pSTM, pFEIn->cfFormat);
return DATA_E_FORMATETC;
}
pSTM->tymed = TYMED_HGLOBAL;
//Platform::DebugPrintf("DOB GetData OK %d %x %x\n", lenDrag, pFEIn, pSTM);
GlobalMemory text;
if (pFEIn->cfFormat == CF_UNICODETEXT) {
int uchars = UTF16Length(drag.s, drag.len);
text.Allocate(2 * uchars);
if (text) {
UTF16FromUTF8(drag.s, drag.len, static_cast<wchar_t *>(text.ptr), uchars);
}
} else {
text.Allocate(drag.len);
if (text) {
memcpy(static_cast<char *>(text.ptr), drag.s, drag.len);
}
}
pSTM->hGlobal = text ? text.Unlock() : 0;
pSTM->pUnkForRelease = 0;
return S_OK;
}
bool ScintillaWin::Register(HINSTANCE hInstance_) {
hInstance = hInstance_;
bool result;
// Register the Scintilla class
if (IsNT()) {
// Register Scintilla as a wide character window
WNDCLASSEXW wndclass;
wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = ScintillaWin::SWndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = sizeof(ScintillaWin *);
wndclass.hInstance = hInstance;
wndclass.hIcon = NULL;
wndclass.hCursor = NULL;
wndclass.hbrBackground = NULL;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = L"Scintilla";
wndclass.hIconSm = 0;
result = ::RegisterClassExW(&wndclass) != 0;
} else {
// Register Scintilla as a normal character window
WNDCLASSEX wndclass;
wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = ScintillaWin::SWndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = sizeof(ScintillaWin *);
wndclass.hInstance = hInstance;
wndclass.hIcon = NULL;
wndclass.hCursor = NULL;
wndclass.hbrBackground = NULL;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = scintillaClassName;
wndclass.hIconSm = 0;
result = ::RegisterClassEx(&wndclass) != 0;
}
if (result) {
// Register the CallTip class
WNDCLASSEX wndclassc;
wndclassc.cbSize = sizeof(wndclassc);
wndclassc.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
wndclassc.cbClsExtra = 0;
wndclassc.cbWndExtra = sizeof(ScintillaWin *);
wndclassc.hInstance = hInstance;
wndclassc.hIcon = NULL;
wndclassc.hbrBackground = NULL;
wndclassc.lpszMenuName = NULL;
wndclassc.lpfnWndProc = ScintillaWin::CTWndProc;
wndclassc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
wndclassc.lpszClassName = callClassName;
wndclassc.hIconSm = 0;
result = ::RegisterClassEx(&wndclassc) != 0;
}
return result;
}
bool ScintillaWin::Unregister() {
bool result = ::UnregisterClass(scintillaClassName, hInstance) != 0;
if (::UnregisterClass(callClassName, hInstance) == 0)
result = false;
return result;
}
bool ScintillaWin::HasCaretSizeChanged() {
if (
( (0 != vs.caretWidth) && (sysCaretWidth != vs.caretWidth) )
|| ((0 != vs.lineHeight) && (sysCaretHeight != vs.lineHeight))
) {
return true;
}
return false;
}
BOOL ScintillaWin::CreateSystemCaret() {
sysCaretWidth = vs.caretWidth;
if (0 == sysCaretWidth) {
sysCaretWidth = 1;
}
sysCaretHeight = vs.lineHeight;
int bitmapSize = (((sysCaretWidth + 15) & ~15) >> 3) *
sysCaretHeight;
char *bits = new char[bitmapSize];
memset(bits, 0, bitmapSize);
sysCaretBitmap = ::CreateBitmap(sysCaretWidth, sysCaretHeight, 1,
1, reinterpret_cast<BYTE *>(bits));
delete []bits;
BOOL retval = ::CreateCaret(
MainHWND(), sysCaretBitmap,
sysCaretWidth, sysCaretHeight);
::ShowCaret(MainHWND());
return retval;
}
BOOL ScintillaWin::DestroySystemCaret() {
::HideCaret(MainHWND());
BOOL retval = ::DestroyCaret();
if (sysCaretBitmap) {
::DeleteObject(sysCaretBitmap);
sysCaretBitmap = 0;
}
return retval;
}
// Take care of 32/64 bit pointers
#ifdef GetWindowLongPtr
static void *PointerFromWindow(HWND hWnd) {
return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0));
}
static void SetWindowPointer(HWND hWnd, void *ptr) {
::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr));
}
#else
static void *PointerFromWindow(HWND hWnd) {
return reinterpret_cast<void *>(::GetWindowLong(hWnd, 0));
}
static void SetWindowPointer(HWND hWnd, void *ptr) {
::SetWindowLong(hWnd, 0, reinterpret_cast<LONG>(ptr));
}
#endif
sptr_t PASCAL ScintillaWin::CTWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam) {
// Find C++ object associated with window.
ScintillaWin *sciThis = reinterpret_cast<ScintillaWin *>(PointerFromWindow(hWnd));
try {
// ctp will be zero if WM_CREATE not seen yet
if (sciThis == 0) {
if (iMessage == WM_CREATE) {
// Associate CallTip object with window
CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT *>(lParam);
SetWindowPointer(hWnd, pCreate->lpCreateParams);
return 0;
} else {
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
} else {
if (iMessage == WM_NCDESTROY) {
::SetWindowLong(hWnd, 0, 0);
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
} else if (iMessage == WM_PAINT) {
PAINTSTRUCT ps;
::BeginPaint(hWnd, &ps);
Surface *surfaceWindow = Surface::Allocate();
if (surfaceWindow) {
surfaceWindow->Init(ps.hdc, hWnd);
surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == sciThis->ct.codePage);
surfaceWindow->SetDBCSMode(sciThis->ct.codePage);
sciThis->ct.PaintCT(surfaceWindow);
surfaceWindow->Release();
delete surfaceWindow;
}
::EndPaint(hWnd, &ps);
return 0;
} else if ((iMessage == WM_NCLBUTTONDOWN) || (iMessage == WM_NCLBUTTONDBLCLK)) {
POINT pt;
pt.x = static_cast<short>(LOWORD(lParam));
pt.y = static_cast<short>(HIWORD(lParam));
ScreenToClient(hWnd, &pt);
sciThis->ct.MouseClick(Point(pt.x, pt.y));
sciThis->CallTipClick();
return 0;
} else if (iMessage == WM_LBUTTONDOWN) {
// This does not fire due to the hit test code
sciThis->ct.MouseClick(Point::FromLong(lParam));
sciThis->CallTipClick();
return 0;
} else if (iMessage == WM_SETCURSOR) {
::SetCursor(::LoadCursor(NULL, IDC_ARROW));
return 0;
} else if (iMessage == WM_NCHITTEST) {
return HTCAPTION;
} else {
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
}
} catch (...) {
sciThis->errorStatus = SC_STATUS_FAILURE;
}
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
sptr_t ScintillaWin::DirectFunction(
ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam) {
PLATFORM_ASSERT(::GetCurrentThreadId() == ::GetWindowThreadProcessId(sci->MainHWND(), NULL));
return sci->WndProc(iMessage, wParam, lParam);
}
extern "C"
#ifndef STATIC_BUILD
__declspec(dllexport)
#endif
sptr_t __stdcall Scintilla_DirectFunction(
ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam) {
return sci->WndProc(iMessage, wParam, lParam);
}
sptr_t PASCAL ScintillaWin::SWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam) {
//Platform::DebugPrintf("S W:%x M:%x WP:%x L:%x\n", hWnd, iMessage, wParam, lParam);
// Find C++ object associated with window.
ScintillaWin *sci = reinterpret_cast<ScintillaWin *>(PointerFromWindow(hWnd));
// sci will be zero if WM_CREATE not seen yet
if (sci == 0) {
try {
if (iMessage == WM_CREATE) {
// Create C++ object associated with window
sci = new ScintillaWin(hWnd);
SetWindowPointer(hWnd, sci);
return sci->WndProc(iMessage, wParam, lParam);
}
} catch (...) {
}
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
} else {
if (iMessage == WM_NCDESTROY) {
try {
sci->Finalise();
delete sci;
} catch (...) {
}
::SetWindowLong(hWnd, 0, 0);
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
} else {
return sci->WndProc(iMessage, wParam, lParam);
}
}
}
// This function is externally visible so it can be called from container when building statically.
// Must be called once only.
int Scintilla_RegisterClasses(void *hInstance) {
Platform_Initialise(hInstance);
bool result = ScintillaWin::Register(reinterpret_cast<HINSTANCE>(hInstance));
#ifdef SCI_LEXER
Scintilla_LinkLexers();
#endif
return result;
}
// This function is externally visible so it can be called from container when building statically.
int Scintilla_ReleaseResources() {
bool result = ScintillaWin::Unregister();
Platform_Finalise();
return result;
}
#ifndef STATIC_BUILD
extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID) {
//Platform::DebugPrintf("Scintilla::DllMain %d %d\n", hInstance, dwReason);
if (dwReason == DLL_PROCESS_ATTACH) {
if (!Scintilla_RegisterClasses(hInstance))
return FALSE;
} else if (dwReason == DLL_PROCESS_DETACH) {
Scintilla_ReleaseResources();
}
return TRUE;
}
#endif
| [
"donho@9e717b3d-e3cd-45c4-bdc4-af0eb0386351"
] | [
[
[
1,
2784
]
]
] |
b421f00d46dbfb62705a018c67d25153737dab37 | bd89d3607e32d7ebb8898f5e2d3445d524010850 | /connectivitylayer/isce/isaaccessextension_dll/src/router.cpp | 3a382985c36d09d6f63bca8179e5e8970700ff44 | [] | no_license | wannaphong/symbian-incubation-projects.fcl-modemadaptation | 9b9c61ba714ca8a786db01afda8f5a066420c0db | 0e6894da14b3b096cffe0182cedecc9b6dac7b8d | refs/heads/master | 2021-05-30T05:09:10.980036 | 2010-10-19T10:16:20 | 2010-10-19T10:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66,877 | cpp | /*
* 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 the License "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:
*
*/
#include <phonetisi.h> // For ISI_HEADER_SIZE
#include <pn_const.h> // For PN_HEADER_SIZE
#include <pipeisi.h> // For PNS_PIPE_DATA_OFFSET_DATA
#include <commisi.h> // For SIZE_COMMON_MESSAGE_COMM_ISA_ENTITY_NOT_REACHABLE_RESP
#include "router.h"
#include "iadtrace.h" // For C_TRACE..
#include "isaaccessextension.h" // For DIsaAccessExtension
#include "queue.h" // For DQueue
#include "iadinternaldefinitions.h" // For EIADAsync...
#include "iadhelpers.h" // For GET_RECEIVER
#include <nsisi.h> // For PN_NAMESERVICE...
#include "pipehandler.h" // For PipeHandler
#include "OstTraceDefinitions.h"
#ifdef OST_TRACE_COMPILER_IN_USE
#include "routerTraces.h"
#endif
//#define MODEM_MCE_DOES_NOT_WORK_AS_IT_SHOULD // TODO: to be removed when Bridge Modem SW is ok
// ISCE
#include "memapi.h" // For MemApi
#include "trxdefs.h" // For ETrx...
#include "ape_commgrisi.h" // For APE_COMMGR...
// ISCE
// CONSTS
DRouter* DRouter::iThisPtr = NULL;
const TUint32 KCommunicationManagerUID( 0x2002B3D0 );
const TUint32 KNameServiceUID( 0x2002A5A1 );
const TUint8 K8BitResourceId( 2 );
const TUint8 K32BitResourceId( 5 );
const TUint8 K32BitResourceOffsetByte1( 0 );
const TUint8 K32BitResourceOffsetByte2( 1 );
const TUint8 K32BitResourceOffsetByte3( 2 );
const TUint8 K32BitResourceOffsetByte4( 3 );
const TUint8 K8BitResourceOffset( 0 );
const TUint8 KEventOffset32Bit( 4 );
const TUint8 KEventOffset8Bit( 1 );
const TUint8 KFiller( 0 );
const TUint8 KNoResource( 0 );
// TODO: change this to use UnuqueID instead and to extension..
void DRouter::CheckDfc()
{
OstTrace0( TRACE_NORMAL, DROUTER_CHECKDFC_ENTRY, ">DRouter::CheckDfc" );
DObject* tempObj = reinterpret_cast<DObject*>( &Kern::CurrentThread() );
TUint8* buffer = ( TUint8* )Kern::Alloc( 100 );
TPtr8* bufferPtr = new ( TPtr8 )( buffer, 100 );
tempObj->Name( *bufferPtr );
C_TRACE( ( _T( "DRouter::CheckDfc" ) ) );
if ( bufferPtr->Compare( KIADExtensionDfc ) != KErrNone )
{
for( TInt i( 0 );i < bufferPtr->Length(); ++i )
{
Kern::Printf( "%c", i, bufferPtr->Ptr()[ i ]);
}
ASSERT_RESET_ALWAYS( 0, EIADWrongDFCQueueUsed | EIADFaultIdentifier2 << KFaultIdentifierShift );
}
Kern::Free( buffer );
delete bufferPtr;
bufferPtr = NULL;
OstTrace0( TRACE_NORMAL, DROUTER_CHECKDFC_EXIT, "<DRouter::CheckDfc" );
}
#ifdef _DEBUG
#define ASSERT_DFCTHREAD_INEXT() CheckDfc()
#else
#define ASSERT_DFCTHREAD_INEXT()
#endif
DRouter::DRouter():
iConnectionStatus( EIADConnectionNotOk )
, iBootDone( EFalse )
{
OstTrace0( TRACE_NORMAL, DROUTER_DROUTER_ENTRY, "<DRouter::DRouter" );
C_TRACE( ( _T( "DRouter::DRouter ->" ) ) );
// owned
#ifdef NCP_COMMON_BRIDGE_FAMILY_PIPE_SUPPORT
iPipeHandler = new DPipeHandler( *this );
#endif
iCommonRxQueue = new DQueue( KIADExtensionRxQueueSize );
// Initialize channels to NULL when channel is opened !NULL.
for( TInt i( 0 ); i < EIADSizeOfChannels; ++i )
{
iChannelTable[ i ].iChannel = NULL;
iChannelTable[ i ].iWaitingChannel = NULL;
iChannelTable[ i ].iType = ENormalOpen;
}
iCommonRxDfc = new TDfc( CommonRxDfc, this, DIsaAccessExtension::GetDFCThread( EIADExtensionDfcQueue ), KIADExtCommonRxPriori );
// not owned, just using.
// Set null when not registered.
iInitCmtDfc = new TDfc( InitCmtDfc, this, DIsaAccessExtension::GetDFCThread( EIADExtensionDfcQueue ), KIADExtInitCmtPriori );
iConnStatDfc = new TDfc( NotifyObjLayerConnStatDfc, this, DIsaAccessExtension::GetDFCThread( EIADExtensionDfcQueue ), KIADExtConnStatPriori );
ASSERT_RESET_ALWAYS( iCommonRxDfc && iInitCmtDfc && iConnStatDfc, EIADMemoryAllocationFailure | EIADFaultIdentifier18 << KFaultIdentifierShift );
iMaxFrameSize = 0x0000;
// ISCE
iLinksArray = new MISIRouterLinkIf*[ DRouter::EISIAmountOfMedias ];
// TODO: fault codes and ids
ASSERT_RESET_ALWAYS( iLinksArray, ( EIADMemoryAllocationFailure | EIADFaultIdentifier17 << KFaultIdentifierShift ) );
// Initialize links
for( TInt i( 0 ); i < DRouter::EISIAmountOfMedias; i++ )
{
iLinksArray[ i ] = NULL;
C_TRACE( ( _T( "DRouter::DRouter %d" ), i ) );
}
// Configuration of ISI links. TODO: devices and link configurations for coming platforms are unknown and to be done later.
iLinksArray[ DRouter::EISIMediaHostSSI ] = MISIRouterLinkIf::CreateLinkF( this, PN_MEDIA_MODEM_HOST_IF, ETrxSharedMemory );
DRouter::iThisPtr = this;
C_TRACE( ( _T( "DRouter::DRouter 0x%x <-" ), this ) );
OstTrace1( TRACE_NORMAL, DROUTER_DROUTER_EXIT, "<DRouter::DRouter;this=%x", this );
}
DRouter::~DRouter(
// None
)
{
OstTrace0( TRACE_NORMAL, DUP1_DROUTER_DROUTER_ENTRY, "<DRouter::~DRouter" );
//ISCE
// owning so deleting
for( TInt i( 0 ); i < EISIAmountOfMedias; i++ )
{
MISIRouterLinkIf* temp = iLinksArray[ i ];
temp->Release();
temp = NULL;
iLinksArray[ i ] = NULL;
}
//ISCE
C_TRACE( ( _T( "DRouter::~DRouter 0x%x ->" ), this ) );
// Initialize channels to NULL when channel is opened !NULL.
for( TInt i( 0 ); i < EIADSizeOfChannels; ++i )
{
iChannelTable[ i ].iChannel = NULL;
iChannelTable[ i ].iWaitingChannel = NULL;
iChannelTable[ i ].iType = ENormalOpen;
}
#ifdef NCP_COMMON_BRIDGE_FAMILY_PIPE_SUPPORT
if( iPipeHandler )
{
delete iPipeHandler;
iPipeHandler = NULL;
}
#endif
if( iCommonRxQueue )
{
delete iCommonRxQueue;
iCommonRxQueue = NULL;
}
if( iCommonRxDfc )
{
iCommonRxDfc->Cancel();
delete iCommonRxDfc;
iCommonRxDfc = NULL;
}
if( iInitCmtDfc )
{
delete iInitCmtDfc;
iInitCmtDfc = NULL;
}
if( iConnStatDfc )
{
delete iConnStatDfc;
iConnStatDfc = NULL;
}
C_TRACE( ( _T( "DRouter::~DRouter 0x%x <-" ), this ) );
OstTrace1( TRACE_NORMAL, DUP1_DROUTER_DROUTER_EXIT, "<DRouter::~DRouter;this=%x", this );
}
// From start
// Do not call from ISR context!! Can only be called from Extension DFCThread context.
EXPORT_C TDes8& DRouter::AllocateBlock(
const TUint16 aSize
)
{
OstTraceExt1( TRACE_NORMAL, DROUTER_ALLOCATEBLOCK_ENTRY, "<>DRouter::AllocateBlock;aSize=%hu", aSize );
C_TRACE( ( _T( "DRouter::AllocateBlock %d <->" ), aSize ) );
ASSERT_CONTEXT_ALWAYS( NKern::EThread, 0 );
ASSERT_DFCTHREAD_INEXT();
ASSERT_RESET_ALWAYS( aSize, EIADWrongParameter | EIADFaultIdentifier9 << KFaultIdentifierShift );
// ISCE
// ASSERT_RESET_ALWAYS( iIST, EIADNullParameter | EIADFaultIdentifier17 << KFaultIdentifierShift );
// return iIST->AllocateBlock( aSize );// TODO: Print ptr!!!
return MemApi::AllocBlock( aSize );
// ISCE
}
EXPORT_C TDes8& DRouter::AllocateDataBlock(
const TUint16 aSize
)
{
OstTraceExt1( TRACE_NORMAL, DROUTER_ALLOCATEDATABLOCK_ENTRY, ">DRouter::AllocateDataBlock;aSize=%hu", aSize );
C_TRACE( ( _T( "DRouter::AllocateDataBlock %d <->" ), aSize ) );
TUint32 neededLength( aSize + ISI_HEADER_SIZE + PNS_PIPE_DATA_OFFSET_DATA );
TDes8& tmp = this->AllocateBlock( neededLength );
#ifdef NCP_COMMON_BRIDGE_FAMILY_PIPE_SUPPORT
tmp.SetLength( neededLength );
TUint8* msgPtr = const_cast<TUint8*>( tmp.Ptr() );
SET_RECEIVER_DEV( msgPtr, PN_DEV_DONT_CARE );
ASSERT_RESET_ALWAYS( neededLength > ISI_HEADER_OFFSET_MESSAGEID, EIADOverTheLimits | EIADFaultIdentifier1 << KFaultIdentifierShift );
msgPtr[ ISI_HEADER_OFFSET_RESOURCEID ] = PN_PIPE;
msgPtr[ ISI_HEADER_OFFSET_MESSAGEID ] = PNS_PIPE_DATA;
SET_RECEIVER_OBJ( msgPtr, PN_OBJ_ROUTER );
SET_LENGTH( tmp, ( tmp.Length() - PN_HEADER_SIZE ) );
#endif
OstTrace1( TRACE_NORMAL, DROUTER_ALLOCATEDATABLOCK_EXIT, "<DRouter::AllocateDataBlock;tmp=%x",( TUint )&( tmp ) );
return tmp;
}
EXPORT_C void DRouter::Close(
const TUint16 aChannelId
)
{
OstTraceExt1( TRACE_NORMAL, DROUTER_CLOSE_ENTRY, ">DRouter::Close;aChannelId=%hx", aChannelId );
C_TRACE( ( _T( "DRouter::Close 0x%x ->" ), aChannelId ) );
// Channel must be from appropiate length and although it is sixteenbit value it must contain only 8-bit values. If over 8-bit changes needed.
ASSERT_RESET_ALWAYS( aChannelId < EIADSizeOfChannels || aChannelId < 0xff, EIADWrongParameter | EIADFaultIdentifier10 << KFaultIdentifierShift | aChannelId << KChannelNumberShift );
ASSERT_DFCTHREAD_INEXT();
// If channel open (!NULL) set as closed (NULL) or if channel open is pending.
ASSERT_RESET_ALWAYS( aChannelId < EIADSizeOfChannels, EIADWrongParameter | (TUint8)aChannelId << KChannelNumberShift | EIADFaultIdentifier21 << KFaultIdentifierShift );
if( iChannelTable[ aChannelId ].iChannel || iChannelTable[ aChannelId ].iWaitingChannel )
{
C_TRACE( ( _T( "DRouter::Close open->close 0x%x" ), aChannelId ) );
#if (NCP_COMMON_SOS_VERSION_SUPPORT >= SOS_VERSION_95)
if( iChannelTable[ aChannelId ].iType != ELoan )
{
#endif
iChannelTable[ aChannelId ].iChannel = NULL;
iChannelTable[ aChannelId ].iWaitingChannel = NULL;
iChannelTable[ aChannelId ].iType = ENormalOpen;
if( iConnectionStatus == EIADConnectionOk )
{
const TInt indicationCancelOrderSize( 2 );
TDes8& cancelOrder = AllocateBlock( indicationCancelOrderSize );
cancelOrder.Append( 0x00 );
cancelOrder.Append( 0x00 );
// Order internally, so no return values above ::Close { 0x00, 0x00 } 8-bit cancel indication.
TInt error( OrderIndication( cancelOrder, aChannelId, EFalse ) );
C_TRACE( ( _T( "DRouter::Close open->close indication order returned %d 0x%x" ), error, aChannelId ) );
OstTraceExt2( TRACE_NORMAL, DROUTER_CLOSE, "DRouter::Close open->close indication order returned;error=%d;aChannelId=%x", error, aChannelId );
ASSERT_RESET_ALWAYS( KErrNone == error, EIADIndicationOrderFailed | static_cast<TUint8>( ( aChannelId << KChannelNumberShift ) ) );
DeAllocateBlock( cancelOrder );
}
#if (NCP_COMMON_SOS_VERSION_SUPPORT >= SOS_VERSION_95)
}
else
{
C_TRACE( ( _T( "DRouter::Close open->close loaned channel 0x%x" ), aChannelId ) );
OstTrace1( TRACE_NORMAL, DROUTER_CLOSE_2, "DRouter::Close open->close loaned channel;aChannelId=%x", aChannelId );
iChannelTable[ aChannelId ].iType = ENormalOpen;
iChannelTable[ aChannelId ].iChannel = iChannelTable[ aChannelId ].iWaitingChannel;
iChannelTable[ aChannelId ].iWaitingChannel = NULL;
// TODO: When pipe functionality working, call PipeLoanReturned
}
#endif
}
C_TRACE( ( _T( "DRouter::Close 0x%x <-" ), aChannelId ) );
OstTrace0( TRACE_NORMAL, DROUTER_CLOSE_EXIT, "<DRouter::Close" );
}
// Do not call from ISR context!! Can only be called from Extension DFCThread context.
EXPORT_C void DRouter::DeAllocateBlock(
TDes8& aBlock
)
{
OstTrace1( TRACE_NORMAL, DROUTER_DEALLOCATEBLOCK_ENTRY, ">DRouter::DeAllocateBlock;aBlock=%x", ( TUint )&( aBlock ) );
C_TRACE( ( _T( "DRouter::DeAllocateBlock 0x%x ->" ), &aBlock ) );
ASSERT_CONTEXT_ALWAYS( NKern::EThread, 0 );
ASSERT_DFCTHREAD_INEXT();
// ISCE
// ASSERT_RESET_ALWAYS( iIST, EIADNullParameter | EIADFaultIdentifier18 << KFaultIdentifierShift );
// iIST->DeallocateBlock( aBlock );
MemApi::DeallocBlock( aBlock );
// ISCE
C_TRACE( ( _T( "DRouter::DeAllocateBlock 0x%x <-" ), &aBlock ) );
OstTrace0( TRACE_NORMAL, DROUTER_DEALLOCATEBLOCK_EXIT, "<DRouter::DeAllocateBlock" );
}
EXPORT_C TInt DRouter::GetConnectionStatus(
// None
)
{
OstTrace0( TRACE_NORMAL, DROUTER_GETCONNECTIONSTATUS_ENTRY, "<DRouter::GetConnectionStatus" );
C_TRACE( ( _T( "DRouter::GetConnectionStatus %d <->" ), iConnectionStatus ) );
ASSERT_DFCTHREAD_INEXT();
OstTrace1( TRACE_NORMAL, DROUTER_GETCONNECTIONSTATUS, "<DRouter::GetConnectionStatus;iConnectionStatus=%x", iConnectionStatus );
return iConnectionStatus;
}
EXPORT_C TInt DRouter::GetFlowControlStatus()
{
OstTrace0( TRACE_NORMAL, DROUTER_GETFLOWCONTROLSTATUS_ENTRY, "<>DRouter::GetFlowControlStatus" );
ASSERT_DFCTHREAD_INEXT();
return KErrNotSupported; // TODO
}
EXPORT_C TInt DRouter::GetMaxDataSize(
// None
)
{
OstTrace0( TRACE_NORMAL, DROUTER_GETMAXDATASIZE_ENTRY, ">DRouter::GetMaxDataSize" );
C_TRACE( ( _T( "DRouter::GetMaxDataSize ->" ) ) );
ASSERT_DFCTHREAD_INEXT();
TInt excludeSize( iMaxFrameSize - ( ISI_HEADER_SIZE + PNS_PIPE_DATA_OFFSET_DATA ) );
// Set the data to be divisible by four.
TInt allowedCount( excludeSize - ( excludeSize % 4 ) );
C_TRACE( ( _T( "DRouter::GetMaxDataSize %d <-" ), allowedCount ) );
OstTrace1( TRACE_NORMAL, DROUTER_GETMAXDATASIZE_EXIT, "<DRouter::GetMaxDataSize;allowedCount=%d", allowedCount );
return allowedCount;
}
// KErrNone, channelid with channel object open ok
// KErrNotSupported, resource not supported or in use causes name_add_req to fail
// KErrInUse, channelid opened by same channel object earlier
// KErrAlreadyExists, channel opened by some other channel object earlier
// In completechannelreq, set ~channel number as ~~channelnumber only if KErrNone or KErrInUse
EXPORT_C void DRouter::Open(
const TUint16 aChannel,
const TUint16 aRequest,
MIAD2ChannelApi* aCallback
)
{
OstTraceExt3( TRACE_NORMAL, DROUTER_OPEN_ENTRY, ">DRouter::Open;aChannel=%hx;aRequest=%hu;aCallback=%x", aChannel, aRequest, ( TUint )( aCallback ) );
C_TRACE( ( _T( "DRouter::Open 0x%x %d 0x%x ->" ), aChannel, aRequest, aCallback ) );
ASSERT_RESET_ALWAYS( aCallback, EIADNullParameter | EIADFaultIdentifier19 << KFaultIdentifierShift );
ASSERT_DFCTHREAD_INEXT();
ASSERT_RESET_ALWAYS( aChannel < EIADSizeOfChannels, EIADWrongParameter | (TUint8)aChannel << KChannelNumberShift | EIADFaultIdentifier26 << KFaultIdentifierShift );
if( iConnectionStatus == EIADConnectionOk )
{
// If not null channel is allready open.
if( iChannelTable[ aChannel ].iChannel ||
iChannelTable[ aChannel ].iWaitingChannel )
{
// If another channel tries to open already open channel.
TRACE_WARNING( iChannelTable[ aChannel ].iChannel == aCallback, (TUint8)aChannel << KChannelNumberShift );
// If same object calling KErrInUser if other but same channel KErrAlreadyExists
aCallback->CompleteChannelRequest( aRequest, ( iChannelTable[ aChannel ].iChannel == aCallback ? KErrInUse : KErrAlreadyExists ) );
}
// Null so channel is not open, set !null to mark opened channel.
else
{
C_TRACE( ( _T( "DRouter::Open channel 0x%x normal 0x%x" ), aChannel, aCallback ) );
OstTraceExt1( TRACE_NORMAL, DUP1_DROUTER_OPEN, "DRouter::Open normal;aChannel=%hx", aChannel );
iChannelTable[ aChannel ].iChannel = aCallback;
aCallback->CompleteChannelRequest( aRequest, KErrNone );
}
}
else
{
C_TRACE( ( _T( "DRouter::Open not ready" ) ) );
OstTrace0( TRACE_NORMAL, DUP2_DROUTER_OPEN, "DRouter::Open Not ready" );
ASSERT_RESET_ALWAYS( !iChannelTable[ aChannel ].iWaitingChannel, EIADWrongRequest | EIADFaultIdentifier15 << KFaultIdentifierShift );
iChannelTable[ aChannel ].iWaitingChannel = aCallback;
iChannelTable[ aChannel ].iType = ( ( aChannel == EIADNokiaDRM || aChannel == EIADNokiaSecurityDriver ) ? ENormalOpen : ENormalOpen );//??? TODO FIX THIS
}
C_TRACE( ( _T( "DRouter::Open 0x%x <-" ), aChannel ) );
OstTraceExt1( TRACE_NORMAL, DROUTER_OPEN_EXIT, "<DRouter::Open;aChannel=%hx", aChannel );
}
// With resource and media
EXPORT_C void DRouter::Open(
const TUint16 aChannel,
const TUint16 aRequest,
const TDesC8& aOpenInfo,
MIAD2ChannelApi* aCallback
)
{
OstTraceExt4( TRACE_NORMAL, DUP1_DROUTER_OPEN_ENTRY, ">DRouter::Open;aChannel=%hx;aRequest=%hu;aOpenInfo=%x;aCallback=%x", aChannel, aRequest, ( TUint )&( aOpenInfo ), ( TUint )( aCallback ) );
C_TRACE( ( _T( "DRouter::Open 0x%x %d 0x%x 0x%x ->" ), aChannel, aRequest, &aOpenInfo, aCallback ) );
// Some maniac from modem sw decided to remove name service in the last meters, hip-hip hurray inform which clients use resource from open to help debug!
TRACE_ASSERT_INFO( 0, (TUint8)aChannel<<KChannelNumberShift );
// Treat as normal open to enable the sending.
// NOTE! SUPPORT FOR RESOURCE OPEN DOES NOT EXISTS: CLIENT SHOULD NAME SERVICE BY ISI IF. SUPPORT FOR NAME SERVICE DOES NOT EXIST IN APE SW YET: NCP_COMMON_BRIDGE_FAMILY_NAME_SERVICE_SUPPORT
Open( aChannel, aRequest, aCallback );
C_TRACE( ( _T( "DRouter::Open 0x%x <-" ), aChannel ) );
OstTraceExt1( TRACE_NORMAL, DUP1_DROUTER_OPEN_EXIT, "<DRouter::Open;aChannel=%hx", aChannel );
}
#if (NCP_COMMON_SOS_VERSION_SUPPORT >= SOS_VERSION_95)
EXPORT_C TInt DRouter::Loan(
const TUint16 aChannel,
const TUint16 aRequest,
MIAD2ChannelApi* aCallback
)
{
C_TRACE( ( _T( "DRouter::Loan 0x%x %d 0x%x ->" ), aChannel, aRequest, aCallback ) );
OstTraceExt3( TRACE_NORMAL, DUP1_DROUTER_LOAN_ENTRY, ">DRouter::Loan;aChannel=%hx;aRequest=%hu;aCallback=%x", aChannel, aRequest, ( TUint )( aCallback ) );
ASSERT_RESET_ALWAYS( aCallback, EIADNullParameter | EIADFaultIdentifier19 << KFaultIdentifierShift );// TODO
ASSERT_RESET_ALWAYS( aChannel < EIADSizeOfChannels, EIADWrongParameter | EIADFaultIdentifier11 << KFaultIdentifierShift );// TODO
ASSERT_DFCTHREAD_INEXT();
ASSERT_RESET_ALWAYS( aChannel < EIADSizeOfChannels, aChannel );
TInt error( KErrNone );
#ifdef NCP_COMMON_BRIDGE_FAMILY_PIPE_SUPPORT
// Is connection lost.
error = ( iConnectionStatus == EIADConnectionNotOk ) ? KErrNotSupported : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
// Is loaning a resticted channel.
error = ( KErrNone == error && ( aChannel == EIADNokiaDRM || aChannel == EIADNokiaSecurityDriver ) ) ? KErrNotSupported : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
// Is loaning it self?
error = ( KErrNone == error && ( iChannelTable[ aChannel ].iChannel == aCallback ) ) ? KErrNotSupported : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
// Is loaning currently not open channel.
error = ( KErrNone == error && ( !iChannelTable[ aChannel ].iChannel ) ) ? KErrNotSupported : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
// Is loaning already loaned channel.
error = ( KErrNone == error && ( iChannelTable[ aChannel ].iType == ELoan ) ) ? KErrAlreadyExists : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
if( KErrNone == error )
{
// Who is loaning whose channel.
C_TRACE( ( _T( "DRouter::Loan loaning ch 0x%x from chObj 0x%x to chObj 0x%x setting previous as waiting" ), aChannel, iChannelTable[ aChannel ].iChannel, aCallback ) );
OstTraceExt3( TRACE_NORMAL, DUP1_DROUTER_LOAN, "DRouter::Loan loaning;aChannel=%hx;channelPtr=%hx;callbackPtr=%hx", aChannel, (TUint)iChannelTable[ aChannel ].iChannel, (TUint)aCallback );
iChannelTable[ aChannel ].iWaitingChannel = iChannelTable[ aChannel ].iChannel;// TEST WITH WAITING CHANNEL FIRST
iChannelTable[ aChannel ].iType = ELoan;
iChannelTable[ aChannel ].iChannel = aCallback;
iPipeHandler->PipeLoaned( aChannel, aCallback );
}
#endif
C_TRACE( ( _T( "DRouter::Loan 0x%x %d<-" ), aChannel, error ) );
OstTraceExt2( TRACE_NORMAL, DUP1_DROUTER_LOAN_EXIT, "<DRouter::Loan;aChannel=%hx;error=%d", aChannel, error );
return error;
}
EXPORT_C TInt DRouter::ReturnLoan(
const TUint16 aChannel,
const TUint16 aRequest,
MIAD2ChannelApi* aCallback
)
{
C_TRACE( ( _T( "DRouter::ReturnLoan 0x%x %d 0x%x ->" ), aChannel, aRequest, aCallback ) );
OstTraceExt3( TRACE_NORMAL, DUP1_DROUTER_RETURNLOAN_ENTRY, ">DRouter::ReturnLoan;aChannel=%hx;aRequest=%hu;aCallback=%x", aChannel, aRequest, ( TUint )( aCallback ) );
ASSERT_RESET_ALWAYS( aCallback, EIADNullParameter | EIADFaultIdentifier19 << KFaultIdentifierShift );// TODO
ASSERT_RESET_ALWAYS( aChannel < EIADSizeOfChannels, EIADWrongParameter | EIADFaultIdentifier11 << KFaultIdentifierShift );// TODO
ASSERT_DFCTHREAD_INEXT();
ASSERT_RESET_ALWAYS( aChannel < EIADSizeOfChannels, aChannel );
TInt error( KErrNone );
#ifdef NCP_COMMON_BRIDGE_FAMILY_PIPE_SUPPORT
// Is connection lost.
error = ( iConnectionStatus == EIADConnectionNotOk ) ? KErrNotSupported : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
// Is loaning a resticted channel.
error = ( KErrNone == error && ( aChannel == EIADNokiaDRM || aChannel == EIADNokiaSecurityDriver ) ) ? KErrNotSupported : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
// Is retuning someone elses loan?
error = ( KErrNone == error && ( iChannelTable[ aChannel ].iChannel != aCallback ) ) ? KErrNotSupported : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
// Is returning currently not open channel.
error = ( KErrNone == error && ( !iChannelTable[ aChannel ].iChannel ) ) ? KErrNotSupported : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
// Is returning a not loaned channel.
error = ( KErrNone == error && ( iChannelTable[ aChannel ].iType != ELoan ) ) ? KErrAlreadyExists : error;
TRACE_ASSERT_INFO( KErrNone == error, error );
if( KErrNone == error )
{
// Who is loaning whose channel.
C_TRACE( ( _T( "DRouter::ReturnLoan returning loan ch 0x%x to chObj 0x%x from chObj 0x%x setting previous as waiting" ), aChannel, iChannelTable[ aChannel ].iWaitingChannel, aCallback ) );
OstTraceExt3( TRACE_NORMAL, DUP1_DROUTER_RETURNLOAN, "DRouter::Loan loaning;aChannel=%hx;waitingchannelPtr=%hx;callbackPtr=%hx", aChannel, (TUint)iChannelTable[ aChannel ].iWaitingChannel, (TUint)aCallback );
iPipeHandler->PipeLoanReturned( aChannel, iChannelTable[ aChannel ].iWaitingChannel );
}
#endif
C_TRACE( ( _T( "DRouter::ReturnLoan 0x%x %d<-" ), aChannel, error ) );
OstTraceExt2( TRACE_NORMAL, DUP1_DROUTER_RETURNLOAN_EXIT, "<DRouter::ReturnLoan;aChannel=%hx;error=%d", aChannel, error );
return error;
}
#endif
EXPORT_C TInt DRouter::OrderIndication(
TDes8& anOrder,
const TUint16 aCh,
const TBool a32Bit
)
{
OstTraceExt3( TRACE_NORMAL, DROUTER_ORDERINDICATION_ENTRY, ">DRouter::OrderIndication;anOrder=%x;aCh=%hx;a32Bit=%d", ( TUint )&( anOrder ), aCh, a32Bit );
C_TRACE( ( _T( "DRouter::OrderIndication 0x%x 0x%x %d ->" ), &anOrder, aCh, a32Bit ) );
ASSERT_DFCTHREAD_INEXT();
TInt orderLength( anOrder.Length() );
TInt msgOk = ( 0 == orderLength ) ? KErrBadDescriptor : KErrNone;
TRACE_ASSERT_INFO( msgOk == KErrNone, (TUint8)aCh<<KChannelNumberShift );
// Should be divisible by two if not 32 bit.
msgOk = ( ( msgOk == KErrNone && ( !a32Bit && 0 != orderLength % 2 ) ) ? KErrBadDescriptor : msgOk );
TRACE_ASSERT_INFO( msgOk == KErrNone, (TUint8)aCh<<KChannelNumberShift );
// Should be divisible by five if 32 bit.
msgOk = ( ( msgOk == KErrNone && ( a32Bit && 0 != orderLength % 5 ) ) ? KErrBadDescriptor : msgOk );
TRACE_ASSERT_INFO( msgOk == KErrNone, (TUint8)aCh<<KChannelNumberShift );
msgOk = ( ( msgOk == KErrNone && ( orderLength > GetMaxDataSize() ) ) ? KErrUnderflow : msgOk );
TRACE_ASSERT_INFO( msgOk == KErrNone, (TUint8)aCh<<KChannelNumberShift );
if( KErrNone == msgOk )
{
TInt numOfOrders( 0 );
if( a32Bit == EFalse )
{
if( anOrder.Ptr()[ K8BitResourceOffset ] == KNoResource ) //Subscription remove
{
numOfOrders = 0x00;
}
else{
numOfOrders = ( anOrder.Length() / K8BitResourceId );
}
}
else
{
if( anOrder.Ptr()[ K32BitResourceOffsetByte4 ] == KNoResource ) //Subscription remove
{
numOfOrders = 0x00;
}
else{
numOfOrders = ( anOrder.Length() / K32BitResourceId );
}
}
TUint16 msgLength = ( ISI_HEADER_SIZE + SIZE_APE_COMMGR_SUBSCRIBE_REQ + ( SIZE_APE_COMMGR_SUBSCRIBE_SB * numOfOrders ) );
TDes8& desPtr = MemApi::AllocBlock( msgLength );
desPtr.SetLength( msgLength );
TUint8* ptr( const_cast<TUint8*>( desPtr.Ptr() ) );
ptr[ ISI_HEADER_OFFSET_MEDIA ] = PN_MEDIA_ROUTING_REQ;
SET_RECEIVER_DEV( ptr, PN_DEV_OWN );
SET_SENDER_DEV( ptr, PN_DEV_OWN );
ptr[ ISI_HEADER_OFFSET_RESOURCEID ] = PN_APE_COMMGR;
SET_LENGTH( ptr, ( desPtr.Length() - PN_HEADER_SIZE ) );
SET_RECEIVER_OBJ( ptr, PN_OBJ_ROUTER );
SET_SENDER_OBJ( ptr, aCh );
ptr[ ISI_HEADER_SIZE + APE_COMMGR_SUBSCRIBE_REQ_OFFSET_TRANSID ] = 0x00;
ptr[ ISI_HEADER_SIZE + APE_COMMGR_SUBSCRIBE_REQ_OFFSET_MESSAGEID ] = APE_COMMGR_SUBSCRIBE_REQ;
ptr[ ISI_HEADER_SIZE + APE_COMMGR_SUBSCRIBE_REQ_OFFSET_FILLERBYTE1 ] = numOfOrders;
ptr[ ISI_HEADER_SIZE + APE_COMMGR_SUBSCRIBE_REQ_OFFSET_SUBBLOCKCOUNT ] = 0x00;
TInt orderIndex( 0 );
//TODO automatically generated ape_commgrisi.h is totally wrong and not according to the specification
for( TInt subBlockOffset( ISI_HEADER_SIZE + SIZE_APE_COMMGR_SUBSCRIBE_REQ + APE_COMMGR_SUBSCRIBE_SB_OFFSET_SUBBLOCKID ); subBlockOffset < msgLength; subBlockOffset += SIZE_APE_COMMGR_SUBSCRIBE_SB )
{
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_SUBBLOCKID ] = APE_COMMGR_SUBSCRIBE_SB;
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_SUBBLOCKLENGTH ] = SIZE_APE_COMMGR_SUBSCRIBE_SB;
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_DEVICEID ] = PN_DEV_HOST;
if( a32Bit == EFalse )
{
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_RESOURCEID ] = ( anOrder.Ptr()[ orderIndex + KEventOffset8Bit ] );
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_FILLERBYTE1 ] = KFiller;
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_FILLERBYTE2 ] = KFiller;
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_FILLERBYTE3 ] = KFiller;
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_MESSAGEID ] = ( anOrder.Ptr()[ orderIndex + K8BitResourceOffset ] );
}
else
{
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_RESOURCEID ] = ( anOrder.Ptr()[ orderIndex + KEventOffset32Bit ] );
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_FILLERBYTE1 ] = ( anOrder.Ptr()[ orderIndex + K32BitResourceOffsetByte1 ] );
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_FILLERBYTE2 ] = ( anOrder.Ptr()[ orderIndex + K32BitResourceOffsetByte2 ] );
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_FILLERBYTE3 ] = ( anOrder.Ptr()[ orderIndex + K32BitResourceOffsetByte3 ]) ;
ptr[ subBlockOffset + APE_COMMGR_SUBSCRIBE_SB_OFFSET_MESSAGEID ] = ( anOrder.Ptr()[ orderIndex + K32BitResourceOffsetByte4 ] );
}
orderIndex = ( a32Bit == EFalse ) ? orderIndex + K8BitResourceId : orderIndex + K32BitResourceId;
}
iCommunicationManager->Receive( desPtr );
}
TRACE_ASSERT_INFO( msgOk == KErrNone, (TUint8)aCh<<KChannelNumberShift );
C_TRACE( ( _T( "DRouter::OrderIndication order:0x%x channel:0x%x 32bit:%d msgok:%d <-" ), &anOrder, aCh, a32Bit, msgOk ) );
OstTrace1( TRACE_NORMAL, DROUTER_ORDERINDICATION, "<DRouter::OrderIndication;msgOk=%x", msgOk );
return msgOk;
}
EXPORT_C TInt DRouter::SendMessage(
TDes8& aMessage,
const TUint16 aCh
)
{
OstTraceExt2( TRACE_NORMAL, DROUTER_SENDMESSAGE_ENTRY, "<DRouter::SendMessage;aMessage=%x;aCh=%hx", ( TUint )&( aMessage ), aCh );
OstTraceExt1( TRACE_NORMAL, DUP4_DROUTER_SENDMESSAGE, "DRouter::SendMessage;aCh=%hx", aCh );
C_TRACE( ( _T( "DRouter::SendMessage 0x%x 0x%x ->" ), &aMessage, aCh ) );
ASSERT_RESET_ALWAYS( iMaxFrameSize != 0x0000, EIADCmtConnectionNotInit );
TInt error( ValiDateIsiMessage( aMessage ) );
error = ( KErrNone == error && iConnectionStatus != EIADConnectionOk ) ? KErrNotReady : error;
if( KErrNone == error )
{
ASSERT_RESET_ALWAYS( aCh != KNotInitializedChannel, EIADWrongParameter | EIADFaultIdentifier12 << KFaultIdentifierShift );
C_TRACE( ( _T( "DRouter::SendMessage sending 0x%x" ), &aMessage ) );
OstTraceExt2( TRACE_NORMAL, DROUTER_SENDMESSAGE, "DRouter::SendMessage;error=%d;aCh=%hx", error, aCh );
SetSenderInfo( aMessage, aCh );
const TUint8* msgBlockPtr( aMessage.Ptr() );
// TODO: Simplify this
ASSERT_RESET_ALWAYS( aMessage.Length() > ISI_HEADER_OFFSET_RESOURCEID, EIADOverTheLimits | EIADFaultIdentifier2 << KFaultIdentifierShift );
if( msgBlockPtr[ ISI_HEADER_OFFSET_RESOURCEID ] == PN_PIPE && msgBlockPtr[ ISI_HEADER_OFFSET_SENDERDEVICE ] == THIS_DEVICE )
{
#ifdef NCP_COMMON_BRIDGE_FAMILY_PIPE_SUPPORT
// This shall send the message and deallocate it too.
error = iPipeHandler->SendPipeMessage( aMessage, aCh );
#else
error = KErrNotSupported;
#endif
if( error != KErrNone )
{
// Deallocate the block.
this->DeAllocateBlock( aMessage );
}
}
else
{
// To communicationmanager
if( ( msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVEROBJECT ] == PN_OBJ_EVENT_MULTICAST )
&& ( msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_OWN ) )
{
C_TRACE( ( _T( "DRouter::SendMessage sending to COMMUNICATIONMANAGER>" ) ) );
iCommunicationManager->Receive( aMessage );
C_TRACE( ( _T( "DRouter::SendMessage sending to COMMUNICATIONMANAGER<" ) ) );
}
else if( ( msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVEROBJECT ] == PN_OBJ_ROUTING_REQ )
&& ( msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_OWN ) )
{
C_TRACE( ( _T( "DRouter::SendMessage sending to NAMESERVICE>" ) ) );
iNameService->Receive( aMessage );
C_TRACE( ( _T( "DRouter::SendMessage sending to NAMESERVICE<" ) ) );
}
else if ( msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_OWN ||
msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_PC )
{
C_TRACE( ( _T( "DRouter::SendMessage to 0x%x" ), msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] ) );
this->MessageReceived( aMessage );
}
else // Normal way
{
// The IST shall deallocate the block when it's approriate to do.
C_TRACE( ( _T( "DRouter::SendMessage sending 0x%x" ), &aMessage ) );
OstTrace1( TRACE_NORMAL, DUP3_DROUTER_SENDMESSAGE, "DRouter::SendMessage;aMessage=%x", (TUint)&(aMessage ));
error = SendMsg( aMessage );
}
}//PIPE
}
else
{
C_TRACE( ( _T( "DRouter::SendMessage not sending due error 0x%x %d %d" ), &aMessage, aCh, error ) );
OstTraceExt2( TRACE_NORMAL, DUP1_DROUTER_SENDMESSAGE, "DRouter::SendMessage;aCh=%hx;error=%d", aCh, error );
// Deallocate the block.
TRACE_ASSERT_INFO( 0, (TUint8)aCh<<KChannelNumberShift | (TUint8)error );
if ( error != KErrNotReady ) // No deallocation if no connection
{
this->DeAllocateBlock( aMessage );
}
// TODO: who should NULL the block? IST or IAD
}
C_TRACE( ( _T( "DRouter::SendMessage 0x%x %d %d <-" ), &aMessage, aCh, error ) );
OstTraceExt2( TRACE_NORMAL, DROUTER_SENDMESSAGE_EXIT, "<DRouter::SendMessage;aCh=%hx;error=%d", aCh, error );
return error;
}
EXPORT_C TInt DRouter::SendIndication(
TDes8& aMessage,
const TUint16 aCh
)
{
OstTraceExt2( TRACE_NORMAL, DROUTER_SENDINDICATION_ENTRY, ">DRouter::SendIndication;aMessage=%x;aCh=%hx", ( TUint )&( aMessage ), aCh );
C_TRACE( ( _T( "DRouter::SendIndication 0x%x 0x%x ->" ), &aMessage, aCh ) );
TUint8* msgPtr = const_cast<TUint8*>( aMessage.Ptr() );
SET_RECEIVER_OBJ( msgPtr,PN_OBJ_EVENT_MULTICAST );
if( GET_RECEIVER_DEV( aMessage ) != PN_DEV_OWN )
{
SET_RECEIVER_DEV( msgPtr, OTHER_DEVICE_1 );
// Copy for receivers in this device -> fake event from modem
TDes8& tmpIndication = MemApi::AllocBlock( aMessage.Length() );
tmpIndication.SetLength( aMessage.Length() );
tmpIndication.Copy( aMessage );
TUint8* indicationPtr = const_cast<TUint8*>( tmpIndication.Ptr() );
SET_SENDER_DEV( indicationPtr, PN_DEV_HOST );
SET_RECEIVER_DEV( indicationPtr, PN_DEV_OWN );
indicationPtr[ ISI_HEADER_OFFSET_MEDIA ] = PN_MEDIA_SOS;
this->MessageReceived( tmpIndication );
}
TInt error( SendMessage( aMessage, aCh ) );
C_TRACE( ( _T( "DRouter::SendIndication 0x%x 0x%x %d <-" ), &aMessage, aCh, error ) );
OstTrace1( TRACE_NORMAL, DROUTER_SENDINDICATION_EXIT, "<DRouter::SendIndication;error=%d", error );
return error;
}
// From end
void DRouter::NotifyObjLayerConnStatDfc(
TAny* aPtr
)
{
OstTrace1( TRACE_NORMAL, DROUTER_NOTIFYOBJLAYERCONNSTATDFC_ENTRY, ">DRouter::NotifyObjLayerConnStatDfc;aPtr=%x", ( TUint )( aPtr ) );
C_TRACE( ( _T( "DRouter::NotifyObjLayerConnStatDfc ->" ) ) );
DRouter* self = reinterpret_cast<DRouter*>( aPtr );
self->NotifyObjLayerConnStat( self->iConnectionStatus );
C_TRACE( ( _T( "DRouter::NotifyObjLayerConnStatDfc to %d <-" ), self->iConnectionStatus ) );
OstTrace1( TRACE_NORMAL, DROUTER_NOTIFYOBJLAYERCONNSTATDFC_EXIT, "<DRouter::NotifyObjLayerConnStatDfc;self->iConnectionStatus=%x", self->iConnectionStatus );
}
void DRouter::NotifyObjLayerConnStat(
const TIADConnectionStatus aStatus
)
{
OstTrace1( TRACE_NORMAL, DROUTER_NOTIFYOBJLAYERCONNSTAT_ENTRY, ">DRouter::NotifyObjLayerConnStat;aStatus=%x", ( TUint )&( aStatus ) );
C_TRACE( ( _T( "DRouter::NotifyObjLayerConnStat %d ->" ), aStatus ) );
ASSERT_DFCTHREAD_INEXT();
for( TUint16 i( 0 ); i < EIADSizeOfChannels; ++i )
{
if( iChannelTable[ i ].iChannel )
{
C_TRACE( ( _T( "DRouter::NotifyObjLayerConnStat ch %d ptr 0x%x" ), i, iChannelTable[ i ].iChannel ) );
OstTraceExt2( TRACE_NORMAL, DUP1_DROUTER_NOTIFYOBJLAYERCONNSTAT, "DRouter::NotifyObjLayerConnStat;i=%hx;iChannelTable[ i ].iChannel=%x", i,( TUint ) ( iChannelTable[ i ].iChannel ) );
iChannelTable[ i ].iChannel->NotifyConnectionStatus( aStatus );
}
// TODO: If we need open to be waiting until connection status is ok, set waiting here.
}
C_TRACE( ( _T( "DRouter::NotifyObjLayerConnStat %d <-" ), aStatus ) );
OstTrace0( TRACE_NORMAL, DROUTER_NOTIFYOBJLAYERCONNSTAT_EXIT, "<DRouter::NotifyObjLayerConnStat" );
}
// Used internally in IAD.
// Can be called in 1..N thread contextes and returns immediately.
void DRouter::MessageReceived(
TDes8& aMsg
)
{
OstTrace1( TRACE_NORMAL, DROUTER_MESSAGERECEIVED_ENTRY, ">DRouter::MessageReceived;aMsg=%x", ( TUint )&( aMsg ) );
C_TRACE( ( _T( "DRouter::MessageReceived 0x%x ->" ), &aMsg ) );
// Let MaxLength to be the length of the allocated block. (IST (SSI&SISA) can work differently.
// SISA set length and maxlength according to ISI msg length, but SSI set length according to block length
// Block length in SSI at the moment always %4.
// Set the length of the descriptor to ISI message length + PN_HEADER_SIZE
// TODO : harmonize these IST differencies.
TInt len( GET_LENGTH( aMsg ) );
len += PN_HEADER_SIZE;
aMsg.SetLength( len );
iCommonRxQueue->Add( aMsg );
iCommonRxDfc->Enque();
C_TRACE( ( _T( "DRouter::MessageReceived 0x%x <-" ), &aMsg ) );
OstTrace0( TRACE_NORMAL, DROUTER_MESSAGERECEIVED_EXIT, "<DRouter::MessageReceived" );
}
//PRIVATES
void DRouter::HandleIsiMessage(
TDes8& aMsg
)
{
OstTrace1( TRACE_NORMAL, DROUTER_HANDLEISIMESSAGE_ENTRY, ">DRouter::HandleIsiMessage;aMsg=%x", ( TUint )&( aMsg ) );
C_TRACE( ( _T( "DRouter::HandleIsiMessage 0x%x ->" ), &aMsg ) );
TUint8* msg = const_cast<TUint8*>( aMsg.Ptr() );
// Message from MODEM to APE, or from APE to APE. If Media SOS -> come through link. If dev OWN -> from APE nameservice
if( ( msg[ ISI_HEADER_OFFSET_MEDIA ] == PN_MEDIA_SOS ) || ( msg[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_OWN ) )
{
const TUint16 rcvObjId( GET_RECEIVER_OBJ( aMsg ) );
C_TRACE( ( _T( "DRouter::HandleIsiMessage rcvObjId 0x%x" ), rcvObjId ) );
ASSERT_RESET_ALWAYS( rcvObjId < EIADSizeOfChannels, EIADWrongParameter | (TUint8)rcvObjId << KChannelNumberShift | EIADFaultIdentifier22 << KFaultIdentifierShift );
if( rcvObjId == PN_OBJ_ROUTER ) //TODO to channel table
{
C_TRACE( ( _T( "DRouter::HandleIsiMessage to NAMESERVICE>" ) ) );
iNameService->Receive( aMsg );
C_TRACE( ( _T( "DRouter::HandleIsiMessage to NAMESERVICE<" ) ) );
}
else if( rcvObjId == PN_OBJ_EVENT_MULTICAST )
{
C_TRACE( ( _T( "DRouter::HandleIsiMessage to COMMUNICATIONMANAGER>" ) ) );
iCommunicationManager->Receive( aMsg );
C_TRACE( ( _T( "DRouter::HandleIsiMessage to COMMUNICATIONMANAGER<" ) ) );
}
else
{
if( iChannelTable[ rcvObjId ].iChannel )
{
if( msg[ ISI_HEADER_OFFSET_RESOURCEID ] == PN_APE_COMMGR )
{
C_TRACE( ( _T( "DRouter::HandleIsiMessage to channel from COMMUNICATIONMANAGER deallocate" ) ) );
DeAllocateBlock( aMsg );
}
else
{
iChannelTable[ rcvObjId ].iChannel->ReceiveMsg( aMsg );
// DeAllocation done by the channel after writing to client's address space.
}
}
else
{
SendCommIsaEntityNotReachableResp( aMsg );
// Not going to anywhere deallocate.
DeAllocateBlock( aMsg );
}
}
}
else // PN_MEDIA_ROUTING_REQ, receivedevice != own, from nameservice, send to modem
{
C_TRACE( ( _T( "DRouter::CheckRouting going to MODEM" ) ) );
msg[ ISI_HEADER_OFFSET_MEDIA ] = PN_MEDIA_SOS; // link should set this
TInt sendError = SendMsg( aMsg );
C_TRACE( ( _T( "DRouter::CheckRouting sendError %d" ), sendError ) );
}
C_TRACE( ( _T( "DRouter::HandleIsiMessage 0x%x <-" ), &aMsg ) );
OstTrace0( TRACE_NORMAL, DROUTER_HANDLEISIMESSAGE_EXIT, "<DRouter::HandleIsiMessage" );
}
void DRouter::HandlePipeMessage(
TDes8& aMsg
)
{
OstTrace1( TRACE_NORMAL, DROUTER_HANDLEPIPEMESSAGE_ENTRY, ">DRouter::HandlePipeMessage;aMsg=%x", ( TUint )&( aMsg ) );
C_TRACE( ( _T( "DRouter::HandlePipeMessage 0x%x ->" ), &aMsg ) );
#ifdef NCP_COMMON_BRIDGE_FAMILY_PIPE_SUPPORT
const TUint16 rcvObjId( GET_RECEIVER_OBJ( aMsg ) );
C_TRACE( ( _T( "DRouter::HandlePipeMessage rcvObjId 0x%x" ), rcvObjId ) );
ASSERT_RESET_ALWAYS( rcvObjId < EIADSizeOfChannels, EIADWrongParameter | (TUint8)rcvObjId << KChannelNumberShift| EIADFaultIdentifier25 << KFaultIdentifierShift );
MIAD2ChannelApi* openChannel = iChannelTable[ rcvObjId ].iChannel;
if( openChannel )
{
// TODO: is it ok to give channel from here?
iPipeHandler->ReceivePipeMessage( aMsg, openChannel );
// DeAllocation done by the pipehandler or someone who it frwd's the message.
}
else
{
// COMM_ISA_ENTITY_NOT_REACHABLE_RESP NOT SEND TO PIPE MESSAGES
TRACE_ASSERT_INFO( 0, (TUint8)rcvObjId<<KChannelNumberShift );
// Not going to anywhere deallocate.
for( TInt i( 0 ); i < aMsg.Length(); i++ )
{
Kern::Printf( "%d 0x%x", i, aMsg.Ptr()[ i ] );
}
DeAllocateBlock( aMsg );
}
#endif
C_TRACE( ( _T( "DRouter::HandlePipeMessage 0x%x <-" ), &aMsg ) );
OstTrace0( TRACE_NORMAL, DROUTER_HANDLEPIPEMESSAGE_EXIT, "<DRouter::HandlePipeMessage" );
}
void DRouter::HandleMediaMessage(
TDes8& aMsg
)
{
OstTrace1( TRACE_NORMAL, DROUTER_HANDLEMEDIAMESSAGE_ENTRY, ">DRouter::HandleMediaMessage;aMsg=%x", ( TUint )&( aMsg ) );
C_TRACE( ( _T( "DRouter::HandleMediaMessage 0x%x ->" ), &aMsg ) );
TUint8 rcvObjId( 0x00);
ASSERT_RESET_ALWAYS( aMsg.Length() > ISI_HEADER_OFFSET_MEDIA, EIADOverTheLimits | EIADFaultIdentifier3 << KFaultIdentifierShift );
rcvObjId = GET_RECEIVER_OBJ( aMsg );
ASSERT_RESET_ALWAYS( 0, EIADUnkownMedia | ( rcvObjId << KChannelNumberShift ) );
// TODO: UNIQUE
ASSERT_RESET_ALWAYS( rcvObjId < EIADSizeOfChannels, EIADWrongParameter | (TUint8)rcvObjId << KChannelNumberShift | EIADFaultIdentifier3 << KFaultIdentifierShift );
if( iChannelTable[ rcvObjId ].iChannel )
{
iChannelTable[ rcvObjId ].iChannel->ReceiveMsg( aMsg );
// DeAllocation done by the channel after writing to client's address space.
}
else
{
SendCommIsaEntityNotReachableResp( aMsg );
// Not going to anywhere deallocate.
DeAllocateBlock( aMsg );
}
C_TRACE( ( _T( "DRouter::HandleMediaMessage 0x%x <-" ), &aMsg ) );
OstTrace0( TRACE_NORMAL, DROUTER_HANDLEMEDIAMESSAGE_EXIT, "<DRouter::HandleMediaMessage" );
}
// KErrBadDescriptor, if message length too small
// KErrUnderFlow, if message length too big.
// KErrCouldNotConnect, if receiver object is out of scope.
TInt DRouter::ValiDateIsiMessage(
TDes8& aMsg
)
{
OstTrace1( TRACE_NORMAL, DROUTER_VALIDATEISIMESSAGE_ENTRY, ">DRouter::ValiDateIsiMessage;aMsg=%x", ( TUint )&( aMsg ) );
C_TRACE( ( _T( "DRouter::ValiDateIsiMessage ->" ) ) );
const TUint16 descLength( aMsg.Length() );
TInt msgOk( KErrNone );
msgOk = ( ISI_HEADER_OFFSET_MESSAGEID >= descLength ) ? KErrBadDescriptor : msgOk;
TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk );
// Get ISI message length after known that the descriptor is big enough.
const TUint8* msgPtr( aMsg.Ptr() );
const TUint16 isiMsgLength( GET_LENGTH( msgPtr ) + PN_HEADER_SIZE );
// TODO: Do we need the underflow information or is it BadDescriptor as good? If so remove msgok == KErrNone...
// If the descriptor length is less than ISI message length.
msgOk = ( ( msgOk == KErrNone && isiMsgLength > descLength ) ? KErrUnderflow : msgOk );
TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk );
// If the ISI message length is bigger that the largest supported.
msgOk = ( ( msgOk == KErrNone && isiMsgLength > KIADMaxIsiMsgSize ) ? KErrUnderflow : msgOk );
TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk );
// If the ISI message length with PN_HEADER_SIZE is less or equal than ISI_HEADER_OFFSET_MESSAGEID.
msgOk = ( ( msgOk == KErrNone && isiMsgLength <= ISI_HEADER_OFFSET_MESSAGEID ) ? KErrUnderflow : msgOk );
TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk );
TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk );
TRACE_ASSERT_INFO( msgOk == KErrNone, isiMsgLength );
TRACE_ASSERT_INFO( msgOk == KErrNone, descLength );
// Check is receiver object valid if going from SOS<->SOS.
msgOk = ( ( msgOk == KErrNone && ( GET_RECEIVER_DEV( msgPtr ) == THIS_DEVICE && GET_RECEIVER_OBJ( msgPtr ) > EIADSizeOfChannels ) ) ? KErrCouldNotConnect : msgOk );
TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk );
// TODO: checking that receiver object is ok in SOS<->ISA cases.
C_TRACE( ( _T( "DRouter::ValiDateIsiMessage <- %d" ), msgOk ) );
OstTrace1( TRACE_NORMAL, DROUTER_VALIDATEISIMESSAGE_EXIT, "<DRouter::ValiDateIsiMessage;msgOk=%x", msgOk );
return msgOk;
}
void DRouter::CheckRouting(
DRouter& aTmp,
TDes8& aMsg
)
{
ASSERT_DFCTHREAD_INEXT();
const TUint8* msg( aMsg.Ptr() );
OstTrace1( TRACE_NORMAL, DROUTER_CHECKROUTING_ENTRY, ">DRouter::CheckRouting;aMsg=%x", ( TUint )( msg ) );
C_TRACE( ( _T( "DRouter::CheckRouting 0x%x 0x%x ->" ), msg, msg[ ISI_HEADER_OFFSET_RESOURCEID ] ) );
TRoutingRule route( ENotKnownMsg );
// Message to symbian side (media sos).
if( msg[ ISI_HEADER_OFFSET_MEDIA ] == PN_MEDIA_SOS )
{
if( ( msg[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == THIS_DEVICE ) || ( msg[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_OWN ) )
{
switch( msg[ ISI_HEADER_OFFSET_RECEIVEROBJECT ] )
{
// Indication NOTE! INDICATION HANDLING IS STILL LEGACY
case KIADEventSubscriptionObjId:
{
ASSERT_RESET_ALWAYS( msg[ ISI_HEADER_OFFSET_RESOURCEID ] != PN_PIPE, EIADWrongParameter | msg[ ISI_HEADER_OFFSET_RESOURCEID ] );
route = EIndicationMsg;
break;
}
// Any other message.
default:
{
// Indication message. Receiver object equals to event subscription obj id (0xfc).
route = ( msg[ ISI_HEADER_OFFSET_RESOURCEID ] == PN_PIPE ) ? EPipeMsg : EIsiMsg;
break;
}
}
}
else if ( msg[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_GLOBAL )// TODO: This (PN_DEV_GLOBAL) should be removed from Bridge when modem SW MCE Server is ok
{
#ifdef MODEM_MCE_DOES_NOT_WORK_AS_IT_SHOULD // TODO: To be removed depends on modem sw version MCE server
if ( aTmp.iBootDone )
{
#endif // MODEM_MCE_DOES_NOT_WORK_AS_IT_SHOULD
C_TRACE( ( _T( "DRouter::CheckRouting message to PN_DEV_GLOBAL -> EIndicationMsg" ) ) );
OstTrace0( TRACE_NORMAL, DROUTER_CHECKROUTING_PN_DEV_GLOBAL, "DRouter::CheckRouting PN_DEV_GLOBAL -> EIndicationMsg");
TUint8* ptr = const_cast<TUint8*>( msg );
SET_RECEIVER_DEV( ptr, THIS_DEVICE );
route = EIndicationMsg;
}
else if ( msg[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_PC )// TODO: This (PN_DEV_GLOBAL) should be removed from Bridge when modem SW MCE Server is ok
{
C_TRACE( ( _T( "DRouter::CheckRouting message to PN_DEV_PC ") ) );
route=EUsbPhonetMsg;
}
#ifdef MODEM_MCE_DOES_NOT_WORK_AS_IT_SHOULD
#include <mceisi.h>
else
{
Kern::Printf("0x%x 0x%x", msg[ ISI_HEADER_SIZE + MCE_MODEM_STATE_IND_OFFSET_MESSAGEID ], msg[ ISI_HEADER_SIZE + MCE_MODEM_STATE_IND_OFFSET_ACTION ] );
if ( ( msg[ ISI_HEADER_SIZE + MCE_MODEM_STATE_IND_OFFSET_MESSAGEID ] == MCE_MODEM_STATE_IND ) &&
( msg[ ISI_HEADER_SIZE + MCE_MODEM_STATE_IND_OFFSET_ACTION ] == MCE_READY ) )
{
//15:08:55.563 xti: MASTER_ASCII_PRINTF; string:M_HSI: TX common: 26ff60c2 06000014 00000004 ffffffff
Kern::Printf("Connection OK");
aTmp.InitConnectionOk();
}
else
{
// just ignore and wait for MCE_READY_IND DEALLOC????
Kern::Printf("Connection NOK");
}
}
}
#endif // MODEM_MCE_DOES_NOT_WORK_AS_IT_SHOULD
else
{
C_TRACE( ( _T( "DRouter::CheckRouting Unknown message" ) ) );
TRACE_ASSERT_ALWAYS;
Kern::Printf("Unknown message 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x", msg[ 0 ], msg[ 1 ], msg[ 2 ], msg[ 3 ], msg[ 4 ], msg[ 5 ], msg[ 6 ], msg[ 7 ], msg[ 8 ], msg[ 9 ] );
}
}
// APE to APE routing
else if( ( msg[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_OWN ) && ( msg[ ISI_HEADER_OFFSET_SENDERDEVICE ] == PN_DEV_OWN ) )
{
C_TRACE( ( _T( "DRouter::CheckRouting APE to APE routing" ) ) );
route = EIsiMsg;
}
// Message to other media than sos in symbian side.
else
{
route = EMediaMsg;
}
C_TRACE( ( _T( "DRouter::CheckRouting msg 0x%x route %d" ), msg, route ) );
OstTraceExt2( TRACE_NORMAL, DROUTER_CHECKROUTING_ROUTE, "DRouter::CheckRouting;aMsg=0x%x;route=%d", ( TUint )msg, route );
switch( route )
{
case EIsiMsg:
{
aTmp.HandleIsiMessage( aMsg );
break;
}
case EPipeMsg:
{
aTmp.HandlePipeMessage( aMsg );
break;
}
case EMediaMsg:
{
aTmp.HandleMediaMessage( aMsg );
break;
}
case EIndicationMsg:
{
// De-allocate, message is multicasted to subsribers as new
// message and the original is ready to be deallocated.
aTmp.DeAllocateBlock( aMsg );
break;
}
case EUsbPhonetMsg:
{
aTmp.iChannelTable[ EIscNokiaUsbPhonetLink ].iChannel->ReceiveMsg( aMsg );
break;
}
case ENotKnownMsg:
{
// Not going to anywhere deallocate.
aTmp.DeAllocateBlock( aMsg );
break;
}
default:
{
ASSERT_RESET_ALWAYS( 0, EIADWrongParameter | EIADFaultIdentifier16 << KFaultIdentifierShift );
break;
}
}
C_TRACE( ( _T( "DRouter::CheckRouting 0x%x<-" ), msg ) );
OstTrace1( TRACE_NORMAL, DROUTER_CHECKROUTING_EXIT, "<DRouter::CheckRouting;msg=0x%x", (TUint)msg );
}
void DRouter::CommonRxDfc(
TAny* aPtr // Pointer to this object.
)
{
OstTrace1( TRACE_NORMAL, DROUTER_COMMONRXDFC_ENTRY, ">DRouter::CommonRxDfc;aPtr=%x", ( TUint )( aPtr ) );
C_TRACE( ( _T( "DRouter::CommonRxDfc ->" ) ) );
DRouter& tmp = *reinterpret_cast<DRouter*>( aPtr );
ASSERT_DFCTHREAD_INEXT();
if( tmp.iCommonRxQueue->Count() > KErrNone )
{
TDes8& msg( tmp.iCommonRxQueue->Get() );
DATA_DUMP_TRACE( msg, EFalse );// TODO: this causes problems in legacy flowcontrol causing main rx to overflow!!
OstTraceData( TRACE_ISIMSG, DROUTER_COMMONRXDFC_DATA, "DRouter::CommonRxDfc RX: 0x%hx", msg.Ptr(), msg.Length() );
CheckRouting( tmp, msg );
// Check here too to avoid unnecessary dfc queuing.
if( tmp.iCommonRxQueue->Count() > KErrNone )
{
C_TRACE( ( _T( "DRouter::CommonRxDfc enque commonrxdfc" ) ) );
tmp.iCommonRxDfc->Enque();
}
}
C_TRACE( ( _T( "DRouter::CommonRxDfc <-" ) ) );
OstTrace0( TRACE_NORMAL, DROUTER_COMMONRXDFC_EXIT, "<DRouter::CommonRxDfc" );
}
void DRouter::SendCommIsaEntityNotReachableResp(
const TDesC8& aMsg
)
{
OstTrace1( TRACE_NORMAL, DROUTER_SENDCOMMISAENTITYNOTREACHABLERESP_ENTRY, ">DRouter::SendCommIsaEntityNotReachableResp;aMsg=%x", ( TUint )&( aMsg ) );
C_TRACE( ( _T( "DRouter::SendCommIsaEntityNotReachableResp 0x%x ->" ), &aMsg ) );
// Make channel opening request followinfg COMM specification: 000.026
// Length is sixteen bytes.
TUint8 length( 16 );
TDes8& tempPtr = AllocateBlock( ISI_HEADER_SIZE + SIZE_COMMON_MESSAGE_COMM_ISA_ENTITY_NOT_REACHABLE_RESP );
ASSERT_RESET_ALWAYS( &tempPtr, EIADMemoryAllocationFailure | EIADFaultIdentifier19 << KFaultIdentifierShift );
ASSERT_RESET_ALWAYS( ISI_HEADER_SIZE + SIZE_COMMON_MESSAGE_COMM_ISA_ENTITY_NOT_REACHABLE_RESP > ISI_HEADER_OFFSET_MESSAGEID, EIADOverTheLimits | EIADFaultIdentifier5 << KFaultIdentifierShift );
TUint8* ptr = const_cast<TUint8*>( tempPtr.Ptr() );
// We start to append from transaction id.
tempPtr.SetLength( ISI_HEADER_OFFSET_TRANSID );
// Get the header until messageid from prev. message.
// Just turn receiver and sender device and object vice versa.
const TUint8* msgTmpPtr( aMsg.Ptr() );
ptr[ ISI_HEADER_OFFSET_MEDIA ] = msgTmpPtr[ ISI_HEADER_OFFSET_MEDIA ];
SET_RECEIVER_DEV( ptr, GET_SENDER_DEV( aMsg ) );
SET_SENDER_DEV ( ptr, GET_RECEIVER_DEV( aMsg ) );
ptr[ ISI_HEADER_OFFSET_RESOURCEID ] = msgTmpPtr[ ISI_HEADER_OFFSET_RESOURCEID ];
SET_LENGTH( ptr, length - PN_HEADER_SIZE );
SET_RECEIVER_OBJ( ptr, GET_SENDER_OBJ( aMsg ) );
SET_SENDER_OBJ( ptr, GET_RECEIVER_OBJ( aMsg ) );
// Transactionid. Set to 0x01 since this is the first.
tempPtr.Append( msgTmpPtr[ ISI_HEADER_OFFSET_TRANSID ] );
// Message ID
tempPtr.Append( 0xF0 );
// Sub message ID.
tempPtr.Append( 0x14 );
// Not Delivered Message from original req.
tempPtr.Append( msgTmpPtr[ ISI_HEADER_OFFSET_MESSAGEID ] );
// Status - COMM_ISA_ENTITY_NOT_AVAILABLE
tempPtr.Append( 0x00 );
// Filler
tempPtr.Append( 0x00 );
// Filler
tempPtr.Append( 0x00 );
// Filler
tempPtr.Append( 0x00 );
if( msgTmpPtr[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_OWN )
{
MessageReceived( tempPtr );
}
else
{
SendMsg( tempPtr );
}
C_TRACE( ( _T( "DRouter::SendCommIsaEntityNotReachableResp 0x%x <-" ), &aMsg ) );
OstTrace0( TRACE_NORMAL, DROUTER_SENDCOMMISAENTITYNOTREACHABLERESP_EXIT, "<DRouter::SendCommIsaEntityNotReachableResp" );
}
void DRouter::InitCmtDfc(
TAny* aPtr
)
{
OstTrace1( TRACE_NORMAL, DROUTER_INITCMTDFC_ENTRY, ">DRouter::InitCmtDfc;aPtr=%x", ( TUint )( aPtr ) );
C_TRACE( ( _T( "DRouter::InitCmtDfc ->" ) ) );
DRouter& tmp = *reinterpret_cast<DRouter*>( aPtr );
if( !tmp.iBootDone )
{
#ifndef MODEM_MCE_DOES_NOT_WORK_AS_IT_SHOULD
tmp.InitConnectionOk();
#endif // MODEM_MCE_DOES_NOT_WORK_AS_IT_SHOULD
}
C_TRACE( ( _T( "DRouter::InitCmtDfc <-" ) ) );
OstTrace0( TRACE_NORMAL, DROUTER_INITCMTDFC_EXIT, "<DRouter::InitCmtDfc" );
}
void DRouter::InitConnectionOk()
{
C_TRACE( ( _T( "DRouter::InitConnectionOk ->" ) ) );
iMaxFrameSize = KIADMaxIsiMsgSize;
iConnectionStatus = EIADConnectionOk;
iBootDone = ETrue;
NotifyObjLayerConnStat( EIADConnectionOk );
// Initialize channels to NULL when channel is opened !NULL.
for( TInt i( 0 ); i < EIADSizeOfChannels; ++i )
{
ASSERT_RESET_ALWAYS( !iChannelTable[ i ].iChannel, EIADChannelOpenedBeforePhysicalLayerInit );
C_TRACE( ( _T( "DRouter::InitConnectionOk %d" ), i ) );
if( iChannelTable[ i ].iWaitingChannel )
{
switch( iChannelTable[ i ].iType )
{
case ENormalOpen:
{
C_TRACE( ( _T( "DRouter::InitConnectionOk booting ENormalOpen 0x%x" ), i ) );
MIAD2ChannelApi* tmpChannel = iChannelTable[ i ].iWaitingChannel;
iChannelTable[ i ].iChannel = tmpChannel;
iChannelTable[ i ].iWaitingChannel = NULL;
iChannelTable[ i ].iChannel->CompleteChannelRequest( EIADAsyncOpen, KErrNone );
break;
}
default:
{
ASSERT_RESET_ALWAYS( 0, -1111 );
break;
}
}
}
}
C_TRACE( ( _T( "DRouter::InitConnectionOk <-" ) ) );
}
// router and handler (pipe and indication)
TInt DRouter::SendMsg(
TDes8& aMsg
)
{
OstTrace1( TRACE_NORMAL, DROUTER_SENDMSG_ENTRY, ">DRouter::SendMsg;aMsg=%x", ( TUint )&( aMsg ) );
C_TRACE( ( _T( " DRouter::SendMsg 0x%x ->" ), &aMsg ) );
// The IST shall deallocate the block when it's approriate to do.
DATA_DUMP_TRACE( aMsg, ETrue );
OstTraceData( TRACE_ISIMSG, DROUTER_SENDMSG_DATA, "DRouter::SendMsg TX: %{hex8[]}", aMsg.Ptr(), aMsg.Length() );
//ISCE
//TInt error = iIST->SendMessage( aMsg, MIAD2ISTApi::EISTPriorityDefault );// priority 0
// TODO error codes and ids
TUint8 linkId = MapMediaToLinkId( aMsg.Ptr()[ ISI_HEADER_OFFSET_MEDIA ] );
ASSERT_RESET_ALWAYS( linkId < DRouter::EISIAmountOfMedias, -1000 );
MISIRouterLinkIf* link = iLinksArray[ linkId ];
ASSERT_RESET_ALWAYS( link, -999 );
TInt error( KErrNone );
if( link->TrxPresent() )
{
link->Send( aMsg );
}
else
{
TRACE_ASSERT_ALWAYS;
// Discard send block if connection lost
MemApi::DeallocBlock( aMsg );
error = KErrNotReady;
}
//ISCE
OstTraceExt2( TRACE_NORMAL, DROUTER_SENDMSG_EXIT, "<DRouter::SendMsg;aMsg=%x;error=%d", ( TUint )&( aMsg ), error );
return error;
}
//pipehandler
MIAD2ChannelApi* DRouter::GetChannel(
const TUint16 aChannel
)
{
OstTraceExt1( TRACE_NORMAL, DROUTER_GETCHANNEL_ENTRY, ">DRouter::GetChannel;aChannel=%hx", aChannel );
ASSERT_RESET_ALWAYS( aChannel < EIADSizeOfChannels, EIADWrongParameter | (TUint8)aChannel << KChannelNumberShift | EIADFaultIdentifier24 << KFaultIdentifierShift );
MIAD2ChannelApi* channelApi = iChannelTable[ aChannel ].iChannel;
OstTrace1( TRACE_NORMAL, DROUTER_GETCHANNEL_EXIT, "<DRouter::GetChannel;channelApi=%x", ( TUint )( channelApi ) );
return channelApi;
}
//pipehandler
void DRouter::SetSenderInfo(
TDes8& aMessage,
const TUint16 aCh
)
{
OstTraceExt2( TRACE_NORMAL, DROUTER_SETSENDERINFO_ENTRY, ">DRouter::SetSenderInfo;aMessage=%x;aCh=%hx", ( TUint )&( aMessage ), aCh );
C_TRACE( ( _T( "DRouter::SetSenderInfo 0x%x ->" ), &aMessage ) );
TUint8* msgBlockPtr = const_cast<TUint8*>( aMessage.Ptr() );
ASSERT_RESET_ALWAYS( aMessage.Length() > ISI_HEADER_OFFSET_MEDIA, EIADOverTheLimits | EIADFaultIdentifier10 << KFaultIdentifierShift );
if ( aCh == EIADNokiaUsbPhonetLink )
{
msgBlockPtr[ ISI_HEADER_OFFSET_MEDIA ] = PN_MEDIA_SOS;
C_TRACE( ( _T( "DRouter::SetSenderInfo 0x%x 0x%x 0x%x" ), aMessage.Ptr()[0], msgBlockPtr[ ISI_HEADER_OFFSET_MEDIA ], PN_MEDIA_SOS ) );
if( GET_RECEIVER_DEV( msgBlockPtr ) != PN_DEV_OWN)
{
C_TRACE( ( _T( "DRouter::SetSenderInfo to OTHER_DEVICE_1" ) ) );
SET_RECEIVER_DEV( msgBlockPtr, OTHER_DEVICE_1 );
}
}
else{
SET_SENDER_OBJ( msgBlockPtr, aCh );
C_TRACE( ( _T( "DRouter::SetSenderInfo receiver device %d" ), msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] ) );
if( msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_OWN || msgBlockPtr[ ISI_HEADER_OFFSET_RECEIVERDEVICE ] == PN_DEV_PC )
{
C_TRACE( ( _T( "DRouter::SetSenderInfo message to APE from APE" ) ) );
SET_SENDER_DEV( msgBlockPtr, PN_DEV_OWN );
}
else
{
C_TRACE( ( _T( "DRouter::SetSenderInfo message to MODEM from APE" ) ) );
msgBlockPtr[ ISI_HEADER_OFFSET_MEDIA ] = PN_MEDIA_SOS;
SET_RECEIVER_DEV( msgBlockPtr, OTHER_DEVICE_1 );
SET_SENDER_DEV( msgBlockPtr, THIS_DEVICE );
}
}
C_TRACE( ( _T( "DRouter::SetSenderInfo 0x%x <-" ), &aMessage ) );
OstTrace0( TRACE_NORMAL, DROUTER_SETSENDERINFO_EXIT, "<DRouter::SetSenderInfo" );
}
void DRouter::CheckSameThreadContext()
{
OstTrace0( TRACE_NORMAL, DROUTER_CHECKSAMETHREADCONTEXT_ENTRY, ">DRouter::CheckSameThreadContext" );
DObject* tempObj = reinterpret_cast<DObject*>( &Kern::CurrentThread() );
// If Null set current thread otherwise ignore
iThreadPtr = !iThreadPtr ? tempObj : iThreadPtr;
IAD_ASSERT_RESET_ALWAYS( ( iThreadPtr == tempObj ? ETrue : EFalse ) , -1112, "NOTSAMETHREAD" );
OstTrace0( TRACE_NORMAL, DROUTER_CHECKSAMETHREADCONTEXT_EXIT, "<DRouter::CheckSameThreadContext" );
}
// FM held, must not block and nor acquire locks.
void DRouter::NotifyTrxPresenceEnqueDfc(
TBool aPresent
)
{
C_TRACE( ( _T( "DRouter::NotifyTrxPresenceEnqueDfc %d ->" ), aPresent ) );
if( !iBootDone )
{
iInitCmtDfc->Enque();
}
else
{
iConnectionStatus = ( aPresent ) ? EIADConnectionOk : EIADConnectionNotOk;// TODO: atomicity check
iConnStatDfc->Enque();
}
C_TRACE( ( _T( "DRouter::NotifyTrxPresenceEnqueDfc %d <-" ), aPresent ) );
}
void DRouter::Receive(
TDes8& aMsg
)
{
C_TRACE( ( _T( "DRouter::Receive 0x%x ->" ), &aMsg ) );
MessageReceived( aMsg );
C_TRACE( ( _T( "DRouter::Receive 0x%x <-" ), &aMsg ) );
}
EXPORT_C void DRouter::DummyDoNothing()
{
ASSERT_RESET_ALWAYS( 0, -1001 );
}
EXPORT_C void DRouter::DummyDoNothing2()
{
ASSERT_RESET_ALWAYS( 0, -1000 );
}
TUint8 DRouter::MapMediaToLinkId(
const TUint8 aMedia
)
{
TUint8 linkdId( DRouter::EISIAmountOfMedias );
switch( aMedia )
{
case PN_MEDIA_SOS:
{
linkdId = EISIMediaHostSSI;
break;
}
// Not supported media
default:
{
ASSERT_RESET_ALWAYS( 0, -998 );
break;
}
}
return linkdId;
}
//From objectapi
EXPORT_C MISIObjectRouterIf* MISIObjectRouterIf::Connect( const TInt32 aUID, TUint8& aObjId, MISIRouterObjectIf* aCallback )
{
C_TRACE( ( _T( "MISIObjectRouterIf::Connect %d 0x%x 0x%x>" ), aUID, aObjId, aCallback ) );
//Connect( aUID, aObjId, aCallback );
if( aUID == KNameServiceUID )
{
C_TRACE( ( _T( "MISIObjectRouterIf was nameservice" ) ) );
DRouter::iThisPtr->iNameService = aCallback;
aObjId = PN_OBJ_ROUTING_REQ; // 0x00
}
else if( aUID == KCommunicationManagerUID )
{
C_TRACE( ( _T( "MISIObjectRouterIf was communicationmanager" ) ) );
DRouter::iThisPtr->iCommunicationManager = aCallback;
aObjId = PN_OBJ_EVENT_MULTICAST; // 0x20
}
else
{
C_TRACE( ( _T( "MISIObjectRouterIf unknown object api client" ) ) );
}
MISIObjectRouterIf* tmp = DRouter::iThisPtr;
C_TRACE( ( _T( "MISIObjectRouterIf::Connect %d 0x%x 0x%x<" ), aUID, aObjId, aCallback ) );
return tmp;
}
TInt DRouter::Send( TDes8& aMessage, const TUint8 aObjId )
{
C_TRACE( ( _T( "DRouter::Send objectapi 0x%x 0x%x>" ), &aMessage, aObjId ) );
if( aObjId == PN_OBJ_EVENT_MULTICAST ) //from communicationmanager
{
// Don't put to mainrxqueue
HandleIsiMessage( aMessage );
}
else
{
Receive( aMessage );
}
C_TRACE( ( _T( "DRouter::Send objectapi 0x%x 0x%x<" ), &aMessage, aObjId ) );
return KErrNone;
}
TDfcQue* DRouter::GetDfcThread(
const TISIDfcQThreadType // aType
)
{
C_TRACE( ( _T( "DRouter::GetDfcThread<>" ) ) );
Kern::Printf( "IADRouter::GetDfcThread" );
return DIsaAccessExtension::GetDFCThread( EIADExtensionDfcQueue );
//ASSERT_RESET_ALWAYS( 0, -1003 );
//return NULL;
}
void DRouter::FreeDfcThread( TDfcQue* aThread )
{
C_TRACE( ( _T( "DRouter::FreeDfcThread 0x%x>" ), aThread ) );
Kern::Printf( "IADRouter::FreeDfcThread" );
ASSERT_RESET_ALWAYS( 0, -1002 );
}
// End of file.
| [
"dalarub@localhost",
"[email protected]"
] | [
[
[
1,
28
],
[
30,
36
],
[
38,
42
],
[
44,
46
],
[
50,
50
],
[
62,
100
],
[
102,
131
],
[
133,
135
],
[
137,
140
],
[
142,
160
],
[
162,
221
],
[
223,
244
],
[
246,
258
],
[
272,
280
],
[
282,
378
],
[
383,
390
],
[
392,
394
],
[
396,
409
],
[
412,
414
],
[
416,
432
],
[
434,
479
],
[
481,
533
],
[
596,
596
],
[
600,
626
],
[
628,
629
],
[
632,
640
],
[
669,
676
],
[
681,
698
],
[
712,
789
],
[
793,
793
],
[
831,
831
],
[
833,
833
],
[
840,
852
],
[
854,
885
],
[
887,
889
],
[
892,
965
],
[
967,
969
],
[
971,
997
],
[
1003,
1029
],
[
1036,
1066
],
[
1068,
1068
],
[
1070,
1097
],
[
1099,
1159
],
[
1168,
1187
],
[
1189,
1285
],
[
1287,
1288
],
[
1303,
1303
],
[
1306,
1306
],
[
1308,
1308
],
[
1310,
1311
],
[
1313,
1314
],
[
1316,
1317
],
[
1319,
1401
],
[
1461,
1462
]
],
[
[
29,
29
],
[
37,
37
],
[
43,
43
],
[
47,
49
],
[
51,
61
],
[
101,
101
],
[
132,
132
],
[
136,
136
],
[
141,
141
],
[
161,
161
],
[
222,
222
],
[
245,
245
],
[
259,
271
],
[
281,
281
],
[
379,
382
],
[
391,
391
],
[
395,
395
],
[
410,
411
],
[
415,
415
],
[
433,
433
],
[
480,
480
],
[
534,
595
],
[
597,
599
],
[
627,
627
],
[
630,
631
],
[
641,
668
],
[
677,
680
],
[
699,
711
],
[
790,
792
],
[
794,
830
],
[
832,
832
],
[
834,
839
],
[
853,
853
],
[
886,
886
],
[
890,
891
],
[
966,
966
],
[
970,
970
],
[
998,
1002
],
[
1030,
1035
],
[
1067,
1067
],
[
1069,
1069
],
[
1098,
1098
],
[
1160,
1167
],
[
1188,
1188
],
[
1286,
1286
],
[
1289,
1302
],
[
1304,
1305
],
[
1307,
1307
],
[
1309,
1309
],
[
1312,
1312
],
[
1315,
1315
],
[
1318,
1318
],
[
1402,
1460
]
]
] |
a0982c5b83cfb0e4c068699609de5934ebdcebd7 | fb4cf44e2c146b26ddde6350180cc420611fe17a | /SDK/CvPlayer.h | b7a75bf55e16faab7557759c227aa435c0b7dbc4 | [] | no_license | dharkness/civ4bullai | 93e0685ef53e404ac4ffa5c1aecf4edaf61acd61 | e56c8a4f1172e2d2b15eb87eaa78adb9d357fae6 | refs/heads/master | 2022-09-15T23:31:55.030351 | 2010-11-13T07:23:13 | 2010-11-13T07:23:13 | 267,723,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88,143 | h | #pragma once
// player.h
#ifndef CIV4_PLAYER_H
#define CIV4_PLAYER_H
#include "CvCityAI.h"
#include "CvUnitAI.h"
#include "CvSelectionGroupAI.h"
#include "CvPlotGroup.h"
#include "LinkedList.h"
#include "CvTalkingHeadMessage.h"
class CvDiploParameters;
class CvPopupInfo;
class CvEventTriggerInfo;
typedef std::list<CvTalkingHeadMessage> CvMessageQueue;
typedef std::list<CvPopupInfo*> CvPopupQueue;
typedef std::list<CvDiploParameters*> CvDiploQueue;
typedef stdext::hash_map<int, int> CvTurnScoreMap;
typedef stdext::hash_map<EventTypes, EventTriggeredData> CvEventMap;
typedef std::vector< std::pair<UnitCombatTypes, PromotionTypes> > UnitCombatPromotionArray;
typedef std::vector< std::pair<UnitClassTypes, PromotionTypes> > UnitClassPromotionArray;
typedef std::vector< std::pair<CivilizationTypes, LeaderHeadTypes> > CivLeaderArray;
class CvPlayer
{
public:
CvPlayer();
virtual ~CvPlayer();
DllExport void init(PlayerTypes eID);
DllExport void setupGraphical();
DllExport void reset(PlayerTypes eID = NO_PLAYER, bool bConstructorCall = false);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 12/30/08 jdog5000 */
/* */
/* */
/************************************************************************************************/
void initInGame(PlayerTypes eID);
void resetPlotAndCityData( );
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
/************************************************************************************************/
/* CHANGE_PLAYER 12/30/08 jdog5000 */
/* */
/* */
/************************************************************************************************/
void logMsg(char* format, ... );
void clearTraitBonuses();
void addTraitBonuses();
void changePersonalityType();
void resetCivTypeEffects();
void changeLeader( LeaderHeadTypes eNewLeader );
void changeCiv( CivilizationTypes eNewCiv );
void setIsHuman( bool bNewValue );
/************************************************************************************************/
/* CHANGE_PLAYER END */
/************************************************************************************************/
protected:
void uninit();
public:
void initFreeState();
void initFreeUnits();
void addFreeUnitAI(UnitAITypes eUnitAI, int iCount);
void addFreeUnit(UnitTypes eUnit, UnitAITypes eUnitAI = NO_UNITAI);
int startingPlotRange() const; // Exposed to Python
bool startingPlotWithinRange(CvPlot* pPlot, PlayerTypes ePlayer, int iRange, int iPass) const; // Exposed to Python
int startingPlotDistanceFactor(CvPlot* pPlot, PlayerTypes ePlayer, int iRange) const;
int findStartingArea() const;
CvPlot* findStartingPlot(bool bRandomize = false); // Exposed to Python
CvPlotGroup* initPlotGroup(CvPlot* pPlot);
CvCity* initCity(int iX, int iY, bool bBumpUnits, bool bUpdatePlotGroups); // Exposed to Python
void acquireCity(CvCity* pCity, bool bConquest, bool bTrade, bool bUpdatePlotGroups); // Exposed to Python
void killCities(); // Exposed to Python
CvWString getNewCityName() const; // Exposed to Python
void getCivilizationCityName(CvWString& szBuffer, CivilizationTypes eCivilization) const;
bool isCityNameValid(CvWString& szName, bool bTestDestroyed = true) const;
CvUnit* initUnit(UnitTypes eUnit, int iX, int iY, UnitAITypes eUnitAI = NO_UNITAI, DirectionTypes eFacingDirection = NO_DIRECTION); // Exposed to Python
void disbandUnit(bool bAnnounce); // Exposed to Python
void killUnits(); // Exposed to Python
CvSelectionGroup* cycleSelectionGroups(CvUnit* pUnit, bool bForward, bool bWorkers, bool* pbWrap);
bool hasTrait(TraitTypes eTrait) const; // Exposed to Python
/************************************************************************************************/
/* AI_AUTO_PLAY_MOD 07/09/08 jdog5000 */
/* */
/* */
/************************************************************************************************/
void setHumanDisabled( bool newVal );
bool isHumanDisabled( );
/************************************************************************************************/
/* AI_AUTO_PLAY_MOD END */
/************************************************************************************************/
DllExport bool isHuman() const; // Exposed to Python
DllExport void updateHuman();
DllExport bool isBarbarian() const; // Exposed to Python
DllExport const wchar* getName(uint uiForm = 0) const; // Exposed to Python
DllExport const wchar* getNameKey() const; // Exposed to Python
DllExport const wchar* getCivilizationDescription(uint uiForm = 0) const; // Exposed to Python
DllExport const wchar* getCivilizationDescriptionKey() const; // Exposed to Python
DllExport const wchar* getCivilizationShortDescription(uint uiForm = 0) const; // Exposed to Python
DllExport const wchar* getCivilizationShortDescriptionKey() const; // Exposed to Python
DllExport const wchar* getCivilizationAdjective(uint uiForm = 0) const; // Exposed to Python
DllExport const wchar* getCivilizationAdjectiveKey() const; // Exposed to Python
DllExport CvWString getFlagDecal() const; // Exposed to Python
DllExport bool isWhiteFlag() const; // Exposed to Python
DllExport const wchar* getStateReligionName(uint uiForm = 0) const; // Exposed to Python
DllExport const wchar* getStateReligionKey() const; // Exposed to Python
DllExport const CvWString getBestAttackUnitName(uint uiForm = 0) const; // Exposed to Python
DllExport const CvWString getWorstEnemyName() const; // Exposed to Python
const wchar* getBestAttackUnitKey() const; // Exposed to Python
DllExport ArtStyleTypes getArtStyleType() const; // Exposed to Python
DllExport const TCHAR* getUnitButton(UnitTypes eUnit) const; // Exposed to Python
void doTurn();
void doTurnUnits();
void verifyCivics();
void updatePlotGroups();
void updateYield();
void updateMaintenance();
void updatePowerHealth();
/********************************************************************************/
/* New Civic AI 02.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited START
void updateExtraBuildingHappiness(bool bLimited = false);
void updateExtraBuildingHealth(bool bLimited = false);
void updateFeatureHappiness(bool bLimited = false);
void updateReligionHappiness(bool bLimited = false);
//Fuyu bLimited END
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
void updateExtraSpecialistYield();
void updateCommerce(CommerceTypes eCommerce);
void updateCommerce();
void updateBuildingCommerce();
void updateReligionCommerce();
void updateCorporation();
void updateCityPlotYield();
void updateCitySight(bool bIncrement, bool bUpdatePlotGroups);
void updateTradeRoutes();
void updatePlunder(int iChange, bool bUpdatePlotGroups);
void updateTimers();
DllExport bool hasReadyUnit(bool bAny = false) const;
DllExport bool hasAutoUnit() const;
DllExport bool hasBusyUnit() const;
/************************************************************************************************/
/* UNOFFICIAL_PATCH 12/07/09 EmperorFool */
/* */
/* Bugfix */
/************************************************************************************************/
// Free Tech Popup Fix
bool isChoosingFreeTech() const;
void setChoosingFreeTech(bool bValue);
/************************************************************************************************/
/* UNOFFICIAL_PATCH END */
/************************************************************************************************/
DllExport void chooseTech(int iDiscover = 0, CvWString szText = "", bool bFront = false); // Exposed to Python
int calculateScore(bool bFinal = false, bool bVictory = false);
int findBestFoundValue() const; // Exposed to Python
int upgradeAllPrice(UnitTypes eUpgradeUnit, UnitTypes eFromUnit);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 11/14/09 jdog5000 */
/* */
/* General AI */
/************************************************************************************************/
int countReligionSpreadUnits(CvArea* pArea, ReligionTypes eReligion, bool bIncludeTraining = false) const; // Exposed to Python
int countCorporationSpreadUnits(CvArea* pArea, CorporationTypes eCorporation, bool bIncludeTraining = false) const; // Exposed to Python
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
int countNumCoastalCities() const; // Exposed to Python
int countNumCoastalCitiesByArea(CvArea* pArea) const; // Exposed to Python
int countTotalCulture() const; // Exposed to Python
int countOwnedBonuses(BonusTypes eBonus) const; // Exposed to Python
int countUnimprovedBonuses(CvArea* pArea, CvPlot* pFromPlot = NULL) const; // Exposed to Python
int countCityFeatures(FeatureTypes eFeature) const; // Exposed to Python
int countNumBuildings(BuildingTypes eBuilding) const; // Exposed to Python
DllExport int countNumCitiesConnectedToCapital() const; // Exposed to Python
int countPotentialForeignTradeCities(CvArea* pIgnoreArea = NULL) const; // Exposed to Python
int countPotentialForeignTradeCitiesConnected() const; // Exposed to Python
DllExport bool canContact(PlayerTypes ePlayer) const; // Exposed to Python
void contact(PlayerTypes ePlayer); // Exposed to Python
DllExport void handleDiploEvent(DiploEventTypes eDiploEvent, PlayerTypes ePlayer, int iData1, int iData2);
bool canTradeWith(PlayerTypes eWhoTo) const; // Exposed to Python
bool canReceiveTradeCity() const;
DllExport bool canTradeItem(PlayerTypes eWhoTo, TradeData item, bool bTestDenial = false) const; // Exposed to Python
DllExport DenialTypes getTradeDenial(PlayerTypes eWhoTo, TradeData item) const; // Exposed to Python
bool canTradeNetworkWith(PlayerTypes ePlayer) const; // Exposed to Python
int getNumAvailableBonuses(BonusTypes eBonus) const; // Exposed to Python
DllExport int getNumTradeableBonuses(BonusTypes eBonus) const; // Exposed to Python
int getNumTradeBonusImports(PlayerTypes ePlayer) const; // Exposed to Python
bool hasBonus(BonusTypes eBonus) const; // Exposed to Python
bool isTradingWithTeam(TeamTypes eTeam, bool bIncludeCancelable) const;
bool canStopTradingWithTeam(TeamTypes eTeam, bool bContinueNotTrading = false) const; // Exposed to Python
void stopTradingWithTeam(TeamTypes eTeam); // Exposed to Python
void killAllDeals(); // Exposed to Python
void findNewCapital(); // Exposed to Python
DllExport int getNumGovernmentCenters() const; // Exposed to Python
DllExport bool canRaze(CvCity* pCity) const; // Exposed to Python
void raze(CvCity* pCity); // Exposed to Python
void disband(CvCity* pCity); // Exposed to Python
bool canReceiveGoody(CvPlot* pPlot, GoodyTypes eGoody, CvUnit* pUnit) const; // Exposed to Python
void receiveGoody(CvPlot* pPlot, GoodyTypes eGoody, CvUnit* pUnit); // Exposed to Python
void doGoody(CvPlot* pPlot, CvUnit* pUnit); // Exposed to Python
DllExport bool canFound(int iX, int iY, bool bTestVisible = false) const; // Exposed to Python
void found(int iX, int iY); // Exposed to Python
DllExport bool canTrain(UnitTypes eUnit, bool bContinue = false, bool bTestVisible = false, bool bIgnoreCost = false) const; // Exposed to Python
bool canConstruct(BuildingTypes eBuilding, bool bContinue = false, bool bTestVisible = false, bool bIgnoreCost = false) const; // Exposed to Python
bool canCreate(ProjectTypes eProject, bool bContinue = false, bool bTestVisible = false) const; // Exposed to Python
bool canMaintain(ProcessTypes eProcess, bool bContinue = false) const; // Exposed to Python
bool isProductionMaxedUnitClass(UnitClassTypes eUnitClass) const; // Exposed to Python
bool isProductionMaxedBuildingClass(BuildingClassTypes eBuildingClass, bool bAcquireCity = false) const; // Exposed to Python
bool isProductionMaxedProject(ProjectTypes eProject) const; // Exposed to Python
DllExport int getProductionNeeded(UnitTypes eUnit) const; // Exposed to Python
DllExport int getProductionNeeded(BuildingTypes eBuilding) const; // Exposed to Python
DllExport int getProductionNeeded(ProjectTypes eProject) const; // Exposed to Python
int getProductionModifier(UnitTypes eUnit) const;
int getProductionModifier(BuildingTypes eBuilding) const;
int getProductionModifier(ProjectTypes eProject) const;
DllExport int getBuildingClassPrereqBuilding(BuildingTypes eBuilding, BuildingClassTypes ePrereqBuildingClass, int iExtra = 0) const; // Exposed to Python
void removeBuildingClass(BuildingClassTypes eBuildingClass); // Exposed to Python
void processBuilding(BuildingTypes eBuilding, int iChange, CvArea* pArea);
int getBuildCost(const CvPlot* pPlot, BuildTypes eBuild) const;
bool canBuild(const CvPlot* pPlot, BuildTypes eBuild, bool bTestEra = false, bool bTestVisible = false) const; // Exposed to Python
RouteTypes getBestRoute(CvPlot* pPlot = NULL) const; // Exposed to Python
int getImprovementUpgradeRate() const; // Exposed to Python
int calculateTotalYield(YieldTypes eYield) const; // Exposed to Python
int calculateTotalExports(YieldTypes eYield) const; // Exposed to Python
int calculateTotalImports(YieldTypes eYield) const; // Exposed to Python
int calculateTotalCityHappiness() const; // Exposed to Python
int calculateTotalCityUnhappiness() const; // Exposed to Python
int calculateTotalCityHealthiness() const; // Exposed to Python
int calculateTotalCityUnhealthiness() const; // Exposed to Python
int calculateUnitCost(int& iFreeUnits, int& iFreeMilitaryUnits, int& iPaidUnits, int& iPaidMilitaryUnits, int& iBaseUnitCost, int& iMilitaryCost, int& iExtraCost) const;
int calculateUnitCost() const; // Exposed to Python
int calculateUnitSupply(int& iPaidUnits, int& iBaseSupplyCost) const; // Exposed to Python
int calculateUnitSupply() const; // Exposed to Python
int calculatePreInflatedCosts() const; // Exposed to Python
int calculateInflationRate() const; // Exposed to Python
int calculateInflatedCosts() const; // Exposed to Python
int calculateBaseNetGold() const;
int calculateBaseNetResearch(TechTypes eTech = NO_TECH) const; // Exposed to Python
int calculateResearchModifier(TechTypes eTech) const; // Exposed to Python
int calculateGoldRate() const; // Exposed to Python
int calculateResearchRate(TechTypes eTech = NO_TECH) const; // Exposed to Python
int calculateTotalCommerce() const;
bool isResearch() const; // Exposed to Python
DllExport bool canEverResearch(TechTypes eTech) const; // Exposed to Python
DllExport bool canResearch(TechTypes eTech, bool bTrade = false) const; // Exposed to Python
DllExport TechTypes getCurrentResearch() const; // Exposed to Python
bool isCurrentResearchRepeat() const; // Exposed to Python
bool isNoResearchAvailable() const; // Exposed to Python
DllExport int getResearchTurnsLeft(TechTypes eTech, bool bOverflow) const; // Exposed to Python
bool isCivic(CivicTypes eCivic) const; // Exposed to Python
bool canDoCivics(CivicTypes eCivic) const; // Exposed to Python
DllExport bool canRevolution(CivicTypes* paeNewCivics) const; // Exposed to Python
DllExport void revolution(CivicTypes* paeNewCivics, bool bForce = false); // Exposed to Python
int getCivicPercentAnger(CivicTypes eCivic, bool bIgnore = false) const; // Exposed to Python
bool canDoReligion(ReligionTypes eReligion) const; // Exposed to Python
bool canChangeReligion() const; // Exposed to Python
DllExport bool canConvert(ReligionTypes eReligion) const; // Exposed to Python
DllExport void convert(ReligionTypes eReligion); // Exposed to Python
bool hasHolyCity(ReligionTypes eReligion) const; // Exposed to Python
int countHolyCities() const; // Exposed to Python
DllExport void foundReligion(ReligionTypes eReligion, ReligionTypes eSlotReligion, bool bAward); // Exposed to Python
bool hasHeadquarters(CorporationTypes eCorporation) const; // Exposed to Python
int countHeadquarters() const; // Exposed to Python
int countCorporations(CorporationTypes eCorporation) const; // Exposed to Python
void foundCorporation(CorporationTypes eCorporation); // Exposed to Python
DllExport int getCivicAnarchyLength(CivicTypes* paeNewCivics) const; // Exposed to Python
DllExport int getReligionAnarchyLength() const; // Exposed to Python
DllExport int unitsRequiredForGoldenAge() const; // Exposed to Python
int unitsGoldenAgeCapable() const; // Exposed to Python
DllExport int unitsGoldenAgeReady() const; // Exposed to Python
void killGoldenAgeUnits(CvUnit* pUnitAlive);
DllExport int greatPeopleThreshold(bool bMilitary = false) const; // Exposed to Python
int specialistYield(SpecialistTypes eSpecialist, YieldTypes eYield) const; // Exposed to Python
int specialistCommerce(SpecialistTypes eSpecialist, CommerceTypes eCommerce) const; // Exposed to Python
DllExport CvPlot* getStartingPlot() const; // Exposed to Python
DllExport void setStartingPlot(CvPlot* pNewValue, bool bUpdateStartDist); // Exposed to Python
DllExport int getTotalPopulation() const; // Exposed to Python
int getAveragePopulation() const; // Exposed to Python
void changeTotalPopulation(int iChange);
long getRealPopulation() const; // Exposed to Python
int getReligionPopulation(ReligionTypes eReligion) const;
int getTotalLand() const; // Exposed to Python
void changeTotalLand(int iChange);
int getTotalLandScored() const; // Exposed to Python
void changeTotalLandScored(int iChange);
DllExport int getGold() const; // Exposed to Python
DllExport void setGold(int iNewValue); // Exposed to Python
DllExport void changeGold(int iChange); // Exposed to Python
int getGoldPerTurn() const; // Exposed to Python
DllExport int getAdvancedStartPoints() const; // Exposed to Python
DllExport void setAdvancedStartPoints(int iNewValue); // Exposed to Python
DllExport void changeAdvancedStartPoints(int iChange); // Exposed to Python
int getEspionageSpending(TeamTypes eAgainstTeam) const; // Exposed to Python
DllExport bool canDoEspionageMission(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, const CvPlot* pPlot, int iExtraData, const CvUnit* pUnit) const; // Exposed to Python
int getEspionageMissionBaseCost(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, const CvPlot* pPlot, int iExtraData, const CvUnit* pSpyUnit) const;
int getEspionageMissionCost(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, const CvPlot* pPlot = NULL, int iExtraData = -1, const CvUnit* pSpyUnit = NULL) const; // Exposed to Python
int getEspionageMissionCostModifier(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, const CvPlot* pPlot = NULL, int iExtraData = -1, const CvUnit* pSpyUnit = NULL) const;
bool doEspionageMission(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, CvPlot* pPlot, int iExtraData, CvUnit* pUnit);
int getEspionageSpendingWeightAgainstTeam(TeamTypes eIndex) const; // Exposed to Python
void setEspionageSpendingWeightAgainstTeam(TeamTypes eIndex, int iValue); // Exposed to Python
DllExport void changeEspionageSpendingWeightAgainstTeam(TeamTypes eIndex, int iChange); // Exposed to Python
bool canStealTech(PlayerTypes eTarget, TechTypes eTech) const;
bool canForceCivics(PlayerTypes eTarget, CivicTypes eCivic) const;
bool canForceReligion(PlayerTypes eTarget, ReligionTypes eReligion) const;
bool canSpyDestroyUnit(PlayerTypes eTarget, CvUnit& kUnit) const;
bool canSpyBribeUnit(PlayerTypes eTarget, CvUnit& kUnit) const;
bool canSpyDestroyBuilding(PlayerTypes eTarget, BuildingTypes eBuilding) const;
bool canSpyDestroyProject(PlayerTypes eTarget, ProjectTypes eProject) const;
DllExport void doAdvancedStartAction(AdvancedStartActionTypes eAction, int iX, int iY, int iData, bool bAdd);
DllExport int getAdvancedStartUnitCost(UnitTypes eUnit, bool bAdd, CvPlot* pPlot = NULL) const; // Exposed to Python
DllExport int getAdvancedStartCityCost(bool bAdd, CvPlot* pPlot = NULL) const; // Exposed to Python
DllExport int getAdvancedStartPopCost(bool bAdd, CvCity* pCity = NULL) const; // Exposed to Python
DllExport int getAdvancedStartCultureCost(bool bAdd, CvCity* pCity = NULL) const; // Exposed to Python
DllExport int getAdvancedStartBuildingCost(BuildingTypes eBuilding, bool bAdd, CvCity* pCity = NULL) const; // Exposed to Python
DllExport int getAdvancedStartImprovementCost(ImprovementTypes eImprovement, bool bAdd, CvPlot* pPlot = NULL) const; // Exposed to Python
DllExport int getAdvancedStartRouteCost(RouteTypes eRoute, bool bAdd, CvPlot* pPlot = NULL) const; // Exposed to Python
DllExport int getAdvancedStartTechCost(TechTypes eTech, bool bAdd) const; // Exposed to Python
DllExport int getAdvancedStartVisibilityCost(bool bAdd, CvPlot* pPlot = NULL) const; // Exposed to Python
DllExport int getGoldenAgeTurns() const; // Exposed to Python
DllExport bool isGoldenAge() const; // Exposed to Python
void changeGoldenAgeTurns(int iChange); // Exposed to Python
int getGoldenAgeLength() const;
int getNumUnitGoldenAges() const; // Exposed to Python
void changeNumUnitGoldenAges(int iChange); // Exposed to Python
int getAnarchyTurns() const; // Exposed to Python
DllExport bool isAnarchy() const; // Exposed to Python
void changeAnarchyTurns(int iChange); // Exposed to Python
int getStrikeTurns() const; // Exposed to Python
void changeStrikeTurns(int iChange);
int getMaxAnarchyTurns() const; // Exposed to Python
void updateMaxAnarchyTurns();
int getAnarchyModifier() const; // Exposed to Python
void changeAnarchyModifier(int iChange);
int getGoldenAgeModifier() const; // Exposed to Python
void changeGoldenAgeModifier(int iChange);
int getHurryModifier() const; // Exposed to Python
void changeHurryModifier(int iChange);
void createGreatPeople(UnitTypes eGreatPersonUnit, bool bIncrementThreshold, bool bIncrementExperience, int iX, int iY);
int getGreatPeopleCreated() const; // Exposed to Python
void incrementGreatPeopleCreated();
int getGreatGeneralsCreated() const; // Exposed to Python
void incrementGreatGeneralsCreated();
int getGreatPeopleThresholdModifier() const; // Exposed to Python
void changeGreatPeopleThresholdModifier(int iChange);
int getGreatGeneralsThresholdModifier() const; // Exposed to Python
void changeGreatGeneralsThresholdModifier(int iChange);
int getGreatPeopleRateModifier() const; // Exposed to Python
void changeGreatPeopleRateModifier(int iChange);
int getGreatGeneralRateModifier() const; // Exposed to Python
void changeGreatGeneralRateModifier(int iChange);
int getDomesticGreatGeneralRateModifier() const; // Exposed to Python
void changeDomesticGreatGeneralRateModifier(int iChange);
int getStateReligionGreatPeopleRateModifier() const; // Exposed to Python
void changeStateReligionGreatPeopleRateModifier(int iChange);
int getMaxGlobalBuildingProductionModifier() const; // Exposed to Python
void changeMaxGlobalBuildingProductionModifier(int iChange);
int getMaxTeamBuildingProductionModifier() const; // Exposed to Python
void changeMaxTeamBuildingProductionModifier(int iChange);
int getMaxPlayerBuildingProductionModifier() const; // Exposed to Python
void changeMaxPlayerBuildingProductionModifier(int iChange);
int getFreeExperience() const; // Exposed to Python
void changeFreeExperience(int iChange);
int getFeatureProductionModifier() const; // Exposed to Python
void changeFeatureProductionModifier(int iChange);
int getWorkerSpeedModifier() const; // Exposed to Python
void changeWorkerSpeedModifier(int iChange);
// BUG - Partial Builds - start
int getWorkRate(BuildTypes eBuild) const;
// BUG - Partial Builds - end
int getImprovementUpgradeRateModifier() const; // Exposed to Python
void changeImprovementUpgradeRateModifier(int iChange);
int getMilitaryProductionModifier() const; // Exposed to Python
void changeMilitaryProductionModifier(int iChange);
int getSpaceProductionModifier() const; // Exposed to Python
void changeSpaceProductionModifier(int iChange);
int getCityDefenseModifier() const; // Exposed to Python
void changeCityDefenseModifier(int iChange);
int getNumNukeUnits() const; // Exposed to Python
void changeNumNukeUnits(int iChange);
int getNumOutsideUnits() const; // Exposed to Python
void changeNumOutsideUnits(int iChange);
int getBaseFreeUnits() const; // Exposed to Python
void changeBaseFreeUnits(int iChange);
int getBaseFreeMilitaryUnits() const; // Exposed to Python
void changeBaseFreeMilitaryUnits(int iChange);
int getFreeUnitsPopulationPercent() const; // Exposed to Python
void changeFreeUnitsPopulationPercent(int iChange);
int getFreeMilitaryUnitsPopulationPercent() const; // Exposed to Python
void changeFreeMilitaryUnitsPopulationPercent(int iChange);
int getGoldPerUnit() const; // Exposed to Python
void changeGoldPerUnit(int iChange);
int getGoldPerMilitaryUnit() const; // Exposed to Python
void changeGoldPerMilitaryUnit(int iChange);
int getExtraUnitCost() const; // Exposed to Python
void changeExtraUnitCost(int iChange);
int getNumMilitaryUnits() const; // Exposed to Python
void changeNumMilitaryUnits(int iChange);
int getHappyPerMilitaryUnit() const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 19.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeHappyPerMilitaryUnit(int iChange, bool bLimited = false);
int getMilitaryFoodProductionCount() const;
bool isMilitaryFoodProduction() const; // Exposed to Python
//Fuyu bLimited
void changeMilitaryFoodProductionCount(int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getHighestUnitLevel() const; // Exposed to Python
void setHighestUnitLevel(int iNewValue);
int getConscriptCount() const; // Exposed to Python
void setConscriptCount(int iNewValue); // Exposed to Python
void changeConscriptCount(int iChange); // Exposed to Python
DllExport int getMaxConscript() const; // Exposed to Python
void changeMaxConscript(int iChange);
DllExport int getOverflowResearch() const; // Exposed to Python
void setOverflowResearch(int iNewValue); // Exposed to Python
void changeOverflowResearch(int iChange); // Exposed to Python
int getNoUnhealthyPopulationCount() const;
bool isNoUnhealthyPopulation() const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 02.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeNoUnhealthyPopulationCount(int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getExpInBorderModifier() const;
void changeExpInBorderModifier(int iChange);
int getBuildingOnlyHealthyCount() const;
bool isBuildingOnlyHealthy() const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 02.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeBuildingOnlyHealthyCount(int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getDistanceMaintenanceModifier() const; // Exposed to Python
void changeDistanceMaintenanceModifier(int iChange);
int getNumCitiesMaintenanceModifier() const; // Exposed to Python
void changeNumCitiesMaintenanceModifier(int iChange);
int getCorporationMaintenanceModifier() const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 19.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeCorporationMaintenanceModifier(int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getTotalMaintenance() const; // Exposed to Python
void changeTotalMaintenance(int iChange);
int getUpkeepModifier() const; // Exposed to Python
void changeUpkeepModifier(int iChange);
int getLevelExperienceModifier() const; // Exposed to Python
void changeLevelExperienceModifier(int iChange);
DllExport int getExtraHealth() const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 02.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeExtraHealth(int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getBuildingGoodHealth() const; // Exposed to Python
void changeBuildingGoodHealth(int iChange);
int getBuildingBadHealth() const; // Exposed to Python
void changeBuildingBadHealth(int iChange);
int getExtraHappiness() const; // Exposed to Python
void changeExtraHappiness(int iChange);
int getBuildingHappiness() const; // Exposed to Python
void changeBuildingHappiness(int iChange);
int getLargestCityHappiness() const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 02.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeLargestCityHappiness(int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getWarWearinessPercentAnger() const; // Exposed to Python
void updateWarWearinessPercentAnger();
int getModifiedWarWearinessPercentAnger(int iWarWearinessPercentAnger) const;
int getWarWearinessModifier() const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 19.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeWarWearinessModifier(int iChange, bool bLimited = false);
int getFreeSpecialist() const; // Exposed to Python
void changeFreeSpecialist(int iChange);
int getNoForeignTradeCount() const;
bool isNoForeignTrade() const; // Exposed to Python
//Fuyu bLimited
void changeNoForeignTradeCount(int iChange, bool bLimited = false);
int getNoCorporationsCount() const;
bool isNoCorporations() const; // Exposed to Python
//Fuyu bLimited
void changeNoCorporationsCount(int iChange, bool bLimited = false);
int getNoForeignCorporationsCount() const;
bool isNoForeignCorporations() const; // Exposed to Python
//Fuyu bLimited
void changeNoForeignCorporationsCount(int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getCoastalTradeRoutes() const; // Exposed to Python
void changeCoastalTradeRoutes(int iChange); // Exposed to Python
int getTradeRoutes() const; // Exposed to Python
void changeTradeRoutes(int iChange); // Exposed to Python
DllExport int getRevolutionTimer() const; // Exposed to Python
void setRevolutionTimer(int iNewValue);
void changeRevolutionTimer(int iChange);
int getConversionTimer() const; // Exposed to Python
void setConversionTimer(int iNewValue);
void changeConversionTimer(int iChange);
int getStateReligionCount() const;
bool isStateReligion() const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 02.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeStateReligionCount(int iChange, bool bLimited = false);
int getNoNonStateReligionSpreadCount() const;
DllExport bool isNoNonStateReligionSpread() const; // Exposed to Python
void changeNoNonStateReligionSpreadCount(int iChange);
DllExport int getStateReligionHappiness() const; // Exposed to Python
//Fuyu bLimited
void changeStateReligionHappiness(int iChange, bool bLimited = false);
int getNonStateReligionHappiness() const; // Exposed to Python
//Fuyu bLimited
void changeNonStateReligionHappiness(int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getStateReligionUnitProductionModifier() const; // Exposed to Python
void changeStateReligionUnitProductionModifier(int iChange);
int getStateReligionBuildingProductionModifier() const; // Exposed to Python
void changeStateReligionBuildingProductionModifier(int iChange); // Exposed to Python
int getStateReligionFreeExperience() const; // Exposed to Python
void changeStateReligionFreeExperience(int iChange);
DllExport CvCity* getCapitalCity() const; // Exposed to Python
void setCapitalCity(CvCity* pNewCapitalCity);
int getCitiesLost() const; // Exposed to Python
void changeCitiesLost(int iChange);
int getWinsVsBarbs() const; // Exposed to Python
void changeWinsVsBarbs(int iChange);
DllExport int getAssets() const; // Exposed to Python
void changeAssets(int iChange); // Exposed to Python
DllExport int getPower() const; // Exposed to Python
void changePower(int iChange);
DllExport int getPopScore(bool bCheckVassal = true) const; // Exposed to Python
void changePopScore(int iChange); // Exposed to Python
DllExport int getLandScore(bool bCheckVassal = true) const; // Exposed to Python
void changeLandScore(int iChange); // Exposed to Python
DllExport int getTechScore() const; // Exposed to Python
void changeTechScore(int iChange); // Exposed to Python
DllExport int getWondersScore() const; // Exposed to Python
void changeWondersScore(int iChange); // Exposed to Python
int getCombatExperience() const; // Exposed to Python
void setCombatExperience(int iExperience); // Exposed to Python
void changeCombatExperience(int iChange); // Exposed to Python
DllExport bool isConnected() const;
DllExport int getNetID() const;
DllExport void setNetID(int iNetID);
DllExport void sendReminder();
uint getStartTime() const;
DllExport void setStartTime(uint uiStartTime);
DllExport uint getTotalTimePlayed() const; // Exposed to Python
bool isMinorCiv() const; // Exposed to Python
DllExport bool isAlive() const; // Exposed to Python
DllExport bool isEverAlive() const; // Exposed to Python
void setAlive(bool bNewValue);
void verifyAlive();
DllExport bool isTurnActive() const;
DllExport void setTurnActive(bool bNewValue, bool bDoTurn = true);
bool isAutoMoves() const;
DllExport void setAutoMoves(bool bNewValue);
DllExport void setTurnActiveForPbem(bool bActive);
DllExport bool isPbemNewTurn() const;
DllExport void setPbemNewTurn(bool bNew);
bool isEndTurn() const;
DllExport void setEndTurn(bool bNewValue);
DllExport bool isTurnDone() const;
bool isExtendedGame() const; // Exposed to Python
DllExport void makeExtendedGame();
bool isFoundedFirstCity() const; // Exposed to Python
void setFoundedFirstCity(bool bNewValue);
DllExport bool isStrike() const; // Exposed to Python
void setStrike(bool bNewValue);
DllExport PlayerTypes getID() const; // Exposed to Python
DllExport HandicapTypes getHandicapType() const; // Exposed to Python
DllExport CivilizationTypes getCivilizationType() const; // Exposed to Python
DllExport LeaderHeadTypes getLeaderType() const; // Exposed to Python
LeaderHeadTypes getPersonalityType() const; // Exposed to Python
void setPersonalityType(LeaderHeadTypes eNewValue); // Exposed to Python
DllExport EraTypes getCurrentEra() const; // Exposed to Python
void setCurrentEra(EraTypes eNewValue);
ReligionTypes getLastStateReligion() const;
DllExport ReligionTypes getStateReligion() const; // Exposed to Python
void setLastStateReligion(ReligionTypes eNewValue); // Exposed to Python
PlayerTypes getParent() const;
void setParent(PlayerTypes eParent);
DllExport TeamTypes getTeam() const; // Exposed to Python
void setTeam(TeamTypes eTeam);
void updateTeamType();
DllExport PlayerColorTypes getPlayerColor() const; // Exposed to Python
DllExport int getPlayerTextColorR() const; // Exposed to Python
DllExport int getPlayerTextColorG() const; // Exposed to Python
DllExport int getPlayerTextColorB() const; // Exposed to Python
DllExport int getPlayerTextColorA() const; // Exposed to Python
int getSeaPlotYield(YieldTypes eIndex) const; // Exposed to Python
void changeSeaPlotYield(YieldTypes eIndex, int iChange);
int getYieldRateModifier(YieldTypes eIndex) const; // Exposed to Python
void changeYieldRateModifier(YieldTypes eIndex, int iChange);
int getCapitalYieldRateModifier(YieldTypes eIndex) const; // Exposed to Python
void changeCapitalYieldRateModifier(YieldTypes eIndex, int iChange);
int getExtraYieldThreshold(YieldTypes eIndex) const; // Exposed to Python
void updateExtraYieldThreshold(YieldTypes eIndex);
int getTradeYieldModifier(YieldTypes eIndex) const; // Exposed to Python
void changeTradeYieldModifier(YieldTypes eIndex, int iChange);
int getFreeCityCommerce(CommerceTypes eIndex) const; // Exposed to Python
void changeFreeCityCommerce(CommerceTypes eIndex, int iChange);
int getCommercePercent(CommerceTypes eIndex) const; // Exposed to Python
void setCommercePercent(CommerceTypes eIndex, int iNewValue); // Exposed to Python
DllExport void changeCommercePercent(CommerceTypes eIndex, int iChange); // Exposed to Python
int getCommerceRate(CommerceTypes eIndex) const; // Exposed to Python
void changeCommerceRate(CommerceTypes eIndex, int iChange);
int getCommerceRateModifier(CommerceTypes eIndex) const; // Exposed to Python
void changeCommerceRateModifier(CommerceTypes eIndex, int iChange);
int getCapitalCommerceRateModifier(CommerceTypes eIndex) const; // Exposed to Python
void changeCapitalCommerceRateModifier(CommerceTypes eIndex, int iChange);
int getStateReligionBuildingCommerce(CommerceTypes eIndex) const; // Exposed to Python
void changeStateReligionBuildingCommerce(CommerceTypes eIndex, int iChange);
int getSpecialistExtraCommerce(CommerceTypes eIndex) const; // Exposed to Python
void changeSpecialistExtraCommerce(CommerceTypes eIndex, int iChange);
int getCommerceFlexibleCount(CommerceTypes eIndex) const;
bool isCommerceFlexible(CommerceTypes eIndex) const; // Exposed to Python
void changeCommerceFlexibleCount(CommerceTypes eIndex, int iChange);
int getGoldPerTurnByPlayer(PlayerTypes eIndex) const; // Exposed to Python
void changeGoldPerTurnByPlayer(PlayerTypes eIndex, int iChange);
bool isFeatAccomplished(FeatTypes eIndex) const; // Exposed to Python
void setFeatAccomplished(FeatTypes eIndex, bool bNewValue); // Exposed to Python
DllExport bool isOption(PlayerOptionTypes eIndex) const; // Exposed to Python
DllExport void setOption(PlayerOptionTypes eIndex, bool bNewValue); // Exposed to Python
DllExport bool isLoyalMember(VoteSourceTypes eVoteSource) const; // Exposed to Python
DllExport void setLoyalMember(VoteSourceTypes eVoteSource, bool bNewValue); // Exposed to Python
DllExport bool isPlayable() const;
DllExport void setPlayable(bool bNewValue);
int getBonusExport(BonusTypes eIndex) const; // Exposed to Python
void changeBonusExport(BonusTypes eIndex, int iChange);
int getBonusImport(BonusTypes eIndex) const; // Exposed to Python
void changeBonusImport(BonusTypes eIndex, int iChange);
int getImprovementCount(ImprovementTypes eIndex) const; // Exposed to Python
void changeImprovementCount(ImprovementTypes eIndex, int iChange);
int getFreeBuildingCount(BuildingTypes eIndex) const;
bool isBuildingFree(BuildingTypes eIndex) const; // Exposed to Python
void changeFreeBuildingCount(BuildingTypes eIndex, int iChange);
int getExtraBuildingHappiness(BuildingTypes eIndex) const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 02.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeExtraBuildingHappiness(BuildingTypes eIndex, int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getExtraBuildingHealth(BuildingTypes eIndex) const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 02.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeExtraBuildingHealth(BuildingTypes eIndex, int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getFeatureHappiness(FeatureTypes eIndex) const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 02.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeFeatureHappiness(FeatureTypes eIndex, int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
int getUnitClassCount(UnitClassTypes eIndex) const; // Exposed to Python
bool isUnitClassMaxedOut(UnitClassTypes eIndex, int iExtra = 0) const; // Exposed to Python
void changeUnitClassCount(UnitClassTypes eIndex, int iChange);
int getUnitClassMaking(UnitClassTypes eIndex) const; // Exposed to Python
void changeUnitClassMaking(UnitClassTypes eIndex, int iChange);
int getUnitClassCountPlusMaking(UnitClassTypes eIndex) const; // Exposed to Python
int getBuildingClassCount(BuildingClassTypes eIndex) const; // Exposed to Python
bool isBuildingClassMaxedOut(BuildingClassTypes eIndex, int iExtra = 0) const; // Exposed to Python
void changeBuildingClassCount(BuildingClassTypes eIndex, int iChange);
int getBuildingClassMaking(BuildingClassTypes eIndex) const; // Exposed to Python
void changeBuildingClassMaking(BuildingClassTypes eIndex, int iChange);
int getBuildingClassCountPlusMaking(BuildingClassTypes eIndex) const; // Exposed to Python
int getHurryCount(HurryTypes eIndex) const; // Exposed to Python
DllExport bool canHurry(HurryTypes eIndex) const; // Exposed to Python
bool canPopRush();
void changeHurryCount(HurryTypes eIndex, int iChange);
int getSpecialBuildingNotRequiredCount(SpecialBuildingTypes eIndex) const; // Exposed to Python
bool isSpecialBuildingNotRequired(SpecialBuildingTypes eIndex) const; // Exposed to Python
void changeSpecialBuildingNotRequiredCount(SpecialBuildingTypes eIndex, int iChange);
int getHasCivicOptionCount(CivicOptionTypes eIndex) const;
bool isHasCivicOption(CivicOptionTypes eIndex) const; // Exposed to Python
void changeHasCivicOptionCount(CivicOptionTypes eIndex, int iChange);
int getNoCivicUpkeepCount(CivicOptionTypes eIndex) const;
bool isNoCivicUpkeep(CivicOptionTypes eIndex) const; // Exposed to Python
void changeNoCivicUpkeepCount(CivicOptionTypes eIndex, int iChange);
int getHasReligionCount(ReligionTypes eIndex) const; // Exposed to Python
int countTotalHasReligion() const; // Exposed to Python
int findHighestHasReligionCount() const; // Exposed to Python
void changeHasReligionCount(ReligionTypes eIndex, int iChange);
int getHasCorporationCount(CorporationTypes eIndex) const; // Exposed to Python
int countTotalHasCorporation() const; // Exposed to Python
void changeHasCorporationCount(CorporationTypes eIndex, int iChange);
bool isActiveCorporation(CorporationTypes eIndex) const;
int getUpkeepCount(UpkeepTypes eIndex) const; // Exposed to Python
void changeUpkeepCount(UpkeepTypes eIndex, int iChange);
int getSpecialistValidCount(SpecialistTypes eIndex) const;
DllExport bool isSpecialistValid(SpecialistTypes eIndex) const; // Exposed to Python
/********************************************************************************/
/* New Civic AI 19.08.2010 Fuyu */
/********************************************************************************/
//Fuyu bLimited
void changeSpecialistValidCount(SpecialistTypes eIndex, int iChange, bool bLimited = false);
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
DllExport bool isResearchingTech(TechTypes eIndex) const; // Exposed to Python
void setResearchingTech(TechTypes eIndex, bool bNewValue);
DllExport CivicTypes getCivics(CivicOptionTypes eIndex) const; // Exposed to Python
int getSingleCivicUpkeep(CivicTypes eCivic, bool bIgnoreAnarchy = false) const; // Exposed to Python
int getCivicUpkeep(CivicTypes* paeCivics = NULL, bool bIgnoreAnarchy = false) const; // Exposed to Python
void setCivics(CivicOptionTypes eIndex, CivicTypes eNewValue); // Exposed to Python
int getSpecialistExtraYield(SpecialistTypes eIndex1, YieldTypes eIndex2) const; // Exposed to Python
void changeSpecialistExtraYield(SpecialistTypes eIndex1, YieldTypes eIndex2, int iChange);
int getImprovementYieldChange(ImprovementTypes eIndex1, YieldTypes eIndex2) const; // Exposed to Python
void changeImprovementYieldChange(ImprovementTypes eIndex1, YieldTypes eIndex2, int iChange);
void updateGroupCycle(CvUnit* pUnit);
void removeGroupCycle(int iID);
CLLNode<int>* deleteGroupCycleNode(CLLNode<int>* pNode);
CLLNode<int>* nextGroupCycleNode(CLLNode<int>* pNode) const;
CLLNode<int>* previousGroupCycleNode(CLLNode<int>* pNode) const;
CLLNode<int>* headGroupCycleNode() const;
CLLNode<int>* tailGroupCycleNode() const;
int findPathLength(TechTypes eTech, bool bCost = true) const; // Exposed to Python
int getQueuePosition(TechTypes eTech) const; // Exposed to Python
DllExport void clearResearchQueue(); // Exposed to Python
DllExport bool pushResearch(TechTypes eTech, bool bClear = false); // Exposed to Python
void popResearch(TechTypes eTech); // Exposed to Python
int getLengthResearchQueue() const; // Exposed to Python
CLLNode<TechTypes>* nextResearchQueueNode(CLLNode<TechTypes>* pNode) const;
CLLNode<TechTypes>* headResearchQueueNode() const;
CLLNode<TechTypes>* tailResearchQueueNode() const;
void addCityName(const CvWString& szName); // Exposed to Python
int getNumCityNames() const; // Exposed to Python
CvWString getCityName(int iIndex) const; // Exposed to Python
CLLNode<CvWString>* nextCityNameNode(CLLNode<CvWString>* pNode) const;
CLLNode<CvWString>* headCityNameNode() const;
// plot groups iteration
CvPlotGroup* firstPlotGroup(int *pIterIdx, bool bRev=false) const;
CvPlotGroup* nextPlotGroup(int *pIterIdx, bool bRev=false) const;
int getNumPlotGroups() const;
CvPlotGroup* getPlotGroup(int iID) const;
CvPlotGroup* addPlotGroup();
void deletePlotGroup(int iID);
// city iteration
DllExport CvCity* firstCity(int *pIterIdx, bool bRev=false) const; // Exposed to Python
DllExport CvCity* nextCity(int *pIterIdx, bool bRev=false) const; // Exposed to Python
DllExport int getNumCities() const; // Exposed to Python
DllExport CvCity* getCity(int iID) const; // Exposed to Python
CvCity* addCity();
void deleteCity(int iID);
// unit iteration
DllExport CvUnit* firstUnit(int *pIterIdx, bool bRev=false) const; // Exposed to Python
DllExport CvUnit* nextUnit(int *pIterIdx, bool bRev=false) const; // Exposed to Python
DllExport int getNumUnits() const; // Exposed to Python
DllExport CvUnit* getUnit(int iID) const; // Exposed to Python
CvUnit* addUnit();
void deleteUnit(int iID);
// selection groups iteration
DllExport CvSelectionGroup* firstSelectionGroup(int *pIterIdx, bool bRev=false) const; // Exposed to Python
DllExport CvSelectionGroup* nextSelectionGroup(int *pIterIdx, bool bRev=false) const; // Exposed to Python
int getNumSelectionGroups() const; // Exposed to Python
CvSelectionGroup* getSelectionGroup(int iID) const; // Exposed to Python
CvSelectionGroup* addSelectionGroup();
void deleteSelectionGroup(int iID);
// pending triggers iteration
EventTriggeredData* firstEventTriggered(int *pIterIdx, bool bRev=false) const;
EventTriggeredData* nextEventTriggered(int *pIterIdx, bool bRev=false) const;
int getNumEventsTriggered() const;
EventTriggeredData* getEventTriggered(int iID) const; // Exposed to Python
EventTriggeredData* addEventTriggered();
void deleteEventTriggered(int iID);
EventTriggeredData* initTriggeredData(EventTriggerTypes eEventTrigger, bool bFire = false, int iCityId = -1, int iPlotX = INVALID_PLOT_COORD, int iPlotY = INVALID_PLOT_COORD, PlayerTypes eOtherPlayer = NO_PLAYER, int iOtherPlayerCityId = -1, ReligionTypes eReligion = NO_RELIGION, CorporationTypes eCorporation = NO_CORPORATION, int iUnitId = -1, BuildingTypes eBuilding = NO_BUILDING); // Exposed to Python
int getEventTriggerWeight(EventTriggerTypes eTrigger) const; // Exposed to python
DllExport void addMessage(const CvTalkingHeadMessage& message);
void showMissedMessages();
void clearMessages();
DllExport const CvMessageQueue& getGameMessages() const;
DllExport void expireMessages();
DllExport void addPopup(CvPopupInfo* pInfo, bool bFront = false);
void clearPopups();
DllExport CvPopupInfo* popFrontPopup();
DllExport const CvPopupQueue& getPopups() const;
DllExport void addDiplomacy(CvDiploParameters* pDiplo);
void clearDiplomacy();
DllExport const CvDiploQueue& getDiplomacy() const;
DllExport CvDiploParameters* popFrontDiplomacy();
DllExport void showSpaceShip();
DllExport void clearSpaceShipPopups();
int getScoreHistory(int iTurn) const; // Exposed to Python
void updateScoreHistory(int iTurn, int iBestScore);
int getEconomyHistory(int iTurn) const; // Exposed to Python
void updateEconomyHistory(int iTurn, int iBestEconomy);
int getIndustryHistory(int iTurn) const; // Exposed to Python
void updateIndustryHistory(int iTurn, int iBestIndustry);
int getAgricultureHistory(int iTurn) const; // Exposed to Python
void updateAgricultureHistory(int iTurn, int iBestAgriculture);
int getPowerHistory(int iTurn) const; // Exposed to Python
void updatePowerHistory(int iTurn, int iBestPower);
int getCultureHistory(int iTurn) const; // Exposed to Python
void updateCultureHistory(int iTurn, int iBestCulture);
int getEspionageHistory(int iTurn) const; // Exposed to Python
void updateEspionageHistory(int iTurn, int iBestEspionage);
// Script data needs to be a narrow string for pickling in Python
std::string getScriptData() const; // Exposed to Python
void setScriptData(std::string szNewValue); // Exposed to Python
DllExport const CvString getPbemEmailAddress() const;
DllExport void setPbemEmailAddress(const char* szAddress);
DllExport const CvString getSmtpHost() const;
DllExport void setSmtpHost(const char* szHost);
const EventTriggeredData* getEventOccured(EventTypes eEvent) const; // Exposed to python
bool isTriggerFired(EventTriggerTypes eEventTrigger) const;
void setEventOccured(EventTypes eEvent, const EventTriggeredData& kEventTriggered, bool bOthers = true);
void resetEventOccured(EventTypes eEvent, bool bAnnounce = true); // Exposed to Python
void setTriggerFired(const EventTriggeredData& kTriggeredData, bool bOthers = true, bool bAnnounce = true);
void resetTriggerFired(EventTriggerTypes eEventTrigger);
void trigger(EventTriggerTypes eEventTrigger); // Exposed to Python
void trigger(const EventTriggeredData& kData);
DllExport void applyEvent(EventTypes eEvent, int iTriggeredId, bool bUpdateTrigger = true);
bool canDoEvent(EventTypes eEvent, const EventTriggeredData& kTriggeredData) const;
TechTypes getBestEventTech(EventTypes eEvent, PlayerTypes eOtherPlayer) const;
int getEventCost(EventTypes eEvent, PlayerTypes eOtherPlayer, bool bRandom) const;
bool canTrigger(EventTriggerTypes eTrigger, PlayerTypes ePlayer, ReligionTypes eReligion) const;
const EventTriggeredData* getEventCountdown(EventTypes eEvent) const;
void setEventCountdown(EventTypes eEvent, const EventTriggeredData& kEventTriggered);
void resetEventCountdown(EventTypes eEvent);
bool isFreePromotion(UnitCombatTypes eUnitCombat, PromotionTypes ePromotion) const;
void setFreePromotion(UnitCombatTypes eUnitCombat, PromotionTypes ePromotion, bool bFree);
bool isFreePromotion(UnitClassTypes eUnitCombat, PromotionTypes ePromotion) const;
void setFreePromotion(UnitClassTypes eUnitCombat, PromotionTypes ePromotion, bool bFree);
PlayerVoteTypes getVote(int iId) const;
void setVote(int iId, PlayerVoteTypes ePlayerVote);
int getUnitExtraCost(UnitClassTypes eUnitClass) const;
void setUnitExtraCost(UnitClassTypes eUnitClass, int iCost);
DllExport bool splitEmpire(int iAreaId);
bool canSplitEmpire() const;
bool canSplitArea(int iAreaId) const;
PlayerTypes getSplitEmpirePlayer(int iAreaId) const;
bool getSplitEmpireLeaders(CivLeaderArray& aLeaders) const;
DllExport void launch(VictoryTypes victoryType);
bool hasShrine(ReligionTypes eReligion);
int getVotes(VoteTypes eVote, VoteSourceTypes eVoteSource) const; // Exposed to Python
void processVoteSourceBonus(VoteSourceTypes eVoteSource, bool bActive);
bool canDoResolution(VoteSourceTypes eVoteSource, const VoteSelectionSubData& kData) const;
bool canDefyResolution(VoteSourceTypes eVoteSource, const VoteSelectionSubData& kData) const;
void setDefiedResolution(VoteSourceTypes eVoteSource, const VoteSelectionSubData& kData);
void setEndorsedResolution(VoteSourceTypes eVoteSource, const VoteSelectionSubData& kData);
bool isFullMember(VoteSourceTypes eVoteSource) const; // Exposed to Python
bool isVotingMember(VoteSourceTypes eVoteSource) const; // Exposed to Python
void invalidatePopulationRankCache();
void invalidateYieldRankCache(YieldTypes eYield = NO_YIELD);
void invalidateCommerceRankCache(CommerceTypes eCommerce = NO_COMMERCE);
PlayerTypes pickConqueredCityOwner(const CvCity& kCity) const;
bool canHaveTradeRoutesWith(PlayerTypes ePlayer) const;
void forcePeace(PlayerTypes ePlayer); // exposed to Python
bool canSpiesEnterBorders(PlayerTypes ePlayer) const;
int getNewCityProductionValue() const;
int getGrowthThreshold(int iPopulation) const;
void verifyUnitStacksValid();
UnitTypes getTechFreeUnit(TechTypes eTech) const;
// BUG - Trade Totals - start
void calculateTradeTotals(YieldTypes eIndex, int& iDomesticYield, int& iDomesticRoutes, int& iForeignYield, int& iForeignRoutes, PlayerTypes eWithPlayer = NO_PLAYER, bool bRound = false, bool bBase = false) const;
int calculateTotalTradeYield(YieldTypes eIndex, PlayerTypes eWithPlayer = NO_PLAYER, bool bRound = false, bool bBase = false) const;
// BUG - Trade Totals - end
DllExport void buildTradeTable(PlayerTypes eOtherPlayer, CLinkList<TradeData>& ourList) const;
DllExport bool getHeadingTradeString(PlayerTypes eOtherPlayer, TradeableItems eItem, CvWString& szString, CvString& szIcon) const;
DllExport bool getItemTradeString(PlayerTypes eOtherPlayer, bool bOffer, bool bShowingCurrent, const TradeData& zTradeData, CvWString& szString, CvString& szIcon) const;
DllExport void updateTradeList(PlayerTypes eOtherPlayer, CLinkList<TradeData>& ourInventory, const CLinkList<TradeData>& ourOffer, const CLinkList<TradeData>& theirOffer) const;
DllExport int getIntroMusicScriptId(PlayerTypes eForPlayer) const;
DllExport int getMusicScriptId(PlayerTypes eForPlayer) const;
DllExport void getGlobeLayerColors(GlobeLayerTypes eGlobeLayerType, int iOption, std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const;
DllExport void cheat(bool bCtrl, bool bAlt, bool bShift);
DllExport const CvArtInfoUnit* getUnitArtInfo(UnitTypes eUnit, int iMeshGroup = 0) const;
DllExport bool hasSpaceshipArrived() const;
// BUG - Reminder Mod - start
void addReminder(int iGameTurn, CvWString szMessage) const;
// BUG - Reminder Mod - end
virtual void AI_init() = 0;
virtual void AI_reset(bool bConstructor) = 0;
virtual void AI_doTurnPre() = 0;
virtual void AI_doTurnPost() = 0;
virtual void AI_doTurnUnitsPre() = 0;
virtual void AI_doTurnUnitsPost() = 0;
virtual void AI_updateFoundValues(bool bStartingLoc = false) const = 0;
virtual void AI_unitUpdate() = 0;
virtual void AI_makeAssignWorkDirty() = 0;
virtual void AI_assignWorkingPlots() = 0;
virtual void AI_updateAssignWork() = 0;
virtual void AI_makeProductionDirty() = 0;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/08/09 jdog5000 */
/* */
/* City AI */
/************************************************************************************************/
//virtual void AI_doCentralizedProduction() = 0;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
virtual void AI_conquerCity(CvCity* pCity) = 0;
virtual int AI_foundValue(int iX, int iY, int iMinUnitRange = -1, bool bStartingLoc = false) const = 0; // Exposed to Python
virtual bool AI_isCommercePlot(CvPlot* pPlot) const = 0;
virtual int AI_getPlotDanger(CvPlot* pPlot, int iRange = -1, bool bTestMoves = true) const = 0;
virtual bool AI_isFinancialTrouble() const = 0; // Exposed to Python
virtual TechTypes AI_bestTech(int iMaxPathLength = 1, bool bIgnoreCost = false, bool bAsync = false, TechTypes eIgnoreTech = NO_TECH, AdvisorTypes eIgnoreAdvisor = NO_ADVISOR) const = 0;
virtual void AI_chooseFreeTech() = 0;
virtual void AI_chooseResearch() = 0;
virtual bool AI_isWillingToTalk(PlayerTypes ePlayer) const = 0;
virtual bool AI_demandRebukedSneak(PlayerTypes ePlayer) const = 0;
virtual bool AI_demandRebukedWar(PlayerTypes ePlayer) const = 0; // Exposed to Python
virtual AttitudeTypes AI_getAttitude(PlayerTypes ePlayer, bool bForced = true) const = 0; // Exposed to Python
virtual PlayerVoteTypes AI_diploVote(const VoteSelectionSubData& kVoteData, VoteSourceTypes eVoteSource, bool bPropose) = 0;
virtual int AI_dealVal(PlayerTypes ePlayer, const CLinkList<TradeData>* pList, bool bIgnoreAnnual = false, int iExtra = 0) const = 0;
virtual bool AI_considerOffer(PlayerTypes ePlayer, const CLinkList<TradeData>* pTheirList, const CLinkList<TradeData>* pOurList, int iChange = 1) const = 0;
virtual bool AI_counterPropose(PlayerTypes ePlayer, const CLinkList<TradeData>* pTheirList, const CLinkList<TradeData>* pOurList, CLinkList<TradeData>* pTheirInventory, CLinkList<TradeData>* pOurInventory, CLinkList<TradeData>* pTheirCounter, CLinkList<TradeData>* pOurCounter) const = 0;
virtual int AI_bonusVal(BonusTypes eBonus, int iChange = 0) const = 0;
virtual int AI_bonusTradeVal(BonusTypes eBonus, PlayerTypes ePlayer, int iChange = 0) const = 0;
virtual DenialTypes AI_bonusTrade(BonusTypes eBonus, PlayerTypes ePlayer) const = 0;
virtual int AI_cityTradeVal(CvCity* pCity) const = 0;
virtual DenialTypes AI_cityTrade(CvCity* pCity, PlayerTypes ePlayer) const = 0;
virtual DenialTypes AI_stopTradingTrade(TeamTypes eTradeTeam, PlayerTypes ePlayer) const = 0;
virtual DenialTypes AI_civicTrade(CivicTypes eCivic, PlayerTypes ePlayer) const = 0;
virtual DenialTypes AI_religionTrade(ReligionTypes eReligion, PlayerTypes ePlayer) const = 0;
/********************************************************************************/
/* City Defenders 24.07.2010 Fuyu */
/********************************************************************************/
//Fuyu bIgnoreNotUnitAIs
virtual int AI_unitValue(UnitTypes eUnit, UnitAITypes eUnitAI, CvArea* pArea, bool bIgnoreNotUnitAIs = false) const = 0; // Exposed to Python
/********************************************************************************/
/* City Defenders END */
/********************************************************************************/
virtual int AI_totalUnitAIs(UnitAITypes eUnitAI) const = 0; // Exposed to Python
virtual int AI_totalAreaUnitAIs(CvArea* pArea, UnitAITypes eUnitAI) const = 0; // Exposed to Python
virtual int AI_totalWaterAreaUnitAIs(CvArea* pArea, UnitAITypes eUnitAI) const = 0; // Exposed to Python
virtual int AI_plotTargetMissionAIs(CvPlot* pPlot, MissionAITypes eMissionAI, CvSelectionGroup* pSkipSelectionGroup = NULL, int iRange = 0) const = 0;
virtual int AI_unitTargetMissionAIs(CvUnit* pUnit, MissionAITypes eMissionAI, CvSelectionGroup* pSkipSelectionGroup = NULL) const = 0;
/********************************************************************************/
/* New Civic AI 19.08.2010 Fuyu */
/********************************************************************************/
virtual int AI_civicValue(CivicTypes eCivic, bool bCivicOptionVacuum = false, bool bCompleteVacuum = false, CivicTypes* paeSelectedCivics = NULL) const = 0; // Exposed to Python
/********************************************************************************/
/* New Civic AI END */
/********************************************************************************/
virtual int AI_getNumAIUnits(UnitAITypes eIndex) const = 0; // Exposed to Python
virtual void AI_changePeacetimeTradeValue(PlayerTypes eIndex, int iChange) = 0;
virtual void AI_changePeacetimeGrantValue(PlayerTypes eIndex, int iChange) = 0;
virtual int AI_getAttitudeExtra(PlayerTypes eIndex) const = 0; // Exposed to Python
virtual void AI_setAttitudeExtra(PlayerTypes eIndex, int iNewValue) = 0; // Exposed to Python
virtual void AI_changeAttitudeExtra(PlayerTypes eIndex, int iChange) = 0; // Exposed to Python
virtual void AI_setFirstContact(PlayerTypes eIndex, bool bNewValue) = 0;
virtual int AI_getMemoryCount(PlayerTypes eIndex1, MemoryTypes eIndex2) const = 0;
virtual void AI_changeMemoryCount(PlayerTypes eIndex1, MemoryTypes eIndex2, int iChange) = 0;
virtual void AI_doCommerce() = 0;
virtual EventTypes AI_chooseEvent(int iTriggeredId) const = 0;
virtual void AI_launch(VictoryTypes eVictory) = 0;
virtual void AI_doAdvancedStart(bool bNoExit = false) = 0;
virtual void AI_updateBonusValue() = 0;
virtual void AI_updateBonusValue(BonusTypes eBonus) = 0;
virtual ReligionTypes AI_chooseReligion() = 0;
virtual int AI_getExtraGoldTarget() const = 0;
virtual void AI_setExtraGoldTarget(int iNewValue) = 0;
virtual int AI_maxGoldPerTurnTrade(PlayerTypes ePlayer) const = 0;
virtual int AI_maxGoldTrade(PlayerTypes ePlayer) const = 0;
protected:
int m_iStartingX;
int m_iStartingY;
int m_iTotalPopulation;
int m_iTotalLand;
int m_iTotalLandScored;
int m_iGold;
int m_iGoldPerTurn;
int m_iAdvancedStartPoints;
int m_iGoldenAgeTurns;
int m_iNumUnitGoldenAges;
int m_iStrikeTurns;
int m_iAnarchyTurns;
int m_iMaxAnarchyTurns;
int m_iAnarchyModifier;
int m_iGoldenAgeModifier;
int m_iGlobalHurryModifier;
int m_iGreatPeopleCreated;
int m_iGreatGeneralsCreated;
int m_iGreatPeopleThresholdModifier;
int m_iGreatGeneralsThresholdModifier;
int m_iGreatPeopleRateModifier;
int m_iGreatGeneralRateModifier;
int m_iDomesticGreatGeneralRateModifier;
int m_iStateReligionGreatPeopleRateModifier;
int m_iMaxGlobalBuildingProductionModifier;
int m_iMaxTeamBuildingProductionModifier;
int m_iMaxPlayerBuildingProductionModifier;
int m_iFreeExperience;
int m_iFeatureProductionModifier;
int m_iWorkerSpeedModifier;
int m_iImprovementUpgradeRateModifier;
int m_iMilitaryProductionModifier;
int m_iSpaceProductionModifier;
int m_iCityDefenseModifier;
int m_iNumNukeUnits;
int m_iNumOutsideUnits;
int m_iBaseFreeUnits;
int m_iBaseFreeMilitaryUnits;
int m_iFreeUnitsPopulationPercent;
int m_iFreeMilitaryUnitsPopulationPercent;
int m_iGoldPerUnit;
int m_iGoldPerMilitaryUnit;
int m_iExtraUnitCost;
int m_iNumMilitaryUnits;
int m_iHappyPerMilitaryUnit;
int m_iMilitaryFoodProductionCount;
int m_iConscriptCount;
int m_iMaxConscript;
int m_iHighestUnitLevel;
int m_iOverflowResearch;
int m_iNoUnhealthyPopulationCount;
int m_iExpInBorderModifier;
int m_iBuildingOnlyHealthyCount;
int m_iDistanceMaintenanceModifier;
int m_iNumCitiesMaintenanceModifier;
int m_iCorporationMaintenanceModifier;
int m_iTotalMaintenance;
int m_iUpkeepModifier;
int m_iLevelExperienceModifier;
int m_iExtraHealth;
int m_iBuildingGoodHealth;
int m_iBuildingBadHealth;
int m_iExtraHappiness;
int m_iBuildingHappiness;
int m_iLargestCityHappiness;
int m_iWarWearinessPercentAnger;
int m_iWarWearinessModifier;
int m_iFreeSpecialist;
int m_iNoForeignTradeCount;
int m_iNoCorporationsCount;
int m_iNoForeignCorporationsCount;
int m_iCoastalTradeRoutes;
int m_iTradeRoutes;
int m_iRevolutionTimer;
int m_iConversionTimer;
int m_iStateReligionCount;
int m_iNoNonStateReligionSpreadCount;
int m_iStateReligionHappiness;
int m_iNonStateReligionHappiness;
int m_iStateReligionUnitProductionModifier;
int m_iStateReligionBuildingProductionModifier;
int m_iStateReligionFreeExperience;
int m_iCapitalCityID;
int m_iCitiesLost;
int m_iWinsVsBarbs;
int m_iAssets;
int m_iPower;
int m_iPopulationScore;
int m_iLandScore;
int m_iTechScore;
int m_iWondersScore;
int m_iCombatExperience;
int m_iPopRushHurryCount;
int m_iInflationModifier;
uint m_uiStartTime; // XXX save these?
bool m_bAlive;
bool m_bEverAlive;
bool m_bTurnActive;
bool m_bAutoMoves;
bool m_bEndTurn;
bool m_bPbemNewTurn;
bool m_bExtendedGame;
bool m_bFoundedFirstCity;
bool m_bStrike;
bool m_bHuman;
/************************************************************************************************/
/* AI_AUTO_PLAY_MOD 09/01/07 MRGENIE */
/* */
/* */
/************************************************************************************************/
bool m_bDisableHuman; // Set to true to disable isHuman() check
/************************************************************************************************/
/* AI_AUTO_PLAY_MOD END */
/************************************************************************************************/
/************************************************************************************************/
/* UNOFFICIAL_PATCH 12/07/09 EmperorFool */
/* */
/* Bugfix */
/************************************************************************************************/
// Free Tech Popup Fix
bool m_bChoosingFreeTech;
/************************************************************************************************/
/* UNOFFICIAL_PATCH END */
/************************************************************************************************/
PlayerTypes m_eID;
LeaderHeadTypes m_ePersonalityType;
EraTypes m_eCurrentEra;
ReligionTypes m_eLastStateReligion;
PlayerTypes m_eParent;
TeamTypes m_eTeamType;
int* m_aiSeaPlotYield;
int* m_aiYieldRateModifier;
int* m_aiCapitalYieldRateModifier;
int* m_aiExtraYieldThreshold;
int* m_aiTradeYieldModifier;
int* m_aiFreeCityCommerce;
int* m_aiCommercePercent;
int* m_aiCommerceRate;
int* m_aiCommerceRateModifier;
int* m_aiCapitalCommerceRateModifier;
int* m_aiStateReligionBuildingCommerce;
int* m_aiSpecialistExtraCommerce;
int* m_aiCommerceFlexibleCount;
int* m_aiGoldPerTurnByPlayer;
int* m_aiEspionageSpendingWeightAgainstTeam;
bool* m_abFeatAccomplished;
bool* m_abOptions;
CvString m_szScriptData;
int* m_paiBonusExport;
int* m_paiBonusImport;
int* m_paiImprovementCount;
int* m_paiFreeBuildingCount;
int* m_paiExtraBuildingHappiness;
int* m_paiExtraBuildingHealth;
int** m_paiExtraBuildingYield;
int** m_paiExtraBuildingCommerce;
int* m_paiFeatureHappiness;
int* m_paiUnitClassCount;
int* m_paiUnitClassMaking;
int* m_paiBuildingClassCount;
int* m_paiBuildingClassMaking;
int* m_paiHurryCount;
int* m_paiSpecialBuildingNotRequiredCount;
int* m_paiHasCivicOptionCount;
int* m_paiNoCivicUpkeepCount;
int* m_paiHasReligionCount;
int* m_paiHasCorporationCount;
int* m_paiUpkeepCount;
int* m_paiSpecialistValidCount;
bool* m_pabResearchingTech;
bool* m_pabLoyalMember;
std::vector<EventTriggerTypes> m_triggersFired;
CivicTypes* m_paeCivics;
int** m_ppaaiSpecialistExtraYield;
int** m_ppaaiImprovementYieldChange;
CLinkList<int> m_groupCycle;
CLinkList<TechTypes> m_researchQueue;
CLinkList<CvWString> m_cityNames;
FFreeListTrashArray<CvPlotGroup> m_plotGroups;
FFreeListTrashArray<CvCityAI> m_cities;
FFreeListTrashArray<CvUnitAI> m_units;
FFreeListTrashArray<CvSelectionGroupAI> m_selectionGroups;
FFreeListTrashArray<EventTriggeredData> m_eventsTriggered;
CvEventMap m_mapEventsOccured;
CvEventMap m_mapEventCountdown;
UnitCombatPromotionArray m_aFreeUnitCombatPromotions;
UnitClassPromotionArray m_aFreeUnitClassPromotions;
std::vector< std::pair<int, PlayerVoteTypes> > m_aVote;
std::vector< std::pair<UnitClassTypes, int> > m_aUnitExtraCosts;
CvMessageQueue m_listGameMessages;
CvPopupQueue m_listPopups;
CvDiploQueue m_listDiplomacy;
CvTurnScoreMap m_mapScoreHistory;
CvTurnScoreMap m_mapEconomyHistory;
CvTurnScoreMap m_mapIndustryHistory;
CvTurnScoreMap m_mapAgricultureHistory;
CvTurnScoreMap m_mapPowerHistory;
CvTurnScoreMap m_mapCultureHistory;
CvTurnScoreMap m_mapEspionageHistory;
void doGold();
void doResearch();
void doEspionagePoints();
void doWarnings();
void doEvents();
bool checkExpireEvent(EventTypes eEvent, const EventTriggeredData& kTriggeredData) const;
void expireEvent(EventTypes eEvent, const EventTriggeredData& kTriggeredData, bool bFail);
bool isValidTriggerReligion(const CvEventTriggerInfo& kTrigger, CvCity* pCity, ReligionTypes eReligion) const;
bool isValidTriggerCorporation(const CvEventTriggerInfo& kTrigger, CvCity* pCity, CorporationTypes eCorporation) const;
CvCity* pickTriggerCity(EventTriggerTypes eTrigger) const;
CvUnit* pickTriggerUnit(EventTriggerTypes eTrigger, CvPlot* pPlot, bool bPickPlot) const;
bool isValidEventTech(TechTypes eTech, EventTypes eEvent, PlayerTypes eOtherPlayer) const;
void verifyGoldCommercePercent();
void processCivics(CivicTypes eCivic, int iChange, bool bLimited = false);
// for serialization
virtual void read(FDataStreamBase* pStream);
virtual void write(FDataStreamBase* pStream);
void doUpdateCacheOnTurn();
int getResearchTurnsLeftTimes100(TechTypes eTech, bool bOverflow) const;
void getTradeLayerColors(std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const; // used by Globeview trade layer
void getUnitLayerColors(GlobeLayerUnitOptionTypes eOption, std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const; // used by Globeview unit layer
void getResourceLayerColors(GlobeLayerResourceOptionTypes eOption, std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const; // used by Globeview resource layer
void getReligionLayerColors(ReligionTypes eSelectedReligion, std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const; // used by Globeview religion layer
void getCultureLayerColors(std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const; // used by Globeview culture layer
};
#endif
| [
"jdog5000@31ee56aa-37e8-4f44-8bdf-1f84a3affbab",
"fim-fuyu@31ee56aa-37e8-4f44-8bdf-1f84a3affbab"
] | [
[
[
1,
38
],
[
44,
45
],
[
55,
62
],
[
66,
99
],
[
105,
106
],
[
110,
141
],
[
154,
170
],
[
183,
190
],
[
201,
503
],
[
509,
511
],
[
517,
533
],
[
542,
547
],
[
556,
563
],
[
572,
582
],
[
591,
604
],
[
613,
618
],
[
624,
629
],
[
632,
634
],
[
637,
639
],
[
645,
661
],
[
667,
672
],
[
675,
676
],
[
682,
860
],
[
869,
869
],
[
878,
879
],
[
888,
934
],
[
943,
1144
],
[
1149,
1160
],
[
1166,
1166
],
[
1170,
1193
],
[
1202,
1206
],
[
1214,
1344
],
[
1350,
1350
],
[
1365,
1476
],
[
1478,
1493
]
],
[
[
39,
43
],
[
46,
54
],
[
63,
65
],
[
100,
104
],
[
107,
109
],
[
142,
153
],
[
171,
182
],
[
191,
200
],
[
504,
508
],
[
512,
516
],
[
534,
541
],
[
548,
555
],
[
564,
571
],
[
583,
590
],
[
605,
612
],
[
619,
623
],
[
630,
631
],
[
635,
636
],
[
640,
644
],
[
662,
666
],
[
673,
674
],
[
677,
681
],
[
861,
868
],
[
870,
877
],
[
880,
887
],
[
935,
942
],
[
1145,
1148
],
[
1161,
1165
],
[
1167,
1169
],
[
1194,
1201
],
[
1207,
1213
],
[
1345,
1349
],
[
1351,
1364
],
[
1477,
1477
]
]
] |
7406a870622565cbf0c1a79469faff662dd115ab | 3201bc35622102fe99b50e5f7d1351ad0d89b2f2 | /design/repository/models/gip/c_gip_full.cpp | a102bce3964914847cf3cb290987f0eb2c30ec14 | [] | no_license | embisi-github/embisi_gip | 1f7e8ce334ae9611f52a2cd6e536ef71fb00cec4 | dd6dfe8667b28f03dba2ac605d67916cb4483005 | refs/heads/master | 2021-01-10T12:33:55.917299 | 2006-11-27T09:43:39 | 2006-11-27T09:43:39 | 48,285,426 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 227,014 | cpp | /*a To do
Hold of writing ALU acc and flags and shf and A/B (for mults) if RF will not take its result - treat it as not condition passed?
Add the register file write buffer (single reg number, single data) for peripheral accesses.
Reading of peripherals in RFR stage
Writing of peripherals in RFW stage
Checking instruction flow is okay and flush never occurs after write of PC - adding 'd' flag to instructions will ensure this
Zero overhead loops - either with special register as count, or immediate count (which should be faster to use)
For ZOLs use the repeat count above, and also have internal registers for the start and lengths
Mapping of registers with thread-based map
Preemption
Deschedule instruction
Thunking library call instruction
SWIs
Native instruction access in ARM mode - with conditional access (break out that coproc space?)
Add in saturated N/P and saturate instructions - how to clear them? No need for sticky V or N I think
Note: need to resolve the mechanism for one-shot scheduling?
Note: the way the 'D' flag is implemented for delay slots, the native decode requires a 'D' instruction to immediately succeed an 'F' instruction, with NO intervening cycles; this means that a conditional branch with delay slot must be placed so that the prefetch logic is GUARANTEED to provide the succeeding instruction on the succeeding cycle.
*/
/*a Includes
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "c_gip_full.h"
#include "c_memory_model.h"
#include "symbols.h"
#include "syscalls.h"
#include "arm_dis.h"
#include "gip_internals.h"
#include "gip_instructions.h"
#include "gip_native.h"
/*a Defines
*/
#define SET_ZN(pd, res) {pd->z=(res==0);pd->n=(res&0x80000000)?1:0;}
#define SET_ZNC(pd, res, car) {pd->z=(res==0);pd->n=(res&0x80000000)?1:0;pd->c=car;}
#define SET_ZNCV(pd, res, car, ovr) {pd->z=(res==0);pd->n=(res&0x80000000)?1:0;pd->c=car;pd->v=ovr;}
#define MAX_BREAKPOINTS (8)
#define MAX_INTERRUPTS (8)
#define SET_DEBUGGING_ENABLED(pd) {pd->debugging_enabled = (pd->breakpoints_enabled != 0) || (pd->halt);}
#define MAX_REGISTERS (32)
#define GIP_REGISTER_MASK (0x1f)
#define GIP_REGISTER_TYPE (0x20)
#define NUM_THREADS (8)
/*a Types
*/
/*t t_shf_type
*/
typedef enum
{
shf_type_lsl=0,
shf_type_lsr=1,
shf_type_asr=2,
shf_type_ror=3,
shf_type_rrx=4,
} t_shf_type;
/*t t_gip_dec_op_state
*/
typedef enum t_gip_dec_op_state
{
gip_dec_op_state_idle,
gip_dec_op_state_native,
gip_dec_op_state_emulate,
gip_dec_op_state_preempt
} t_gip_dec_op_state;
/*t t_gip_dec_extcmd
*/
typedef struct t_gip_dec_extcmd
{
int extended; // zero if rest of fields are not valid (no extcmd instruction)
int cc; // 4 bits of condition
int sign_or_stack; // 1 bit, set sign or 'is stack' for loads
int acc; // 1 bit, set accumulator
int op; // 2 bits of operation extension
int burst; // 4 bits of burst size
} t_gip_dec_extcmd;
/*t t_gip_sched_thread - Per thread register file storage
*/
typedef struct t_gip_sched_thread
{
unsigned int restart_pc;
int flag_dependencies; // 4-bit field indicating which sempahores are important
int register_map;
int config; // 1 for ARM, 0 for GIP native
int running; // 1 if the thread has been scheduled and is running (or is currently preempted)
} t_gip_sched_thread;
/*t t_gip_sched_state
*/
typedef struct t_gip_sched_state
{
/*b State in the scheduler guaranteed by the design
*/
t_gip_sched_thread thread_data[NUM_THREADS]; // 'Register file' of thread data for all eight threads
int thread; // Actual thread number that is currently running
int running; // 1 if a thread is running, 0 otherwise
int preempted_medium_thread; // 0 if none, else number
int preempted_low_thread; // 0 if not, else 1
int thread_to_start_valid; // 1 if the bus contents are valid; bus contents may only change when this signal rises
int thread_to_start; // Thread number to start
int thread_to_start_pc; // Thread number to start
int thread_to_start_config; // GIP pipeline configuration including operating mode
int thread_to_start_level; // 0 for low, 1 for medium, 2 for high
} t_gip_sched_state;
/*t t_gip_sched_data
*/
typedef struct t_gip_sched_data
{
/*b State of the scheduler
*/
t_gip_sched_state state;
t_gip_sched_state next_state;
/*b Combinatorials in the scheduler
*/
int next_thread_to_start; // Next thread, presented to decoder
int next_thread_to_start_valid; // 1 if next_thread_to_start is valid and indicates a thread to change to
int thread_data_to_read; // Thread number to read data for; if scheduling, then the next thread, else the selected_thread register
unsigned int thread_data_pc; // PC from the thread data bank for thread_data_to_read
int thread_data_config; // Config from the thread data bank for thread_data_to_read
} t_gip_sched_data;
/*t t_gip_special_state
*/
typedef struct t_gip_special_state
{
/*b State in the special registers guaranteed by the design
*/
unsigned int semaphores;
int cooperative;
int round_robin;
int thread_0_privilege;
int selected_thread; // Thread to read or write
int write_thread; // Thread to actually use for writing thread_data_pc/config
int thread_data_write_pc; // 1 if the thread_data_pc should be written to write_thread
int thread_data_write_config; // 1 if the thread_data_config should be written to write_thread
unsigned int thread_data_pc;
int thread_data_config;
int repeat_count; // repeat count
} t_gip_special_state;
/*t t_gip_special_data
*/
typedef struct t_gip_special_data
{
/*b State of the special registers
*/
t_gip_special_state state;
t_gip_special_state next_state;
/*b Combinatorials in the special registers
*/
} t_gip_special_data;
/*t t_gip_dec_idle_data
*/
typedef struct t_gip_dec_idle_data
{
int next_pc_valid;
int next_pc;
int next_thread;
} t_gip_dec_idle_data;
/*t t_gip_dec_native_data
*/
typedef struct t_gip_dec_native_data
{
unsigned int next_pc;
int next_cycle_of_opcode;
int inst_valid; // If 1 then instruction is valid, else not
t_gip_instruction inst; // Instruction to be executed by the RF stage
int next_instruction_extended;
unsigned int next_extended_immediate;
t_gip_ins_r next_extended_rd; // if extended instruction this specifies rd; if none, then do not extend rd
t_gip_ins_r next_extended_rm; // if extended instruction this specifies rm; if none, then do not extend rm
t_gip_ins_r next_extended_rn; // if extended instruction this specifies rn; if none, then do not extend rn
t_gip_dec_extcmd next_extended_cmd; // 6-bit field of extension bits for a command - needs to cover burst size (k), and whether to increment register
int extending; // 1 if the current native decode is an extension command; if this is not set and an instruction is being decoded then the next extension values should be cleared
int next_in_delay_slot; // 1 if in will be in a delay slot; ignore if flushed
int next_follow_delay_pc; // 1 if the next instruction will be the delay slot for a known taken branch
unsigned int next_delay_pc; // if it will be in a delay slot next as part of a know taken branch, then this is the PC that should be fetched for after that delay slot; otherwise, ignore
int next_in_immediate_shadow;
} t_gip_dec_native_data;
/*t t_gip_dec_arm_data
*/
typedef struct t_gip_dec_arm_data
{
unsigned int next_pc;
int next_cycle_of_opcode;
int next_acc_valid;
int next_reg_in_acc;
int inst_valid; // If 1 then instruction is valid, else not
t_gip_instruction inst; // Instruction to be executed by the RF stage
} t_gip_dec_arm_data;
/*t t_gip_dec_state
*/
typedef struct t_gip_dec_state
{
/*b State in the decoder stage guaranteed by the design
*/
t_gip_dec_op_state op_state;
unsigned int opcode;
unsigned int pc;
int in_delay_slot; // 1 if in a delay slot
int follow_delay_pc; // 1 if delay_pc should be taken rather than what the instruction decodes to
unsigned int delay_pc; // If in decoding a branch delay slot, then this is the next pc after the slot independent of what that instruction says
int pc_valid;
int acknowledge_scheduler;
int cycle_of_opcode;
int acc_valid; // 1 if the register in the accumulator is valid, 0 if the accumulator should not be used
int reg_in_acc; // register number (0 through 14) that is in the accumulator; 15 means none.
int fetch_requested; // 1 if at end of previous cycle a new instruction was stored in the opcode - basically comb cycle_of_opcode==0
unsigned int extended_immediate; // 28-bit extended immediate value for native instructions (ORred in with ARM decode immediate also); if zero, no extension yet
t_gip_ins_r extended_rd; // if extended instruction this specifies rd; if none, then do not extend rd
t_gip_ins_r extended_rm; // if extended instruction this specifies rm; if none, then do not extend rm - note for loads this is the whole rm if extended, for others just top half of rm
t_gip_ins_r extended_rn; // if extended instruction this specifies rn; if none, then do not extend rn
t_gip_dec_extcmd extended_cmd; // Command extension
int in_conditional_shadow; // 1 if in immediate shadow or (if shadow length of 2) if last accepted instruction was in immediate shadow
int in_immediate_shadow;
} t_gip_dec_state;
/*t t_gip_dec_data
*/
typedef struct t_gip_dec_data
{
/*b State in the RF guaranteed by the design
*/
t_gip_dec_state state;
t_gip_dec_state next_state;
/*b Combinatorials in the decoder
*/
int inst_valid; // If 1 then instruction is valid, else not
t_gip_instruction inst; // Instruction to be executed by the RF stage
t_gip_dec_op_state next_op_state;
int next_acknowledge_scheduler; // 1 to acknowledge scheduler on next cycle
t_gip_ins_cc gip_ins_cc;
/*b Subelement
*/
t_gip_dec_native_data native;
t_gip_dec_arm_data arm;
t_gip_dec_idle_data idle;
} t_gip_dec_data;
/*t t_gip_rf_state
*/
typedef struct t_gip_rf_state
{
/*b State in the RF itself
*/
unsigned int regs[ MAX_REGISTERS ];
/*b State in the RF read stage guaranteed by the design
*/
int inst_valid; // If 1 then instruction is valid, else not
t_gip_instruction inst; // Instruction being executed by the RF stage
/*b State in the RF write stage guaranteed by the design
*/
t_gip_ins_r alu_rd; // Type of register file write requested for the result of ALU operation
int use_shifter; // If 1 and alu_rd indicates a write then use the shifter result not the ALU result
unsigned int alu_result; // Registered result of the ALU
unsigned int shf_result; // Registered result of the shifter
t_gip_ins_r mem_rd; // Type of register file write requested for the result of memory operation
unsigned int mem_result; // Register result of the memory stage
int accepting_alu_rd; // 1 if the RFW stage can take an ALU register write; 0 only if the mem_rd is not-none and the alu_rd is not-none
} t_gip_rf_state;
/*t t_gip_rf_data
*/
typedef struct t_gip_rf_data
{
/*b State in the RF guaranteed by the design
*/
t_gip_rf_state state;
t_gip_rf_state next_state;
/*b Combinatorials in the RF
*/
unsigned int read_port_0, read_port_1; // Two register file read port values
int special_read, special_write, special_read_address;
unsigned int special_read_data;
int postbus_read, postbus_write, postbus_read_address;
unsigned int postbus_read_data, periph_read_data; // Read data from other places
unsigned int port_0_data, port_1_data; // Outputs to ALU stage
t_gip_ins_r rd;
unsigned int rfw_data;
int accepting_dec_instruction; // 1 if the RF stage is taking a proffered instruction from the decode independent of the ALU; will be asserted if the RF stage has no valid instruction to decode currently
int accepting_dec_instruction_if_alu_does; // 1 if the RF stage is taking a proffered instruction from the decode depending on the ALU taking the current instruction; 0 if the RF has no valid instruction, or if it has an instruction blocking on a pending register scoreboard; 1 if the RF has all the data and instruction ready for the ALU, and so depends on the ALU taking its instruction
} t_gip_rf_data;
/*t t_gip_alu_state
*/
typedef struct t_gip_alu_state
{
/*b State in the ALU guaranteed by the design
*/
int inst_valid; // If 1 then instruction is valid, else not
t_gip_instruction inst; // Instruction being executed by the ALU stage
unsigned int alu_a_in; // Registered input from the register file stage
unsigned int alu_b_in; // Registered input from the register file stage
unsigned int acc; // Accumulator value
unsigned int shf; // Shifter value
int z; // Zero flag result from previous ALU operation
int c; // Carry flag result from previous ALU operation
int v; // last V flag from the ALU, or sticky version thereof
int n; // last N flag from the ALU
int p; // last carry out of the shifter
int cp; // last condition passed indication
int old_cp; // previous-to-last condition passed indication; use if we have a 'trail' of 2
} t_gip_alu_state;
/*t t_gip_alu_data
*/
typedef struct t_gip_full_alu_data
{
/*b State in the ALU guaranteed by the design
*/
t_gip_alu_state state;
t_gip_alu_state next_state;
/*b Combinatorials in the ALU
*/
int condition_passed; // Requested condition in the ALU stage passed
t_gip_alu_op1_src op1_src;
t_gip_alu_op2_src op2_src;
unsigned int alu_constant; // Constant 0, 1, 2 or 4 for offsets for stores
int set_acc;
int set_zcvn;
int set_p;
t_gip_alu_op gip_alu_op; // Actual ALU operation to perform
unsigned int alu_op1; // Operand 1 to the ALU logic itself
unsigned int alu_op2; // Operand 2 to the ALU logic itself
int alu_z, alu_n, alu_c, alu_v;
int logic_z, logic_n;
unsigned int shf_result; // Result of the shifter
int shf_carry; // Carry out of the shifter
unsigned int arith_result; // Result of the arithmetic operation
unsigned int logic_result; // Result of the logical operation
unsigned int alu_result; // Result of the ALU as a whole
unsigned int use_shifter; // Use shf_result instead of alu_result
unsigned int next_acc;
int next_c;
int next_z;
int next_v;
int next_n;
int next_p;
unsigned int next_shf;
int next_cp; // equal to condition_passed unless destination is a condition, in which case use old value (if not condition_passed) or result of condition evaluation (if condition_passed)
int next_old_cp; // equal to current cp state, unless destination is a condtion, in which case this is 1
t_gip_ins_r alu_rd; // Type of register file write requested for the result of ALU operation
t_gip_ins_r mem_rd; // Type of register file write requested for the result of ALU operation
t_gip_mem_op gip_mem_op; // Type of memory operation the memory stage should perform in the next cycle
unsigned int mem_data_in; // Data in for a write to the memory operation
unsigned int mem_address; // Address for a memory operation
int accepting_rf_instruction; // 1 if the ALU stage is taking a proffered instruction from the RF state; if not asserted then the ALU stage should not assert flush for the pipeline, and the instruction within the ALU will not complete. Should only be deasserted if the ALU instruction is valid and writes to the RF but the RF indicates a stall, or if the ALU instruction is valid and causes a memory operation and the memory stage indicates a stall
} t_gip_alu_data;
/*t t_gip_mem_state
*/
typedef struct t_gip_mem_state
{
/*b State in the memory stage guaranteed by the design
*/
t_gip_ins_r mem_rd; // Type of register file write requested for the result of ALU operation
t_gip_mem_op gip_mem_op; // Type of memory operation the memory stage should perform in the next cycle
unsigned int mem_data_in; // Data in for a write to the memory operation
unsigned int mem_address; // Address for a memory operation
} t_gip_mem_state;
/*t t_gip_mem_data
*/
typedef struct t_gip_mem_data
{
/*b State in the memory stage guaranteed by the design
*/
t_gip_mem_state state;
t_gip_mem_state next_state;
/*b Combinatorials in the memory stage
*/
unsigned int mem_result; // Combinatorial, but effectively generated off the clock edge ending the previous cycle for a sync RAM
} t_gip_mem_data;
/*t t_private_data
*/
typedef struct t_private_data
{
c_memory_model *memory;
int cycle;
int verbose;
/*b Configuration of the pipeline
*/
int sticky_v;
int sticky_z;
int sticky_c;
int sticky_n;
int cp_trail_2; // Assert to have a 'condition passed' trail of 2, else it is one.
int arm_trap_semaphore; // Number of semaphore to assert when an undefined instruction or SWI is hit
int alu_mode; // 2-bit mode; 01 => math mode; 10 => bit mode; 11 => general purpose; 00=>bit mode (for now)
// these instructions force a deschedule, mov pc to r15 (optional), mov instruction to r?, set semaphore bit (in some order)
/*b State and combinatorials in the GIP internal pipeline stages
*/
t_gip_dec_data dec;
t_gip_rf_data rf;
t_gip_alu_data alu;
t_gip_sched_data sched;
t_gip_special_data special;
t_gip_mem_data mem;
t_gip_pipeline_results gip_pipeline_results;
/*b Unsorted
*/
/*b Combinatorials in the pipeline
*/
/*b Irrelevant stuff for now
*/
unsigned int last_address;
int seq_count;
int debugging_enabled;
int breakpoints_enabled;
unsigned int breakpoint_addresses[ MAX_BREAKPOINTS ];
int halt;
} t_private_data;
/*a Static variables
*/
/*a Support functions
*/
/*f is_condition_met
*/
static int is_condition_met( t_private_data *pd, t_gip_full_alu_data *alu, t_gip_ins_cc gip_ins_cc )
{
switch (gip_ins_cc)
{
case gip_ins_cc_eq:
return alu->state.z;
case gip_ins_cc_ne:
return !alu->state.z;
case gip_ins_cc_cs:
return alu->state.c;
case gip_ins_cc_cc:
return !alu->state.c;
case gip_ins_cc_mi:
return alu->state.n;
case gip_ins_cc_pl:
return !alu->state.n;
case gip_ins_cc_vs:
return alu->state.v;
case gip_ins_cc_vc:
return !alu->state.v;
case gip_ins_cc_hi:
return alu->state.c && !alu->state.z;
case gip_ins_cc_ls:
return !alu->state.c || alu->state.z;
case gip_ins_cc_ge:
return (!alu->state.n && !alu->state.v) || (alu->state.n && alu->state.v);
case gip_ins_cc_lt:
return (!alu->state.n && alu->state.v) || (alu->state.n && !alu->state.v);
case gip_ins_cc_gt:
return ((!alu->state.n && !alu->state.v) || (alu->state.n && alu->state.v)) && !alu->state.z;
case gip_ins_cc_le:
return (!alu->state.n && alu->state.v) || (alu->state.n && !alu->state.v) || alu->state.z;
case gip_ins_cc_always:
return 1;
case gip_ins_cc_cp:
if (pd->cp_trail_2)
{
return alu->state.cp && alu->state.old_cp;
}
return alu->state.cp;
}
return 0;
}
/*f rotate_right
*/
static unsigned int rotate_right( unsigned int value, int by )
{
unsigned int result;
result = value>>by;
result |= value<<(32-by);
return result;
}
/*f barrel_shift
*/
static unsigned int barrel_shift( int c_in, t_shf_type type, unsigned int val, int by, int *c_out )
{
//printf("Barrel shift %08x.%d type %d by %02x\n", val, c_in, type, by );
by &= 0xff;
if (by==0)
{
*c_out = c_in;
return val;
}
if (by>32)
{
switch (type)
{
case shf_type_lsl:
*c_out = 0;
return 0;
case shf_type_lsr:
*c_out = 0;
return 0;
case shf_type_asr:
*c_out = (val>>31)&1;
return ((val>>31)&1) ? 0xfffffff : 0;
case shf_type_ror:
by = by&31;
if (by==0)
{
by=32;
}
break;
default:
break;
}
}
if (by==32)
{
switch (type)
{
case shf_type_lsl:
*c_out = val&1;
return 0;
case shf_type_lsr:
*c_out = (val>>31)&1;
return 0;
case shf_type_asr:
*c_out = (val>>31)&1;
return ((val>>31)&1) ? 0xffffffff : 0;
case shf_type_ror:
*c_out = (val>>31)&1;
return val;
default:
break;
}
}
switch (type)
{
case shf_type_lsl:
*c_out = (val>>(32-by))&1;
return val<<by;
case shf_type_lsr:
*c_out = (val>>(by-1))&1;
return val>>by;
case shf_type_asr:
*c_out = (((int)val)>>(by-1))&1;
return (unsigned int)(((int)val)>>by);
case shf_type_ror:
*c_out = (val>>(by-1))&1;
return rotate_right( val, by );
case shf_type_rrx:
*c_out = val&1;
val = (val>>1)&0x7fffffff;
if (c_in)
val |= 0x80000000;
return val;
}
return 0;
}
/*f find_bit_set
*/
static unsigned int find_bit_set( unsigned int value, int dirn )
{
unsigned int chain_left, chain_right;
unsigned int single_bit;
unsigned int result;
int i;
chain_left = 0;
chain_right = 0;
for (i=0; i<32; i++)
{
chain_right = (chain_right|value)>>1;
chain_left = (chain_left|value)<<1;
}
single_bit = ((dirn==1)?chain_left:chain_right) ^ value; // Will be zero or will have precisely one bit set
result = 0;
if (single_bit & 0xaaaaaaaa) // bits 1,3,5,7,9 etc
{
result |= 1;
}
if (single_bit & 0xcccccccc) // bits 2,3,6,7,10,11,14,15 etc
{
result |= 2;
}
if (single_bit & 0xf0f0f0f0) // bits 4,5,6,7,12,13,14,15 etc
{
result |= 4;
}
if (single_bit & 0xff00ff00) // bits 8-15, 24-31
{
result |= 8;
}
if (single_bit & 0xffff0000) // bits 16-31
{
result |= 16;
}
return (single_bit)?result:0xffffffff; // single_bit of zero implies no bits set
}
/*f bit_count
*/
static unsigned int bit_count( unsigned int value )
{
int i, j;
for (i=0; i<32; i++)
{
if (value&(1<<i))
{
j++;
}
}
return j;
}
/*f add_op
in 8-bit world
0x7f + 0xc0 = 0x13f, (0x3f C v)
0x00 + 0x00 = 0x000, (0x00 c v)
0x40 + 0x3f = 0x07f, (0x7f c v)
0x40 + 0x40 = 0x080, (0x80 c V)
0x7f + 0x80 = 0x1ff, (0xff C v)
0xff + 0xff = 0x1fe, (0xfe C v)
0x80 + 0x00 = 0x080, (0x80 c v)
0x80 + 0x80 = 0x100, (0x00 C V)
0x7f + 0x7f = 0x0fe, (0xfe c V)
Note: +ve + -ve cannot overflow (V never set): smallest is 0x00+0x80+0 = 0x80, largest is 0x7f+0xff+1 = 0x7f.
i.e. opposite top bits => V clear
+ve + +ve overflows if carry in to top bit (i.e. top bit is set) (V set if res is negative)
i.e. top bits both clear, result tb set => V set
-ve + -ve overflows if carry in to top bit is clear, (i.e. result is positive)
i.e. top bits both set, result tb clear => V set
*/
static unsigned int add_op( unsigned int a, unsigned int b, int c_in, int *c_out, int *v_out )
{
unsigned int result_lo, result_hi;
unsigned int sign_a, sign_b, sign_r;
result_lo = (a&0xffff) + (b&0xffff) + (unsigned int)c_in;
result_hi = (a>>16) + (b>>16) + (result_lo>>16);
result_lo &= 0xffff;
if (result_hi>>16)
{
*c_out = 1;
}
else
{
*c_out = 0;
}
sign_a = a>>31;
sign_b = b>>31;
sign_r = (result_hi>>15)&1;
if (sign_a && sign_b && !sign_r)
{
*v_out = 1;
}
else if (!sign_a && !sign_b && sign_r)
{
*v_out = 1;
}
else
{
*v_out = 0;
}
return (result_hi<<16) | result_lo;
}
/*f disassemble_native_instruction
*/
static void disassemble_native_instruction( unsigned int pc, int opcode, char *buffer, int length )
{
char *op;
char *rm, *rd;
char rm_buffer[16], rd_buffer[8];
char text[128];
t_gip_native_ins_class ins_class;
t_gip_native_ins_subclass ins_subclass;
int imm;
int is_imm;
/*b Generated 'op'
*/
ins_class = (t_gip_native_ins_class) ((opcode>>12)&0xf);
switch (ins_class)
{
/*b ALU
*/
case gip_native_ins_class_alu_reg:
case gip_native_ins_class_alu_imm:
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>8)&0xf);
imm = (opcode&0xf);
switch (ins_subclass)
{
case gip_native_ins_subclass_alu_and:
op = "AND";
break;
case gip_native_ins_subclass_alu_or:
op = "OR ";
break;
case gip_native_ins_subclass_alu_xor:
op = "XOR";
break;
case gip_native_ins_subclass_alu_dis_orn_mla:
op = "ORN|MLA";
break;
case gip_native_ins_subclass_alu_dis_bic_init:
op = "BIC|INIT";
break;
case gip_native_ins_subclass_alu_mov:
op = "MOV";
break;
case gip_native_ins_subclass_alu_mvn:
op = "MVN";
break;
case gip_native_ins_subclass_alu_add:
op = "ADD";
break;
case gip_native_ins_subclass_alu_sub:
op = "SUB";
break;
case gip_native_ins_subclass_alu_rsb:
op = "RSB";
break;
case gip_native_ins_subclass_alu_dis_andcnt_mlb:
op = "ANDC|MLB";
break;
case gip_native_ins_subclass_alu_adc:
op = "ADC";
break;
case gip_native_ins_subclass_alu_dis_xorlast_sbc:
op = "XORL|SBC";
break;
case gip_native_ins_subclass_alu_rsc:
op = "RSC";
break;
case gip_native_ins_subclass_alu_dis_bitreverse_dva:
op = "BITR|DVA";
break;
case gip_native_ins_subclass_alu_dis_bytereverse_dvb:
op = "BYTRE|DVB";
break;
case gip_native_ins_subclass_alu_xorfirst:
op = "XORF";
break;
default:
op = "<UNEXPECTED>";
break;
}
break;
/*b Conditional
*/
case gip_native_ins_class_cond_reg:
case gip_native_ins_class_cond_imm:
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>8)&0xf);
imm = (opcode&0xf);
switch (ins_subclass)
{
case gip_native_ins_subclass_cond_eq: op = "CMPEQ"; break;
case gip_native_ins_subclass_cond_ne: op = "CMPNE"; break;
case gip_native_ins_subclass_cond_gt: op = "CMPGT"; break;
case gip_native_ins_subclass_cond_ge: op = "CMPGE"; break;
case gip_native_ins_subclass_cond_lt: op = "CMPLT"; break;
case gip_native_ins_subclass_cond_le: op = "CMPLE"; break;
case gip_native_ins_subclass_cond_hi: op = "CMPHI"; break;
case gip_native_ins_subclass_cond_hs: op = "CMPHS"; break;
case gip_native_ins_subclass_cond_lo: op = "CMPLO"; break;
case gip_native_ins_subclass_cond_ls: op = "CMPLS"; break;
case gip_native_ins_subclass_cond_seq: op = "TSTSEQ"; break;
case gip_native_ins_subclass_cond_sne: op = "TSTSNE"; break;
case gip_native_ins_subclass_cond_sgt: op = "TSTSGT"; break;
case gip_native_ins_subclass_cond_sge: op = "TSTSGE"; break;
case gip_native_ins_subclass_cond_slt: op = "TSTSLT"; break;
case gip_native_ins_subclass_cond_sle: op = "TSTSLE"; break;
case gip_native_ins_subclass_cond_shi: op = "TSTSHI"; break;
case gip_native_ins_subclass_cond_shs: op = "TSTSHS"; break;
case gip_native_ins_subclass_cond_slo: op = "TSTSLO"; break;
case gip_native_ins_subclass_cond_sls: op = "TSTSLS"; break;
case gip_native_ins_subclass_cond_smi: op = "TSTSMI"; break;
case gip_native_ins_subclass_cond_spl: op = "TSTSPL"; break;
case gip_native_ins_subclass_cond_svs: op = "TSTSVS"; break;
case gip_native_ins_subclass_cond_svc: op = "TSTSVC"; break;
case gip_native_ins_subclass_cond_sps: op = "TSTSPS"; break;
case gip_native_ins_subclass_cond_spc: op = "TSTSPC"; break;
case gip_native_ins_subclass_cond_allset: op = "TSTALLSET"; break;
case gip_native_ins_subclass_cond_anyclr: op = "TSTANYCLR"; break;
case gip_native_ins_subclass_cond_allclr: op = "TSTALLCLR"; break;
case gip_native_ins_subclass_cond_anyset: op = "TSTANYSET"; break;
default: op = "<UNEXPECTED>"; break;
}
break;
/*b Shift
*/
case gip_native_ins_class_shift:
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>10)&0x3);
imm = (opcode&0xf)|(((opcode>>8)&1)<<4);
is_imm = (opcode>>9)&1;
switch (ins_subclass)
{
case gip_native_ins_subclass_shift_lsl: op = "LSL"; break;
case gip_native_ins_subclass_shift_lsr: op = "LSR"; break;
case gip_native_ins_subclass_shift_asr: op = "ASR"; break;
case gip_native_ins_subclass_shift_ror:
op = "ROR";
if (is_imm && imm==0)
{
op = "ROR33";
}
break;
default: op = "<UNEXPECTED>"; break;
}
break;
/*b Memoty (load/store)
*/
case gip_native_ins_class_memory:
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>9)&0x7);
switch ((t_gip_native_ins_subclass) ((opcode>>8)&1))
{
case gip_native_ins_subclass_memory_load: op = "LDR"; break;
case gip_native_ins_subclass_memory_store: op = "STR"; break;
default: op = "<UNEXPECTED>"; break;
}
break;
/*b Branch
*/
case gip_native_ins_class_branch:
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>11)&0x1);
switch (ins_subclass)
{
case gip_native_ins_subclass_branch_no_delay: op = "B"; break;
case gip_native_ins_subclass_branch_delay: op = "B #1, "; break;
default: op = "<UNEXPECTED>"; break;
}
break;
/*b Done
*/
default:
break;
}
/*b Get text of Rd
*/
switch ((opcode>>4)&0xf)
{
default:
rd = rd_buffer;
sprintf( rd_buffer, "R%d", ((opcode>>4)&0xf) );
break;
}
/*b Get text of Rm
*/
switch ((opcode>>0)&0xf)
{
default:
rm = rm_buffer;
sprintf( rm_buffer, "R%d", ((opcode>>0)&0xf) );
break;
}
/*b Decode instruction
*/
switch (ins_class)
{
case gip_native_ins_class_alu_reg:
case gip_native_ins_class_cond_reg:
sprintf( text, "%s %s, %s",
op,
rd,
rm );
break;
case gip_native_ins_class_alu_imm:
case gip_native_ins_class_cond_imm:
sprintf( text, "%s %s, #0x%01x",
op,
rd,
imm );
break;
case gip_native_ins_class_shift:
if ((is_imm) && (imm==0))
{
sprintf( text, "%s %s",
op,
rd );
}
else if (is_imm)
{
sprintf( text, "%s %s, #%d",
op,
rd,
imm );
}
else
{
sprintf( text, "%s %s, %s",
op,
rd,
rm );
}
break;
case gip_native_ins_class_memory:
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>9)&0x7);
switch (ins_subclass)
{
case gip_native_ins_subclass_memory_word_noindex: sprintf( text, "%s %s, [%s]", op, rd, rm ); break;
case gip_native_ins_subclass_memory_half_noindex: sprintf( text, "%sH %s, [%s]", op, rd, rm ); break;
case gip_native_ins_subclass_memory_byte_noindex: sprintf( text, "%sB %s, [%s]", op, rd, rm ); break;
case gip_native_ins_subclass_memory_word_preindex_up: sprintf( text, "%s %s, [%s, #4]%s", op, rd, rm, (opcode>>8)&1?"!":"" ); break;
case gip_native_ins_subclass_memory_word_preindex_up_shf: sprintf( text, "%s %s, [%s, SHF]", op, rd, rm ); break;
case gip_native_ins_subclass_memory_word_preindex_down_shf: sprintf( text, "%s %s, [%s, -SHF]", op, rd, rm ); break;
case gip_native_ins_subclass_memory_word_postindex_up: sprintf( text, "%s %s, [%s], #4", op, rd, rm ); break;
case gip_native_ins_subclass_memory_word_postindex_down: sprintf( text, "%s %s, [%s], #-4", op, rd, rm ); break;
default: break;
}
break;
case gip_native_ins_class_branch:
sprintf( text, "%s 0x%08x",
op,
pc-8+((opcode<<20)>>20) );
break;
case gip_native_ins_class_extimm_0:
case gip_native_ins_class_extimm_1:
case gip_native_ins_class_extimm_2:
case gip_native_ins_class_extimm_3:
sprintf( text, "EXTIMM #%08x",
((opcode<<18)>>18) );
break;
case gip_native_ins_class_extrdrm:
sprintf( text, "EXTRDRM #%02x, #%02x", (opcode>>4)&0xff, ((opcode>>0)&0xf)<<4 );
break;
case gip_native_ins_class_extrnrm:
sprintf( text, "EXTRNRM #%02x, #%02x", (opcode>>4)&0xf0, ((opcode>>0)&0xf)<<4 );
break;
default:
sprintf( text, "NO DISASSEMBLY YET" );
break;
}
/*b Display instruction
*/
strncpy( buffer, text, length );
buffer[length-1] = 0;
}
/*f c_gip_full::disassemble_int_instruction
*/
void c_gip_full::disassemble_int_instruction( int valid, t_gip_instruction *inst, char *buffer, int length )
{
char *op;
char *cc;
char *rn, *rm, *rd;
const char *offset;
char rn_buffer[8], rm_buffer[16], rd_buffer[8];
int no_rn;
char text[128];
char *tptr;
text[0] = valid?'V':'I';
text[1] = ':';
tptr = text+2;
/*b Get text of CC
*/
switch (inst->gip_ins_cc)
{
case gip_ins_cc_eq:
cc = "EQ";
break;
case gip_ins_cc_ne:
cc = "NE";
break;
case gip_ins_cc_cs:
cc = "CS";
break;
case gip_ins_cc_cc:
cc = "CC";
break;
case gip_ins_cc_mi:
cc = "MI";
break;
case gip_ins_cc_pl:
cc = "PL";
break;
case gip_ins_cc_vs:
cc = "VS";
break;
case gip_ins_cc_vc:
cc = "VC";
break;
case gip_ins_cc_hi:
cc = "HI";
break;
case gip_ins_cc_ls:
cc = "LS";
break;
case gip_ins_cc_ge:
cc = "GE";
break;
case gip_ins_cc_lt:
cc = "LT";
break;
case gip_ins_cc_gt:
cc = "GT";
break;
case gip_ins_cc_le:
cc = "LE";
break;
case gip_ins_cc_always:
cc = "";
break;
case gip_ins_cc_cp:
cc = "CP";
break;
}
/*b Get text of Rd
*/
switch (inst->gip_ins_rd.type)
{
case gip_ins_r_type_none:
case gip_ins_r_type_none_b:
rd = "";
break;
case gip_ins_r_type_register:
rd = rd_buffer;
sprintf( rd_buffer, "-> R%d", inst->gip_ins_rd.data.r );
break;
case gip_ins_r_type_register_indirect:
rd = rd_buffer;
sprintf( rd_buffer, "-> [[R%d]]", inst->gip_ins_rd.data.r );
break;
case gip_ins_r_type_internal:
switch (inst->gip_ins_rd.data.rd_internal)
{
case gip_ins_rd_int_eq:
rd = "-> EQ";
break;
case gip_ins_rd_int_ne:
rd = "-> NE";
break;
case gip_ins_rd_int_cs:
rd = "-> CS";
break;
case gip_ins_rd_int_cc:
rd = "-> CC";
break;
case gip_ins_rd_int_hi:
rd = "-> HI";
break;
case gip_ins_rd_int_ls:
rd = "-> LS";
break;
case gip_ins_rd_int_ge:
rd = "-> GE";
break;
case gip_ins_rd_int_lt:
rd = "-> LT";
break;
case gip_ins_rd_int_gt:
rd = "-> GT";
break;
case gip_ins_rd_int_le:
rd = "-> LE";
break;
case gip_ins_rd_int_pc:
rd = "-> PC";
break;
}
break;
case gip_ins_r_type_periph:
rd = rd_buffer;
sprintf( rd_buffer, "-> P%d", inst->gip_ins_rd.data.r );
break;
case gip_ins_r_type_postbus:
rd = rd_buffer;
sprintf( rd_buffer, "-> C%d", inst->gip_ins_rd.data.r );
break;
case gip_ins_r_type_special:
rd = rd_buffer;
sprintf( rd_buffer, "-> S%d", inst->gip_ins_rd.data.r );
break;
default:
rd = rd_buffer;
sprintf( rd_buffer, "-> ???C%d", inst->gip_ins_rd.data.r );
break;
}
/*b Get text of Rn
*/
switch (inst->gip_ins_rn.type)
{
case gip_ins_r_type_none:
case gip_ins_r_type_none_b:
rn = "<NONE>";
break;
case gip_ins_r_type_register:
rn = rn_buffer;
sprintf( rn_buffer, "-> R%d", inst->gip_ins_rn.data.r );
break;
case gip_ins_r_type_register_indirect:
rn = rn_buffer;
sprintf( rn_buffer, "-> [[R%d]]", inst->gip_ins_rn.data.r );
break;
case gip_ins_r_type_internal:
switch (inst->gip_ins_rn.data.rnm_internal)
{
case gip_ins_rnm_int_acc:
rn = "ACC";
break;
case gip_ins_rnm_int_shf:
rn = "SHF";
break;
case gip_ins_rnm_int_pc:
rn = "PC";
break;
default:
rn = "<UNKNOWN>";
break;
}
break;
case gip_ins_r_type_periph:
rn = rn_buffer;
sprintf( rn_buffer, "-> P%d", inst->gip_ins_rn.data.r );
break;
case gip_ins_r_type_postbus:
rn = rn_buffer;
sprintf( rn_buffer, "-> C%d", inst->gip_ins_rn.data.r );
break;
case gip_ins_r_type_special:
rn = rn_buffer;
sprintf( rn_buffer, "-> S%d", inst->gip_ins_rn.data.r );
break;
default:
rn = rn_buffer;
sprintf( rn_buffer, "-> ???C%d", inst->gip_ins_rn.data.r );
break;
}
/*b Get text of Rm
*/
if (inst->rm_is_imm)
{
sprintf( rm_buffer, "#%08x", inst->rm_data.immediate );
rm = rm_buffer;
}
else
{
switch (inst->rm_data.gip_ins_rm.type)
{
case gip_ins_r_type_none:
case gip_ins_r_type_none_b:
rm = "<NONE>";
break;
case gip_ins_r_type_register:
rm = rm_buffer;
sprintf( rm_buffer, "-> R%d", inst->rm_data.gip_ins_rm.data.r );
break;
case gip_ins_r_type_register_indirect:
rm = rm_buffer;
sprintf( rm_buffer, "-> [[R%d]]", inst->rm_data.gip_ins_rm.data.r );
break;
case gip_ins_r_type_internal:
switch (inst->rm_data.gip_ins_rm.data.rnm_internal)
{
case gip_ins_rnm_int_acc:
rm = "ACC";
break;
case gip_ins_rnm_int_shf:
rm = "SHF";
break;
case gip_ins_rnm_int_pc:
rm = "PC";
break;
default:
rm = "<UNKNOWN>";
break;
}
break;
case gip_ins_r_type_periph:
rm = rm_buffer;
sprintf( rm_buffer, "-> P%d", inst->rm_data.gip_ins_rm.data.r );
break;
case gip_ins_r_type_postbus:
rm = rm_buffer;
sprintf( rm_buffer, "-> C%d", inst->rm_data.gip_ins_rm.data.r );
break;
case gip_ins_r_type_special:
rm = rm_buffer;
sprintf( rm_buffer, "-> S%d", inst->rm_data.gip_ins_rm.data.r );
break;
default:
rm = rm_buffer;
sprintf( rm_buffer, "-> ???C%d", inst->rm_data.gip_ins_rm.data.r );
break;
}
}
/*b Decode instruction
*/
switch (inst->gip_ins_class)
{
case gip_ins_class_logic:
no_rn = 0;
switch (inst->gip_ins_subclass)
{
case gip_ins_subclass_logic_and:
op = "IAND";
break;
case gip_ins_subclass_logic_or:
op = "IOR";
break;
case gip_ins_subclass_logic_xor:
op = "IXOR";
break;
case gip_ins_subclass_logic_bic:
op = "IBIC";
break;
case gip_ins_subclass_logic_orn:
op = "IORN";
break;
case gip_ins_subclass_logic_mov:
op = "IMOV";
no_rn = 1;
break;
case gip_ins_subclass_logic_mvn:
op = "IMVN";
no_rn = 1;
break;
case gip_ins_subclass_logic_andcnt:
op = "IANDC";
break;
case gip_ins_subclass_logic_andxor:
op = "IANDX";
break;
case gip_ins_subclass_logic_xorfirst:
op = "IXORF";
break;
case gip_ins_subclass_logic_xorlast:
op = "IXORL";
no_rn = 1;
break;
case gip_ins_subclass_logic_bitreverse:
op = "IBITR";
no_rn = 1;
break;
case gip_ins_subclass_logic_bytereverse:
op = "IBYTR";
no_rn = 1;
break;
default:
break;
}
sprintf( tptr, "%s%s%s%s%s%s %s%s%s %s",
op,
cc,
inst->gip_ins_opts.alu.s?"S":"",
inst->gip_ins_opts.alu.p?"P":"",
inst->a?"A":"",
inst->f?"F":"",
no_rn?"":rn,
no_rn?"":", ",
rm,
rd );
break;
case gip_ins_class_arith:
switch (inst->gip_ins_subclass)
{
case gip_ins_subclass_arith_add:
op = "IADD";
break;
case gip_ins_subclass_arith_adc:
op = "IADC";
break;
case gip_ins_subclass_arith_sub:
op = "ISUB";
break;
case gip_ins_subclass_arith_sbc:
op = "ISBC";
break;
case gip_ins_subclass_arith_rsb:
op = "IRSB";
break;
case gip_ins_subclass_arith_rsc:
op = "IRSC";
break;
case gip_ins_subclass_arith_init:
op = "INIT";
break;
case gip_ins_subclass_arith_mla:
op = "IMLA";
break;
case gip_ins_subclass_arith_mlb:
op = "IMLB";
break;
default:
break;
}
sprintf( tptr, "%s%s%s%s%s %s, %s %s",
op,
cc,
inst->gip_ins_opts.alu.s?"S":"",
inst->a?"A":"",
inst->f?"F":"",
rn,
rm,
rd );
break;
case gip_ins_class_shift:
switch (inst->gip_ins_subclass)
{
case gip_ins_subclass_shift_lsl:
op = "ILSL";
break;
case gip_ins_subclass_shift_lsr:
op = "ILSR";
break;
case gip_ins_subclass_shift_asr:
op = "IASR";
break;
case gip_ins_subclass_shift_ror:
op = "IROR";
break;
case gip_ins_subclass_shift_ror33:
op = "IROR33";
break;
default:
break;
}
sprintf( tptr, "%s%s%s%s %s, %s %s",
op,
cc,
inst->gip_ins_opts.alu.s?"S":"",
inst->f?"F":"",
rn,
rm,
rd );
break;
case gip_ins_class_load:
op = "<OP>";
offset = "<OFS>";
switch (inst->gip_ins_subclass & gip_ins_subclass_memory_size)
{
case gip_ins_subclass_memory_word: op=""; break;
case gip_ins_subclass_memory_half: op="H"; break;
case gip_ins_subclass_memory_byte: op="B"; break;
default: break;
}
switch (inst->gip_ins_subclass & gip_ins_subclass_memory_dirn)
{
case gip_ins_subclass_memory_up: offset="+"; break;
default: offset="-"; break;
}
sprintf( tptr, "ILDR%s%s%s%s%s #%d (%s%s, %s%s%s %s",
cc,
op,
inst->a?"A":"",
inst->gip_ins_opts.load.stack?"S":"",
inst->f?"F":"",
inst->k,
rn,
((inst->gip_ins_subclass&gip_ins_subclass_memory_index)==gip_ins_subclass_memory_postindex)?")":"",
offset,
rm,
((inst->gip_ins_subclass&gip_ins_subclass_memory_index)==gip_ins_subclass_memory_postindex)?"":")",
rd );
break;
case gip_ins_class_store:
op = "<OP>";
offset = "<OFS>";
switch (inst->gip_ins_subclass & gip_ins_subclass_memory_size)
{
case gip_ins_subclass_memory_word: op=""; break;
case gip_ins_subclass_memory_half: op="H"; break;
case gip_ins_subclass_memory_byte: op="B"; break;
default: break;
}
if (inst->gip_ins_opts.store.offset_type)
{
if ((inst->gip_ins_subclass & gip_ins_subclass_memory_dirn) == gip_ins_subclass_memory_up)
{
offset="+SHF";
}
else
{
offset="-SHF";
}
}
else
{
switch (inst->gip_ins_subclass & gip_ins_subclass_memory_size)
{
case gip_ins_subclass_memory_word:
offset = ((inst->gip_ins_subclass & gip_ins_subclass_memory_dirn) == gip_ins_subclass_memory_up)?"+4":"-4";
break;
case gip_ins_subclass_memory_half:
offset = ((inst->gip_ins_subclass & gip_ins_subclass_memory_dirn) == gip_ins_subclass_memory_up)?"+2":"-2";
break;
case gip_ins_subclass_memory_byte:
offset = ((inst->gip_ins_subclass & gip_ins_subclass_memory_dirn) == gip_ins_subclass_memory_up)?"+1":"-1";
break;
default:
break;
}
}
sprintf( tptr, "ISTR%s%s%s%s #%d (%s%s%s%s <- %s %s",
cc,
op,
inst->a?"A":"",
inst->gip_ins_opts.store.stack?"S":"",
inst->k,
rn,
((inst->gip_ins_subclass&gip_ins_subclass_memory_index)==gip_ins_subclass_memory_postindex)?")":"",
offset,
((inst->gip_ins_subclass&gip_ins_subclass_memory_index)==gip_ins_subclass_memory_postindex)?"":")",
rm,
rd );
break;
default:
sprintf( tptr, "NO DISASSEMBLY YET %d/%d", inst->gip_ins_class, inst->gip_ins_subclass );
break;
}
/*b Display instruction
*/
strncpy( buffer, text, length );
buffer[length-1] = 0;
}
/*a Constructors/destructors
*/
/*f c_gip_full::c_gip_full
*/
c_gip_full::c_gip_full( c_memory_model *memory ) : c_execution_model_class( memory )
{
int i;
pd = (t_private_data *)malloc(sizeof(t_private_data));
pd->cycle = 0;
pd->memory = memory;
pd->verbose = 0;
/*b Initialize the special registers
*/
pd->special.state.semaphores = 1;
pd->special.state.cooperative = 1;
pd->special.state.round_robin = 0;
pd->special.state.thread_0_privilege = 1;
pd->special.state.selected_thread = 0;
pd->special.state.write_thread = 0;
pd->special.state.thread_data_write_pc = 0;
pd->special.state.thread_data_write_config = 0;
pd->special.state.repeat_count = 0;
/*b Initialize the scheduler
*/
for (i=0; i<NUM_THREADS; i++)
{
pd->sched.state.thread_data[i].restart_pc = 0;
pd->sched.state.thread_data[i].flag_dependencies = 0;
pd->sched.state.thread_data[i].register_map = 0;
pd->sched.state.thread_data[i].config = 0;
pd->sched.state.thread_data[i].running = 0;
}
pd->sched.state.thread_data[0].flag_dependencies = 1;
pd->sched.state.thread = 0;
pd->sched.state.running = 0;
pd->sched.state.preempted_medium_thread = 0;
pd->sched.state.preempted_low_thread = 0;
/*b Initialize the decoder
*/
pd->dec.state.op_state = gip_dec_op_state_idle;
pd->dec.state.pc = 0;
pd->dec.state.pc_valid = 0;
pd->dec.state.opcode = 0;
pd->dec.state.acknowledge_scheduler = 0;
pd->dec.state.cycle_of_opcode = 0;
pd->dec.state.fetch_requested = 0;
pd->dec.state.extended_immediate = 0;
pd->dec.state.extended_rd.type= gip_ins_r_type_none;
pd->dec.state.extended_rm.type = gip_ins_r_type_none;
pd->dec.state.extended_rn.type = gip_ins_r_type_none;
pd->dec.state.extended_cmd.extended = 0;
pd->dec.state.reg_in_acc = 0;
pd->dec.state.acc_valid = 0;
pd->dec.state.in_delay_slot = 0;
pd->dec.state.follow_delay_pc = 0;
pd->dec.state.delay_pc = 0;
pd->dec.state.in_conditional_shadow = 0;
pd->dec.state.in_immediate_shadow = 0;
/*b Initialize the register file
*/
for (i=0; i<MAX_REGISTERS; i++)
{
pd->rf.state.regs[i] = 0;
}
build_gip_instruction_nop( &pd->rf.state.inst );
pd->rf.state.inst_valid = 0;
pd->rf.state.alu_rd.type = gip_ins_r_type_none;
pd->rf.state.mem_rd.type = gip_ins_r_type_none;
pd->rf.state.accepting_alu_rd = 1;
pd->rf.state.use_shifter = 0;
/*b Initialize the ALU
*/
build_gip_instruction_nop( &pd->alu.state.inst );
pd->alu.state.inst_valid = 0;
pd->alu.state.acc = 0;
pd->alu.state.alu_a_in = 0;
pd->alu.state.alu_b_in = 0;
pd->alu.state.shf = 0;
pd->alu.state.z = 0;
pd->alu.state.c = 0;
pd->alu.state.v = 0;
pd->alu.state.n = 0;
pd->alu.state.p = 0;
pd->alu.state.cp = 0;
/*b Initialize the memory stage
*/
pd->mem.state.mem_rd.type = gip_ins_r_type_none;
pd->mem.state.gip_mem_op = gip_mem_op_none;
pd->mem.state.mem_data_in = 0;
pd->mem.state.mem_address = 0;
/*b Initialize the other stuff for the model
*/
pd->last_address = 0;
pd->seq_count = 0;
/*
pd->debugging_enabled = 0;
pd->breakpoints_enabled = 0;
pd->tracing_enabled = 0;
for (i=0; i<MAX_BREAKPOINTS; i++)
{
pd->breakpoint_addresses[i] = 0;
}
for (i=0; i<MAX_TRACING; i++)
{
pd->trace_region_starts[i] = 0;
pd->trace_region_ends[i] = 0;
}
pd->halt = 0;
for (i=0; i<8; i++)
{
pd->interrupt_handler[i] = 0;
}
pd->swi_return_addr = 0xdeadadd0;
pd->swi_sp = 0xdeadadd1;
pd->swi_code = 0xdeadadd2;
pd->kernel_sp = 0xdeadadd3;
pd->super = 0xdeadadd4;
*/
}
/*f c_gip_full::~c_gip_full
*/
c_gip_full::~c_gip_full()
{
}
/*a Debug information methods
*/
/*f c_gip_full:debug
*/
void c_gip_full::debug( int mask )
{
char buffer[256];
unsigned int address;
unsigned int opcode;
if (mask&8)
{
address = pd->dec.state.pc;
if (address!=pd->last_address+4)
{
pd->last_address = address;
pd->seq_count = 0;
}
else
{
pd->last_address = address;
pd->seq_count++;
}
}
if (mask&2)
{
printf( "\t r0: %08x r1: %08x r2: %08x r3: %08x\n",
pd->rf.state.regs[0],
pd->rf.state.regs[1],
pd->rf.state.regs[2],
pd->rf.state.regs[3] );
printf( "\t r4: %08x r5: %08x r6: %08x r7: %08x\n",
pd->rf.state.regs[4],
pd->rf.state.regs[5],
pd->rf.state.regs[6],
pd->rf.state.regs[7] );
printf( "\t r8: %08x r9: %08x r10: %08x r11: %08x\n",
pd->rf.state.regs[8],
pd->rf.state.regs[9],
pd->rf.state.regs[10],
pd->rf.state.regs[11] );
printf( "\tr12: %08x r13: %08x r14: %08x r15: %08x\n",
pd->rf.state.regs[12],
pd->rf.state.regs[13],
pd->rf.state.regs[14],
pd->rf.state.regs[15] );
}
if (mask&4)
{
printf( "\t acc:%08x shf:%08x c:%d n:%d z:%d v:%d p:%d cp:%d ocp:%d\n",
pd->alu.state.acc,
pd->alu.state.shf,
pd->alu.state.c,
pd->alu.state.n,
pd->alu.state.z,
pd->alu.state.v,
pd->alu.state.p,
pd->alu.state.cp,
pd->alu.state.old_cp );
printf( "\t alu a:%08x alu b:%08x\n",
pd->alu.state.alu_a_in,
pd->alu.state.alu_b_in );
}
if (mask&1)
{
address = pd->dec.state.pc;
opcode = pd->memory->read_memory( address );
arm_disassemble( address, opcode, buffer );
const char * label = symbol_lookup (address);
printf( "%32s %08x %08x: %s\n",
label?label:"",
address,
opcode,
buffer );
}
if (mask)
{
fflush(stdout);
}
}
/*a Public level methods
*/
/*f c_gip_full:step
Returns number of instructions executed
*/
int c_gip_full::step( int *reason, int requested_count )
{
int i;
*reason = 0;
/*b Loop for requested count
*/
for (i=0; i<requested_count; i++)
{
comb();
preclock();
clock();
}
return requested_count;
}
/*f c_gip_full::load_code
*/
void c_gip_full::load_code( FILE *f, unsigned int base_address )
{
unsigned int opcode;
unsigned int address;
while (!feof(f))
{
if (fscanf(f, "%08x: %08x %*s\n", &address, &opcode)==2)
{
pd->memory->write_memory( address, opcode, 0xf );
}
else
{
int c;
c=fgetc(f);
while ((c!=EOF) && (c!='\n'))
{
c=fgetc(f);
}
c=fgetc(f);
}
}
}
/*f c_gip_full::load_code_binary
*/
void c_gip_full::load_code_binary( FILE *f, unsigned int base_address )
{
unsigned int opcode;
unsigned int address;
address = base_address;
while (!feof(f))
{
if (fread( &opcode, 1, 4, f )!=4)
{
break;
}
pd->memory->write_memory( address, opcode, 0xf );
address+=4;
}
printf ("Code loaded, end address was %x\n", address);
}
/*f c_gip_full::load_symbol_table
*/
void c_gip_full::load_symbol_table( char *filename )
{
symbol_initialize( filename );
}
/*a Scheduler stage methods
The scheduler presents (from a clock edge) its request to change to another thread
The decode also has information from its clock edge based on the previous instruction
decoded indicating whether it can be preempted; if it is idle, then it can be :-)
The decode stage combinatorially combines this information to determine if the
instruction it currently has should be decoded, or if a NOP should be decoded instead.
This information is given to the scheduler as an acknowledge
Note that if a deschedule instruction (even if conditional) has been inserted in to the pipeline then that must
block any acknowledge - it implicitly ensures the 'atomic' indication is set.
In addition to the scheduling above, the register file read stage can indicate to the scheduler that
a thread execution has completed (i.e. the thread has descheduled). This may be accompanied by a restart address.
The scheduler should also restart lower priority threads when high priority threads
complete.
So, if we fo for the discard of prefetched instructions, we have:
decoder -> scheduler indicates that any presented thread preempt or start will be taken
scheduler -> decoder indicates a thread to start and its PC and decode/pipeline configuration
register file read -> scheduler indicates that a thread has completed (possibly with restart PC)
register file write -> scheduler indicates restart PC for a thread and configuration
decoder -> ALU indicates priority level that is being operated at (for CZVN and accumulator and shifter)
register file read -> decoder indicates that a deschedule event actually took place (qualifier for flush)
*/
/*f c_gip_full::sched_comb
The scheduler operates in three modes:
cooperative round robin
cooperative prioritized
preemptive prioritized
*/
void c_gip_full::sched_comb( void )
{
int i;
int schedulable[NUM_THREADS];
int priority_thread, priority_schedulable;
int round_robin_thread, round_robin_schedulable;
int chosen_thread, chosen_schedulable;
/*b Determine the schedulability of each thread, and highest priority
*/
priority_schedulable = 0;
priority_thread = 0;
for (i=0; i<NUM_THREADS; i++)
{
schedulable[i] = ( ( pd->sched.state.thread_data[i].flag_dependencies &
(pd->special.state.semaphores>>(i*4)) &
0xf ) &&
!pd->sched.state.thread_data[i].running
);
if (schedulable[i])
{
priority_thread = i;
priority_schedulable = 1;
printf("Schedule %d\n", i );
}
}
/*b Determine round-robin thread
*/
round_robin_thread = (pd->sched.state.thread+1)%NUM_THREADS;
round_robin_schedulable = 0;
if (!pd->sched.state.running) // If running, hold the round robin thread at the next thread, else...
{
if (schedulable[pd->sched.state.thread]) // If the next thread is schedulable, then use it
{
round_robin_thread = pd->sched.state.thread;
round_robin_schedulable = 1;
}
else if (schedulable[pd->sched.state.thread|1]) // Else try (possibly) the one after that
{
round_robin_thread = pd->sched.state.thread|1;
round_robin_schedulable = 1;
}
else // Else just move on the thread
{
round_robin_thread = ((pd->sched.state.thread|1)+1)%NUM_THREADS;
round_robin_schedulable = 0;
}
}
/*b Choose high priority or round-robin
*/
chosen_thread = priority_thread;
chosen_schedulable = priority_schedulable;
if (pd->special.state.round_robin)
{
chosen_thread = round_robin_thread;
chosen_schedulable = round_robin_schedulable;
}
/*b Determine requester - if not running we will pick the chosen thread; if running we only do so if preempting and the levels allow it
*/
pd->sched.next_thread_to_start = chosen_thread;
pd->sched.next_thread_to_start_valid = 0;
switch (chosen_thread)
{
case 0:
if (!pd->sched.state.running)
{
pd->sched.next_thread_to_start_valid = chosen_schedulable;
}
break;
case 1:
case 2:
case 3:
if ( (!pd->sched.state.running) ||
((pd->sched.state.thread==0) && !pd->special.state.cooperative) )
{
pd->sched.next_thread_to_start_valid = chosen_schedulable;
}
break;
case 4:
case 5:
case 6:
case 7:
if ( (!pd->sched.state.running) ||
(!(pd->sched.state.thread&4) && !pd->special.state.cooperative) )
{
pd->sched.next_thread_to_start_valid = chosen_schedulable;
}
break;
}
pd->sched.thread_data_to_read = pd->special.state.selected_thread;
if (pd->sched.next_thread_to_start_valid && !(pd->sched.state.thread_to_start_valid))
{
pd->sched.thread_data_to_read = pd->sched.next_thread_to_start;
}
pd->sched.thread_data_pc = pd->sched.state.thread_data[ pd->sched.thread_data_to_read ].restart_pc;
pd->sched.thread_data_config = pd->sched.state.thread_data[ pd->sched.thread_data_to_read ].config;
}
/*f c_gip_full::sched_preclock
*/
void c_gip_full::sched_preclock( void )
{
/*b Copy current to next
*/
memcpy( &pd->sched.next_state, &pd->sched.state, sizeof(pd->sched.state) );
/*b Store thread and running
*/
pd->sched.next_state.thread_to_start = pd->sched.state.thread_to_start; // Ensure the bus is held constant unless we are raising request
if (pd->dec.state.acknowledge_scheduler)
{
pd->sched.next_state.thread = pd->sched.next_thread_to_start;
pd->sched.next_state.thread_data[ pd->sched.next_state.thread_to_start ].running = 1;
pd->sched.next_state.running = 1;
}
pd->sched.next_state.thread_to_start_valid = pd->sched.next_thread_to_start_valid;
if (pd->sched.next_state.thread_to_start_valid && !(pd->sched.state.thread_to_start_valid))
{
pd->sched.next_state.thread_to_start = pd->sched.next_thread_to_start;
pd->sched.next_state.thread_to_start_pc = pd->sched.thread_data_pc;
pd->sched.next_state.thread_to_start_config = pd->sched.thread_data_config;
pd->sched.next_state.thread_to_start_level = 0;
}
/*b Write thread data register file
*/
if (pd->special.state.thread_data_write_pc)
{
pd->sched.next_state.thread_data[ pd->special.state.write_thread ].restart_pc = pd->special.state.thread_data_pc;
pd->sched.next_state.thread_data[ pd->special.state.write_thread ].running = 0;
}
if (pd->special.state.thread_data_write_config)
{
pd->sched.next_state.thread_data[ pd->special.state.write_thread ].config = pd->special.state.thread_data_config;
}
}
/*f c_gip_full::sched_clock
*/
void c_gip_full::sched_clock( void )
{
/*b Debug
*/
if (pd->verbose)
{
printf( "\t**:SCH %d/%d @ %08x/%02x/%d (%08x)\n",
pd->sched.state.thread_to_start_valid,
pd->sched.state.thread_to_start,
pd->sched.state.thread_to_start_pc,
pd->sched.state.thread_to_start_config,
pd->sched.state.thread_to_start_level,
pd->special.state.semaphores
);
}
/*b Copy next to current
*/
memcpy( &pd->sched.state, &pd->sched.next_state, sizeof(pd->sched.state) );
}
/*a Decode stage methods
*/
/*f c_gip_full::dec_comb
*/
void c_gip_full::dec_comb( void )
{
char buffer[256];
unsigned int native_opcode;
/*b Fake the prefetch of the instruction
*/
if ( pd->dec.state.pc_valid && pd->dec.state.fetch_requested)
{
pd->dec.state.opcode = pd->memory->read_memory( pd->dec.state.pc );
}
/*b Native decode - use top or bottom half of instruction (pc bit 1 is set AND native AND valid)
*/
build_gip_instruction_nop( &pd->dec.native.inst );
pd->dec.gip_ins_cc = gip_ins_cc_always;
if (pd->dec.state.in_conditional_shadow)
{
pd->dec.gip_ins_cc = gip_ins_cc_cp;
}
pd->dec.native.inst_valid = 0;
native_opcode = pd->dec.state.opcode;
if ( (!pd->dec.state.pc_valid) ||
(pd->dec.state.op_state!=gip_dec_op_state_native) ||
((pd->dec.state.pc&2)==0) )
{
native_opcode = native_opcode & 0xffff;
}
else
{
native_opcode = native_opcode>>16;
}
pd->dec.native.next_pc = pd->dec.state.pc;
pd->dec.native.next_cycle_of_opcode = 0;
pd->dec.native.next_in_delay_slot = 0;
pd->dec.native.next_follow_delay_pc = 0;
pd->dec.native.next_in_immediate_shadow = 0;
pd->dec.native.next_extended_immediate = pd->dec.state.extended_immediate;
pd->dec.native.extending = 0;
if ( decode_native_debug( native_opcode ) ||
decode_native_extend( native_opcode ) ||
decode_native_alu( native_opcode ) ||
decode_native_cond( native_opcode ) ||
decode_native_shift( native_opcode ) ||
decode_native_ldr( native_opcode ) ||
decode_native_str( native_opcode ) ||
decode_native_branch( native_opcode ) ||
0 )
{
pd->dec.native.inst_valid = !pd->dec.native.extending;
}
if (pd->dec.state.follow_delay_pc)
{
pd->dec.native.next_pc = pd->dec.state.delay_pc;
}
if ((!pd->dec.native.extending) || (pd->gip_pipeline_results.flush) )
{
pd->dec.native.next_extended_immediate = 0;
pd->dec.native.next_extended_cmd.extended = 0;
pd->dec.native.next_extended_rd.type = gip_ins_r_type_no_override;
pd->dec.native.next_extended_rn.type = gip_ins_r_type_no_override;
pd->dec.native.next_extended_rm.type = gip_ins_r_type_no_override;
}
if (!pd->dec.state.pc_valid)
{
pd->dec.native.next_pc = pd->dec.state.pc;
pd->dec.native.next_cycle_of_opcode = 0;
pd->dec.native.inst_valid = 0;
}
if (pd->gip_pipeline_results.write_pc)
{
pd->dec.native.next_pc = pd->gip_pipeline_results.rfw_data;
}
if (pd->gip_pipeline_results.flush)
{
pd->dec.native.inst_valid = 0;
pd->dec.native.next_in_delay_slot = 0;
pd->dec.native.next_follow_delay_pc = 0;
pd->dec.native.next_in_immediate_shadow = 0;
}
/*b ARM decode - attempt to decode opcode, trying each instruction coding one at a time till we succeed
*/
build_gip_instruction_nop( &pd->dec.arm.inst );
pd->dec.arm.inst_valid = 0;
pd->dec.arm.next_acc_valid = 0;
pd->dec.arm.next_reg_in_acc = pd->dec.state.reg_in_acc;
pd->dec.arm.next_pc = pd->dec.state.pc;
pd->dec.arm.next_cycle_of_opcode = pd->dec.state.cycle_of_opcode+1;
if ( decode_arm_debug() ||
decode_arm_mul() ||
decode_arm_alu() ||
decode_arm_ld_st() ||
decode_arm_ldm_stm() ||
decode_arm_branch() ||
decode_arm_trace() ||
0 )
{
pd->dec.arm.inst_valid = 1;
}
if ( (pd->dec.arm.inst.gip_ins_rn.type == gip_ins_r_type_register) &&
(pd->dec.arm.inst.gip_ins_rn.data.r == pd->dec.state.reg_in_acc) &&
(pd->dec.state.acc_valid) )
{
pd->dec.arm.inst.gip_ins_rn.type = gip_ins_r_type_internal;
pd->dec.arm.inst.gip_ins_rn.data.rnm_internal = gip_ins_rnm_int_acc;
}
if ( (!pd->dec.arm.inst.rm_is_imm) &&
(pd->dec.arm.inst.rm_data.gip_ins_rm.type == gip_ins_r_type_register) &&
(pd->dec.arm.inst.rm_data.gip_ins_rm.data.r == pd->dec.state.reg_in_acc) &&
(pd->dec.state.acc_valid) )
{
pd->dec.arm.inst.rm_data.gip_ins_rm.type = gip_ins_r_type_internal;
pd->dec.arm.inst.rm_data.gip_ins_rm.data.rnm_internal = gip_ins_rnm_int_acc;
}
if (!pd->dec.state.pc_valid)
{
pd->dec.arm.next_pc = pd->dec.state.pc;
pd->dec.arm.next_cycle_of_opcode = 0;
pd->dec.arm.inst_valid = 0;
}
if (pd->gip_pipeline_results.write_pc)
{
pd->dec.arm.next_pc = pd->gip_pipeline_results.rfw_data;
}
if (pd->gip_pipeline_results.flush)
{
pd->dec.arm.inst_valid = 0;
}
/*b Handle according to operating state
*/
pd->dec.next_op_state = pd->dec.state.op_state;
switch (pd->dec.state.op_state)
{
/*b Idle - wait for schedule request
*/
case gip_dec_op_state_idle:
pd->dec.idle.next_pc_valid = 0;
pd->dec.next_acknowledge_scheduler = 0;
if (pd->sched.state.thread_to_start_valid)
{
pd->dec.next_op_state = gip_dec_op_state_emulate;
pd->dec.next_op_state = gip_dec_op_state_native;
pd->dec.next_acknowledge_scheduler = 1;
pd->dec.idle.next_thread = pd->sched.state.thread_to_start;
pd->dec.idle.next_pc = pd->sched.state.thread_to_start_pc;
pd->dec.idle.next_pc_valid = 1;
pd->dec.arm.next_cycle_of_opcode=0;
pd->dec.arm.next_acc_valid = 0;
}
break;
/*b ARM mode
*/
case gip_dec_op_state_emulate:
/*b Disassemble instruction if verbose
*/
if ( pd->dec.state.pc_valid && (pd->dec.state.cycle_of_opcode==0))
{
if (pd->verbose)
{
arm_disassemble( pd->dec.state.pc, pd->dec.state.opcode, buffer );
printf( "%08x %08x: %s\n", pd->dec.state.pc, pd->dec.state.opcode, buffer );
}
}
/*b Select ARM decode as our decode (NEED TO MUX IN NATIVE IF ENCODED NATIVE - BUT THEN STILL USE OUR CC)
*/
pd->dec.inst = pd->dec.arm.inst;
pd->dec.inst_valid = pd->dec.arm.inst_valid;
break;
/*b Native - decode top or bottom half of instruction (pc bit 1 is set AND native AND valid)
*/
case gip_dec_op_state_native:
/*b Disassemble instruction if verbose
*/
if ( pd->dec.state.pc_valid && (pd->dec.state.cycle_of_opcode==0))
{
if (pd->verbose)
{
disassemble_native_instruction( pd->dec.state.pc, native_opcode, buffer, sizeof(buffer) );
printf( "%08x %04x: %s (native)\n", pd->dec.state.pc, native_opcode, buffer );
}
}
/*b Select native instruction as our decode
*/
pd->dec.inst = pd->dec.native.inst;
pd->dec.inst_valid = pd->dec.native.inst_valid;
break;
/*b Preempt - NOT WRITTEN YET
*/
case gip_dec_op_state_preempt:
break;
/*b All done
*/
}
}
/*f c_gip_full::dec_preclock
*/
void c_gip_full::dec_preclock( void )
{
/*b Copy current to next
*/
memcpy( &pd->dec.next_state, &pd->dec.state, sizeof(pd->dec.state) );
/*b Handle according to operating state
*/
pd->dec.next_state.acknowledge_scheduler = 0;
switch (pd->dec.state.op_state)
{
/*b Idle - wait for schedule request
*/
case gip_dec_op_state_idle:
pd->dec.next_state.pc = pd->dec.idle.next_pc;
pd->dec.next_state.pc_valid = pd->dec.idle.next_pc_valid;
pd->dec.next_state.cycle_of_opcode = 0;
pd->dec.next_state.acc_valid = pd->dec.arm.next_acc_valid;
pd->dec.next_state.op_state = pd->dec.next_op_state;
pd->dec.next_state.acknowledge_scheduler = pd->dec.next_acknowledge_scheduler;
pd->dec.next_state.in_conditional_shadow = 0;
pd->dec.next_state.in_immediate_shadow = 0;
pd->dec.next_state.extended_immediate = 0;
pd->dec.next_state.extended_cmd.extended = 0;
pd->dec.next_state.extended_rd.type = gip_ins_r_type_no_override;
pd->dec.next_state.extended_rn.type = gip_ins_r_type_no_override;
pd->dec.next_state.extended_rm.type = gip_ins_r_type_no_override;
printf("Idle %d %d %d\n", pd->dec.next_op_state, pd->dec.next_acknowledge_scheduler, pd->sched.state.thread_to_start_valid );
break;
case gip_dec_op_state_emulate:
/*b ARM - Move on PC
*/
if ( (pd->rf.accepting_dec_instruction) ||
(pd->rf.accepting_dec_instruction_if_alu_does && pd->alu.accepting_rf_instruction) )
{
pd->dec.next_state.pc = pd->dec.arm.next_pc;
pd->dec.next_state.cycle_of_opcode = pd->dec.arm.next_cycle_of_opcode;
pd->dec.next_state.acc_valid = pd->dec.arm.next_acc_valid;
pd->dec.next_state.reg_in_acc = pd->dec.arm.next_reg_in_acc;
}
if (pd->gip_pipeline_results.write_pc)
{
pd->dec.next_state.pc = pd->gip_pipeline_results.rfw_data;
pd->dec.next_state.pc_valid = 1;
}
if (pd->gip_pipeline_results.flush)
{
pd->dec.next_state.cycle_of_opcode=0;
pd->dec.next_state.pc_valid = pd->gip_pipeline_results.write_pc;
pd->dec.next_state.acc_valid = 0;
}
pd->dec.next_state.in_delay_slot = 0;
pd->dec.next_state.follow_delay_pc = 0;
pd->dec.next_state.delay_pc = 0;
pd->dec.next_state.in_conditional_shadow = 0;
pd->dec.next_state.in_immediate_shadow = 0;
pd->dec.next_state.extended_immediate = 0;
pd->dec.next_state.extended_cmd.extended = 0;
pd->dec.next_state.extended_rd.type = gip_ins_r_type_no_override;
pd->dec.next_state.extended_rn.type = gip_ins_r_type_no_override;
pd->dec.next_state.extended_rm.type = gip_ins_r_type_no_override;
break;
/*b Native
*/
case gip_dec_op_state_native:
if ( (pd->rf.accepting_dec_instruction) ||
(pd->rf.accepting_dec_instruction_if_alu_does && pd->alu.accepting_rf_instruction) )
{
pd->dec.next_state.pc = pd->dec.native.next_pc;
pd->dec.next_state.cycle_of_opcode = pd->dec.native.next_cycle_of_opcode;
pd->dec.next_state.acc_valid = pd->dec.arm.next_acc_valid;
pd->dec.next_state.reg_in_acc = pd->dec.arm.next_reg_in_acc;
pd->dec.next_state.in_delay_slot = pd->dec.native.next_in_delay_slot;
pd->dec.next_state.follow_delay_pc = pd->dec.native.next_follow_delay_pc;
pd->dec.next_state.delay_pc = pd->dec.native.next_delay_pc;
pd->dec.next_state.extended_immediate = pd->dec.native.next_extended_immediate;
pd->dec.next_state.extended_cmd.extended = pd->dec.native.next_extended_cmd.extended;
pd->dec.next_state.extended_rd = pd->dec.native.next_extended_rd;
pd->dec.next_state.extended_rn = pd->dec.native.next_extended_rn;
pd->dec.next_state.extended_rm = pd->dec.native.next_extended_rm;
pd->dec.next_state.in_conditional_shadow = 0;
pd->dec.next_state.in_immediate_shadow = 0;
if (pd->dec.native.next_in_immediate_shadow)
{
pd->dec.next_state.in_conditional_shadow = 1;
pd->dec.next_state.in_immediate_shadow = 1;
}
if ( (pd->dec.state.in_immediate_shadow) && (pd->cp_trail_2) )
{
pd->dec.next_state.in_conditional_shadow = 1;
}
}
if (pd->gip_pipeline_results.write_pc)
{
pd->dec.next_state.pc = pd->gip_pipeline_results.rfw_data;
pd->dec.next_state.pc_valid = 1;
}
if (pd->gip_pipeline_results.flush)
{
pd->dec.next_state.cycle_of_opcode=0;
pd->dec.next_state.pc_valid = pd->gip_pipeline_results.write_pc;
pd->dec.next_state.acc_valid = 0;
pd->dec.next_state.in_conditional_shadow = 0;
pd->dec.next_state.extended_immediate = 0;
pd->dec.next_state.extended_cmd.extended = 0;
pd->dec.next_state.extended_rd.type = gip_ins_r_type_no_override;
pd->dec.next_state.extended_rn.type = gip_ins_r_type_no_override;
pd->dec.next_state.extended_rm.type = gip_ins_r_type_no_override;
}
break;
/*b Preempt - NOT WRITTEN YET
*/
case gip_dec_op_state_preempt:
break;
/*b All done
*/
}
pd->dec.next_state.fetch_requested=0;
if (pd->dec.next_state.cycle_of_opcode==0)
{
pd->dec.next_state.fetch_requested=1;
}
}
/*f c_gip_full::dec_clock
*/
void c_gip_full::dec_clock( void )
{
/*b Debug
*/
if (pd->verbose)
{
char buffer[256];
disassemble_int_instruction( pd->dec.inst_valid, &pd->dec.inst, buffer, sizeof(buffer) );
printf( "\t**:DEC %08x(%d)/%08x (ARM c %d ACC %d/%02d)\t:\t... %s\n",
pd->dec.state.pc,
pd->dec.state.pc_valid,
pd->dec.state.opcode,
pd->dec.state.cycle_of_opcode,
pd->dec.state.acc_valid,
pd->dec.state.reg_in_acc,
buffer
);
}
/*b Handle simulation debug instructions
*/
if ( (pd->rf.accepting_dec_instruction) ||
(pd->rf.accepting_dec_instruction_if_alu_does && pd->alu.accepting_rf_instruction) )
{
if ( (pd->dec.state.pc_valid) &&
((pd->dec.state.opcode&0xff000000)==0xf0000000) )
{
switch (pd->dec.state.opcode&0xff)
{
case 0x90:
printf( "********************************************************************************\nTest passed\n********************************************************************************\n\n");
break;
case 0x91:
printf( "********************************************************************************\n--------------------------------------------------------------------------------\nTest failed\n--------------------------------------------------------------------------------\n\n");
break;
case 0xa0:
char buffer[256];
pd->memory->copy_string( buffer, pd->rf.state.regs[0], sizeof(buffer) );
printf( buffer, pd->rf.state.regs[1], pd->rf.state.regs[2], pd->rf.state.regs[3] );
break;
case 0xa1:
printf( "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nDump regs\n");
debug(-1);
break;
case 0xa2:
printf( "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nVerbose on\n");
pd->verbose = 1;
break;
case 0xa3:
printf( "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nVerbose off\n");
pd->verbose = 0;
break;
}
}
}
/*b Copy current to next
*/
memcpy( &pd->dec.state, &pd->dec.next_state, sizeof(pd->dec.state) );
}
/*a Register file operation
*/
/*f rf_read_int_register
*/
static unsigned int rf_read_int_register( t_gip_rf_data *rf, unsigned int pc, t_gip_ins_r r )
{
/*b Simple forwarding path through register file, or read register file itself
*/
if (r.type==gip_ins_r_type_register)
{
if ( (rf->state.mem_rd.type==gip_ins_r_type_register) &&
(r.data.r==rf->state.mem_rd.data.r) )
{
return rf->state.mem_result;
}
if ( (rf->state.alu_rd.type==gip_ins_r_type_register) &&
(r.data.r==rf->state.alu_rd.data.r) )
{
return rf->state.use_shifter ? rf->state.shf_result : rf->state.alu_result;
}
return rf->state.regs[r.data.r&0x1f];
}
/*b For internal results give the PC - other possibles are ACC and SHF, which will be replaced in ALU stage anyway
*/
return pc;
}
/*f c_gip_full::rf_comb
*/
void c_gip_full::rf_comb( t_gip_pipeline_results *results )
{
/*b Determine whether to accept another instruction from decode
*/
pd->rf.accepting_dec_instruction = 0;
pd->rf.accepting_dec_instruction_if_alu_does = 0;
if (pd->rf.state.inst_valid)
{
pd->rf.accepting_dec_instruction_if_alu_does = 1;
if (pd->rf.state.inst.gip_ins_rn.type==gip_ins_r_type_register)
{
if ( pd->alu.state.inst_valid &&
(pd->alu.state.inst.gip_ins_rd.type==gip_ins_r_type_register) &&
(pd->rf.state.inst.gip_ins_rn.data.r==pd->alu.state.inst.gip_ins_rd.data.r) )
{
pd->rf.accepting_dec_instruction_if_alu_does = 0;
}
if ( (pd->mem.state.mem_rd.type==gip_ins_r_type_register) &&
(pd->rf.state.inst.gip_ins_rn.data.r==pd->mem.state.mem_rd.data.r) )
{
pd->rf.accepting_dec_instruction_if_alu_does = 0;
}
if ( (pd->rf.state.mem_rd.type!=gip_ins_r_type_none) &&
(pd->rf.state.alu_rd.type==gip_ins_r_type_register) &&
(pd->rf.state.inst.gip_ins_rn.data.r==pd->rf.state.alu_rd.data.r) )
{
pd->rf.accepting_dec_instruction_if_alu_does = 0;
}
}
if (pd->rf.state.inst.rm_data.gip_ins_rm.type==gip_ins_r_type_register)
{
if ( pd->alu.state.inst_valid &&
(pd->alu.state.inst.gip_ins_rd.type==gip_ins_r_type_register) &&
(pd->rf.state.inst.rm_data.gip_ins_rm.data.r==pd->alu.state.inst.gip_ins_rd.data.r) )
{
pd->rf.accepting_dec_instruction_if_alu_does = 0;
}
if ( (pd->mem.state.mem_rd.type==gip_ins_r_type_register) &&
(pd->rf.state.inst.rm_data.gip_ins_rm.data.r==pd->mem.state.mem_rd.data.r) )
{
pd->rf.accepting_dec_instruction_if_alu_does = 0;
}
if ( (pd->rf.state.mem_rd.type!=gip_ins_r_type_none) &&
(pd->rf.state.alu_rd.type==gip_ins_r_type_register) &&
(pd->rf.state.inst.rm_data.gip_ins_rm.data.r==pd->rf.state.alu_rd.data.r) )
{
pd->rf.accepting_dec_instruction_if_alu_does = 0;
}
}
}
else
{
pd->rf.accepting_dec_instruction = 1;
}
/*b If a deschedule then execute IF condition passed UNLESS flushing in ALU stage OR ALU is not taking instruction
the instruction should not be in the pipeline at this stage if there is any other earlier instruction writing
the PC. This will be true in general as instructions that write the PC will cause a flush. However, a
deschedule in the shadow of a branch (in a delay slot particularly) would not be flushed.
*/
printf("decode handles deschedule - if condition passed unless flushing in ALU stage or ALU is not taking instructoin; must not be here if any previous instruction is writing PC\n");
/*b Read the register file
*/
pd->rf.read_port_0 = rf_read_int_register( &pd->rf, pd->rf.state.inst.pc, pd->rf.state.inst.gip_ins_rn ); // Read register, with forwarding
pd->rf.read_port_1 = rf_read_int_register( &pd->rf, pd->rf.state.inst.pc, pd->rf.state.inst.rm_data.gip_ins_rm ); // Read register, with forwarding
/*b Read the special and postbus data
*/
pd->rf.postbus_read = 0;
pd->rf.postbus_read_address = pd->rf.state.inst.gip_ins_rn.data.r;
pd->rf.special_read = 0;
pd->rf.special_read_address = pd->rf.state.inst.gip_ins_rn.data.r;
switch (pd->rf.state.inst.gip_ins_rn.type)
{
case gip_ins_r_type_postbus:
pd->rf.postbus_read = 1;
pd->rf.postbus_read_address = pd->rf.state.inst.gip_ins_rn.data.r;
break;
case gip_ins_r_type_special:
pd->rf.special_read = 1;
pd->rf.special_read_address = pd->rf.state.inst.gip_ins_rn.data.r;
break;
default:
break;
}
switch (pd->rf.state.inst.rm_data.gip_ins_rm.type)
{
case gip_ins_r_type_postbus:
pd->rf.postbus_read = 1;
pd->rf.postbus_read_address |= pd->rf.state.inst.rm_data.gip_ins_rm.data.r;
break;
case gip_ins_r_type_special:
pd->rf.special_read = 1;
pd->rf.special_read_address |= pd->rf.state.inst.rm_data.gip_ins_rm.data.r;
break;
default:
break;
}
/*b Call the postbus and special register combinatorial functions!
*/
postbus_comb( pd->rf.postbus_read, pd->rf.postbus_read_address, &pd->rf.postbus_read_data );
special_comb( pd->rf.special_read, pd->rf.special_read_address, &pd->rf.special_read_data );
/*b Multiplex the read data - can only be done once special, postbus and periph comb functions are called, so we have called them!
*/
switch (pd->rf.state.inst.gip_ins_rn.type)
{
case gip_ins_r_type_special:
pd->rf.port_0_data = pd->rf.postbus_read_data;
break;
case gip_ins_r_type_postbus:
pd->rf.port_0_data = pd->rf.special_read_data;
break;
default:
pd->rf.port_0_data = pd->rf.read_port_0;
break;
}
switch (pd->rf.state.inst.rm_data.gip_ins_rm.type)
{
case gip_ins_r_type_special:
pd->rf.port_1_data = pd->rf.postbus_read_data;
break;
case gip_ins_r_type_postbus:
pd->rf.port_1_data = pd->rf.special_read_data;
break;
default:
pd->rf.port_1_data = pd->rf.read_port_1;
break;
}
/*b Register file writeback
*/
pd->rf.rfw_data = pd->rf.state.use_shifter ? pd->rf.state.shf_result : pd->rf.state.alu_result;
results->write_pc = 0;
pd->rf.rd = pd->rf.state.alu_rd;
if (pd->rf.state.mem_rd.type!=gip_ins_r_type_none)
{
pd->rf.rd = pd->rf.state.mem_rd;
pd->rf.rfw_data = pd->rf.state.mem_result;
}
if ( (pd->rf.rd.type==gip_ins_r_type_internal) &&
(pd->rf.rd.data.rd_internal==gip_ins_rd_int_pc) )
{
results->write_pc = 1;
}
results->rfw_data = pd->rf.rfw_data;
}
/*f c_gip_full::rf_preclock
*/
void c_gip_full::rf_preclock( void )
{
/*b Copy current to next
*/
memcpy( &pd->rf.next_state, &pd->rf.state, sizeof(pd->rf.state) );
/*b Pipeline instruction for RF read stage
*/
if ( (pd->rf.accepting_dec_instruction) ||
(pd->rf.accepting_dec_instruction_if_alu_does && pd->alu.accepting_rf_instruction) )
{
pd->rf.next_state.inst = pd->dec.inst;
pd->rf.next_state.inst_valid = pd->dec.inst_valid;
if (pd->gip_pipeline_results.flush)
{
pd->rf.next_state.inst_valid = 0;
}
}
else // Not willing to take another instruction; we must have one on hold - flush if asked AND if it is not 'D'
{
if ( pd->gip_pipeline_results.flush && !pd->rf.state.inst.d )
{
pd->rf.next_state.inst_valid = 0;
}
}
/*b Record RFW stage results for the write stage
*/
if (pd->rf.state.accepting_alu_rd)
{
pd->rf.next_state.alu_rd = pd->alu.alu_rd;
pd->rf.next_state.alu_result = pd->alu.alu_result;
pd->rf.next_state.use_shifter = pd->alu.use_shifter;
pd->rf.next_state.shf_result = pd->alu.shf_result;
}
pd->rf.next_state.mem_rd = pd->mem.state.mem_rd;
pd->rf.next_state.mem_result = pd->mem.mem_result;
pd->rf.next_state.accepting_alu_rd = 0;
if (pd->rf.next_state.alu_rd.type==gip_ins_r_type_none)
{
pd->rf.next_state.accepting_alu_rd = 1;
}
if (pd->rf.next_state.mem_rd.type==gip_ins_r_type_none)
{
pd->rf.next_state.accepting_alu_rd = 1;
}
/*b Register file writeback operation
*/
pd->rf.postbus_write = 0;
pd->rf.special_write = 0;
switch (pd->rf.rd.type)
{
case gip_ins_r_type_register:
pd->rf.next_state.regs[ pd->rf.rd.data.r&0x1f ] = pd->rf.rfw_data;
break;
case gip_ins_r_type_special:
pd->rf.special_write = 1;
break;
case gip_ins_r_type_postbus:
pd->rf.postbus_write = 1;
break;
default:
break;
}
/*b Call the postbus and special register preclocks
*/
postbus_preclock( pd->gip_pipeline_results.flush, pd->rf.postbus_read, pd->rf.postbus_read_address, pd->rf.postbus_write, pd->rf.rd.data.r, pd->rf.rfw_data );
special_preclock( pd->gip_pipeline_results.flush, pd->rf.special_read, pd->rf.special_read_address, pd->rf.special_write, pd->rf.rd.data.r, pd->rf.rfw_data );
}
/*f c_gip_full::rf_clock
*/
void c_gip_full::rf_clock( void )
{
/*b Debug
*/
if (pd->verbose)
{
char buffer[256];
disassemble_int_instruction( pd->rf.state.inst_valid, &pd->rf.state.inst, buffer, sizeof(buffer) );
printf( "\t**:RFR IV %d P0 (%d/%02x) %08x P1 (%d/%02x) %08x Rd %d/%02x\t:\t...%s\n",
pd->rf.state.inst_valid,
pd->rf.state.inst.gip_ins_rn.type,
pd->rf.state.inst.gip_ins_rn.data.r,
pd->rf.read_port_0,
pd->rf.state.inst.rm_data.gip_ins_rm.type,
pd->rf.state.inst.rm_data.gip_ins_rm.data.r,
pd->rf.read_port_1,
pd->rf.state.inst.gip_ins_rd.type,
pd->rf.state.inst.gip_ins_rd.data.r,
buffer
);
printf("\t**:RFW ALU %d/%02x %08x SHF %d/%08x MEM %d/%02x %08x\n",
pd->rf.state.alu_rd.type,
pd->rf.state.alu_rd.data.r,
pd->rf.state.alu_result,
pd->rf.state.use_shifter,
pd->rf.state.shf_result,
pd->rf.state.mem_rd.type,
pd->rf.state.mem_rd.data.r,
pd->rf.state.mem_result );
}
/*b Copy next to current
*/
memcpy( &pd->rf.state, &pd->rf.next_state, sizeof(pd->rf.state) );
/*b Clock postbs and special
*/
postbus_clock( );
special_clock( );
}
/*a ALU methods
*/
/*f c_gip_full::alu_comb
*/
void c_gip_full::alu_comb( t_gip_pipeline_results *results )
{
int writes_conditional;
int conditional_result;
/*b Evaluate condition associated with the instruction - simultaneous with ALU stage, blocks all results from instruction if it fails
*/
pd->alu.condition_passed = 0;
if (pd->alu.state.inst_valid)
{
pd->alu.condition_passed = is_condition_met( pd, &pd->alu, pd->alu.state.inst.gip_ins_cc );
}
/*b Get values for ALU operands
*/
pd->alu.op1_src = gip_alu_op1_src_a_in;
if ( (pd->alu.state.inst.gip_ins_rn.type==gip_ins_r_type_internal) &&
(pd->alu.state.inst.gip_ins_rn.data.rnm_internal==gip_ins_rnm_int_acc) )
{
pd->alu.op1_src = gip_alu_op1_src_acc;
}
if (pd->alu.state.inst.rm_is_imm)
{
pd->alu.op2_src = gip_alu_op2_src_b_in;
}
else
{
pd->alu.op2_src = gip_alu_op2_src_b_in;
if ( (pd->alu.state.inst.rm_data.gip_ins_rm.type==gip_ins_r_type_internal) &&
(pd->alu.state.inst.rm_data.gip_ins_rm.data.rnm_internal==gip_ins_rnm_int_acc) )
{
pd->alu.op2_src = gip_alu_op2_src_acc;
}
if ( (pd->alu.state.inst.rm_data.gip_ins_rm.type==gip_ins_r_type_internal) &&
(pd->alu.state.inst.rm_data.gip_ins_rm.data.rnm_internal==gip_ins_rnm_int_shf) )
{
pd->alu.op2_src = gip_alu_op2_src_shf;
}
}
/*b Determine which flags and accumulator to set, and the ALU operation
*/
pd->alu.set_zcvn = 0;
pd->alu.set_p = 0;
pd->alu.set_acc = pd->alu.state.inst.a;
pd->alu.use_shifter = 0;
pd->alu.gip_alu_op = gip_alu_op_add;
switch (pd->alu.state.inst.gip_ins_class)
{
case gip_ins_class_arith:
pd->alu.set_zcvn = pd->alu.state.inst.gip_ins_opts.alu.s;
pd->alu.set_p = pd->alu.state.inst.gip_ins_opts.alu.p;
switch (pd->alu.state.inst.gip_ins_subclass)
{
case gip_ins_subclass_arith_add:
pd->alu.gip_alu_op = gip_alu_op_add;
break;
case gip_ins_subclass_arith_adc:
pd->alu.gip_alu_op = gip_alu_op_adc;
break;
case gip_ins_subclass_arith_sub:
pd->alu.gip_alu_op = gip_alu_op_sub;
break;
case gip_ins_subclass_arith_sbc:
pd->alu.gip_alu_op = gip_alu_op_sbc;
break;
case gip_ins_subclass_arith_rsb:
pd->alu.gip_alu_op = gip_alu_op_rsub;
break;
case gip_ins_subclass_arith_rsc:
pd->alu.gip_alu_op = gip_alu_op_rsbc;
break;
case gip_ins_subclass_arith_init:
pd->alu.gip_alu_op = gip_alu_op_init;
break;
case gip_ins_subclass_arith_mla:
pd->alu.gip_alu_op = gip_alu_op_mla;
break;
case gip_ins_subclass_arith_mlb:
pd->alu.gip_alu_op = gip_alu_op_mlb;
break;
default:
break;
}
break;
case gip_ins_class_logic:
pd->alu.set_zcvn = pd->alu.state.inst.gip_ins_opts.alu.s;
pd->alu.set_p = pd->alu.state.inst.gip_ins_opts.alu.p;
switch (pd->alu.state.inst.gip_ins_subclass)
{
case gip_ins_subclass_logic_and:
pd->alu.gip_alu_op = gip_alu_op_and;
break;
case gip_ins_subclass_logic_or:
pd->alu.gip_alu_op = gip_alu_op_or;
break;
case gip_ins_subclass_logic_xor:
pd->alu.gip_alu_op = gip_alu_op_xor;
break;
case gip_ins_subclass_logic_bic:
pd->alu.gip_alu_op = gip_alu_op_bic;
break;
case gip_ins_subclass_logic_orn:
pd->alu.gip_alu_op = gip_alu_op_orn;
break;
case gip_ins_subclass_logic_mov:
pd->alu.gip_alu_op = gip_alu_op_mov;
break;
case gip_ins_subclass_logic_mvn:
pd->alu.gip_alu_op = gip_alu_op_mvn;
break;
case gip_ins_subclass_logic_andcnt:
pd->alu.gip_alu_op = gip_alu_op_and_cnt;
break;
case gip_ins_subclass_logic_andxor:
pd->alu.gip_alu_op = gip_alu_op_and_xor;
break;
case gip_ins_subclass_logic_xorfirst:
pd->alu.gip_alu_op = gip_alu_op_xor_first;
break;
case gip_ins_subclass_logic_xorlast:
pd->alu.gip_alu_op = gip_alu_op_xor_last;
break;
case gip_ins_subclass_logic_bitreverse:
pd->alu.gip_alu_op = gip_alu_op_bit_reverse;
break;
case gip_ins_subclass_logic_bytereverse:
pd->alu.gip_alu_op = gip_alu_op_byte_reverse;
break;
default:
break;
}
break;
case gip_ins_class_shift:
pd->alu.set_zcvn = pd->alu.state.inst.gip_ins_opts.alu.s;
pd->alu.set_p = 0;
pd->alu.use_shifter = 1;
switch (pd->alu.state.inst.gip_ins_subclass)
{
case gip_ins_subclass_shift_lsl:
pd->alu.gip_alu_op = gip_alu_op_lsl;
break;
case gip_ins_subclass_shift_lsr:
pd->alu.gip_alu_op = gip_alu_op_lsr;
break;
case gip_ins_subclass_shift_asr:
pd->alu.gip_alu_op = gip_alu_op_asr;
break;
case gip_ins_subclass_shift_ror:
pd->alu.gip_alu_op = gip_alu_op_ror;
break;
case gip_ins_subclass_shift_ror33:
pd->alu.gip_alu_op = gip_alu_op_ror33;
break;
default:
break;
}
break;
case gip_ins_class_load:
if ((pd->alu.state.inst.gip_ins_subclass & gip_ins_subclass_memory_dirn)==gip_ins_subclass_memory_up)
{
pd->alu.gip_alu_op = gip_alu_op_add;
}
else
{
pd->alu.gip_alu_op = gip_alu_op_sub;
}
break;
case gip_ins_class_store:
if ((pd->alu.state.inst.gip_ins_subclass & gip_ins_subclass_memory_dirn)==gip_ins_subclass_memory_up)
{
pd->alu.gip_alu_op = gip_alu_op_add;
}
else
{
pd->alu.gip_alu_op = gip_alu_op_sub;
}
switch (pd->alu.state.inst.gip_ins_subclass & gip_ins_subclass_memory_size)
{
case gip_ins_subclass_memory_word:
pd->alu.alu_constant = 4;
break;
case gip_ins_subclass_memory_half:
pd->alu.alu_constant = 2;
break;
case gip_ins_subclass_memory_byte:
pd->alu.alu_constant = 1;
break;
default:
pd->alu.alu_constant = 0;
break;
}
if (pd->alu.state.inst.gip_ins_opts.store.offset_type==1)
{
pd->alu.op2_src = gip_alu_op2_src_shf;
}
else
{
pd->alu.op2_src = gip_alu_op2_src_constant;
}
break;
}
if (!pd->alu.condition_passed)
{
pd->alu.set_acc = 0;
pd->alu.set_zcvn = 0;
pd->alu.set_p = 0;
}
/*b Determine inputs to the shifter and ALU
*/
switch (pd->alu.op1_src)
{
case gip_alu_op1_src_a_in:
pd->alu.alu_op1 = pd->alu.state.alu_a_in;
break;
case gip_alu_op1_src_acc:
pd->alu.alu_op1 = pd->alu.state.acc;
break;
}
switch (pd->alu.op2_src)
{
case gip_alu_op2_src_b_in:
pd->alu.alu_op2 = pd->alu.state.alu_b_in;
break;
case gip_alu_op2_src_acc:
pd->alu.alu_op2 = pd->alu.state.acc;
break;
case gip_alu_op2_src_shf:
pd->alu.alu_op2 = pd->alu.state.shf;
break;
case gip_alu_op2_src_constant:
pd->alu.alu_op2 = pd->alu.alu_constant;
break;
}
/*b Perform shifter operation - operates on C, ALU A in, ALU B in: what about accumulator?
*/
switch (pd->alu.gip_alu_op)
{
case gip_alu_op_lsl:
pd->alu.shf_result = barrel_shift( pd->alu.state.c, shf_type_lsl, pd->alu.alu_op1, pd->alu.alu_op2, &pd->alu.shf_carry );
break;
case gip_alu_op_lsr:
pd->alu.shf_result = barrel_shift( pd->alu.state.c, shf_type_lsr, pd->alu.alu_op1, pd->alu.alu_op2, &pd->alu.shf_carry );
break;
case gip_alu_op_asr:
pd->alu.shf_result = barrel_shift( pd->alu.state.c, shf_type_asr, pd->alu.alu_op1, pd->alu.alu_op2, &pd->alu.shf_carry );
break;
case gip_alu_op_ror:
pd->alu.shf_result = barrel_shift( pd->alu.state.c, shf_type_ror, pd->alu.alu_op1, pd->alu.alu_op2, &pd->alu.shf_carry );
break;
case gip_alu_op_ror33:
pd->alu.shf_result = barrel_shift( pd->alu.state.c, shf_type_rrx, pd->alu.alu_op1, pd->alu.alu_op2, &pd->alu.shf_carry );
break;
case gip_alu_op_init:
pd->alu.shf_result = barrel_shift( 0&pd->alu.state.c, shf_type_lsr, pd->alu.alu_op1, 0, &pd->alu.shf_carry );
break;
case gip_alu_op_mla:
case gip_alu_op_mlb:
pd->alu.shf_result = barrel_shift( pd->alu.state.c, shf_type_lsr, pd->alu.state.shf, 2, &pd->alu.shf_carry );
break;
case gip_alu_op_divst:
break;
default:
break;
}
/*b Perform logical operation - operates on ALU op 1 and ALU op 2
*/
switch (pd->alu.gip_alu_op)
{
case gip_alu_op_mov:
pd->alu.logic_result = pd->alu.alu_op2;
break;
case gip_alu_op_mvn:
pd->alu.logic_result = ~pd->alu.alu_op2;
break;
case gip_alu_op_and:
pd->alu.logic_result = pd->alu.alu_op1 & pd->alu.alu_op2;
break;
case gip_alu_op_or:
pd->alu.logic_result = pd->alu.alu_op1 | pd->alu.alu_op2;
break;
case gip_alu_op_xor:
pd->alu.logic_result = pd->alu.alu_op1 ^ pd->alu.alu_op2;
break;
case gip_alu_op_bic:
pd->alu.logic_result = pd->alu.alu_op1 &~ pd->alu.alu_op2;
break;
case gip_alu_op_orn:
pd->alu.logic_result = pd->alu.alu_op1 |~ pd->alu.alu_op2;
break;
case gip_alu_op_and_cnt:
pd->alu.logic_result = bit_count(pd->alu.alu_op1 & pd->alu.alu_op2);
break;
case gip_alu_op_and_xor:
pd->alu.logic_result = (pd->alu.alu_op1 & pd->alu.alu_op2) ^ pd->alu.alu_op2;
break;
case gip_alu_op_xor_first:
pd->alu.logic_result = find_bit_set(pd->alu.alu_op1 ^ pd->alu.alu_op2, -1);
break;
case gip_alu_op_xor_last:
pd->alu.logic_result = find_bit_set(pd->alu.alu_op1 ^ pd->alu.alu_op2, 1);
break;
case gip_alu_op_bit_reverse:
pd->alu.logic_result = ( (pd->alu.alu_op2&0xffffff00) |
((pd->alu.alu_op2&0x00000080)>>7) |
((pd->alu.alu_op2&0x00000040)>>5) |
((pd->alu.alu_op2&0x00000020)>>3) |
((pd->alu.alu_op2&0x00000010)>>1) |
((pd->alu.alu_op2&0x00000008)<<1) |
((pd->alu.alu_op2&0x00000004)<<3) |
((pd->alu.alu_op2&0x00000002)<<5) |
((pd->alu.alu_op2&0x00000001)<<7) );
break;
case gip_alu_op_byte_reverse:
pd->alu.logic_result = ( ((pd->alu.alu_op2&0x000000ff)<<24) |
((pd->alu.alu_op2&0x0000ff00)<<8) |
((pd->alu.alu_op2&0x00ff0000)>>8) |
((pd->alu.alu_op2&0xff000000)>>24) );
break;
case gip_alu_op_init:
case gip_alu_op_mla:
case gip_alu_op_mlb:
case gip_alu_op_divst:
break;
default:
break;
}
pd->alu.logic_z = (pd->alu.logic_result==0);
pd->alu.logic_n = ((pd->alu.logic_result&0x80000000)!=0);
/*b Perform arithmetic operation - operates on C, ALU op 1 and ALU op 2
*/
switch (pd->alu.gip_alu_op)
{
case gip_alu_op_add:
pd->alu.arith_result = add_op( pd->alu.alu_op1, pd->alu.alu_op2, 0, &pd->alu.alu_c, &pd->alu.alu_v );
break;
case gip_alu_op_adc:
pd->alu.arith_result = add_op( pd->alu.alu_op1, pd->alu.alu_op2, pd->alu.state.c, &pd->alu.alu_c, &pd->alu.alu_v );
break;
case gip_alu_op_sub:
pd->alu.arith_result = add_op( pd->alu.alu_op1, ~pd->alu.alu_op2, 1, &pd->alu.alu_c, &pd->alu.alu_v );
break;
case gip_alu_op_sbc:
pd->alu.arith_result = add_op( pd->alu.alu_op1, ~pd->alu.alu_op2, pd->alu.state.c, &pd->alu.alu_c, &pd->alu.alu_v );
break;
case gip_alu_op_rsub:
pd->alu.arith_result = add_op( ~pd->alu.alu_op1, pd->alu.alu_op2, 1, &pd->alu.alu_c, &pd->alu.alu_v );
break;
case gip_alu_op_rsbc:
pd->alu.arith_result = add_op( ~pd->alu.alu_op1, pd->alu.alu_op2, pd->alu.state.c, &pd->alu.alu_c, &pd->alu.alu_v );
break;
case gip_alu_op_init:
pd->alu.arith_result = add_op( 0&pd->alu.alu_op1, pd->alu.alu_op2, 0, &pd->alu.alu_c, &pd->alu.alu_v );
break;
case gip_alu_op_mla:
case gip_alu_op_mlb:
switch ((pd->alu.state.shf&3)+pd->alu.state.p)
{
case 0:
pd->alu.arith_result = add_op( pd->alu.alu_op1, 0&pd->alu.alu_op2, 0, &pd->alu.alu_c, &pd->alu.alu_v );
pd->alu.shf_carry = 0;
break;
case 1:
pd->alu.arith_result = add_op( pd->alu.alu_op1, pd->alu.alu_op2, 0, &pd->alu.alu_c, &pd->alu.alu_v );
pd->alu.shf_carry = 0;
break;
case 2:
pd->alu.arith_result = add_op( pd->alu.alu_op1, pd->alu.alu_op2<<1, 0, &pd->alu.alu_c, &pd->alu.alu_v );
pd->alu.shf_carry = 0;
break;
case 3:
pd->alu.arith_result = add_op( pd->alu.alu_op1, ~pd->alu.alu_op2, 1, &pd->alu.alu_c, &pd->alu.alu_v );
pd->alu.shf_carry = 1;
break;
case 4:
pd->alu.arith_result = add_op( pd->alu.alu_op1, 0&pd->alu.alu_op2, 0, &pd->alu.alu_c, &pd->alu.alu_v );
pd->alu.shf_carry = 1;
break;
}
break;
case gip_alu_op_divst:
break;
default:
break;
}
pd->alu.alu_z = (pd->alu.arith_result==0);
pd->alu.alu_n = ((pd->alu.arith_result&0x80000000)!=0);
/*b Determine ALU result, next accumulator, next shifter and next flags
*/
pd->alu.next_acc = pd->alu.state.acc;
pd->alu.next_c = pd->alu.state.c;
pd->alu.next_z = pd->alu.state.z;
pd->alu.next_v = pd->alu.state.v;
pd->alu.next_n = pd->alu.state.n;
pd->alu.next_p = pd->alu.state.p;
pd->alu.next_shf = pd->alu.state.shf;
switch (pd->alu.gip_alu_op)
{
case gip_alu_op_mov:
case gip_alu_op_mvn:
case gip_alu_op_and:
case gip_alu_op_or:
case gip_alu_op_xor:
case gip_alu_op_bic:
case gip_alu_op_orn:
case gip_alu_op_and_cnt:
case gip_alu_op_and_xor:
case gip_alu_op_xor_first:
case gip_alu_op_xor_last:
case gip_alu_op_bit_reverse:
case gip_alu_op_byte_reverse:
pd->alu.alu_result = pd->alu.logic_result;
if (pd->alu.set_p)
{
pd->alu.next_c = pd->alu.state.p;
}
if (pd->alu.set_zcvn)
{
pd->alu.next_z = pd->alu.logic_z;
pd->alu.next_n = pd->alu.logic_n;
}
if (pd->alu.set_acc)
{
pd->alu.next_acc = pd->alu.logic_result;
}
break;
case gip_alu_op_add:
case gip_alu_op_adc:
case gip_alu_op_sub:
case gip_alu_op_sbc:
case gip_alu_op_rsub:
case gip_alu_op_rsbc:
pd->alu.alu_result = pd->alu.arith_result;
if (pd->alu.set_zcvn)
{
pd->alu.next_z = pd->alu.alu_z;
pd->alu.next_n = pd->alu.alu_n;
pd->alu.next_c = pd->alu.alu_c;
pd->alu.next_v = pd->alu.alu_v;
}
if (pd->alu.set_acc)
{
pd->alu.next_acc = pd->alu.arith_result;
}
pd->alu.next_shf = 0;// should only be with the 'C' flag, but have not defined that yet
break;
case gip_alu_op_init:
case gip_alu_op_mla:
case gip_alu_op_mlb:
pd->alu.alu_result = pd->alu.arith_result;
if (pd->alu.set_zcvn)
{
pd->alu.next_z = (pd->alu.arith_result==0);
pd->alu.next_n = ((pd->alu.arith_result&0x80000000)!=0);
pd->alu.next_c = pd->alu.alu_c;
pd->alu.next_v = pd->alu.alu_v;
}
if (pd->alu.set_acc)
{
pd->alu.next_acc = pd->alu.arith_result;
}
pd->alu.next_shf = pd->alu.shf_result;
pd->alu.next_p = pd->alu.shf_carry;
break;
case gip_alu_op_lsl:
case gip_alu_op_lsr:
case gip_alu_op_asr:
case gip_alu_op_ror:
case gip_alu_op_ror33:
if (pd->alu.set_zcvn)
{
pd->alu.next_z = (pd->alu.shf_result==0);
pd->alu.next_n = ((pd->alu.shf_result&0x80000000)!=0);
pd->alu.next_c = pd->alu.shf_carry;
}
pd->alu.next_shf = pd->alu.shf_result;
pd->alu.next_p = pd->alu.shf_carry;
break;
case gip_alu_op_divst:
break;
}
/*b Determine 'cp' and 'old_cp' state
*/
writes_conditional = 0;
if (pd->alu.state.inst.gip_ins_rd.type == gip_ins_r_type_internal)
{
switch (pd->alu.state.inst.gip_ins_rd.data.rd_internal)
{
case gip_ins_rd_int_eq:
conditional_result = pd->alu.alu_z;
writes_conditional = 1;
break;
case gip_ins_rd_int_ne:
conditional_result = !pd->alu.alu_z;
writes_conditional = 1;
break;
case gip_ins_rd_int_cs:
conditional_result = pd->alu.alu_c;
writes_conditional = 1;
break;
case gip_ins_rd_int_cc:
conditional_result = !pd->alu.alu_c;
writes_conditional = 1;
break;
case gip_ins_rd_int_hi:
conditional_result = pd->alu.alu_c && !pd->alu.alu_z;
writes_conditional = 1;
break;
case gip_ins_rd_int_ls:
conditional_result = !pd->alu.alu_c || pd->alu.alu_z;
writes_conditional = 1;
break;
case gip_ins_rd_int_ge:
conditional_result = (!pd->alu.alu_n && !pd->alu.alu_v) || (pd->alu.alu_n && pd->alu.alu_v);
writes_conditional = 1;
break;
case gip_ins_rd_int_lt:
conditional_result = (!pd->alu.alu_n && pd->alu.alu_v) || (pd->alu.alu_n && !pd->alu.alu_v);
writes_conditional = 1;
break;
case gip_ins_rd_int_gt:
conditional_result = ((!pd->alu.alu_n && !pd->alu.alu_v) || (pd->alu.alu_n && pd->alu.alu_v)) && !pd->alu.alu_z;
writes_conditional = 1;
break;
case gip_ins_rd_int_le:
conditional_result = (!pd->alu.alu_n && pd->alu.alu_v) || (pd->alu.alu_n && !pd->alu.alu_v) || pd->alu.alu_z;
writes_conditional = 1;
break;
default:
break;
}
}
if (writes_conditional)
{
if (pd->alu.condition_passed) // could be first of a sequence, or later on; if first of a sequence, we must set it to our result; if later then condition should be CP for ANDing condition passed
// if ANDing (CP is therefore set) and our result is 1, then the next result is 1; if our result is 0, then the next result is zero; so this is the same as the first condition
{
pd->alu.next_cp = conditional_result;
}
else // must be later in a sequence; condition ought to have been 'CP', so this means 'state.cp' should be zero already. No reason to make it one.
{
pd->alu.next_cp = 0;
}
pd->alu.next_old_cp = 1;
}
else
{
pd->alu.next_cp = pd->alu.condition_passed;
pd->alu.next_old_cp = pd->alu.state.cp;
}
/*b Get inputs to memory stage
*/
pd->alu.mem_address = ((pd->alu.state.inst.gip_ins_subclass & gip_ins_subclass_memory_index)==gip_ins_subclass_memory_preindex)?pd->alu.alu_result:pd->alu.alu_op1;
pd->alu.mem_data_in = pd->alu.state.alu_b_in;
/*b Determine next Rd for the ALU operation, and memory operation, and if the instruction is blocked
*/
pd->alu.alu_rd.type = gip_ins_r_type_none;
pd->alu.mem_rd.type = gip_ins_r_type_none;
pd->alu.gip_mem_op = gip_mem_op_none;
pd->alu.accepting_rf_instruction = 1;
if (pd->alu.condition_passed) // This is zero if instruction is not valid, so no writeback from invalid instructions!
{
switch (pd->alu.state.inst.gip_ins_class)
{
case gip_ins_class_arith:
case gip_ins_class_logic:
case gip_ins_class_shift:
pd->alu.alu_rd = pd->alu.state.inst.gip_ins_rd;
pd->alu.accepting_rf_instruction = pd->rf.state.accepting_alu_rd;
break;
case gip_ins_class_store:
pd->alu.alu_rd = pd->alu.state.inst.gip_ins_rd;
switch (pd->alu.state.inst.gip_ins_subclass & gip_ins_subclass_memory_size)
{
case gip_ins_subclass_memory_word:
pd->alu.gip_mem_op = gip_mem_op_store_word;
break;
case gip_ins_subclass_memory_half:
pd->alu.gip_mem_op = gip_mem_op_store_half;
break;
case gip_ins_subclass_memory_byte:
pd->alu.gip_mem_op = gip_mem_op_store_byte;
break;
default:
break;
}
pd->alu.accepting_rf_instruction = pd->rf.state.accepting_alu_rd && 1; // GJS - ADD MEMORY BLOCK HERE
break;
case gip_ins_class_load:
pd->alu.mem_rd = pd->alu.state.inst.gip_ins_rd;
switch (pd->alu.state.inst.gip_ins_subclass & gip_ins_subclass_memory_size)
{
case gip_ins_subclass_memory_word:
pd->alu.gip_mem_op = gip_mem_op_load_word;
break;
case gip_ins_subclass_memory_half:
pd->alu.gip_mem_op = gip_mem_op_load_half;
break;
case gip_ins_subclass_memory_byte:
pd->alu.gip_mem_op = gip_mem_op_load_byte;
break;
default:
break;
}
pd->alu.accepting_rf_instruction = 1; // GJS - ADD MEMORY BLOCK HERE
break;
}
}
/*b Determine flush output
*/
results->flush = pd->alu.state.inst.f;
if (!pd->alu.condition_passed) // Also kills flush if the instruction is invalid
{
results->flush = 0;
}
if (!pd->alu.accepting_rf_instruction) // Also kill flush if we are blocked for actually completing the instruction
{
results->flush = 0;
}
}
/*f c_gip_full::alu_preclock
*/
void c_gip_full::alu_preclock( void )
{
/*b Copy current to next
*/
memcpy( &pd->alu.next_state, &pd->alu.state, sizeof(pd->alu.state) );
/*b Copy the instruction across
*/
if (pd->alu.accepting_rf_instruction )
{
pd->alu.next_state.inst = pd->rf.state.inst;
pd->alu.next_state.inst_valid = pd->rf.state.inst_valid; // Zero this if it does not mean to proffer the instruction...
if (pd->rf.accepting_dec_instruction_if_alu_does==0)
{
pd->alu.next_state.inst_valid = 0;
}
}
if (pd->gip_pipeline_results.flush)
{
pd->alu.next_state.inst_valid = 0;
}
/*b Select next values for ALU inputs based on execution blocked, or particular ALU operation (multiplies particularly)
*/
if ( (pd->rf.state.inst_valid) &&
!(pd->gip_pipeline_results.flush) &&
pd->alu.accepting_rf_instruction )
{
if ( 0 && (pd->rf.state.inst.gip_ins_class==gip_ins_class_arith) &&
(pd->rf.state.inst.gip_ins_subclass==gip_ins_subclass_arith_mlb) )
{
pd->alu.next_state.alu_a_in = pd->alu.state.alu_a_in;
}
else
{
pd->alu.next_state.alu_a_in = pd->rf.read_port_0;
}
if ( (pd->rf.state.inst.gip_ins_class==gip_ins_class_arith) &&
(pd->rf.state.inst.gip_ins_subclass==gip_ins_subclass_arith_mlb) )
{
pd->alu.next_state.alu_b_in = pd->alu.state.alu_b_in<<2;// An MLB instruction in RF read stage implies shift left by 2; but only if it moves to the ALU stage, which it does here
}
else if (pd->rf.state.inst.rm_is_imm)
{
pd->alu.next_state.alu_b_in = pd->rf.state.inst.rm_data.immediate; // If immediate, pass immediate data in
}
else
{
pd->alu.next_state.alu_b_in = pd->rf.read_port_1; // Else read register/special
}
}
/*b Update ALU result, accumulator, shifter and flags
*/
if ( (pd->alu.accepting_rf_instruction) &&
(pd->alu.state.inst_valid) )
{
pd->alu.next_state.c = pd->alu.next_c;
pd->alu.next_state.z = pd->alu.next_z;
pd->alu.next_state.v = pd->alu.next_v;
pd->alu.next_state.n = pd->alu.next_n;
pd->alu.next_state.p = pd->alu.next_p;
pd->alu.next_state.acc = pd->alu.next_acc;
pd->alu.next_state.shf = pd->alu.next_shf;
}
/*b Record condition passed indications
*/
if ( (pd->alu.accepting_rf_instruction) &&
(pd->alu.state.inst_valid) )
{
pd->alu.next_state.old_cp = pd->alu.next_old_cp;
pd->alu.next_state.cp = pd->alu.next_cp;
}
}
/*f c_gip_full::alu_clock
*/
void c_gip_full::alu_clock( void )
{
/*b Debug
*/
if (pd->verbose)
{
char buffer[256];
disassemble_int_instruction( pd->alu.state.inst_valid, &pd->alu.state.inst, buffer, sizeof(buffer) );
printf( "\t**:ALU OP %d Op1 %08x Op2 %08x CP %d A %08x B %08x R %08x ACC %08x ARd %d/%02x MRd %d/%02x\t:\t...%s\n",
pd->alu.gip_alu_op,
pd->alu.alu_op1,
pd->alu.alu_op2,
pd->alu.condition_passed,
pd->alu.state.alu_a_in,
pd->alu.state.alu_b_in,
pd->alu.alu_result,
pd->alu.state.acc,
pd->alu.alu_rd.type,
pd->alu.alu_rd.data.r,
pd->alu.mem_rd.type,
pd->alu.mem_rd.data.r,
buffer );
}
/*b Copy next to current
*/
memcpy( &pd->alu.state, &pd->alu.next_state, sizeof(pd->alu.state) );
}
/*a Memory stage methods
*/
/*f c_gip_full::mem_comb
*/
void c_gip_full::mem_comb( t_gip_pipeline_results *results )
{
/*b No need to do anything here as the actual combinatorials derive from the previous clock edge - see the clock funcion for that operation
*/
}
/*f c_gip_full::mem_preclock
*/
void c_gip_full::mem_preclock( void )
{
/*b Copy current to next
*/
memcpy( &pd->mem.next_state, &pd->mem.state, sizeof(pd->mem.state) );
/*b Record input state
*/
pd->mem.next_state.mem_rd = pd->alu.mem_rd;
pd->mem.next_state.gip_mem_op = pd->alu.gip_mem_op;
pd->mem.next_state.mem_data_in = pd->alu.mem_data_in;
pd->mem.next_state.mem_address = pd->alu.mem_address;
}
/*f c_gip_full::mem_clock
*/
void c_gip_full::mem_clock( void )
{
int offset_in_word;
unsigned int data;
unsigned int address;
/*b Debug
*/
if (pd->verbose)
{
printf( "\t**:MEM OP %d at %08x with %08x Rd %d/%02x\n",
pd->mem.state.gip_mem_op,
pd->mem.state.mem_address,
pd->mem.state.mem_data_in,
pd->mem.state.mem_rd.type,
pd->mem.state.mem_rd.data.r );
}
/*b Perform a memory write if required
*/
address = pd->mem.state.mem_address;
switch (pd->mem.state.gip_mem_op)
{
case gip_mem_op_store_word:
pd->memory->write_memory( address, pd->mem.state.mem_data_in, 0xf );
break;
case gip_mem_op_store_half:
offset_in_word = address&0x2;
address &= ~2;
pd->memory->write_memory( address, pd->mem.state.mem_data_in<<(8*offset_in_word), 3<<offset_in_word );
break;
case gip_mem_op_store_byte:
offset_in_word = address&0x3;
address &= ~3;
pd->memory->write_memory( address, pd->mem.state.mem_data_in<<(8*offset_in_word), 1<<offset_in_word );
break;
default:
break;
}
/*b Copy next to current
*/
memcpy( &pd->mem.state, &pd->mem.next_state, sizeof(pd->mem.state) );
/*b Perform a memory read if required
*/
address = pd->mem.state.mem_address;
switch (pd->mem.state.gip_mem_op)
{
case gip_mem_op_load_word:
pd->mem.mem_result = pd->memory->read_memory( address );
break;
case gip_mem_op_load_half:
data = pd->memory->read_memory( address );
offset_in_word = address&0x2;
data >>= 8*offset_in_word;
pd->mem.mem_result = data;
break;
case gip_mem_op_load_byte:
data = pd->memory->read_memory( address );
offset_in_word = address&0x3;
data >>= 8*offset_in_word;
pd->mem.mem_result = data;
break;
default:
break;
}
}
/*a Full pipeline methods
*/
/*f c_gip_full::comb
*/
void c_gip_full::comb( void )
{
/*b Combinatorial functions
*/
rf_comb( &pd->gip_pipeline_results );
alu_comb( &pd->gip_pipeline_results );
mem_comb( &pd->gip_pipeline_results );
sched_comb( );
dec_comb( );
}
/*f c_gip_full::preclock
*/
void c_gip_full::preclock( void )
{
/*b Preclock the stages
*/
sched_preclock( );
dec_preclock( );
rf_preclock( );
alu_preclock( );
mem_preclock( );
}
/*f c_gip_full::clock
*/
void c_gip_full::clock( void )
{
if (pd->verbose)
{
debug(6);
}
/*b Clock the stages
*/
sched_clock( );
dec_clock( );
rf_clock( );
alu_clock( );
mem_clock( );
/*b Done
*/
}
/*a Internal instruction building
*/
/*f c_gip_full::build_gip_instruction_nop
*/
void c_gip_full::build_gip_instruction_nop( t_gip_instruction *gip_instr )
{
gip_instr->gip_ins_class = gip_ins_class_logic;
gip_instr->gip_ins_subclass = gip_ins_subclass_logic_mov;
gip_instr->gip_ins_opts.alu.s = 0;
gip_instr->gip_ins_opts.alu.p = 0;
gip_instr->gip_ins_cc = gip_ins_cc_always;
gip_instr->a = 0;
gip_instr->f = 0;
gip_instr->d = 0;
gip_instr->gip_ins_rn.type = gip_ins_r_type_internal;
gip_instr->gip_ins_rn.data.rnm_internal = gip_ins_rnm_int_acc;
gip_instr->rm_is_imm = 1;
gip_instr->rm_data.immediate = 0;
gip_instr->gip_ins_rd.type = gip_ins_r_type_none;
gip_instr->pc = pd->dec.state.pc+8;
}
/*f c_gip_full::build_gip_instruction_alu
*/
void c_gip_full::build_gip_instruction_alu( t_gip_instruction *gip_instr, t_gip_ins_class gip_ins_class, t_gip_ins_subclass gip_ins_subclass, int a, int s, int p, int f )
{
gip_instr->gip_ins_class = gip_ins_class;
gip_instr->gip_ins_subclass = gip_ins_subclass;
gip_instr->gip_ins_opts.alu.s = s;
gip_instr->gip_ins_opts.alu.p = p;
gip_instr->gip_ins_cc = gip_ins_cc_always;
gip_instr->a = a;
gip_instr->f = f;
gip_instr->d = 0;
gip_instr->gip_ins_rn.type = gip_ins_r_type_internal;
gip_instr->gip_ins_rn.data.rnm_internal = gip_ins_rnm_int_acc;
gip_instr->rm_is_imm = 1;
gip_instr->rm_data.immediate = 0;
gip_instr->gip_ins_rd.type = gip_ins_r_type_none;
gip_instr->pc = pd->dec.state.pc+8;
}
/*f c_gip_full::build_gip_instruction_shift
*/
void c_gip_full::build_gip_instruction_shift( t_gip_instruction *gip_instr, t_gip_ins_subclass gip_ins_subclass, int s, int f )
{
gip_instr->gip_ins_class = gip_ins_class_shift;
gip_instr->gip_ins_subclass = gip_ins_subclass;
gip_instr->gip_ins_opts.alu.s = s;
gip_instr->gip_ins_opts.alu.p = 0;
gip_instr->gip_ins_cc = gip_ins_cc_always;
gip_instr->a = 0;
gip_instr->f = f;
gip_instr->d = 0;
gip_instr->gip_ins_rn.type = gip_ins_r_type_internal;
gip_instr->gip_ins_rn.data.rnm_internal = gip_ins_rnm_int_acc;
gip_instr->rm_is_imm = 1;
gip_instr->rm_data.immediate = 0;
gip_instr->gip_ins_rd.type = gip_ins_r_type_none;
gip_instr->pc = pd->dec.state.pc+8;
}
/*f c_gip_full::build_gip_instruction_load
*/
void c_gip_full::build_gip_instruction_load( t_gip_instruction *gip_instr, t_gip_ins_subclass gip_ins_subclass, int preindex, int up, int stack, int burst_left, int a, int f )
{
gip_instr->gip_ins_class = gip_ins_class_load;
if (preindex)
{
gip_ins_subclass = (t_gip_ins_subclass) (gip_ins_subclass | gip_ins_subclass_memory_preindex);
}
else
{
gip_ins_subclass = (t_gip_ins_subclass) (gip_ins_subclass | gip_ins_subclass_memory_postindex);
}
if (up)
{
gip_ins_subclass = (t_gip_ins_subclass) (gip_ins_subclass | gip_ins_subclass_memory_up);
}
else
{
gip_ins_subclass = (t_gip_ins_subclass) (gip_ins_subclass | gip_ins_subclass_memory_down);
}
gip_instr->gip_ins_subclass = gip_ins_subclass;
gip_instr->gip_ins_opts.load.stack = stack;
gip_instr->gip_ins_cc = gip_ins_cc_always;
gip_instr->a = a;
gip_instr->f = f;
gip_instr->d = 0;
gip_instr->k = burst_left;
gip_instr->gip_ins_rn.type = gip_ins_r_type_internal;
gip_instr->gip_ins_rn.data.rnm_internal = gip_ins_rnm_int_acc;
gip_instr->rm_is_imm = 1;
gip_instr->rm_data.immediate = 0;
gip_instr->gip_ins_rd.type = gip_ins_r_type_none;
gip_instr->pc = pd->dec.state.pc+8;
}
/*f c_gip_full::build_gip_instruction_store
*/
void c_gip_full::build_gip_instruction_store( t_gip_instruction *gip_instr, t_gip_ins_subclass gip_ins_subclass, int preindex, int up, int use_shift, int stack, int burst_left, int a, int f )
{
gip_instr->gip_ins_class = gip_ins_class_store;
if (preindex)
{
gip_ins_subclass = (t_gip_ins_subclass) (gip_ins_subclass | gip_ins_subclass_memory_preindex);
}
else
{
gip_ins_subclass = (t_gip_ins_subclass) (gip_ins_subclass | gip_ins_subclass_memory_postindex);
}
if (up)
{
gip_ins_subclass = (t_gip_ins_subclass) (gip_ins_subclass | gip_ins_subclass_memory_up);
}
else
{
gip_ins_subclass = (t_gip_ins_subclass) (gip_ins_subclass | gip_ins_subclass_memory_down);
}
gip_instr->gip_ins_subclass = gip_ins_subclass;
gip_instr->gip_ins_opts.store.stack = stack;
gip_instr->gip_ins_opts.store.offset_type = use_shift;
gip_instr->gip_ins_cc = gip_ins_cc_always;
gip_instr->a = a;
gip_instr->f = f;
gip_instr->d = 0;
gip_instr->k = burst_left;
gip_instr->gip_ins_rn.type = gip_ins_r_type_internal;
gip_instr->gip_ins_rn.data.rnm_internal = gip_ins_rnm_int_acc;
gip_instr->rm_is_imm = 1;
gip_instr->rm_data.immediate = 0;
gip_instr->gip_ins_rd.type = gip_ins_r_type_none;
gip_instr->pc = pd->dec.state.pc+8;
}
/*f c_gip_full::build_gip_instruction_immediate
*/
void c_gip_full::build_gip_instruction_immediate( t_gip_instruction *gip_instr, unsigned int imm_val )
{
gip_instr->rm_is_imm = 1;
gip_instr->rm_data.immediate = imm_val;
}
/*f c_gip_full::build_gip_instruction_cc
*/
void c_gip_full::build_gip_instruction_cc( t_gip_instruction *gip_instr, t_gip_ins_cc gip_ins_cc)
{
gip_instr->gip_ins_cc = gip_ins_cc;
}
/*f c_gip_full::build_gip_instruction_rn
*/
void c_gip_full::build_gip_instruction_rn( t_gip_instruction *gip_instr, t_gip_ins_r gip_ins_rn )
{
gip_instr->gip_ins_rn = gip_ins_rn;
}
/*f c_gip_full::build_gip_instruction_rn_int
*/
void c_gip_full::build_gip_instruction_rn_int( t_gip_instruction *gip_instr, t_gip_ins_rnm_int gip_ins_rn_int )
{
gip_instr->gip_ins_rn.type = gip_ins_r_type_internal;
gip_instr->gip_ins_rn.data.rnm_internal = gip_ins_rn_int;
}
/*f c_gip_full::build_gip_instruction_rm
*/
void c_gip_full::build_gip_instruction_rm( t_gip_instruction *gip_instr, t_gip_ins_r gip_ins_rm )
{
gip_instr->rm_is_imm = 0;
gip_instr->rm_data.gip_ins_rm = gip_ins_rm;
}
/*f c_gip_full::build_gip_instruction_rm_int
*/
void c_gip_full::build_gip_instruction_rm_int( t_gip_instruction *gip_instr, t_gip_ins_rnm_int gip_ins_rm_int )
{
gip_instr->rm_is_imm = 0;
gip_instr->rm_data.gip_ins_rm.type = gip_ins_r_type_internal;
gip_instr->rm_data.gip_ins_rm.data.rnm_internal = gip_ins_rm_int;
}
/*f c_gip_full::build_gip_instruction_rd
*/
void c_gip_full::build_gip_instruction_rd( t_gip_instruction *gip_instr, t_gip_ins_r gip_ins_rd )
{
gip_instr->gip_ins_rd = gip_ins_rd;
}
/*f c_gip_full::build_gip_instruction_rd_int
*/
void c_gip_full::build_gip_instruction_rd_int( t_gip_instruction *gip_instr, t_gip_ins_rd_int gip_ins_rd_int )
{
gip_instr->gip_ins_rd.type = gip_ins_r_type_internal;
gip_instr->gip_ins_rd.data.rd_internal = gip_ins_rd_int;
}
/*f c_gip_full::build_gip_instruction_rd_reg
*/
void c_gip_full::build_gip_instruction_rd_reg( t_gip_instruction *gip_instr, int gip_ins_rd_r )
{
gip_instr->gip_ins_rd.type = gip_ins_r_type_register;
gip_instr->gip_ins_rd.data.r = gip_ins_rd_r;
}
/*f c_gip_full::map_condition_code
*/
t_gip_ins_cc c_gip_full::map_condition_code( int arm_cc )
{
switch (arm_cc&0xf)
{
case 0x0: return gip_ins_cc_eq;
case 0x1: return gip_ins_cc_ne;
case 0x2: return gip_ins_cc_cs;
case 0x3: return gip_ins_cc_cc;
case 0x4: return gip_ins_cc_mi;
case 0x5: return gip_ins_cc_pl;
case 0x6: return gip_ins_cc_vs;
case 0x7: return gip_ins_cc_vc;
case 0x8: return gip_ins_cc_hi;
case 0x9: return gip_ins_cc_ls;
case 0xa: return gip_ins_cc_ge;
case 0xb: return gip_ins_cc_lt;
case 0xc: return gip_ins_cc_gt;
case 0xd: return gip_ins_cc_le;
case 0xe: return gip_ins_cc_always;
case 0xf: return gip_ins_cc_always;
}
return gip_ins_cc_always;
}
/*f c_gip_full::map_source_register
*/
t_gip_ins_r c_gip_full::map_source_register( int arm_r )
{
t_gip_ins_r result;
result.type = gip_ins_r_type_register;
result.data.r = arm_r;
if (arm_r==15)
{
result.type = gip_ins_r_type_internal;
result.data.rnm_internal = gip_ins_rnm_int_pc;
}
return result;
}
/*f c_gip_full::map_destination_register
*/
t_gip_ins_r c_gip_full::map_destination_register( int arm_rd )
{
t_gip_ins_r result;
result.type = gip_ins_r_type_register;
result.data.r = arm_rd;
if (arm_rd==15)
{
result.type = gip_ins_r_type_internal;
result.data.rd_internal = gip_ins_rd_int_pc;
}
return result;
}
/*f c_gip_full::map_shift
*/
t_gip_ins_subclass c_gip_full::map_shift( int shf_how, int imm, int amount )
{
t_gip_ins_subclass shift;
switch ((t_shf_type)(shf_how))
{
case shf_type_lsl:
shift = gip_ins_subclass_shift_lsl;
break;
case shf_type_lsr:
shift = gip_ins_subclass_shift_lsr;
break;
case shf_type_asr:
shift = gip_ins_subclass_shift_asr;
break;
case shf_type_ror:
shift = gip_ins_subclass_shift_ror;
if ((imm) && (amount==0))
{
shift = gip_ins_subclass_shift_ror33;
}
break;
default:
break;
}
return shift;
}
/*f c_gip_full::map_native_rm
*/
t_gip_ins_r c_gip_full::map_native_rm( int rm, int use_full_ext_rm )
{
t_gip_ins_r result;
if ( pd->dec.state.extended_rm.type!=gip_ins_r_type_no_override )
{
result.type = pd->dec.state.extended_rm.type;
if (use_full_ext_rm)
{
result.data.r = (pd->dec.state.extended_rm.data.r&0x3f);
}
else
{
result.data.r = (pd->dec.state.extended_rm.data.r&0x30) | (rm&0xf);
}
}
else
{
result.type = gip_ins_r_type_register;
result.data.r = rm;
if (rm==15)
{
result.type = gip_ins_r_type_internal;
result.data.rnm_internal = gip_ins_rnm_int_acc;
}
}
return result;
}
/*f c_gip_full::map_native_rn
*/
t_gip_ins_r c_gip_full::map_native_rn( int rn )
{
t_gip_ins_r result;
if ( pd->dec.state.extended_rn.type!=gip_ins_r_type_no_override )
{
result.type = pd->dec.state.extended_rn.type;
result.data.r = pd->dec.state.extended_rn.data.r;
}
else
{
result.type = gip_ins_r_type_register;
result.data.r = rn;
if (rn==15)
{
result.type = gip_ins_r_type_internal;
result.data.rnm_internal = gip_ins_rnm_int_acc;
}
}
return result;
}
/*f c_gip_full::map_native_rd
*/
t_gip_ins_r c_gip_full::map_native_rd( int rd )
{
t_gip_ins_r result;
if ( pd->dec.state.extended_rd.type!=gip_ins_r_type_no_override )
{
result.type = pd->dec.state.extended_rd.type;
result.data.r = pd->dec.state.extended_rd.data.r;
}
else
{
result.type = gip_ins_r_type_register;
result.data.r = rd;
if (rd==15)
{
result.type = gip_ins_r_type_internal;
result.data.rd_internal = gip_ins_rd_int_pc;
}
}
return result;
}
/*f c_gip_full::map_native_immediate
*/
unsigned int c_gip_full::map_native_immediate( int imm )
{
unsigned int result;
if ( pd->dec.state.extended_immediate )
{
result = (imm&0xf) | (pd->dec.state.extended_immediate<<4);
}
else
{
result = imm;
}
return result;
}
/*a Native Decode functions
*/
/*f c_gip_full::decode_native_debug
*/
int c_gip_full::decode_native_debug( unsigned int opcode )
{
int ins_class;
int type;
ins_class = ((opcode>>12)&0xf);
type = (opcode>>8)&0xf;
if ((ins_class==0xf) && (type==0x0))
{
build_gip_instruction_nop( &pd->dec.native.inst );
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
}
return 0;
}
/*f c_gip_full::decode_native_extend
*/
int c_gip_full::decode_native_extend( unsigned int opcode )
{
t_gip_native_ins_class ins_class;
int rd;
int rm;
int rn;
int imm;
int cond, sign, acc, op, burst;
ins_class = (t_gip_native_ins_class) ((opcode>>12)&0xf);
rd = (opcode>>4)&0xff; // full extension of rd
rm = (opcode>>0)&0xf; // top 4 bits of rm
rn = (opcode>>8)&0xf; // top 4 bits of rn
imm = (opcode>>0)&0x3fff; // 14 bit immediate extension
cond = (opcode>>8)&0x0f; // 4 bit cond
sign = (opcode>>7)&0x01; // 1 bit sign
acc = (opcode>>6)&0x01; // 1 bit acc
op = (opcode>>4)&0x03; // 2 bit options
burst = (opcode>>0)&0x0f; // 4 bit burst
switch (ins_class)
{
case gip_native_ins_class_extimm_0:
case gip_native_ins_class_extimm_1:
case gip_native_ins_class_extimm_2:
case gip_native_ins_class_extimm_3:
if (pd->dec.state.extended_immediate==0)
{
pd->dec.native.next_extended_immediate = (imm<<18)>>18;
}
else
{
pd->dec.native.next_extended_immediate = (pd->dec.state.extended_immediate<<18) | imm;
}
pd->dec.native.extending = 1;
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
case gip_native_ins_class_extrdrm:
pd->dec.native.next_extended_rd.type = (t_gip_ins_r_type) ((rd>>5)&7);
pd->dec.native.next_extended_rd.data.r = (rd&0x1f);
pd->dec.native.next_extended_rm.type = (t_gip_ins_r_type) ((rm>>1)&7);
pd->dec.native.next_extended_rm.data.r = (rm&1)<<4;
pd->dec.native.extending = 1;
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
case gip_native_ins_class_extrnrm:
pd->dec.native.next_extended_rn.type = (t_gip_ins_r_type) ((rn>>1)&7);
pd->dec.native.next_extended_rn.data.r = (rn&1)<<4;
pd->dec.native.next_extended_rm.type = (t_gip_ins_r_type) ((rm>>1)&7);
pd->dec.native.next_extended_rm.data.r = (rm&1)<<4;
pd->dec.native.extending = 1;
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
case gip_native_ins_class_extcmd:
pd->dec.native.next_extended_cmd.extended = 1;
pd->dec.native.next_extended_cmd.cc = cond;
pd->dec.native.next_extended_cmd.sign_or_stack = sign;
pd->dec.native.next_extended_cmd.acc = acc;
pd->dec.native.next_extended_cmd.op = op;
pd->dec.native.next_extended_cmd.burst = burst;
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
default:
break;
}
return 0;
}
/*f c_gip_full::decode_native_alu
*/
int c_gip_full::decode_native_alu( unsigned int opcode )
{
t_gip_native_ins_class ins_class;
t_gip_native_ins_subclass ins_subclass;
int rd;
int rm;
int imm;
int mode;
int gip_ins_a, gip_ins_s;
t_gip_ins_cc gip_ins_cc;
t_gip_ins_class gip_ins_class;
t_gip_ins_subclass gip_ins_subclass;
t_gip_ins_r gip_ins_rd;
t_gip_ins_r gip_ins_rn;
t_gip_ins_r gip_ins_rm;
unsigned int imm_val;
ins_class = (t_gip_native_ins_class) ((opcode>>12)&0xf);
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>8)&0xf);
rd = (opcode>>4)&0xf;
rm = (opcode>>0)&0xf;
imm = (opcode>>0)&0xf;
if ( (ins_class==gip_native_ins_class_alu_reg) ||
(ins_class==gip_native_ins_class_alu_imm) )
{
/*b Decode mode and ALU operations
*/
mode = pd->alu_mode;
gip_ins_a = 1;
gip_ins_s = 1;
gip_ins_cc = pd->dec.gip_ins_cc;
if (pd->dec.state.extended_cmd.extended)
{
if (pd->dec.state.extended_cmd.op!=0) mode = pd->dec.state.extended_cmd.op;
gip_ins_a = pd->dec.state.extended_cmd.acc;
gip_ins_s = pd->dec.state.extended_cmd.sign_or_stack;
if (pd->dec.state.extended_cmd.cc!=14) gip_ins_cc = (t_gip_ins_cc) pd->dec.state.extended_cmd.cc;
}
if (((int)ins_subclass)<8) // basic instructions
{
/*b Basic instructions
*/
switch (ins_subclass)
{
case gip_native_ins_subclass_alu_and:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_and;
break;
case gip_native_ins_subclass_alu_or:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_or;
break;
case gip_native_ins_subclass_alu_xor:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_xor;
break;
case gip_native_ins_subclass_alu_mov:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_mov;
break;
case gip_native_ins_subclass_alu_mvn:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_mvn;
break;
case gip_native_ins_subclass_alu_add:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_add;
break;
case gip_native_ins_subclass_alu_sub:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_sub;
break;
case gip_native_ins_subclass_alu_adc:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_adc;
break;
default:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_and;
break;
}
}
else
{
/*b Modal instructions
*/
switch (mode)
{
/*b Bit mode
*/
case gip_native_mode_bit:
switch (ins_subclass)
{
case gip_native_ins_subclass_alu_xorfirst:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_xorfirst;
break;
case gip_native_ins_subclass_alu_rsb:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_rsb;
break;
case gip_native_ins_subclass_alu_bic:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_bic;
break;
case gip_native_ins_subclass_alu_orn:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_orn;
break;
case gip_native_ins_subclass_alu_andcnt:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_andcnt;
break;
case gip_native_ins_subclass_alu_xorlast:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_xorlast;
break;
case gip_native_ins_subclass_alu_bitreverse:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_bitreverse;
break;
case gip_native_ins_subclass_alu_bytereverse:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_bytereverse;
break;
default:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_and;
break;
}
break;
/*b Math mode
*/
case gip_native_mode_math:
switch (ins_subclass)
{
case gip_native_ins_subclass_alu_xorfirst:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_xorfirst;
break;
case gip_native_ins_subclass_alu_rsb:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_rsb;
break;
case gip_native_ins_subclass_alu_init:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_init;
break;
case gip_native_ins_subclass_alu_mla:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_mla;
break;
case gip_native_ins_subclass_alu_mlb:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_mlb;
break;
case gip_native_ins_subclass_alu_sbc:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_sbc;
break;
case gip_native_ins_subclass_alu_dva:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_dva;
break;
case gip_native_ins_subclass_alu_dvb:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_dvb;
break;
default:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_and;
break;
}
break;
/*b GP mode
*/
case gip_native_mode_gp:
switch (ins_subclass)
{
case gip_native_ins_subclass_alu_xorfirst:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_xorfirst;
break;
case gip_native_ins_subclass_alu_rsb:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_rsb;
break;
case gip_native_ins_subclass_alu_bic:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_bic;
break;
case gip_native_ins_subclass_alu_andxor:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_logic_andxor;
break;
case gip_native_ins_subclass_alu_rsc:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_rsc;
break;
default:
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_and;
break;
}
break;
}
}
gip_ins_rd = map_native_rd( rd );
gip_ins_rm = map_native_rm( rm, 0);
gip_ins_rn = map_native_rn( rd );
imm_val = map_native_immediate( imm );
build_gip_instruction_alu( &pd->dec.native.inst, gip_ins_class, gip_ins_subclass, gip_ins_a, gip_ins_s, 0, (gip_ins_rd.type==gip_ins_r_type_internal)&&(gip_ins_rd.data.rd_internal==gip_ins_rd_int_pc) ); // a s p f
build_gip_instruction_cc( &pd->dec.native.inst, gip_ins_cc );
build_gip_instruction_rn( &pd->dec.native.inst, gip_ins_rn );
build_gip_instruction_rd( &pd->dec.native.inst, gip_ins_rd );
if (ins_class==gip_native_ins_class_alu_imm)
{
build_gip_instruction_immediate( &pd->dec.native.inst, imm_val );
}
else
{
build_gip_instruction_rm( &pd->dec.native.inst, gip_ins_rm );
}
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
}
return 0;
}
/*f c_gip_full::decode_native_cond
*/
int c_gip_full::decode_native_cond( unsigned int opcode )
{
t_gip_native_ins_class ins_class;
t_gip_native_ins_subclass ins_subclass;
int rd;
int rm;
int imm;
int gip_ins_a, gip_ins_s, gip_ins_p;
t_gip_ins_cc gip_ins_cc;
t_gip_ins_class gip_ins_class;
t_gip_ins_subclass gip_ins_subclass;
t_gip_ins_r gip_ins_rd;
t_gip_ins_r gip_ins_rn;
t_gip_ins_r gip_ins_rm;
unsigned int imm_val;
ins_class = (t_gip_native_ins_class) ((opcode>>12)&0xf);
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>8)&0xf);
rd = (opcode>>4)&0xf;
rm = (opcode>>0)&0xf;
imm = (opcode>>0)&0xf;
if ( (ins_class==gip_native_ins_class_cond_reg) ||
(ins_class==gip_native_ins_class_cond_imm) )
{
/*b Decode mode and operation, rd
*/
gip_ins_a = 1;
gip_ins_s = 0;
gip_ins_p = 0;
gip_ins_cc = gip_ins_cc_always; // Unless in AND mode and in direct shadow of a conditional, when it should be CP
if (pd->dec.state.in_immediate_shadow)
{
gip_ins_cc = gip_ins_cc_cp;
printf("c_gip_full:decode_native_cond:Hope we are in AND mode\n");
}
if (pd->dec.state.extended_cmd.extended)
{
gip_ins_a = pd->dec.state.extended_cmd.acc;
gip_ins_s = pd->dec.state.extended_cmd.sign_or_stack;
if (pd->dec.state.extended_cmd.cc!=14) gip_ins_cc = (t_gip_ins_cc) pd->dec.state.extended_cmd.cc;
ins_subclass = (t_gip_native_ins_subclass) ( ((int)(ins_subclass)) | ((pd->dec.state.extended_cmd.op&1)<<4) ); // use op bit 0 as top bit of conditional
}
/*b Get arithmetic operation
*/
gip_ins_rd.type = gip_ins_r_type_internal;
switch (ins_subclass)
{
case gip_native_ins_subclass_cond_eq:
case gip_native_ins_subclass_cond_ne:
case gip_native_ins_subclass_cond_gt:
case gip_native_ins_subclass_cond_ge:
case gip_native_ins_subclass_cond_lt:
case gip_native_ins_subclass_cond_le:
case gip_native_ins_subclass_cond_hi:
case gip_native_ins_subclass_cond_hs:
case gip_native_ins_subclass_cond_lo:
case gip_native_ins_subclass_cond_ls:
case gip_native_ins_subclass_cond_seq:
case gip_native_ins_subclass_cond_sne:
case gip_native_ins_subclass_cond_sgt:
case gip_native_ins_subclass_cond_sge:
case gip_native_ins_subclass_cond_slt:
case gip_native_ins_subclass_cond_sle:
case gip_native_ins_subclass_cond_shi:
case gip_native_ins_subclass_cond_shs:
case gip_native_ins_subclass_cond_slo:
case gip_native_ins_subclass_cond_sls:
case gip_native_ins_subclass_cond_smi:
case gip_native_ins_subclass_cond_spl:
case gip_native_ins_subclass_cond_svs:
case gip_native_ins_subclass_cond_svc:
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_sub;
break;
case gip_native_ins_subclass_cond_sps:
case gip_native_ins_subclass_cond_spc:
printf("Will not work in GIP pipeline without using logic Z for eq\n");
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_mov;
gip_ins_p = 1;
break;
case gip_native_ins_subclass_cond_allset:
case gip_native_ins_subclass_cond_anyclr:
printf("Will not work in GIP pipeline without using logic Z for eq\n");
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_andxor;
break;
case gip_native_ins_subclass_cond_allclr:
case gip_native_ins_subclass_cond_anyset:
printf("Will not work in GIP pipeline without using logic Z for eq\n");
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_and;
break;
}
/*b Get target condition
*/
gip_ins_rd.type = gip_ins_r_type_internal;
switch (ins_subclass)
{
case gip_native_ins_subclass_cond_eq:
case gip_native_ins_subclass_cond_allset:
case gip_native_ins_subclass_cond_allclr:
case gip_native_ins_subclass_cond_seq:
case gip_native_ins_subclass_cond_sne:
case gip_native_ins_subclass_cond_sgt:
case gip_native_ins_subclass_cond_sge:
case gip_native_ins_subclass_cond_slt:
case gip_native_ins_subclass_cond_sle:
case gip_native_ins_subclass_cond_shi:
case gip_native_ins_subclass_cond_shs:
case gip_native_ins_subclass_cond_slo:
case gip_native_ins_subclass_cond_sls:
case gip_native_ins_subclass_cond_smi:
case gip_native_ins_subclass_cond_spl:
case gip_native_ins_subclass_cond_svs:
case gip_native_ins_subclass_cond_svc:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_eq;
break;
case gip_native_ins_subclass_cond_anyclr:
case gip_native_ins_subclass_cond_anyset:
case gip_native_ins_subclass_cond_ne:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_ne;
break;
case gip_native_ins_subclass_cond_gt:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_gt;
break;
case gip_native_ins_subclass_cond_ge:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_ge;
break;
case gip_native_ins_subclass_cond_lt:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_lt;
break;
case gip_native_ins_subclass_cond_le:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_le;
break;
case gip_native_ins_subclass_cond_hi:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_hi;
break;
case gip_native_ins_subclass_cond_hs:
case gip_native_ins_subclass_cond_sps:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_cs;
break;
case gip_native_ins_subclass_cond_spc:
case gip_native_ins_subclass_cond_lo:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_cc;
break;
case gip_native_ins_subclass_cond_ls:
gip_ins_rd.data.rd_internal = gip_ins_rd_int_ls;
break;
}
/*b Get conditional if override required
*/
gip_ins_rd.type = gip_ins_r_type_internal;
switch (ins_subclass)
{
case gip_native_ins_subclass_cond_eq:
case gip_native_ins_subclass_cond_ne:
case gip_native_ins_subclass_cond_gt:
case gip_native_ins_subclass_cond_ge:
case gip_native_ins_subclass_cond_lt:
case gip_native_ins_subclass_cond_le:
case gip_native_ins_subclass_cond_hi:
case gip_native_ins_subclass_cond_hs:
case gip_native_ins_subclass_cond_sps:
case gip_native_ins_subclass_cond_spc:
case gip_native_ins_subclass_cond_lo:
case gip_native_ins_subclass_cond_ls:
case gip_native_ins_subclass_cond_anyclr:
case gip_native_ins_subclass_cond_anyset:
case gip_native_ins_subclass_cond_allset:
case gip_native_ins_subclass_cond_allclr:
break;
case gip_native_ins_subclass_cond_seq:
gip_ins_cc = gip_ins_cc_eq;
break;
case gip_native_ins_subclass_cond_sne:
gip_ins_cc = gip_ins_cc_ne;
break;
case gip_native_ins_subclass_cond_sgt:
gip_ins_cc = gip_ins_cc_gt;
break;
case gip_native_ins_subclass_cond_sge:
gip_ins_cc = gip_ins_cc_ge;
break;
case gip_native_ins_subclass_cond_slt:
gip_ins_cc = gip_ins_cc_lt;
break;
case gip_native_ins_subclass_cond_sle:
gip_ins_cc = gip_ins_cc_le;
break;
case gip_native_ins_subclass_cond_shi:
gip_ins_cc = gip_ins_cc_hi;
break;
case gip_native_ins_subclass_cond_shs:
gip_ins_cc = gip_ins_cc_cs;
break;
case gip_native_ins_subclass_cond_slo:
gip_ins_cc = gip_ins_cc_cc;
break;
case gip_native_ins_subclass_cond_sls:
gip_ins_cc = gip_ins_cc_ls;
break;
case gip_native_ins_subclass_cond_smi:
gip_ins_cc = gip_ins_cc_mi;
break;
case gip_native_ins_subclass_cond_spl:
gip_ins_cc = gip_ins_cc_pl;
break;
case gip_native_ins_subclass_cond_svs:
gip_ins_cc = gip_ins_cc_vs;
break;
case gip_native_ins_subclass_cond_svc:
gip_ins_cc = gip_ins_cc_vc;
break;
}
gip_ins_rm = map_native_rm( rm, 0 );
gip_ins_rn = map_native_rn( rd );
imm_val = map_native_immediate( imm );
build_gip_instruction_alu( &pd->dec.native.inst, gip_ins_class, gip_ins_subclass, gip_ins_a, gip_ins_s, gip_ins_p, 0 ); // a s p f
build_gip_instruction_cc( &pd->dec.native.inst, gip_ins_cc );
build_gip_instruction_rn( &pd->dec.native.inst, gip_ins_rn );
build_gip_instruction_rd( &pd->dec.native.inst, gip_ins_rd );
if (ins_class==gip_native_ins_class_cond_imm)
{
build_gip_instruction_immediate( &pd->dec.native.inst, imm_val );
}
else
{
build_gip_instruction_rm( &pd->dec.native.inst, gip_ins_rm );
}
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
pd->dec.native.next_in_immediate_shadow = 1;
return 1;
}
return 0;
}
/*f c_gip_full::decode_native_shift
*/
int c_gip_full::decode_native_shift( unsigned int opcode )
{
t_gip_native_ins_class ins_class;
t_gip_native_ins_subclass ins_subclass;
int rd;
int rm;
int imm;
int is_imm;
int gip_ins_s;
t_gip_ins_cc gip_ins_cc;
t_gip_ins_subclass gip_ins_subclass;
t_gip_ins_r gip_ins_rd;
t_gip_ins_r gip_ins_rn;
t_gip_ins_r gip_ins_rm;
unsigned int imm_val;
ins_class = (t_gip_native_ins_class) ((opcode>>12)&0xf);
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>10)&0x3);
is_imm = (opcode>>9)&1;
rd = (opcode>>4)&0xf;
rm = (opcode>>0)&0xf;
imm = ((opcode>>0)&0xf) | ((opcode&0x100)>>4);
if (ins_class==gip_native_ins_class_shift)
{
/*b Decode shift operation
*/
gip_ins_s = 1;
gip_ins_cc = pd->dec.gip_ins_cc;
if (pd->dec.state.extended_cmd.extended)
{
gip_ins_s = pd->dec.state.extended_cmd.sign_or_stack;
if (pd->dec.state.extended_cmd.cc!=14) gip_ins_cc = (t_gip_ins_cc) pd->dec.state.extended_cmd.cc;
}
switch (ins_subclass)
{
case gip_native_ins_subclass_shift_lsl:
gip_ins_subclass = gip_ins_subclass_shift_lsl;
break;
case gip_native_ins_subclass_shift_lsr:
gip_ins_subclass = gip_ins_subclass_shift_lsr;
break;
case gip_native_ins_subclass_shift_asr:
gip_ins_subclass = gip_ins_subclass_shift_asr;
break;
case gip_native_ins_subclass_shift_ror:
default:
gip_ins_subclass = gip_ins_subclass_shift_ror;
if (is_imm && imm==0)
{
gip_ins_subclass = gip_ins_subclass_shift_ror33;
}
break;
}
gip_ins_rd = map_native_rd( rd );
gip_ins_rm = map_native_rm( rm, 0);
gip_ins_rn = map_native_rn( rd );
imm_val = map_native_immediate( imm );
build_gip_instruction_shift( &pd->dec.native.inst, gip_ins_subclass, gip_ins_s, (gip_ins_rd.type==gip_ins_r_type_internal)&&(gip_ins_rd.data.rd_internal==gip_ins_rd_int_pc) ); // s f
build_gip_instruction_cc( &pd->dec.native.inst, gip_ins_cc );
build_gip_instruction_rn( &pd->dec.native.inst, gip_ins_rn );
build_gip_instruction_rd( &pd->dec.native.inst, gip_ins_rd );
if (is_imm)
{
build_gip_instruction_immediate( &pd->dec.native.inst, imm_val );
}
else
{
build_gip_instruction_rm( &pd->dec.native.inst, gip_ins_rm );
}
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
}
return 0;
}
/*f c_gip_full::decode_native_ldr
*/
int c_gip_full::decode_native_ldr( unsigned int opcode )
{
t_gip_native_ins_class ins_class;
int store_not_load;
t_gip_native_ins_subclass ins_subclass;
int rd, rn;
int imm;
int gip_ins_a, gip_ins_s;
t_gip_ins_cc gip_ins_cc;
t_gip_ins_subclass gip_ins_subclass;
t_gip_ins_r gip_ins_rd;
t_gip_ins_r gip_ins_rn;
t_gip_ins_r gip_ins_rm;
int gip_ins_burst;
int gip_ins_up;
int gip_ins_preindex;
int use_imm;
unsigned int imm_val;
ins_class = (t_gip_native_ins_class) ((opcode>>12)&0xf);
store_not_load = ((opcode>>8)&1);
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>9)&0x7);
rn = (opcode>>4)&0xf;
rd = (opcode>>0)&0xf;
if ( (ins_class==gip_native_ins_class_memory) && (!store_not_load) )
{
/*b Decode mode and operation, rd
*/
gip_ins_a = 1;
gip_ins_s = 0;
gip_ins_burst = 0;
gip_ins_cc = pd->dec.gip_ins_cc;
gip_ins_rm = map_native_rm( rd, 1 ); // first argument is irrelevant
use_imm = (pd->dec.state.extended_rm.type==gip_ins_r_type_no_override);
switch (ins_subclass)
{
case gip_native_ins_subclass_memory_word_noindex: // Preindex Up Word, immediate of zero (unless extended - then preindex up by immediate value)
gip_ins_preindex = 1;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
imm = 0;
break;
case gip_native_ins_subclass_memory_half_noindex: // Preindex Up Half, immediate of zero (unless extended - then preindex up by immediate value)
gip_ins_preindex = 1;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_half;
imm = 0;
break;
case gip_native_ins_subclass_memory_byte_noindex: // Preindex Up Byte, immediate of zero (unless extended - then preindex up by immediate value)
gip_ins_preindex = 1;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_byte;
imm = 0;
break;
case gip_native_ins_subclass_memory_word_preindex_up: // Preindex Up Word, immediate of four (unless extended - then preindex up by immediate value)
gip_ins_preindex = 1;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
imm = 4;
use_imm = 1;
break;
case gip_native_ins_subclass_memory_word_preindex_up_shf: // Preindex Up Word by SHF
gip_ins_preindex = 1;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
gip_ins_rm.type = gip_ins_r_type_internal;
gip_ins_rm.data.rnm_internal = gip_ins_rnm_int_shf;
break;
case gip_native_ins_subclass_memory_word_preindex_down_shf: // Preindex Up Word by SHF
gip_ins_preindex = 1;
gip_ins_up = 0;
gip_ins_subclass = gip_ins_subclass_memory_word;
gip_ins_rm.type = gip_ins_r_type_internal;
gip_ins_rm.data.rnm_internal = gip_ins_rnm_int_shf;
break;
case gip_native_ins_subclass_memory_word_postindex_up: // Postindex Up Word, immediate of four (unless extended - then preindex up by immediate value)
gip_ins_preindex = 0;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
imm = 4;
use_imm = 1;
break;
case gip_native_ins_subclass_memory_word_postindex_down: // Postindex down Word, immediate of four (unless extended - then preindex up by immediate value)
gip_ins_preindex = 0;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
imm = 4;
use_imm = 1;
break;
default:
break;
}
if (pd->dec.state.extended_cmd.extended)
{
gip_ins_a = pd->dec.state.extended_cmd.acc;
gip_ins_s = pd->dec.state.extended_cmd.sign_or_stack;
if (pd->dec.state.extended_cmd.cc!=14) gip_ins_cc = (t_gip_ins_cc) pd->dec.state.extended_cmd.cc;
if (pd->dec.state.extended_cmd.op&1)
{
gip_ins_burst = pd->special.state.repeat_count;
}
else
{
gip_ins_burst = pd->dec.state.extended_cmd.burst;
}
gip_ins_preindex = !pd->dec.state.extended_cmd.op&1;
}
gip_ins_rd = map_native_rd( rd );
gip_ins_rn = map_native_rn( rn );
imm_val = map_native_immediate( imm );
build_gip_instruction_load( &pd->dec.native.inst, gip_ins_subclass, gip_ins_preindex, gip_ins_up, gip_ins_s, gip_ins_burst, gip_ins_a, (gip_ins_rd.type==gip_ins_r_type_internal)&&(gip_ins_rd.data.rd_internal==gip_ins_rd_int_pc) ); // preindex up stack burst_left a f
build_gip_instruction_cc( &pd->dec.native.inst, gip_ins_cc );
build_gip_instruction_rn( &pd->dec.native.inst, gip_ins_rn );
build_gip_instruction_rd( &pd->dec.native.inst, gip_ins_rd );
if (use_imm)
{
build_gip_instruction_immediate( &pd->dec.native.inst, imm_val );
}
else
{
build_gip_instruction_rm( &pd->dec.native.inst, gip_ins_rm );
}
pd->dec.native.next_extended_cmd.burst = (gip_ins_burst==0)?0:gip_ins_burst-1;
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
}
return 0;
}
/*f c_gip_full::decode_native_str
*/
int c_gip_full::decode_native_str( unsigned int opcode )
{
t_gip_native_ins_class ins_class;
int store_not_load;
t_gip_native_ins_subclass ins_subclass;
int rm, rn;
int gip_ins_a, gip_ins_s;
t_gip_ins_cc gip_ins_cc;
t_gip_ins_subclass gip_ins_subclass;
t_gip_ins_r gip_ins_rd;
t_gip_ins_r gip_ins_rn;
t_gip_ins_r gip_ins_rm;
int gip_ins_burst;
int gip_ins_up;
int gip_ins_preindex;
int gip_ins_use_shift;
ins_class = (t_gip_native_ins_class) ((opcode>>12)&0xf);
store_not_load = ((opcode>>8)&1);
ins_subclass = (t_gip_native_ins_subclass) ((opcode>>9)&0x7);
rn = (opcode>>4)&0xf;
rm = (opcode>>0)&0xf;
if ( (ins_class==gip_native_ins_class_memory) && (store_not_load) )
{
/*b Decode mode and operation, rd
*/
gip_ins_a = 1;
gip_ins_s = 0;
gip_ins_burst = 0;
gip_ins_cc = pd->dec.gip_ins_cc;
gip_ins_rm = map_native_rm( rm, 0 );
gip_ins_rd = map_native_rd( rn );
gip_ins_rn = map_native_rn( rn );
gip_ins_use_shift = 0;
switch (ins_subclass)
{
case gip_native_ins_subclass_memory_word_noindex: // Postindex Up Word, no setting accumulator ; should not extend with rd set to something!
gip_ins_a = 0;
gip_ins_preindex = 0;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
break;
case gip_native_ins_subclass_memory_half_noindex: // Postindex Up Half, no setting accumulator ; should not extend with rd set to something!
gip_ins_a = 0;
gip_ins_preindex = 0;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_half;
break;
case gip_native_ins_subclass_memory_byte_noindex: // Postindex Up Byte, no setting accumulator ; should not extend with rd set to something!
gip_ins_a = 0;
gip_ins_preindex = 0;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_byte;
break;
case gip_native_ins_subclass_memory_word_preindex_up: // Preindex Up Word with writeback
gip_ins_preindex = 1;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
if (pd->dec.state.extended_rd.type==gip_ins_r_type_no_override)
{
gip_ins_rd = gip_ins_rn;
}
break;
case gip_native_ins_subclass_memory_word_preindex_up_shf: // Preindex Up Word by SHF
gip_ins_preindex = 1;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
gip_ins_use_shift = 1;
break;
case gip_native_ins_subclass_memory_word_preindex_down_shf: // Preindex Up Word by SHF
gip_ins_preindex = 1;
gip_ins_up = 0;
gip_ins_subclass = gip_ins_subclass_memory_word;
gip_ins_use_shift = 1;
break;
case gip_native_ins_subclass_memory_word_postindex_up: // Postindex Up Word
gip_ins_preindex = 0;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
if (pd->dec.state.extended_rd.type==gip_ins_r_type_no_override)
{
gip_ins_rd = gip_ins_rn;
}
break;
case gip_native_ins_subclass_memory_word_postindex_down: // Postindex down Word
gip_ins_preindex = 0;
gip_ins_up = 1;
gip_ins_subclass = gip_ins_subclass_memory_word;
if (pd->dec.state.extended_rd.type==gip_ins_r_type_no_override)
{
gip_ins_rd = gip_ins_rn;
}
break;
default:
break;
}
if (pd->dec.state.extended_cmd.extended)
{
gip_ins_a = pd->dec.state.extended_cmd.acc;
gip_ins_s = pd->dec.state.extended_cmd.sign_or_stack;
if (pd->dec.state.extended_cmd.cc!=14) gip_ins_cc = (t_gip_ins_cc) pd->dec.state.extended_cmd.cc;
if (pd->dec.state.extended_cmd.op&1)
{
gip_ins_burst = pd->special.state.repeat_count;
}
else
{
gip_ins_burst = pd->dec.state.extended_cmd.burst;
}
gip_ins_preindex = !pd->dec.state.extended_cmd.op&1;
}
build_gip_instruction_store( &pd->dec.native.inst, gip_ins_subclass, gip_ins_preindex, gip_ins_up, gip_ins_use_shift, gip_ins_s, gip_ins_burst, gip_ins_a, (gip_ins_rd.type==gip_ins_r_type_internal)&&(gip_ins_rd.data.rd_internal==gip_ins_rd_int_pc) ); // preindex up stack burst_left a f
build_gip_instruction_cc( &pd->dec.native.inst, gip_ins_cc );
build_gip_instruction_rn( &pd->dec.native.inst, gip_ins_rn );
build_gip_instruction_rd( &pd->dec.native.inst, gip_ins_rd );
build_gip_instruction_rm( &pd->dec.native.inst, gip_ins_rm );
pd->dec.native.next_extended_cmd.burst = (gip_ins_burst==0)?0:gip_ins_burst-1;
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
}
return 0;
}
/*f c_gip_full::decode_native_branch
*/
int c_gip_full::decode_native_branch( unsigned int opcode )
{
t_gip_native_ins_class ins_class;
int delay_slot;
int offset;
t_gip_ins_cc gip_ins_cc;
ins_class = (t_gip_native_ins_class) ((opcode>>12)&0xf);
delay_slot = ((opcode>>0)&1);
offset = (opcode>>0)&0xffe;
offset = (offset<<20)>>20;
if (ins_class==gip_native_ins_class_branch)
{
if (!pd->dec.state.in_conditional_shadow)
{
printf("********************************************************************************\nShould insert instruction to reset CPs to true - taken branch resets these!\n");
offset = map_native_immediate( offset );
if (delay_slot)
{
pd->dec.native.next_delay_pc = pd->dec.state.pc+8+offset;
pd->dec.native.next_follow_delay_pc = 1;
pd->dec.native.next_in_delay_slot = 1;
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
}
else
{
pd->dec.native.next_pc = pd->dec.state.pc+8+offset;
pd->dec.native.next_cycle_of_opcode = 0;
}
return 1;
}
/*b Build a conditional flushing instruction (ADD<cc>F pc, #offset), mark next instruction as delayed if required
*/
gip_ins_cc = pd->dec.gip_ins_cc;
if (pd->dec.state.extended_cmd.extended)
{
if (pd->dec.state.extended_cmd.cc!=14) gip_ins_cc = (t_gip_ins_cc) pd->dec.state.extended_cmd.cc;
}
build_gip_instruction_alu( &pd->dec.native.inst, gip_ins_class_arith, gip_ins_subclass_arith_add, 0, 0, 0, 1 ); // a s p f
build_gip_instruction_cc( &pd->dec.native.inst, gip_ins_cc ); // !cc is CC with bottom bit inverted, in ARM
build_gip_instruction_rn_int( &pd->dec.native.inst, gip_ins_rnm_int_pc );
build_gip_instruction_immediate( &pd->dec.native.inst, offset );
build_gip_instruction_rd_int( &pd->dec.native.inst, gip_ins_rd_int_pc );
pd->dec.native.next_in_delay_slot = 1;
pd->dec.native.next_pc = pd->dec.state.pc+2;
pd->dec.native.next_cycle_of_opcode = 0;
return 1;
}
return 0;
}
/*a ARM Decode functions
*/
/*f c_gip_full::decode_arm_debug
*/
int c_gip_full::decode_arm_debug( void )
{
/*b Check if instruction is 0xf00000..
*/
if ((pd->dec.state.opcode&0xffffff00)==0xf0000000)
{
pd->dec.arm.next_cycle_of_opcode = 0;
pd->dec.arm.next_pc = pd->dec.state.pc+4;
return 1;
}
return 0;
}
/*f c_gip_full::decode_arm_alu
ALU instructions map to one or more internal instructions
Those that do not set the PC and are immediate or have a shift of LSL #0 map to one internal ALU instruction
Those that do not set the PC and have a shift other than LSL #0 map to one internal SHIFT instruction and one internal ALU instruction
Those that set the PC and have a shift of LSL #0 map to one internal ALU instruction with 'flush' set
Those that set the PC and have a shift other than LSL #0 map to one internal SHIFT instruction and one internal ALU instruction with 'flush' set
*/
int c_gip_full::decode_arm_alu( void )
{
int cc, zeros, imm, alu_op, sign, rn, rd, op2;
int imm_val, imm_rotate;
int shf_rs, shf_reg_zero, shf_imm_amt, shf_how, shf_by_reg, shf_rm;
int conditional;
t_gip_ins_class gip_ins_class;
t_gip_ins_subclass gip_ins_subclass;
t_gip_ins_cc gip_ins_cc;
t_gip_ins_r gip_ins_rn;
t_gip_ins_r gip_ins_rm;
t_gip_ins_r gip_ins_rs;
t_gip_ins_r gip_ins_rd;
int gip_set_flags, gip_set_acc, gip_pass_p;
/*b Decode ARM instruction
*/
cc = (pd->dec.state.opcode>>28) & 0x0f;
zeros = (pd->dec.state.opcode>>26) & 0x03;
imm = (pd->dec.state.opcode>>25) & 0x01;
alu_op = (pd->dec.state.opcode>>21) & 0x0f;
sign = (pd->dec.state.opcode>>20) & 0x01;
rn = (pd->dec.state.opcode>>16) & 0x0f;
rd = (pd->dec.state.opcode>>12) & 0x0f;
op2 = (pd->dec.state.opcode>> 0) & 0xfff;
/*b If not an ALU instruction, then exit
*/
if (zeros)
{
return 0;
}
/*b Determine the shift
*/
imm_rotate = (op2>>8) & 0x0f; // RRRRiiiiiiii
imm_val = (op2>>0) & 0xff;
shf_rs = (op2>> 8) & 0x0f; // ssss0tt1mmmm
shf_reg_zero = (op2>> 7) & 0x01;
shf_imm_amt = (op2>> 7) & 0x1f; // iiiiitt0mmmm
shf_how = (op2>> 5) & 0x03;
shf_by_reg = (op2>> 4) & 0x01;
shf_rm = (op2>> 0) & 0x0f;
if (!imm && shf_by_reg && shf_reg_zero)
{
fprintf( stderr, "Slow:ALU:Abort - imm zero, shf by reg 1, shf_reg_zero not zero\n");
return 0;
}
/*b Map condition code
*/
conditional = (cc!=14);
gip_ins_cc = map_condition_code( cc );
/*b Map operation and setting flags
*/
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_add;
gip_set_acc = 0;
gip_set_flags = 0;
gip_pass_p = 0;
gip_ins_rn = map_source_register( rn );
gip_ins_rm = map_source_register( shf_rm );
gip_ins_rs = map_source_register( shf_rs );
gip_ins_rd = map_destination_register( rd );
switch (alu_op)
{
case 0: // and
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_and;
gip_set_flags = sign;
gip_pass_p = sign;
gip_set_acc = !conditional;
break;
case 1: // eor
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_xor;
gip_set_flags = sign;
gip_pass_p = sign;
gip_set_acc = !conditional;
break;
case 2: // sub
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_sub;
gip_set_flags = sign;
gip_set_acc = !conditional;
break;
case 3: // rsb
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_rsb;
gip_set_flags = sign;
gip_set_acc = !conditional;
break;
case 4: // add
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_add;
gip_set_flags = sign;
gip_set_acc = !conditional;
break;
case 5: // adc
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_adc;
gip_set_flags = sign;
gip_set_acc = !conditional;
break;
case 6: // sbc
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_sbc;
gip_set_flags = sign;
gip_set_acc = !conditional;
break;
case 7: // rsc
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_rsc;
gip_set_flags = sign;
gip_set_acc = !conditional;
break;
case 8: // tst
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_and;
gip_set_flags = 1;
gip_pass_p = sign;
gip_set_acc = 0;
gip_ins_rd.type = gip_ins_r_type_none;
break;
case 9: // teq
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_xor;
gip_set_flags = 1;
gip_pass_p = sign;
gip_set_acc = 0;
gip_ins_rd.type = gip_ins_r_type_none;
break;
case 10: // cmp
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_sub;
gip_set_flags = 1;
gip_set_acc = 0;
gip_ins_rd.type = gip_ins_r_type_none;
break;
case 11: // cmn
gip_ins_class = gip_ins_class_arith;
gip_ins_subclass = gip_ins_subclass_arith_add;
gip_set_flags = 1;
gip_set_acc = 0;
gip_ins_rd.type = gip_ins_r_type_none;
break;
case 12: // orr
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_or;
gip_set_flags = sign;
gip_pass_p = sign;
gip_set_acc = !conditional;
break;
case 13: // mov
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_mov;
gip_set_flags = sign;
gip_pass_p = sign;
gip_set_acc = !conditional;
break;
case 14: // bic
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_bic;
gip_set_flags = sign;
gip_pass_p = sign;
gip_set_acc = !conditional;
break;
case 15: // mvn
gip_ins_class = gip_ins_class_logic;
gip_ins_subclass = gip_ins_subclass_logic_mvn;
gip_set_flags = sign;
gip_pass_p = sign;
gip_set_acc = !conditional;
break;
default:
break;
}
pd->dec.arm.next_acc_valid = pd->dec.state.acc_valid;
pd->dec.arm.next_reg_in_acc = pd->dec.state.reg_in_acc;
if (gip_set_acc)
{
if (gip_ins_rd.type==gip_ins_r_type_register)
{
pd->dec.arm.next_acc_valid = !conditional;
pd->dec.arm.next_reg_in_acc = gip_ins_rd.data.r;
}
else
{
pd->dec.arm.next_acc_valid = 0;
}
}
else if ((gip_ins_rd.type==gip_ins_r_type_register) && (gip_ins_rd.data.r==pd->dec.state.reg_in_acc))
{
pd->dec.arm.next_acc_valid = 0;
}
/*b Test for shift of 'LSL #0' or plain immediate
*/
if (imm)
{
gip_pass_p = 0;
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class, gip_ins_subclass, gip_set_acc, gip_set_flags, gip_pass_p, (rd==15) );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc );
build_gip_instruction_rn( &pd->dec.arm.inst, gip_ins_rn );
build_gip_instruction_immediate( &pd->dec.arm.inst, rotate_right(imm_val,imm_rotate*2) );
build_gip_instruction_rd( &pd->dec.arm.inst, gip_ins_rd );
pd->dec.arm.next_cycle_of_opcode = 0;
pd->dec.arm.next_pc = pd->dec.state.pc+4;
}
else if ( (((t_shf_type)shf_how)==shf_type_lsl) &&
(!shf_by_reg) &&
(shf_imm_amt==0) )
{
gip_pass_p = 0;
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class, gip_ins_subclass, gip_set_acc, gip_set_flags, gip_pass_p, (rd==15) );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc );
build_gip_instruction_rn( &pd->dec.arm.inst, gip_ins_rn );
build_gip_instruction_rm( &pd->dec.arm.inst, gip_ins_rm );
build_gip_instruction_rd( &pd->dec.arm.inst, gip_ins_rd );
pd->dec.arm.next_cycle_of_opcode = 0;
pd->dec.arm.next_pc = pd->dec.state.pc+4;
}
else if (!shf_by_reg) // Immediate shift, non-zero or non-LSL: ISHF Rm, #imm; IALU{CC}(SP|)[A][F] Rn, SHF -> Rd
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_shift( &pd->dec.arm.inst, map_shift( shf_how, 1, shf_imm_amt), 0, 0 );
build_gip_instruction_rn( &pd->dec.arm.inst, gip_ins_rm );
build_gip_instruction_immediate( &pd->dec.arm.inst, (shf_imm_amt==0)?32:shf_imm_amt );
pd->dec.arm.next_acc_valid = pd->dec.state.acc_valid; // First internal does not set acc
pd->dec.arm.next_reg_in_acc = pd->dec.state.reg_in_acc;
break;
default:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class, gip_ins_subclass, gip_set_acc, gip_set_flags, gip_pass_p, (rd==15) );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc );
build_gip_instruction_rn( &pd->dec.arm.inst, gip_ins_rn );
build_gip_instruction_rm_int( &pd->dec.arm.inst, gip_ins_rnm_int_shf );
build_gip_instruction_rd( &pd->dec.arm.inst, gip_ins_rd );
pd->dec.arm.next_cycle_of_opcode = 0;
pd->dec.arm.next_pc = pd->dec.state.pc+4;
break;
}
}
else // if (shf_by_reg) - must be! ISHF Rm, Rs; IALU{CC}(SP|)[A][F] Rn, SHF -> Rd
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_shift( &pd->dec.arm.inst, map_shift(shf_how, 0, 0 ), 0, 0 );
build_gip_instruction_rn( &pd->dec.arm.inst, gip_ins_rm );
build_gip_instruction_rm( &pd->dec.arm.inst, gip_ins_rs );
pd->dec.arm.next_acc_valid = pd->dec.state.acc_valid; // First internal does not set acc
pd->dec.arm.next_reg_in_acc = pd->dec.state.reg_in_acc;
break;
default:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class, gip_ins_subclass, gip_set_acc, gip_set_flags, gip_pass_p, (rd==15) );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc );
build_gip_instruction_rn( &pd->dec.arm.inst, gip_ins_rn );
build_gip_instruction_rm_int( &pd->dec.arm.inst, gip_ins_rnm_int_shf );
build_gip_instruction_rd( &pd->dec.arm.inst, gip_ins_rd );
pd->dec.arm.next_cycle_of_opcode = 0;
pd->dec.arm.next_pc = pd->dec.state.pc+4;
break;
}
}
return 1;
}
/*f c_gip_full::decode_arm_branch
*/
int c_gip_full::decode_arm_branch( void )
{
int cc, five, link, offset;
/*b Decode ARM instruction
*/
cc = (pd->dec.state.opcode>>28) & 0x0f;
five = (pd->dec.state.opcode>>25) & 0x07;
link = (pd->dec.state.opcode>>24) & 0x01;
offset = (pd->dec.state.opcode>> 0) & 0x00ffffff;
/*b Return if not a branch
*/
if (five != 5)
return 0;
/*b Handle 5 cases; conditional or not, link or not; split conditional branches to predicted or not, also
*/
if (!link)
{
if (cc==14) // guaranteed branch
{
pd->dec.arm.next_pc = pd->dec.state.pc+8+((offset<<8)>>6);
pd->dec.arm.next_cycle_of_opcode = 0;
}
else
{
if (offset&0x800000) // backward conditional branch; sub(!cc)f pc, #4 -> pc
{
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_sub, 0, 0, 0, 1 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc^0x1 ) ); // !cc is CC with bottom bit inverted, in ARM
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_pc );
build_gip_instruction_immediate( &pd->dec.arm.inst, 4 );
build_gip_instruction_rd_int( &pd->dec.arm.inst, gip_ins_rd_int_pc );
pd->dec.arm.next_pc = pd->dec.state.pc+8+((offset<<8)>>6);
pd->dec.arm.next_cycle_of_opcode = 0;
}
else // forward conditional branch; mov[cc]f #target -> pc
{
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_logic, gip_ins_subclass_logic_mov, 0, 0, 0, 1 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc ) );
build_gip_instruction_immediate( &pd->dec.arm.inst, pd->dec.state.pc+8+((offset<<8)>>6) );
build_gip_instruction_rd_int( &pd->dec.arm.inst, gip_ins_rd_int_pc );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
}
}
}
else
{
if (cc==14) // guaranteed branch with link; sub pc, #4 -> r14
{
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_sub, 0, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_always );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_pc );
build_gip_instruction_immediate( &pd->dec.arm.inst, 4 );
build_gip_instruction_rd_reg( &pd->dec.arm.inst, 14 );
pd->dec.arm.next_pc = pd->dec.state.pc+8+((offset<<8)>>6);
pd->dec.arm.next_cycle_of_opcode = 0;
}
else // conditional branch with link; sub{!cc}f pc, #4 -> pc; sub pc, #4 -> r14
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_sub, 0, 0, 0, 1 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc^0x1 ) ); // !cc is CC with bottom bit inverted, in ARM
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_pc );
build_gip_instruction_immediate( &pd->dec.arm.inst, 4 );
build_gip_instruction_rd_int( &pd->dec.arm.inst, gip_ins_rd_int_pc );
break;
default:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_sub, 0, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_always );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_pc );
build_gip_instruction_immediate( &pd->dec.arm.inst, 4 );
build_gip_instruction_rd_reg( &pd->dec.arm.inst, 14 );
pd->dec.arm.next_pc = pd->dec.state.pc+8+((offset<<8)>>6);
pd->dec.arm.next_cycle_of_opcode = 0;
}
}
}
return 1;
}
/*f c_gip_full::decode_arm_ld_st
*/
int c_gip_full::decode_arm_ld_st( void )
{
int cc, one, not_imm, pre, up, byte, wb, load, rn, rd, offset;
int imm_val;
int shf_imm_amt, shf_how, shf_zero, shf_rm;
/*b Decode ARM instruction
*/
cc = (pd->dec.state.opcode>>28) & 0x0f;
one = (pd->dec.state.opcode>>26) & 0x03;
not_imm = (pd->dec.state.opcode>>25) & 0x01;
pre = (pd->dec.state.opcode>>24) & 0x01;
up = (pd->dec.state.opcode>>23) & 0x01;
byte = (pd->dec.state.opcode>>22) & 0x01;
wb = (pd->dec.state.opcode>>21) & 0x01;
load = (pd->dec.state.opcode>>20) & 0x01;
rn = (pd->dec.state.opcode>>16) & 0x0f;
rd = (pd->dec.state.opcode>>12) & 0x0f;
offset = (pd->dec.state.opcode>> 0) & 0xfff;
/*b Validate this is a load/store
*/
if (one != 1)
return 0;
/*b Break out offset
*/
imm_val = (offset>>0) & 0xfff;
shf_imm_amt = (offset>> 7) & 0x1f;
shf_how = (offset>> 5) & 0x03;
shf_zero = (offset>> 4) & 0x01;
shf_rm = (offset>> 0) & 0x0f;
/*b Validate this is a load/store again
*/
if (not_imm && shf_zero)
return 0;
/*b Handle loads - preindexed immediate/reg, preindexed reg with shift, preindexed immediate/reg with wb, preindexed reg with shift with wb, postindexed immediate/reg, postindexed reg with shift
*/
if (load)
{
/*b Handle immediate or reg without shift
*/
if (!not_imm ||
(((t_shf_type)(shf_how)==shf_type_lsl) && (shf_imm_amt==0)) ) // immediate or reg without shift
{
/*b Preindexed, no writeback
*/
if (pre && !wb) // preindexed immediate/reg: ILDR[CC]A[F] #0 (Rn, #+/-imm or +/-Rm) -> Rd
{
build_gip_instruction_load( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 1, up, (rn==13), 0, 1, (rd==15) );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc ) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
if (not_imm)
{
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(shf_rm) );
}
else
{
build_gip_instruction_immediate( &pd->dec.arm.inst, imm_val );
}
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rd) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
return 1;
}
/*b Preindexed, writeback
*/
else if (pre) // preindexed immediate/reg with writeback: IADD[CC]A/ISUB[CC]A Rn, #imm/Rm -> Rn; ILDRCP[F] #0, (Acc) -> Rd
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, up?gip_ins_subclass_arith_add:gip_ins_subclass_arith_sub, 1, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc ) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
if (not_imm)
{
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(shf_rm) );
}
else
{
build_gip_instruction_immediate( &pd->dec.arm.inst, imm_val );
}
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
break;
default:
build_gip_instruction_load( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 0, up, (rn==13), 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register( rd ) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
break;
}
return 1;
}
/*b Postindexed
*/
else // postindexed immediate/reg: ILDR[CC]A #0, (Rn), +/-Rm/Imm -> Rd; MOVCP[F] Acc -> Rn
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_load( &pd->dec.arm.inst,gip_ins_subclass_memory_word, 0, up, (rn==13), 0, 1, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc ) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
if (not_imm)
{
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(shf_rm) );
}
else
{
build_gip_instruction_immediate( &pd->dec.arm.inst, imm_val );
}
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rd) );
break;
default:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_logic, gip_ins_subclass_logic_mov, 0, 0, 0, (rd==15) );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rm_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
break;
}
return 1;
}
}
/*b Register with shift
*/
else // reg with shift
{
/*b Preindexed without writeback
*/
if (pre && !wb) // preindexed reg with shift: ISHF Rm, #imm; ILDR[CC]A[F] (Rn, +/-SHF) -> Rd
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_shift( &pd->dec.arm.inst, map_shift(shf_how, 1, shf_imm_amt ), 0, 0 );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(shf_rm) );
build_gip_instruction_immediate( &pd->dec.arm.inst, shf_imm_amt );
break;
default:
build_gip_instruction_load( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 1, up, (rn==13), 0, 1, (rd==15) );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc ) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
build_gip_instruction_rm_int( &pd->dec.arm.inst, gip_ins_rnm_int_shf );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rd) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
break;
}
return 1;
}
/*b Preindexed with writeback
*/
else if (pre) // preindexed reg with shift with writeback: ILSL Rm, #imm; IADD[CC]A/ISUB[CC]A Rn, SHF -> Rn; ILDRCP[F] #0 (Acc) -> Rd
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_shift( &pd->dec.arm.inst, map_shift(shf_how, 1, shf_imm_amt ), 0, 0 );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(shf_rm) );
build_gip_instruction_immediate( &pd->dec.arm.inst, shf_imm_amt );
break;
case 1:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, up?gip_ins_subclass_arith_add:gip_ins_subclass_arith_sub, 1, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc ) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
build_gip_instruction_rm_int( &pd->dec.arm.inst, gip_ins_rnm_int_shf );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
break;
default:
build_gip_instruction_load( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 0, 1, (rn==13), 0, 0, (rd==15) );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rd) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
break;
}
return 1;
}
/*b Postindexed
*/
else // postindexed reg with shift with writeback: ILSL Rm, #imm; ILDR[CC]A #0 (Rn), +/-SHF -> Rd; MOVCP[F] Acc -> Rn
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_shift( &pd->dec.arm.inst, map_shift(shf_how, 1, shf_imm_amt ), 0, 0 );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(shf_rm) );
build_gip_instruction_immediate( &pd->dec.arm.inst, shf_imm_amt );
break;
case 1:
build_gip_instruction_load( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 0, up, (rn==13), 0, 1, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst,map_condition_code(cc) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
build_gip_instruction_rm_int( &pd->dec.arm.inst, gip_ins_rnm_int_shf );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rd) );
break;
default:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_logic, gip_ins_subclass_logic_mov, 0, 0, 0, (rd==15) );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rm_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
break;
}
return 1;
}
}
return 0;
}
/*b Handle stores - no offset, preindexed immediate, preindexed reg, preindexed reg with shift, postindexed immediate, postindexed reg, postindexed reg with shift
*/
/*b Immediate offset of zero
*/
if ( !not_imm && (imm_val==0) ) // no offset (hence no writeback, none needed); ISTR[CC] #0 (Rn) <- Rd
{
build_gip_instruction_store( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 0, 1, 0, (rn==13), 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc ) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(rd) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
return 1;
}
/*b Preindexed store
*/
else if (pre)
{
/*b preindexed immediate or rm no shift: IADD[CC]AC/ISUB[CC]AC Rn, #imm/Rm; ISTRCPA[S] #0, (ACC, +/-SHF) <- Rd [-> Rn]
*/
if ( !not_imm ||
(((t_shf_type)(shf_how)==shf_type_lsl) && (shf_imm_amt==0)) )
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, up?gip_ins_subclass_arith_add:gip_ins_subclass_arith_sub, 1, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code(cc) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
if (!not_imm)
{
build_gip_instruction_immediate( &pd->dec.arm.inst, imm_val );
}
else
{
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(shf_rm) );
}
break;
default:
build_gip_instruction_store( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 1, up, 1, (rn==13), 0, 1, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(rd) );
if (wb)
{
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
}
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
}
return 1;
}
/*b Preindexed Rm with shift: ISHF[CC] Rm, #imm; ISTRCPA[S] #0, (Rn, +/-SHF) <- Rd [-> Rn]
*/
else
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_shift( &pd->dec.arm.inst, map_shift(shf_how, 1, shf_imm_amt ), 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc ) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(shf_rm) );
build_gip_instruction_immediate( &pd->dec.arm.inst, shf_imm_amt );
break;
default:
build_gip_instruction_store( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 1, up, 1, (rn==13), 0, 1, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(rd) );
if (wb)
{
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
}
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
break;
}
return 1;
}
}
/*b Postindexed
*/
else // if (!pre) - must be postindexed:
{
/*b Postindexed immediate or reg without shift; ISTR[CC][S] #0 (Rn) <-Rd; IADDCPA/ISUBCPA Rn, #Imm/Rm -> Rn
*/
if ( !not_imm ||
(((t_shf_type)(shf_how)==shf_type_lsl) && (shf_imm_amt==0)) )
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_store( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 0, 0, 0, (rn==13), 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code(cc) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(rd) );
break;
default:
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, up?gip_ins_subclass_arith_add:gip_ins_subclass_arith_sub, 1, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
if (!not_imm)
{
build_gip_instruction_immediate( &pd->dec.arm.inst, imm_val );
}
else
{
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(shf_rm) );
}
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
break;
}
return 1;
}
/*b Postindexed reg with shift
*/
else // ISHF[CC] Rm, #imm; ISTRCPA[S] #0 (Rn), +/-SHF) <-Rd -> Rn
{
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
build_gip_instruction_shift( &pd->dec.arm.inst, map_shift(shf_how, 1, shf_imm_amt ), 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code( cc ) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(shf_rm) );
build_gip_instruction_immediate( &pd->dec.arm.inst, shf_imm_amt );
break;
default:
build_gip_instruction_store( &pd->dec.arm.inst, gip_ins_subclass_memory_word, 0, up, 1, (rn==13), 0, 1, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(rd) );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
break;
}
return 1;
}
}
/*b Done
*/
return 0;
}
/*f c_gip_full::decode_arm_ldm_stm
*/
int c_gip_full::decode_arm_ldm_stm( void )
{
int cc, four, pre, up, psr, wb, load, rn, regs;
int i, j, num_regs;
/*b Decode ARM instruction
*/
cc = (pd->dec.state.opcode>>28) & 0x0f;
four = (pd->dec.state.opcode>>25) & 0x07;
pre = (pd->dec.state.opcode>>24) & 0x01;
up = (pd->dec.state.opcode>>23) & 0x01;
psr = (pd->dec.state.opcode>>22) & 0x01;
wb = (pd->dec.state.opcode>>21) & 0x01;
load = (pd->dec.state.opcode>>20) & 0x01;
rn = (pd->dec.state.opcode>>16) & 0x0f;
regs = (pd->dec.state.opcode>> 0) & 0xffff;
/*b If not an LDM/STM, then return
*/
if (four != 4)
return 0;
/*b Calculate memory address and writeback value
*/
for (i=regs, num_regs=0; i; i>>=1)
{
if (i&1)
{
num_regs++;
}
}
/*b Handle load
*/
if (load)
{
/*b If DB/DA, do first instruction to generate base address: ISUB[CC]A Rn, #num_regs*4 [-> Rn]
*/
if ((!up) && (pd->dec.state.cycle_of_opcode==0))
{
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_sub, 1, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code(cc) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
build_gip_instruction_immediate( &pd->dec.arm.inst, num_regs*4 );
if (wb)
{
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
}
else
{
}
return 1;
}
/*b Generate num_regs 'ILDR[CC|CP]A[S][F] #i (Rn|Acc), #+4 or preindexed version
*/
for (i=0; i<num_regs; i++)
{
for (j=0; (j<16) && ((regs&(1<<j))==0); j++);
regs &= ~(1<<j);
if ( (!up && (i==pd->dec.state.cycle_of_opcode+1)) ||
(up && (i==pd->dec.state.cycle_of_opcode)) )
{
build_gip_instruction_load( &pd->dec.arm.inst, gip_ins_subclass_memory_word, pre^!up, 1, (rn==13), (num_regs-1-i), 1, (j==15)&&!(up&&wb) );
if (pd->dec.state.cycle_of_opcode==0)
{
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code(cc) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
}
else
{
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
}
build_gip_instruction_immediate( &pd->dec.arm.inst, 4 );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(j) );
}
if ( (!up && (pd->dec.state.cycle_of_opcode==num_regs)) ||
((up&&!wb) && (pd->dec.state.cycle_of_opcode==num_regs-1)) )
{
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
}
}
/*b If IB/IA with writeback then do final MOVCP[F] Acc -> Rn; F if PC was read in the list
*/
if ((up&&wb) && (pd->dec.state.cycle_of_opcode==num_regs))
{
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_logic, gip_ins_subclass_logic_mov, 0, 0, 0, ((pd->dec.state.opcode&0x8000)!=0) );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rm_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
}
return 1;
}
/*b Handle store
*/
if (!load)
{
/*b If DB/DA, do first instruction to generate base address: ISUB[CC]A Rn, #num_regs*4 [-> Rn]
*/
if ((!up) && (pd->dec.state.cycle_of_opcode==0))
{
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_sub, 1, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code(cc) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
build_gip_instruction_immediate( &pd->dec.arm.inst, num_regs*4 );
if (wb)
{
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
}
else
{
}
return 1;
}
/*b Generate num_regs 'ISTR[CC|CP]A[S][F] #i (Rn|Acc), #+4 [->Rn] or preindexed version
*/
for (i=0; i<num_regs; i++)
{
for (j=0; (j<16) && ((regs&(1<<j))==0); j++);
regs &= ~(1<<j);
if ( (!up && (pd->dec.state.cycle_of_opcode==(i+1))) ||
(up && (pd->dec.state.cycle_of_opcode==i)) )
{
build_gip_instruction_store( &pd->dec.arm.inst, gip_ins_subclass_memory_word, pre^!up, 1, 0, (rn==13), (num_regs-1-i), 1, 0 );
if (pd->dec.state.cycle_of_opcode==0)
{
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code(cc) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rn) );
}
else
{
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
}
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(j) );
if ((pd->dec.state.cycle_of_opcode==num_regs-1) && (up) && (wb))
{
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rn) );
}
else
{
}
if ( (!up && (pd->dec.state.cycle_of_opcode==num_regs)) ||
(up && (pd->dec.state.cycle_of_opcode==num_regs-1)) )
{
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
}
}
}
return 1;
}
/*b Done
*/
return 0;
}
/*f c_gip_full::decode_arm_mul
*/
int c_gip_full::decode_arm_mul( void )
{
int cc, zero, nine, accum, sign, rd, rn, rs, rm;
/*b Decode ARM instruction
*/
cc = (pd->dec.state.opcode>>28) & 0x0f;
zero = (pd->dec.state.opcode>>22) & 0x3f;
accum = (pd->dec.state.opcode>>21) & 0x01;
sign = (pd->dec.state.opcode>>20) & 0x01;
rd = (pd->dec.state.opcode>>16) & 0x0f;
rn = (pd->dec.state.opcode>>12) & 0x0f;
rs = (pd->dec.state.opcode>>8) & 0x0f;
nine = (pd->dec.state.opcode>>4) & 0x0f;
rm = (pd->dec.state.opcode>>0) & 0x0f;
/*b Validate MUL/MLA instruction
*/
if ((zero!=0) || (nine!=9) || (cc==15))
return 0;
/*b Decode according to stage
*/
switch (pd->dec.state.cycle_of_opcode)
{
case 0:
/*b First the INIT instruction
*/
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_init, 1, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, map_condition_code(cc) );
build_gip_instruction_rn( &pd->dec.arm.inst, map_source_register(rm) ); // Note these are
if (accum)
{
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(rn) ); // correctly reversed
}
else
{
build_gip_instruction_immediate( &pd->dec.arm.inst, 0 );
}
break;
case 1:
/*b Then the MLA instruction to get the ALU inputs ready, and do the first step
*/
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_mla, 1, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
build_gip_instruction_rm( &pd->dec.arm.inst, map_source_register(rs) );
break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
/*b Then 14 MLB instructions to churn
*/
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_mlb, 1, 0, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
build_gip_instruction_immediate( &pd->dec.arm.inst, 0 ); // Not used
break;
default:
/*b Then the last MLB instructions to produce the final results
*/
build_gip_instruction_alu( &pd->dec.arm.inst, gip_ins_class_arith, gip_ins_subclass_arith_mlb, 1, sign, 0, 0 );
build_gip_instruction_cc( &pd->dec.arm.inst, gip_ins_cc_cp );
build_gip_instruction_rn_int( &pd->dec.arm.inst, gip_ins_rnm_int_acc );
build_gip_instruction_immediate( &pd->dec.arm.inst, 0 ); // Not used
build_gip_instruction_rd( &pd->dec.arm.inst, map_destination_register(rd) );
pd->dec.arm.next_pc = pd->dec.state.pc+4;
pd->dec.arm.next_cycle_of_opcode = 0;
break;
}
/*b Done
*/
return 1;
}
/*f c_gip_full::decode_arm_trace
Steal top half of SWI space
*/
int c_gip_full::decode_arm_trace( void )
{
int cc, fifteen, code;
/*b Decode ARM instruction
*/
cc = (pd->dec.state.opcode>>28) & 0xf;
fifteen = (pd->dec.state.opcode>>24) & 0xf;
code = (pd->dec.state.opcode>> 0) & 0xffffff;
if (fifteen!=15)
return 0;
if (1 || (code & 0x800000))
{
return 0;
}
return 0;
}
/*a Debug interface
*/
/*f c_gip_full::set_register
*/
void c_gip_full::set_register( int r, unsigned int value )
{
pd->rf.state.regs[r&0x1f] = value;
}
/*f c_gip_full::get_register
*/
unsigned int c_gip_full::get_register( int r )
{
return pd->rf.state.regs[r&0x1f];
}
/*f c_gip_full::set_flags
*/
void c_gip_full::set_flags( int value, int mask )
{
if (mask & gip_flag_mask_z)
pd->alu.state.z = ((value & gip_flag_mask_z)!=0);
if (mask & gip_flag_mask_c)
pd->alu.state.c = ((value & gip_flag_mask_c)!=0);
if (mask & gip_flag_mask_n)
pd->alu.state.n = ((value & gip_flag_mask_n)!=0);
if (mask & gip_flag_mask_v)
pd->alu.state.v = ((value & gip_flag_mask_v)!=0);
}
/*f c_gip_full::get_flags
*/
int c_gip_full::get_flags( void )
{
int result;
result = 0;
if (pd->alu.state.z)
result |= gip_flag_mask_z;
if (pd->alu.state.c)
result |= gip_flag_mask_c;
if (pd->alu.state.n)
result |= gip_flag_mask_n;
if (pd->alu.state.v)
result |= gip_flag_mask_v;
return result;
}
/*f c_gip_full::set_breakpoint
*/
int c_gip_full::set_breakpoint( unsigned int address )
{
int bkpt;
for (bkpt = 0; bkpt < MAX_BREAKPOINTS && (pd->breakpoints_enabled & (1<<bkpt)); bkpt++)
;
if ((bkpt<0) || (bkpt>=MAX_BREAKPOINTS))
return 0;
pd->breakpoint_addresses[bkpt] = address;
pd->breakpoints_enabled = pd->breakpoints_enabled | (1<<bkpt);
pd->debugging_enabled = 1;
// printf("c_gip_full::set_breakpoint:%d:%08x\n", bkpt, address );
return 1;
}
/*f c_gip_full::unset_breakpoint
*/
int c_gip_full::unset_breakpoint( unsigned int address )
{
int bkpt;
for (bkpt = 0; bkpt < MAX_BREAKPOINTS && pd->breakpoint_addresses[bkpt] != address; bkpt++)
;
if ((bkpt<0) || (bkpt>=MAX_BREAKPOINTS))
return 0;
pd->breakpoints_enabled = pd->breakpoints_enabled &~ (1<<bkpt);
SET_DEBUGGING_ENABLED(pd);
// printf("c_gip_full::unset_breakpoint:%d\n", bkpt );
return 1;
}
/*f c_gip_full::halt_cpu
If we are currently executing, forces an immediate halt
This is used by a memory model to abort execution after an unmapped access, for example
*/
void c_gip_full::halt_cpu( void )
{
pd->debugging_enabled = 1;
pd->halt = 1;
printf("c_gip_full::halt_cpu\n");
}
/*a Special register handling
*/
/*f c_gip_full::special_comb
*/
void c_gip_full::special_comb( int read_select, int read_address, unsigned int *read_data )
{
unsigned int result;
result = 0;
switch ((t_gip_special_reg)read_address)
{
case gip_special_reg_semaphores:
result = pd->special.state.semaphores;
break;
case gip_special_reg_thread:
result = pd->special.state.selected_thread;
break;
case gip_special_reg_thread_pc:
result = pd->special.state.thread_data_pc;
break;
case gip_special_reg_thread_data:
result = pd->special.state.thread_data_config;
break;
case gip_special_reg_preempted_pc_l:
printf("special_comb:Do not have mechanism for preemption yet\n");
result = 0;
break;
case gip_special_reg_preempted_pc_m:
printf("special_comb:Do not have mechanism for preemption yet\n");
result = 0;
break;
case gip_special_reg_preempted_flags:
printf("special_comb:Do not have mechanism for preemption yet\n");
result = 0;
break;
default:
break;
}
*read_data = result;
}
/*f c_gip_full::special_preclock
*/
void c_gip_full::special_preclock( int flush, int read_select, int read_address, int write_select, int write_address, unsigned int write_data )
{
/*b Copy current to next
*/
memcpy( &pd->special.next_state, &pd->special.state, sizeof(pd->special.state) );
/*b Default values for interacting with scheduler
*/
pd->special.next_state.thread_data_write_pc = 0;
pd->special.next_state.thread_data_write_config = 0;
pd->special.next_state.thread_data_pc = pd->sched.thread_data_pc;
pd->special.next_state.thread_data_config = pd->sched.thread_data_config;
pd->special.next_state.write_thread = pd->special.state.selected_thread;
/*b Handle writes
*/
switch ((t_gip_special_reg)write_address)
{
case gip_special_reg_gip_config:
if (write_select)
{
pd->special.next_state.cooperative = (write_data>>0)&1;
pd->special.next_state.round_robin = (write_data>>1)&1;
pd->special.next_state.thread_0_privilege = (write_data>>2)&1;
pd->arm_trap_semaphore = (write_data>>16)&0x1f;
}
break;
case gip_special_reg_semaphores_set:
if (write_select)
{
pd->special.next_state.semaphores = pd->special.state.semaphores | write_data;
}
break;
case gip_special_reg_semaphores_clear:
if (write_select)
{
pd->special.next_state.semaphores = pd->special.state.semaphores &~ write_data;
}
break;
case gip_special_reg_thread:
if (write_select)
{
pd->special.next_state.selected_thread = write_data & (NUM_THREADS-1);
}
break;
case gip_special_reg_thread_pc:
if (write_select)
{
pd->special.next_state.thread_data_write_pc = 1;
pd->special.next_state.thread_data_pc = write_data&~1;
if (write_data&1)
{
pd->special.next_state.write_thread = pd->sched.state.thread;
}
else
{
pd->special.next_state.write_thread = pd->special.state.selected_thread;
}
printf("special_preclock:Do not have mechanism for current thread yet\n");
}
break;
case gip_special_reg_thread_data:
if (write_select)
{
pd->special.next_state.thread_data_write_config = 1;
pd->special.next_state.thread_data_config = write_data;
if (write_data&1)
{
pd->special.next_state.write_thread = pd->sched.state.thread;
}
else
{
pd->special.next_state.write_thread = pd->special.state.selected_thread;
}
}
break;
case gip_special_reg_repeat_count:
if (write_select)
{
pd->special.next_state.repeat_count = write_data&0xff;
}
break;
default:
break;
}
}
/*f c_gip_full::special_clock
*/
void c_gip_full::special_clock( void )
{
memcpy( &pd->special.state, &pd->special.next_state, sizeof(pd->special.state) );
}
/*a Postbus register handling
*/
/*f c_gip_full::postbus_comb
*/
void c_gip_full::postbus_comb( int read_select, int read_address, unsigned int *read_data )
{
}
/*f c_gip_full::postbus_preclock
*/
void c_gip_full::postbus_preclock( int flush, int read_select, int read_address, int write_select, int write_address, unsigned int write_data )
{
}
/*f c_gip_full::postbus_clock
*/
void c_gip_full::postbus_clock( void )
{
}
| [
""
] | [
[
[
1,
6176
]
]
] |
f1524d27095e441a3dee0ac8023d598dbc879e33 | 967868cbef4914f2bade9ef8f6c300eb5d14bc57 | /Thread/Thread.cpp | 40aadf4db160e704c944368e05f4eb357705c7de | [] | no_license | saminigod/baseclasses-001 | 159c80d40f69954797f1c695682074b469027ac6 | 381c27f72583e0401e59eb19260c70ee68f9a64c | refs/heads/master | 2023-04-29T13:34:02.754963 | 2009-10-29T11:22:46 | 2009-10-29T11:22:46 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,682 | cpp | /*
© Vestris Inc., Geneva, Switzerland
http://www.vestris.com, 1994-1999 All Rights Reserved
______________________________________________
written by Daniel Doubrovkine - [email protected]
*/
#include <baseclasses.hpp>
#include "Thread.hpp"
#ifdef _WIN32
unsigned long WINAPI
#endif
#ifdef _UNIX
void *
#endif
CThread::CThreadExecute(void * ThreadPointer) {
((CThread *) ThreadPointer)->Execute(((CThread *) ThreadPointer)->GetArguments());
#ifdef _WIN32
long UserTime, KernelTime; if (((CThread *) ThreadPointer)->GetTimes(KernelTime, UserTime)) { m_UserTime.Inc(UserTime); m_KernelTime.Inc(KernelTime); }
#endif
delete (CThread *) ThreadPointer;
#ifdef _WIN32
ExitThread(ctsTerminated);
#endif
#ifdef _UNIX
#ifdef HAVE_PTH
pth_exit(NULL);
#else
pthread_exit(NULL);
#endif
#endif
return
#ifdef _UNIX
(void *)
#endif
0;
}
CThread::CThread(void * Arguments, CThreadState InitialState) {
m_ThreadStartMutex = NULL;
m_ThreadState = ctsStopped;
m_Arguments = Arguments;
m_InitialState = InitialState;
}
void CThread::Launch(void) {
switch(m_InitialState) {
case ctsRunning:
Run();
break;
case ctsSuspended:
m_ThreadState = ctsSuspended;
Run();
break;
default:
cerr << "CThread::CThread(WIN32) - creation of thread in an invalid state!" << endl;
break;
}
}
CThread::~CThread(void) {
#ifdef _WIN32
CloseHandle(m_ThreadHandle);
#endif
if (m_ThreadState != ctsTerminated) {
cerr << "CThread::~CThread(BOTH) - destructor violates thread termination!" << endl;
while (m_ThreadState != ctsTerminated)
base_sleep(0);
}
}
| [
"[email protected]"
] | [
[
[
1,
74
]
]
] |
a8f20f261dcd350c2067c2e2765003a365c6f54e | 10ca2ff28e0119ef1a96b26ef2336717fd48f6c2 | /source/mscommon.cpp | 7f845c4e7a5d31b4de5d58591adb0171e462df53 | [
"LicenseRef-scancode-other-permissive"
] | permissive | ysei/multiman-slim | e50a885f9f51c9f0101ff2b248485f287f79636f | ca165be2924304b2d786a81a9bc7d4901afb35bd | refs/heads/master | 2021-01-24T22:44:41.282547 | 2011-11-13T23:11:04 | 2011-11-13T23:11:04 | 15,376,393 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,784 | cpp | #include "mscommon.h"
static int audioInitCell(void);
// SPURS information
#define SPURS_SPU_NUM 1
#define SPU_THREAD_GROUP_PRIORITY 128
CellSpurs spurs __attribute__((aligned (128)));
sys_ppu_thread_t s_MultiStreamPuThread = 0;
void * s_pMultiStreamMemory = NULL;
#define CHANNEL CELL_AUDIO_PORT_8CH
#define BLOCK CELL_AUDIO_BLOCK_8
#define EXIT_CODE (0xbee)
/**********************************************************************************
audioInitCell
Returns: audio port number returned from cellAudioPortOpen(..)
**********************************************************************************/
static int audioInitCell(void)
{
int ret = 0;
unsigned int portNum = -1;
// cellMSSystemConfigureSysUtil returns the following data:
// Bits 0-3: Number of available output channels
// Bit 4: Dolby On status
// unsigned int retSysUtil = cellMSSystemConfigureSysUtil();
// unsigned int numChans = (retSysUtil & 0x0000000F);
// unsigned int dolbyOn = (retSysUtil & 0x00000010) >> 4;
// printf("Number Of Channels: %u\n", numChans);
// printf("Dolby enabled: %u\n", dolbyOn);
ret = cellAudioInit();
if (ret !=CELL_OK) return -1;
audioParam.nChannel = CHANNEL;
audioParam.nBlock = BLOCK;
ret = cellAudioPortOpen(&audioParam, &portNum);
if (ret != CELL_OK)
{
cellAudioQuit();
return -1;
}
ret = cellAudioGetPortConfig(portNum, &portConfig);
if (ret != CELL_OK)
{
cellAudioQuit();
return -1;
}
cellMSSystemConfigureLibAudio(&audioParam, &portConfig);
return portNum;
}
int InitSPURS(void)
{
int ret = -1;
sys_ppu_thread_t thread_id;
int ppu_thr_prio __attribute__((aligned (128))); // information for the reverb
sys_ppu_thread_get_id(&thread_id);
ret = sys_ppu_thread_get_priority(thread_id, &ppu_thr_prio);
if(ret == CELL_OK)
ret = cellSpursInitialize(&spurs, SPURS_SPU_NUM, SPU_THREAD_GROUP_PRIORITY, ppu_thr_prio-1, 1);
if(ret != CELL_OK) return -1;
return 1;
}
/**********************************************************************************
InitialiseAudio
This function sets up the audio system.
Requires: nStreams Maximum number of streams to be active at any time
nmaxSubs Maximum number of sub channels to init in MultiStream
_nPortNumber Reference to int - Returns port number from CELL audio init
_audioParam Reference to CellAudioPortParam - Returns audio params from CELL audio init
_portConfig Reference to CellAudioPortConfig - Returns port configuration from CELL audio init
Returns: 0 OK
-1 Error
**********************************************************************************/
long InitialiseAudio( const long nStreams, const long nmaxSubs, int &_nPortNumber , CellAudioPortParam &_audioParam, CellAudioPortConfig &_portConfig)
{
CellMSSystemConfig cfg;
uint8_t prios[8] = {13, 13, 13, 13, 13, 13, 13, 13};
cfg.channelCount=nStreams;
cfg.subCount=nmaxSubs;
cfg.dspPageCount=0;
cfg.flags=CELL_MS_DISABLE_SPU_PRINTF_SERVER | CELL_MS_TD_ONLY_128;
_nPortNumber = audioInitCell();
if(_nPortNumber < 0)
{
return -1;
}
_audioParam = audioParam;
_portConfig = portConfig;
// Initialise SPURS MultiStream version
int nMemoryNeeded = cellMSSystemGetNeededMemorySize(&cfg);
s_pMultiStreamMemory = memalign(128, nMemoryNeeded);
if(InitSPURS()==1)
cellMSSystemInitSPURS(s_pMultiStreamMemory, &cfg, &spurs, &prios[0]);
else return -1;
return 0;
}
void ShutdownMultiStream()
{
void* pMemory = cellMSSystemClose();
assert(pMemory == s_pMultiStreamMemory);
free( s_pMultiStreamMemory);
s_pMultiStreamMemory = NULL;
pMemory = NULL;
}
| [
"[email protected]"
] | [
[
[
1,
138
]
]
] |
4f81c3a4ac605c63f1a5ebda54588af929989c8d | 57f014e835e566614a551f70f2da15145c7683ab | /src/contour/contourframe.cpp | eaff6dc2102e3e3220f1cafcc9616ffd735f0a17 | [] | no_license | vcer007/contour | d5c3a1bbd7f5c948fbda9d9bbc7d40333640568d | 6917e4b4f24882df2111ca4af5634645cb2700eb | refs/heads/master | 2020-05-30T05:35:15.107140 | 2011-05-23T12:59:00 | 2011-05-23T12:59:00 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,791 | cpp | #include "contourframe.h"
#include "dialog/randsetdialog.h"
#include "dialog/tracesetdialog.h"
#include "dialog/colormapedit.h"
#include "../color/colormap.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QMessageBox>
#include <QTime>
#include <QDebug>
ContourFrame::ContourFrame(QFrame* parent /*= 0*/, Qt::WindowFlags f/* = 0*/)
:QFrame(parent,f)
{
setupUi(this);
setWindowTitle("Contour Tracing");
ycoordinate->setType(Coordinate::Vertical);
xcoordinate->setType(Coordinate::Horizonal);
_scatterData = NULL;
_out = NULL;
_fillColor = true;
_showGrid = true;
_isRand = false;
_showPoint = false;
_hasShowGrid = false;
_hasShowGrid = false;
_traceNum = 50;
tracer = new ContourTracer;
initial();
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
connect(horizontalScrollBar,SIGNAL(valueChanged(int)),view->horizontalScrollBar(),
SLOT(setValue(int)));
connect(verticalScrollBar,SIGNAL(valueChanged(int)),view->verticalScrollBar(),
SLOT(setValue(int)));
connect(view->horizontalScrollBar(),SIGNAL(valueChanged(int)),horizontalScrollBar,
SLOT(setValue(int)));
connect(view->verticalScrollBar(),SIGNAL(valueChanged(int)),verticalScrollBar,
SLOT(setValue(int)));
connect(view->horizontalScrollBar(),SIGNAL(rangeChanged(int,int)),this,
SLOT(setHorizonBar()));
connect(view->verticalScrollBar(),SIGNAL(rangeChanged(int,int)),this,
SLOT(setVerticalBar()));
connect(view->horizontalScrollBar(),SIGNAL(valueChanged(int)),
xcoordinate->horizontalScrollBar(),SLOT(setValue(int)));
connect(view->verticalScrollBar(),SIGNAL(valueChanged(int)),
ycoordinate->verticalScrollBar(),SLOT(setValue(int)));
connect(view,SIGNAL(setVCoordinate(float,float,float,float)),ycoordinate
,SLOT(addjust(float,float,float,float)));
connect(view,SIGNAL(setHCoordinate(float,float,float,float)),xcoordinate
,SLOT(addjust(float,float,float,float)));
connect(view,SIGNAL(indexChanged(int,int)),this,SLOT(setLabel(int,int)));
}
ContourFrame::~ContourFrame()
{
}
void ContourFrame::randContour()
{
delete _scatterData;
_isRand = true;
_scatterData = &(ScatterData::randScatterData(_randInfo.xMin,_randInfo.xMax,
_randInfo.yMin,_randInfo.yMax,
_randInfo.zMin,_randInfo.zMax,_randNum));
CGridDataInfo info;
info.zMin = _randInfo.zMin;
info.zMax = _randInfo.zMax;
info.cols = _randInfo.cols;
info.rows = _randInfo.rows;
_op.setScatterData(*_scatterData);
_op.setGridding(_randInfo.rows,_randInfo.cols);
double xMin , xMax ,yMin,yMax;
if(_out != NULL )
delete _out;
_out = &(_op.getGridding(xMin,xMax,yMin,yMax));
info.xMin = xMin;
info.xMax = xMax;
info.yMin = yMin;
info.yMax = yMax;
_gridData.data = _out;
_gridData.info = info;
_valueList.clear();
tracing();
}
void ContourFrame::tracing()
{
QTime tm;
tm.start();
CCurveList *pCurveList = new CCurveList ;
tracer->setGridDataInfo(_gridData.info);
tracer->setInput(*(_gridData.data));
if(_valueList.count() == 0)
{
float step = (_gridData.info.zMax - _gridData.info.zMin)/_traceNum;
for(int i=0;i<_traceNum;i++)
_valueList<<_gridData.info.zMin + i*step;
}
for(int i=0;i<_valueList.count();i++)
{
tracer->setOutput(pCurveList);
tracer->executeTracing(_valueList[i]);
}
qDebug()<<"time:traing:"<<tm.elapsed();tm.restart();
view->cleanData();
qDebug()<<"time:clean:"<<tm.elapsed();tm.restart();
view->setGridData(*pCurveList,_gridData.info);
view->drawData();
qDebug()<<"time:draw:"<<tm.elapsed();tm.restart();
_hasShowGrid = false; // 重新绘制网格
_hasShowColor = false; // 重新填充颜色
if(_fillColor)
setFillColor(true);
qDebug()<<"time:fill:"<<tm.elapsed();tm.restart();
if(_showGrid)
setGrid(true);
qDebug()<<"time:grid:"<<tm.elapsed();tm.restart();
if(_showPoint&_isRand)
view->drawScatterPoints(_scatterData);
colorFrame->setRange(_gridData.info.zMin,_gridData.info.zMax);
}
void ContourFrame::setHorizonBar()
{
horizontalScrollBar->setRange(view->horizontalScrollBar()->minimum(),
view->horizontalScrollBar()->maximum());
horizontalScrollBar->setPageStep(view->horizontalScrollBar()->pageStep());
}
void ContourFrame::setVerticalBar()
{
verticalScrollBar->setRange(view->verticalScrollBar()->minimum(),
view->verticalScrollBar()->maximum());
verticalScrollBar->setPageStep(view->verticalScrollBar()->pageStep());
}
void ContourFrame::setLabel(int i,int j)
{
if(i>=0&& i<=_gridData.info.cols -1&&j>=0&& j<=_gridData.info.rows -1 )
{
iLabel->setText("j: "+QString::number(j));
jLabel->setText("i: "+QString::number(i));
if(_gridData.data != NULL){
zLabel->setText(QString::number((*_gridData.data)[j][i]));
}
}
}
void ContourFrame::importGridFile()
{
_isRand = false;
QString fileName =QFileDialog::getOpenFileName(this,tr("open file"),QDir::homePath(),
tr("Grid Data Files (*.grd)"));
if(fileName=="") return;
if(_gridData.data != NULL)
{
delete _gridData.data;
_out = NULL;
}
QTime tm;
tm.start();
if(!ScatterData::readGridFile(QFile::encodeName ( fileName ).data(),_gridData)){
QMessageBox::warning(this,"warning","Open file error,the file"
" may be is not a right file!");
return;
}
qDebug()<<"time:reading:"<<tm.elapsed();
_valueList.clear();
tracing();
}
void ContourFrame::importScatterFile()
{
_isRand = true;
QString fileName = QFileDialog::getOpenFileName(this,tr("open file"),QDir::homePath(),
tr("Scatter Data Files (*.srd)"));
if(fileName=="") return;
if(_scatterData != NULL)
delete _scatterData;
if(!ScatterData::readScatterFile(QFile::encodeName ( fileName ).data(),&_scatterData)){
QMessageBox::warning(this,"warning","Open file error,the file"
" may be is not a right file!");
return;
}
CGridDataInfo info;
float f;
info.zMax = info.zMin = (*_scatterData)[0][2];
for(int i=0;i<_scatterData->getRowCount();i++)
{
f = (*_scatterData)[i][2];
if( f > info.zMax)
info.zMax = f;
else if(f <info.zMin)
info.zMin = f;
}
_op.setScatterData(*_scatterData);
_op.setGridding(_randInfo.cols,_randInfo.rows);
double xMin , xMax ,yMin,yMax;
Matrix out = _op.getGridding(xMin,xMax,yMin,yMax);
info.xMin = xMin;
info.xMax = xMax;
info.yMin = yMin;
info.yMax = yMax;
info.rows = _randInfo.rows;
info.cols = _randInfo.cols;
_gridData.data = &out;
_gridData.info = info;
_valueList.clear();
tracing();
}
void ContourFrame::saveRandData()
{
QString fileName = QFileDialog::getSaveFileName(this);
if(fileName =="") return;
_op.toScatterFile(fileName.toStdString());
}
void ContourFrame::saveGridData()
{
QString fileName = QFileDialog::getSaveFileName(this);
if(fileName =="") return;
_op.toGridFile(fileName.toStdString());
}
void ContourFrame::setRandInfo()
{
RandSetDialog *dialog = new RandSetDialog;
dialog->initialInfo(_randInfo,_randNum);
if(dialog->exec()){
dialog->getInfo(_randInfo,_randNum);
}
}
void ContourFrame::initial()
{
_randInfo.xMin = 0;
_randInfo.xMax = 9;
_randInfo.yMin = 10;
_randInfo.yMax = 15;
_randInfo.zMin = 50;
_randInfo.zMax = 100;
_randInfo.cols = 50;
_randInfo.rows = 50;
_randNum = 15;
QList<QColor> colors;
Rgb* sc = view->colorMap->getColors();//ColorMap::getColors();
for(int i=0;i<32;i++)
colors<<QColor(sc[i].r,sc[i].g,sc[i].b);
colorFrame->setColorMap(colors);
}
void ContourFrame::setTraceValue()
{
TraceDialog dialog;
dialog.setTraceValue(_valueList);
if(_isRand)
dialog.setDefault(_randInfo.zMin,_randInfo.zMax,_traceNum);
else
dialog.setDefault(_gridData.info.zMin,_gridData.info.zMax,_traceNum);
if(dialog.exec())
{
_valueList = dialog.getTraceValue();
_traceNum = dialog.getTraceNumber();
tracing();
}
}
void ContourFrame::editColorMap()
{
ColormapEdit *edit = new ColormapEdit(this);
connect(edit,SIGNAL(newColorList(QList<QColor>)),this,SLOT(newColorMap(QList<QColor>)));
Rgb* color = view->colorMap->getColors();
edit->setColorList(color);
edit->show();
}
void ContourFrame::newColorMap(QList<QColor> colors)
{
QTime a;
static int t1;
static int t2;
static int t3;
static int t4;
Rgb myColors[32];
for(int i=0;i<32;i++)
myColors[i] = Rgb(colors[i].red(),colors[i].green(),colors[i].blue());
view->colorMap->clear();
view->colorMap->setColor(myColors);
a.start();
view->colorMap->setRange(0,1);
view->colorMap->interpose(INTERPOSE_NUM);
t1+=a.elapsed();
qDebug()<<"interpose:"<<t1;a.restart();
colorFrame->setColorMap(colors);
t2+=a.elapsed();
qDebug()<<"setColorMap:"<<(t2);a.restart();
view->cleanColor();
t3+=a.elapsed();
qDebug()<<"cleanColor:"<<(t3);a.restart();
view->fillColor();
t4+=a.elapsed();
qDebug()<<"fillColor:"<<(t4);a.restart();
}
| [
"[email protected]"
] | [
[
[
1,
327
]
]
] |
c0f2832b9c176db3eade8922c1a0eda8dcc5ad57 | f9351a01f0e2dec478e5b60c6ec6445dcd1421ec | /itl/boost/itl_xt/enum_bitset.hpp | 66b700bf170e14b43e8b2417806b4a5c9b64479b | [
"BSL-1.0"
] | permissive | WolfgangSt/itl | e43ed68933f554c952ddfadefef0e466612f542c | 6609324171a96565cabcf755154ed81943f07d36 | refs/heads/master | 2016-09-05T20:35:36.628316 | 2008-11-04T11:44:44 | 2008-11-04T11:44:44 | 327,076 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,690 | hpp | /*----------------------------------------------------------------------------+
Copyright (c) 2007-2008: Joachim Faulhaber
+-----------------------------------------------------------------------------+
Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin
+-----------------------------------------------------------------------------+
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+----------------------------------------------------------------------------*/
#ifndef __itl_enum_bitset_JOFA_021204_H__
#define __itl_enum_bitset_JOFA_021204_H__
#include <bitset>
#include <boost/itl/notate.hpp>
namespace boost{namespace itl
{
template <class EnumT, size_t EnumSize>
class enum_bitset: public std::bitset<EnumSize>
{
public:
/// Default Ctor
enum_bitset() : std::bitset<EnumSize>(){}
/// Copy Ctor
enum_bitset(const enum_bitset& src): std::bitset<EnumSize>(src){}
/// Construct from unsigned
enum_bitset(unsigned long val): std::bitset<EnumSize>(val){}
/** Add the bit 'bit' to the set. This enables shorthand notation
myBitSet.add(bit_1).add(bit_2). ... .add(bit_n); */
enum_bitset& add(int bit){this->set(bit); return *this;}
};
}} // namespace itl boost
#endif // __itl_enum_bitset_JOFA_021204_H__
| [
"jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a"
] | [
[
[
1,
61
]
]
] |
3f13b9e01dee9d0e8245fc899e53f60e8e22ce36 | d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189 | /pyplusplus_dev/unittests/data/function_adaptor_to_be_exported.hpp | f32f3dcec498b06c7db780af63e9b2c3f1a70e1b | [
"BSL-1.0"
] | permissive | gatoatigrado/pyplusplusclone | 30af9065fb6ac3dcce527c79ed5151aade6a742f | a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede | refs/heads/master | 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,298 | hpp | // Copyright 2004-2008 Roman Yakovenko.
// 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)
#ifndef __function_adaptor_to_be_exported_hpp__
#define __function_adaptor_to_be_exported_hpp__
//#include <boost/preprocessor/facilities/identity.hpp>
//I need it for BOOST_PP_IDENTITY macro
#define PYPP_IDENTITY( X ) X
struct foo_t{
int get_zero() const{ return 0; }
static int get_two(){ return 2; }
};
inline int get_one(){ return 1; }
struct base_t{
protected:
virtual int get_zero() const { return 0; }
virtual int get_two() const { return 2; }
};
struct derived_t : public base_t{
protected:
virtual int get_two() const { return 22; }
};
struct base3_t{
protected:
virtual int get_zero() const = 0;
};
struct base4_t{
virtual int get_zero() const = 0;
};
class Foo
{
public:
Foo() { }
virtual ~Foo() { }
public:
virtual int virtual_public()
{
return 1;
}
int call_virtual_protected(){
return virtual_protected();
}
protected:
virtual int virtual_protected()
{
return 2;
}
};
#endif//__function_adaptor_to_be_exported_hpp__
| [
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] | [
[
[
1,
65
]
]
] |
f7686c7c53922907c87ace56c8f5bb6fdd401332 | 90aa2eebb1ab60a2ac2be93215a988e3c51321d7 | /castor/branches/boost/libs/castor/test/compile_pause_f.cpp | 4e27a2e3cf2890e7e388d70c989f8e7852954d11 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | roshannaik/castor | b9f4ea138a041fe8bccf2d8fc0dceeb13bcca5a6 | e86e2bf893719bf3164f9da9590217c107cbd913 | refs/heads/master | 2021-04-18T19:24:38.612073 | 2010-08-18T05:10:39 | 2010-08-18T05:10:39 | 126,150,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 333 | cpp | #include <boost/castor.h>
#include <boost/test/minimal.hpp>
using namespace castor;
int test_main(int, char * [])
{
{ // basic compilation checks only
lref<std::string> s;
lref<std::vector<std::string> > names;
relation r = item(s, names) && pause_f(s + "\n");
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
17
]
]
] |
28044116185b796e4d2e32baac2dd98bd0127bfb | a892ac72a3de1382f19a2b691874ff7a0572fcc8 | /Test/FogbugzAdd/FogbugzAdd.cpp | a22c4d4b2f3a322e4c56712baea3dd9c4b19e615 | [] | no_license | tjurik/fogbugzpp | 9cc2a247046561d5baa29f7dd12f68af52fef718 | b83f5c7c2c082cdb236e06ea4d908b1cddf25237 | refs/heads/master | 2021-01-10T22:57:34.661758 | 2010-12-28T03:54:46 | 2010-12-28T03:54:46 | 69,718,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,230 | cpp | /*
Copyright (c) 2010, Tim Jurik, Open Cage Software
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 Open Cage Software 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 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.
*/
#include "stdafx.h"
#include <iostream>
#include "CreateFogbugzCase.h"
using namespace std;
void Usage()
{
cout << "Usage:\nFogbugzAdd <FB url> <user> <password> <title> [content] [ScoutDescription] [Project]" << endl << endl;
}
int _tmain(int argc, char* argv[])
{
if (argc < 5)
{
Usage();
return 0;
}
string content;
string project;
string scout;
if (argc > 5)
{
content = argv[5];
}
if (argc > 6)
{
scout = argv[6];
}
if (argc > 7)
{
project = argv[7];
}
FogBugz fb(argv[1], argv[2], argv[3]);
string fbcase = fb.AddCase(argv[4], content, scout, project);
cout << "FB Case : " << fbcase << endl;
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
f400d878851b542958233215f122c821b696b4fc | 54745d6fa529d0adcd19a41e115bbccfb804b575 | /PokerPlayerMFC/PictureCtrl.h | d71d3efb900800e47b2f5f39a314a8662e5ad376 | [] | no_license | jackylee1/regretitron | e7a5f1a8794f0150b57f3ca679438d0f38984bca | bb241e6dea4d345e48d633da48ed2cfd410a5fdf | refs/heads/master | 2020-03-26T17:53:07.040365 | 2011-11-14T03:38:53 | 2011-11-14T03:38:53 | 145,185,451 | 0 | 1 | null | 2018-08-18T03:04:05 | 2018-08-18T03:04:04 | null | UTF-8 | C++ | false | false | 1,828 | h | ///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////
// PictureCtrl.h
//
// Author: Tobias Eiseler
//
// E-Mail: [email protected]
//
// Function: A MFC Picture Control to display
// an image on a Dialog, etc.
///////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//Note: I found this code at:
// http://www.codeproject.com/KB/graphics/CPictureControl.aspx
#pragma once
#include "afxwin.h"
#include <poker_defs.h> //for CardMask
class CPictureCtrl :
public CStatic
{
public:
//Constructor
CPictureCtrl(void);
//Destructor
~CPictureCtrl(void);
public:
//Loads an image from a CardMask
BOOL LoadFromCardMask(CardMask mycard);
//Loads an image from a file
BOOL LoadFromFile(CString szFilePath);
//Loads an image from an IStream interface
BOOL LoadFromStream(IStream* piStream);
//Loads an image from a byte stream;
BOOL LoadFromStream(BYTE* pData, size_t nSize);
//Loads an image from a Resource
// BOOL LoadFromResource(HMODULE hModule, LPCTSTR lpName, LPCTSTR lpType);
//Overload - Single load function
BOOL Load(CString &szFilePath);
BOOL Load(IStream* piStream);
BOOL Load(BYTE* pData, size_t nSize);
// BOOL Load(HMODULE hModule, LPCTSTR lpName, LPCTSTR lpType);
//Frees the image data
void FreeData();
protected:
virtual void PreSubclassWindow();
//Draws the Control
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
virtual BOOL OnEraseBkgnd(CDC* pDC);
private:
//Internal image stream buffer
IStream* m_pStream;
//Control flag if a pic is loaded
BOOL m_bIsPicLoaded;
//GDI Plus Token
ULONG_PTR m_gdiplusToken;
};
| [
"[email protected]"
] | [
[
[
1,
77
]
]
] |
2fff987f2acf5c85734d358444a6751167ac2a0b | 0454def9ffc8db9884871a7bccbd7baa4322343b | /src/report/QUPdfReport.cpp | 35ba9799542b66386866ce4f3940100026fc1620 | [] | no_license | escaped/uman | e0187d1d78e2bb07dade7ef6ef041b6ed424a2d3 | bedc1c6c4fc464be4669f03abc9bac93e7e442b0 | refs/heads/master | 2016-09-05T19:26:36.679240 | 2010-07-26T07:55:31 | 2010-07-26T07:55:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,072 | cpp | #include "QUPdfReport.h"
#include "QULogService.h"
#include <QPrinter>
#include <QPainter>
#include <QFont>
#include <QFontMetrics>
QUPdfReport::QUPdfReport(
const QList<QUSongFile*> &songFiles,
const QList<QUAbstractReportData*> &reportDataList,
const QFileInfo &fi,
QU::ReportOptions options,
const QVariant &userData,
QObject *parent): QUAbstractReport(songFiles, reportDataList, fi, options, userData, parent)
{
}
bool QUPdfReport::save() {
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileInfo().filePath());
printer.setPaperSize(QPrinter::A4);
printer.setPageMargins(10, 10, 10, 10, QPrinter::Millimeter);
QPainter painter;
painter.begin(&printer);
QFont f("Verdana", 12, QFont::Bold, false);
painter.setFont(f);
painter.drawText(printer.pageRect(), "Hello, World!", Qt::AlignTop | Qt::AlignLeft);
// printer.newPage();
painter.end();
logSrv->add(tr("Adding PDF report...done."), QU::Information);
return true;
}
| [
"[email protected]"
] | [
[
[
1,
44
]
]
] |
b2857b18cf78a552df277ef8319b702eaae79aa7 | dadae22098e24c412a8d8d4133c8f009a8a529c9 | /tp2/src/tp2/main.cpp | c89618b589ead5822ba49220bb8b4247f3c2d352 | [] | no_license | maoueh/PHS4700 | 9fe2bdf96576975b0d81e816c242a8f9d9975fbc | 2c2710fcc5dbe4cd496f7329379ac28af33dc44d | refs/heads/master | 2021-01-22T22:44:17.232771 | 2009-10-06T18:49:30 | 2009-10-06T18:49:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,982 | cpp | #include "application_manager.h"
#include "command_line.h"
#include "tp2_constants.h"
#include "tp2_simulation.h"
BOOL promptData(Vector4d& initialLinearVelocity, Vector4d& initialAngularVelocity);
void promptLinearVelocity(Vector4d& initialLinearVelocity);
void promptAngularVelocity(Vector4d& initialAngularVelocity);
BOOL gFirstRun = true;
int main(int argumentCount, const CHAR** arguments)
{
CommandLine commandLine(argumentCount, arguments);
BOOL continueLoop = !Tp2Constants::SKIP_DATA_INPUT;
do
{
Vector4d initialLinearVelocity = Tp2Constants::INITIAL_LINEAR_VELOCITY;
Vector4d initialAngularVelocity = Tp2Constants::INITIAL_ANGULAR_VELOCITY;
if ( !Tp2Constants::SKIP_DATA_INPUT )
{
BOOL breakLoop = promptData(initialLinearVelocity, initialAngularVelocity);
if ( breakLoop )
return 0;
}
cout << endl << "Fermer la fenetre pour recommencer pour revenir a la console" << endl << endl;
ApplicationManager::get()->startApplication(new Tp2Simulation(&commandLine,
initialLinearVelocity,
initialAngularVelocity));
// Les resultat sont afficher dans la simulation directement
ApplicationManager::destroy();
} while( continueLoop );
// Will never get to this point
return 0;
}
// The return value indicate the main loop to break the loop or not
BOOL promptData(Vector4d& initialLinearVelocity, Vector4d& initialAngularVelocity)
{
STRING simulationStart;
if (!gFirstRun)
{
cout << "Pesez la toucher [Enter] pour continuer la simulation ou q pour quitter : ";
getline(cin, simulationStart);
}
gFirstRun = false;
UINT quitLetterPosition = simulationStart.find("q");
if ( quitLetterPosition != string::npos )
return TRUE;
promptLinearVelocity(initialLinearVelocity);
promptAngularVelocity(initialAngularVelocity);
return FALSE;
}
void promptLinearVelocity(Vector4d& initialLinearVelocity)
{
BOOL validVelocity = FALSE;
do
{
STRING initialVelocityString;
cout << "Entrez la vitesse lineaire initiale comme suit Vx, Vy, Vz: ";
getline(cin, initialVelocityString);
CHAR* nextToken = NULL;
INT tokenCount = 0;
CHAR* token = strtok_s((CHAR*) initialVelocityString.c_str(), ", ", &nextToken);
while (token != NULL && tokenCount < 3) {
initialLinearVelocity[tokenCount++] = atof(token);
token = strtok_s(NULL, ", ", &nextToken);
}
validVelocity = tokenCount == 3;
if ( !validVelocity )
{
cout << "Nombre de composants invalide" << endl;
cout << "Vitesse lineaire initiale invalide, veuillez recommencer" << endl << endl;
}
} while( !validVelocity );
}
void promptAngularVelocity(Vector4d& initialAngularVelocity)
{
BOOL validVelocity = FALSE;
do
{
STRING initialVelocityString;
cout << "Entrez la vitesse angulaire initiale comme suit Wx, Wy, Wz: ";
getline(cin, initialVelocityString);
CHAR* nextToken = NULL;
INT tokenCount = 0;
CHAR* token = strtok_s((CHAR*) initialVelocityString.c_str(), ", ", &nextToken);
while (token != NULL && tokenCount < 3) {
initialAngularVelocity[tokenCount++] = atof(token);
token = strtok_s(NULL, ", ", &nextToken);
}
validVelocity = tokenCount == 3;
if ( !validVelocity )
{
cout << "Nombre de composants invalide" << endl;
cout << "Vitesse angulaire initiale invalide, veuillez recommencer" << endl << endl;
}
} while( !validVelocity );
}
| [
"[email protected]"
] | [
[
[
1,
119
]
]
] |
46826c8885eb8de3c14ee4f15d914f6ff73edb5f | 3276915b349aec4d26b466d48d9c8022a909ec16 | /c++/模板/stack/stack.h | a774063147f2c6128823f358161ddc5ca4a12f6f | [] | no_license | flyskyosg/3dvc | c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82 | 0279b1a7ae097b9028cc7e4aa2dcb67025f096b9 | refs/heads/master | 2021-01-10T11:39:45.352471 | 2009-07-31T13:13:50 | 2009-07-31T13:13:50 | 48,670,844 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,121 | h | #ifndef STACK_H
#define STACK_H
#include"stdafx.h"
template<typename T> //类模板
class c_stack
{
T * stack;
int m;
public:
c_stack(int n)
{
stack=new T [n];
m=-1;
}
void push(T a);
void pop();
};
template<typename T>
void c_stack<T> ::pop()
{
m--;
}
template<typename T>
void c_stack<T>:: push(T a)
{
cout<<"调用一般模板"<<endl;
m++;
stack[m]=a;
}
//类模板特化
template<>
class c_stack<char>
{
char * stack;
int m;
public:
c_stack(int n)
{
stack=new char [n];
m=-1;
}
void push(char a);
void pop();
};
void c_stack<char>::pop()
{
m--;
}
void c_stack<char>:: push(char a)
{
cout<<"调用特化"<<endl;
m++;
stack[m]=a;
}
template<class T,class T1> //函数模板
void c_push(T & a,T1 b)
{
cout<<"调用函数模板"<<endl;
a.push(b);
}
void c_push(c_stack<int> & a,int b) //函数模板特化
{
cout<<"调用函数模板特化"<<endl;
}
#endif | [
"[email protected]"
] | [
[
[
1,
94
]
]
] |
090a2405ab6083be827e0c208d9926d8310ee050 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /easyMule/easyMule/src/WorkLayer/AICHSyncThread.h | 20caf09c84ff9897099d95f3de2862379ea123d9 | [] | no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | h | /*
* $Id: AICHSyncThread.h 4483 2008-01-02 09:19:06Z soarchin $
*
* this file is part of eMule
* Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#pragma once
class CKnownFile;
class CSafeFile;
/////////////////////////////////////////////////////////////////////////////////////////
///CAICHSyncThread
class CAICHSyncThread : public CWinThread
{
DECLARE_DYNCREATE(CAICHSyncThread)
protected:
CAICHSyncThread();
public:
virtual BOOL InitInstance();
virtual int Run();
protected:
bool ConvertToKnown2ToKnown264(CSafeFile* pTargetFile);
private:
CTypedPtrList<CPtrList, CKnownFile*> m_liToHash;
};
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
] | [
[
[
1,
42
]
]
] |
a4582303cdf0b2a76bd01860c6cb7f0ec678fd99 | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/contrib/mpg123decoder/MP3Decoder.h | fdbeb4c04c7f11a96be5d4355ab30196c11f3f96 | [
"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 | UTF-8 | C++ | false | false | 2,978 | 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/audio/IDecoder.h>
#include <mpg123.h>
//#include <boost/thread/mutex.hpp>
#define STREAM_FEED_SIZE 1024
//////////////////////////////////////////////////////////////////////////////
using namespace musik::core::audio;
//////////////////////////////////////////////////////////////////////////////
class MP3Decoder : public IDecoder{
public:
MP3Decoder(void);
~MP3Decoder(void);
virtual void Destroy();
// virtual double Length();
virtual double SetPosition(double second,double totalLength);
// virtual bool GetFormat(unsigned long * SampleRate, unsigned long * Channels);
virtual bool GetBuffer(IBuffer *buffer);
virtual bool Open(musik::core::filestreams::IFileStream *fileStream);
private:
bool Feed();
// bool GuessLength();
private:
musik::core::filestreams::IFileStream *fileStream;
mpg123_handle *decoder;
unsigned long cachedLength;
long cachedRate;
int cachedChannels;
long sampleSize;
int lastMpg123Status;
// boost::mutex mutex;
};
| [
"[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e",
"Urioxis@6a861d04-ae47-0410-a6da-2d49beace72e"
] | [
[
[
1,
1
],
[
3,
5
],
[
7,
11
],
[
14,
15
],
[
19,
19
],
[
31,
35
],
[
37,
77
]
],
[
[
2,
2
],
[
6,
6
],
[
12,
13
],
[
16,
18
],
[
20,
30
],
[
36,
36
]
]
] |
9c4140430e530ea8a1db012f3ae252e055158391 | f2b4a9d938244916aa4377d4d15e0e2a6f65a345 | /Common/Army.h | 867a64d9bd5fa9538b52916c29037d0a480e933e | [
"Apache-2.0"
] | permissive | notpushkin/palm-heroes | d4523798c813b6d1f872be2c88282161cb9bee0b | 9313ea9a2948526eaed7a4d0c8ed2292a90a4966 | refs/heads/master | 2021-05-31T19:10:39.270939 | 2010-07-25T12:25:00 | 2010-07-25T12:25:00 | 62,046,865 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,451 | h | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#ifndef _HMM_COMMON_ARMY_H_
#define _HMM_COMMON_ARMY_H_
/////////////////////////////////////////////////////////////////////////
class iCreatGroup
{
private:
CREATURE_TYPE m_creatType;
sint32 m_count;
public:
iCreatGroup(CREATURE_TYPE ct = CREAT_UNKNOWN, sint32 count = RANDOM_QUANTITY);
inline void Reset(CREATURE_TYPE ct = CREAT_UNKNOWN, sint32 count = RANDOM_QUANTITY) { m_creatType = ct; m_count = count; }
inline bool IsValid() const { return m_creatType != CREAT_UNKNOWN; }
inline CREATURE_TYPE& Type() { return m_creatType; }
inline CREATURE_TYPE Type() const { return m_creatType; }
inline sint32& Count() { return m_count; }
inline sint32 Count() const { return m_count; }
inline uint32 GroupPower() const { return m_count*CREAT_DESC[m_creatType].pidx; }
void Grow(uint32 weeks = 1);
};
//////////////////////////////////////////////////////////////////////////
class iArmy
{
private:
iCreatGroup m_creatGroups[7];
public:
bool CanAddGroup(CREATURE_TYPE ct) const;
bool AddGroup(CREATURE_TYPE ct, sint32 count);
sint32 SlowestSpeed() const;
iCreatGroup& WeakestCreatures();
iCreatGroup& WeakestGroup();
bool JoinGroups();
void ResetGroup(uint32 idx);
void ResetArmy();
void SetGroup(uint32 idx, CREATURE_TYPE ct, sint32 count);
CREATURE_TYPE StrongestCreature() const;
sint32 MoraleModifier() const;
inline bool Empty() const
{
for (uint32 xx=0; xx<7; ++xx)
if (m_creatGroups[xx].Type() != CREAT_UNKNOWN)
return false;
return true;
}
inline bool HasCreatures(CREATURE_TYPE ct) const { for (uint32 xx=0; xx<7; ++xx) if (m_creatGroups[xx].Type() == ct) return true; return false; }
inline iCreatGroup& FirstGroup() { for (uint32 xx=0; xx<7; ++xx) if (m_creatGroups[xx].Type() != CREAT_UNKNOWN) return m_creatGroups[xx]; check(0); return m_creatGroups[0]; }
inline sint32 GroupCount() const { sint32 cnt=0; for (uint32 xx=0; xx<7; ++xx) if (m_creatGroups[xx].Type() != CREAT_UNKNOWN) ++cnt; return cnt; }
inline uint32 ArmyPower() const { uint32 res=0; for (uint32 xx=0; xx<7; ++xx) if (m_creatGroups[xx].Type() != CREAT_UNKNOWN) res += m_creatGroups[xx].GroupPower(); return res; }
inline const iCreatGroup& At(uint32 idx) const { check(idx<7); return m_creatGroups[idx]; }
inline iCreatGroup& At(uint32 idx) { check(idx<7); return m_creatGroups[idx]; }
inline const iCreatGroup& operator[](uint32 idx) const { return At(idx); }
inline iCreatGroup& operator[](uint32 idx) { return At(idx); }
void operator= (const iArmy& other) { memcpy(m_creatGroups, other.m_creatGroups, sizeof(m_creatGroups)); }
};
#endif //_HMM_COMMON_ARMY_H_
| [
"palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276"
] | [
[
[
1,
84
]
]
] |
9f35c51877a18526e299b36016fec83697d38a47 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/extras/collision/collision_dll/vmap/VMapManager.cpp | fffdd3cdc593c25e323e03bad71510561db34ada | [] | no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,349 | cpp | /*
* Copyright (C) 2005,2006,2007 MaNGOS <http://www.mangosproject.org/>
* Copyright (C) 2007-2008 Ascent Team <http://www.ascentemu.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 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
*/
#include "VMapManager.h"
#if defined(WIN32)
#define snprintf _snprintf
#endif
#define MAX_MAPS 600
namespace VMAP
{
inline bool IsTileMap(unsigned int mapid)
{
switch( mapid )
{
case 509:
case 469:
case 189:
case 30:
case 37:
case 33:
case 533:
case 209:
case 309:
case 560:
case 534:
case 532:
case 543:
case 568:
case 564:
case 0:
case 1:
case 530:
return true;
break;
default:
return false;
break;
}
}
static MapTree * m_maps[MAX_MAPS];
//=========================================================
VMapManager::VMapManager()
{
memset( m_maps, 0, sizeof(MapTree*) * MAX_MAPS );
}
//=========================================================
VMapManager::~VMapManager(void)
{
for(unsigned int i = 0; i < MAX_MAPS; ++i)
{
if( m_maps[i] != NULL )
delete m_maps[i];
m_maps[i] = NULL;
}
}
//=========================================================
inline Vector3 VMapManager::convertPositionToInternalRep(float x, float y, float z) const
{
float pos[3];
pos[0] = y;
pos[1] = z;
pos[2] = x;
double full = 64.0*533.33333333;
double mid = full/2.0;
pos[0] = full- (pos[0] + mid);
pos[2] = full- (pos[2] + mid);
return(Vector3(pos));
}
//=========================================================
inline Vector3 VMapManager::convertPositionToMangosRep(float x, float y, float z) const
{
float pos[3];
pos[0] = z;
pos[1] = x;
pos[2] = y;
double full = 64.0*533.33333333;
double mid = full/2.0;
pos[0] = -((mid+pos[0])-full);
pos[1] = -((mid+pos[1])-full);
return(Vector3(pos));
}
//=========================================================
//=========================================================
inline Vector3 VMapManager::convertPositionToInternalRep(LocationVector & vec) const
{
float pos[3];
pos[0] = vec.y;
pos[1] = vec.z;
pos[2] = vec.x;
double full = 64.0*533.33333333;
double mid = full/2.0;
pos[0] = full- (pos[0] + mid);
pos[2] = full- (pos[2] + mid);
return(Vector3(pos));
}
inline Vector3 VMapManager::convertPositionToInternalRepMod(LocationVector & vec) const
{
float pos[3];
pos[0] = vec.y;
pos[1] = vec.z + 2.0f;
pos[2] = vec.x;
double full = 64.0*533.33333333;
double mid = full/2.0;
pos[0] = full- (pos[0] + mid);
pos[2] = full- (pos[2] + mid);
return(Vector3(pos));
}
//=========================================================
inline Vector3 VMapManager::convertPositionToMangosRep(LocationVector & vec) const
{
float pos[3];
pos[0] = vec.y;
pos[1] = vec.z;
pos[2] = vec.x;
double full = 64.0*533.33333333;
double mid = full/2.0;
pos[0] = -((mid+pos[0])-full);
pos[1] = -((mid+pos[1])-full);
return(Vector3(pos));
}
inline LocationVector VMapManager::convertPositionToMangosRep(Vector3 & src) const
{
float pos[3];
pos[0] = src.z;
pos[1] = src.x;
pos[2] = src.y;
double full = 64.0*533.33333333;
double mid = full/2.0;
pos[0] = -((mid+pos[0])-full);
pos[1] = -((mid+pos[1])-full);
return LocationVector(pos[0], pos[1], pos[2]);
}
//=========================================================
std::string VMapManager::getDirFileName(unsigned int pMapId, int x, int y) const
{
char name[FILENAMEBUFFER_SIZE];
snprintf(name, FILENAMEBUFFER_SIZE, "%03u_%d_%d%s",pMapId, x, y, DIR_FILENAME_EXTENSION);
return(std::string(name));
}
//=========================================================
std::string VMapManager::getDirFileName(unsigned int pMapId) const
{
char name[FILENAMEBUFFER_SIZE];
snprintf(name, FILENAMEBUFFER_SIZE, "%03d%s",pMapId, DIR_FILENAME_EXTENSION);
return(std::string(name));
}
//=========================================================
// remote last return or LF
void chomp(std::string& str)
{
while(str.length() >0)
{
char lc = str[str.length()-1];
if(lc == '\r' || lc == '\n')
{
str = str.substr(0,str.length()-1);
}
else
{
break;
}
}
}
//=========================================================
void chompAndTrim(std::string& str)
{
while(str.length() >0)
{
char lc = str[str.length()-1];
if(lc == '\r' || lc == '\n' || lc == ' ' || lc == '"' || lc == '\'')
{
str = str.substr(0,str.length()-1);
}
else
{
break;
}
}
while(str.length() >0)
{
char lc = str[0];
if(lc == ' ' || lc == '"' || lc == '\'')
{
str = str.substr(1,str.length()-1);
}
else
{
break;
}
}
}
//=========================================================
int VMapManager::loadMap(const char* pBasePath, unsigned int pMapId, int x, int y)
{
bool result = false;
std::string dirFileName;
if( pMapId >= MAX_MAPS )
return false;
if( IsTileMap( pMapId ) )
dirFileName = getDirFileName( pMapId, x, y );
else
dirFileName = getDirFileName( pMapId );
MapTree* instanceTree = m_maps[pMapId];
if( instanceTree == NULL )
{
instanceTree = new MapTree( pBasePath );
m_maps[pMapId] = instanceTree;
}
unsigned int mapTileIdent = MAP_TILE_IDENT(x,y);
result = instanceTree->loadMap(dirFileName, mapTileIdent);
if(!result) // remove on fail
{
if(instanceTree->size() == 0)
{
m_maps[pMapId] = NULL;
delete instanceTree;
}
}
return(result);
}
//=========================================================
void VMapManager::unloadMap(unsigned int pMapId, int x, int y)
{
if( m_maps[pMapId] != NULL )
{
MapTree * instanceTree = m_maps[pMapId];
std::string dirFileName;
if( IsTileMap( pMapId ) )
dirFileName = getDirFileName( pMapId, x, y );
else
dirFileName = getDirFileName( pMapId );
unsigned int mapTileIdent = MAP_TILE_IDENT(x,y);
instanceTree->unloadMap(dirFileName, mapTileIdent);
if(instanceTree->size() == 0)
{
m_maps[ pMapId ] = NULL;
delete instanceTree;
}
}
}
//=========================================================
void VMapManager::unloadMap(unsigned int pMapId)
{
if( m_maps[pMapId] != NULL )
{
MapTree* instanceTree = m_maps[ pMapId ];
std::string dirFileName = getDirFileName(pMapId);
instanceTree->unloadMap(dirFileName, 0);
if(instanceTree->size() == 0)
{
m_maps[pMapId]=NULL;
delete instanceTree;
}
}
}
//==========================================================
bool VMapManager::isInLineOfSight(unsigned int pMapId, float x1, float y1, float z1, float x2, float y2, float z2)
{
bool result = true;
if( m_maps[pMapId] != NULL )
{
Vector3 pos1 = convertPositionToInternalRep(x1,y1,z1);
Vector3 pos2 = convertPositionToInternalRep(x2,y2,z2);
if(pos1 != pos2)
{
MapTree* mapTree = m_maps[pMapId];
result = mapTree->isInLineOfSight(pos1, pos2);
}
}
return(result);
}
bool VMapManager::isInLineOfSight(unsigned int pMapId, LocationVector & v1, LocationVector & v2)
{
bool result = true;
if( m_maps[pMapId] != NULL )
{
Vector3 pos1 = convertPositionToInternalRepMod(v1);
Vector3 pos2 = convertPositionToInternalRepMod(v2);
if(pos1 != pos2)
{
MapTree* mapTree = m_maps[pMapId];
result = mapTree->isInLineOfSight(pos1, pos2);
}
}
return(result);
}
bool VMapManager::isInDoors(unsigned int mapid, float x, float y, float z)
{
bool result = false;
if( m_maps[mapid] != NULL )
{
Vector3 pos = convertPositionToInternalRep(x,y,z);
MapTree* mapTree = m_maps[mapid];
result = mapTree->isInDoors(pos);
}
return(result);
}
bool VMapManager::isInDoors(unsigned int mapid, LocationVector & vec)
{
bool result = false;
if( m_maps[mapid] != NULL )
{
Vector3 pos = convertPositionToInternalRepMod(vec);
MapTree* mapTree = m_maps[mapid];
result = mapTree->isInDoors(pos);
}
return(result);
}
bool VMapManager::isOutDoors(unsigned int mapid, float x, float y, float z)
{
bool result = false;
if( m_maps[mapid] != NULL )
{
Vector3 pos = convertPositionToInternalRep(x,y,z);
MapTree* mapTree = m_maps[mapid];
result = mapTree->isOutDoors(pos);
}
return(result);
}
bool VMapManager::isOutDoors(unsigned int mapid, LocationVector & vec)
{
bool result = false;
if( m_maps[mapid] != NULL )
{
Vector3 pos = convertPositionToInternalRepMod(vec);
MapTree* mapTree = m_maps[mapid];
result = mapTree->isOutDoors(pos);
}
return(result);
}
//=========================================================
/**
get the hit position and return true if we hit something
otherwise the result pos will be the dest pos
*/
bool VMapManager::getObjectHitPos(unsigned int pMapId, float x1, float y1, float z1, float x2, float y2, float z2, float& rx, float &ry, float& rz, float pModifyDist)
{
bool result = false;
rx=x2;
ry=y2;
rz=z2;
if( m_maps[pMapId] != NULL )
{
Vector3 pos1 = convertPositionToInternalRep(x1,y1,z1);
Vector3 pos2 = convertPositionToInternalRep(x2,y2,z2);
Vector3 resultPos;
MapTree* mapTree = m_maps[pMapId];
result = mapTree->getObjectHitPos(pos1, pos2, resultPos, pModifyDist);
resultPos = convertPositionToMangosRep(resultPos.x,resultPos.y,resultPos.z);
rx = resultPos.x;
ry = resultPos.y;
rz = resultPos.z;
}
return result;
}
bool VMapManager::getObjectHitPos(unsigned int pMapId, LocationVector & v1, LocationVector & v2, LocationVector & vout, float pModifyDist)
{
bool result = false;
vout = v2;
if( m_maps[pMapId] != NULL )
{
Vector3 pos1 = convertPositionToInternalRepMod(v1);
Vector3 pos2 = convertPositionToInternalRepMod(v2);
Vector3 resultPos;
MapTree* mapTree = m_maps[pMapId];
result = mapTree->getObjectHitPos(pos1, pos2, resultPos, pModifyDist);
vout = convertPositionToMangosRep(resultPos);
}
return result;
}
//=========================================================
/**
get height or INVALID_HEIGHT if to hight was calculated
*/
//int gGetHeightCounter = 0;
float VMapManager::getHeight(unsigned int pMapId, float x, float y, float z)
{
float height = VMAP_INVALID_HEIGHT; //no height
if( m_maps[pMapId] != NULL )
{
Vector3 pos = convertPositionToInternalRep(x,y,z);
height = m_maps[pMapId]->getHeight(pos);
if(!(height < inf()))
{
return VMAP_INVALID_HEIGHT;
}
}
return(height);
}
float VMapManager::getHeight(unsigned int mapid, LocationVector & vec)
{
float height = VMAP_INVALID_HEIGHT; //no height
if( m_maps[mapid] != NULL )
{
Vector3 pos = convertPositionToInternalRepMod(vec);
height = m_maps[mapid]->getHeight(pos);
if(!(height < inf()))
{
return VMAP_INVALID_HEIGHT;
}
}
return(height);
}
//=========================================================
//=========================================================
//=========================================================
MapTree::MapTree(const char* pBaseDir)
{
iBasePath = std::string(pBaseDir);
if(iBasePath.length() > 0 && (iBasePath[iBasePath.length()-1] != '/' || iBasePath[iBasePath.length()-1] != '\\'))
{
iBasePath.append("/");
}
iTree = new AABSPTree<ModelContainer *>();
}
//=========================================================
MapTree::~MapTree()
{
Array<ModelContainer *> mcArray;
iTree->getMembers(mcArray);
int no = mcArray.size();
while(no >0)
{
--no;
delete mcArray[no];
}
delete iTree;
}
//=========================================================
// just for visual debugging with an external debug class
#ifdef _DEBUG_VMAPS
#ifndef gBoxArray
extern Vector3 p1,p2,p3,p4,p5,p6,p7;
extern Array<AABox>gBoxArray;
extern int gCount1, gCount2, gCount3, gCount4;
extern bool myfound;
#endif
#endif
typedef AABSPTree<ModelContainer*>::RayIntersectionIterator IT;
//=========================================================
/**
return dist to hit or inf() if no hit
*/
float MapTree::getIntersectionTime(const Ray& pRay, float pMaxDist, bool pStopAtFirstHit)
{
double firstDistance = inf();
const IT end = iTree->endRayIntersection();
IT obj = iTree->beginRayIntersection(pRay, pMaxDist);
for ( ;obj != end; ++obj) // (preincrement is *much* faster than postincrement!)
{
/*
Call your accurate intersection test here. It is guaranteed
that the ray hits the bounding box of obj. (*obj) has type T,
so you can call methods directly using the "->" operator.
*/
ModelContainer *model = (ModelContainer *) (*obj);
float t = model->getIntersectionTime(pRay, pStopAtFirstHit, pMaxDist);
// just for visual debugging with an external debug class
#ifdef _DEBUG_VMAPS
if(gCount3 == gCount1)
{
AABox testBox;
testBox = model->getAABoxBounds();
gBoxArray.append(testBox);
}
++gCount3;
#endif
if(t > 0 && t < inf())
{
obj.markBreakNode();
if(firstDistance > t && pMaxDist >= t)
{
firstDistance = t;
if(pStopAtFirstHit) break;
}
}
}
return firstDistance;
}
//=========================================================
bool MapTree::isInLineOfSight(const Vector3& pos1, const Vector3& pos2)
{
bool result = true;
float maxDist = abs((pos2 - pos1).magnitude());
// direction with length of 1
Ray ray = Ray::fromOriginAndDirection(pos1, (pos2 - pos1)/maxDist);
if(getIntersectionTime(ray, maxDist, true) < inf())
{
result = false;
}
return result;
}
//=========================================================
/**
When moving from pos1 to pos2 check if we hit an object. Return true and the position if we hit one
Return the hit pos or the original dest pos
*/
bool MapTree::getObjectHitPos(const Vector3& pPos1, const Vector3& pPos2, Vector3& pResultHitPos, float pModifyDist)
{
bool result;
float maxDist = abs((pPos2 - pPos1).magnitude());
Vector3 dir = (pPos2 - pPos1)/maxDist; // direction with length of 1
Ray ray = Ray::fromOriginAndDirection(pPos1, dir);
float dist = getIntersectionTime(ray, maxDist, false);
if(dist < inf())
{
pResultHitPos = pPos1 + dir * dist;
if(pModifyDist < 0)
{
if(abs((pResultHitPos - pPos1).magnitude()) > -pModifyDist)
{
pResultHitPos = pResultHitPos + dir*pModifyDist;
}
else
{
pResultHitPos = pPos1;
}
}
else
{
pResultHitPos = pResultHitPos + dir*pModifyDist;
}
result = true;
}
else
{
pResultHitPos = pPos2;
result = false;
}
return result;
}
//=========================================================
float MapTree::getHeight(const Vector3& pPos)
{
float height = inf();
Vector3 dir = Vector3(0,-1,0);
Ray ray = Ray::fromOriginAndDirection(pPos, dir); // direction with length of 1
float dist = getIntersectionTime(ray, MAX_CAN_FALL_DISTANCE, false);
if(dist < inf())
{
height = (pPos + dir * dist).y;
}
return(height);
}
//=========================================================
bool MapTree::isInDoors(const Vector3& pos)
{
Vector3 dir = Vector3(0,-1,0);
Ray ray = Ray::fromOriginAndDirection(pos, dir); // direction with length of 1
unsigned int flags;
AABSPTree<ModelContainer*>::RayIntersectionIterator MITR;
AABSPTree<ModelContainer*>::RayIntersectionIterator MITREND;
RayIntersectionIterator<TreeNode, SubModel> SMITR;
RayIntersectionIterator<TreeNode, SubModel> SMITREND;
ModelContainer * mc;
SubModel * sm;
MITR = iTree->beginRayIntersection( ray, MAX_CAN_FALL_DISTANCE );
MITREND = iTree->endRayIntersection();
for(; MITR != MITREND; ++MITR)
{
mc = ((ModelContainer*)*MITR);
Ray relativeRay = Ray::fromOriginAndDirection(ray.origin - mc->getBasePosition(), ray.direction);
SMITR = mc->beginRayIntersection( relativeRay, MAX_CAN_FALL_DISTANCE );
SMITREND = mc->endRayIntersection();
for( ; SMITR != SMITREND; ++SMITR )
{
sm = ((SubModel*)&(*SMITR));
#if 0
if( sm->getIndoorFlag() != 0 )
{
unsigned int i = sm->getIndoorFlag();
printf("=========================================================\n");
printf("Model indoor flags: %u\n", sm->getIndoorFlag());
unsigned int z, b;
for(z = 1, b = 1; b < 32;)
{
if(i & z)
printf(" Bit %u (0x%.8X or %u) is set!\n", b, z, z);
z <<= 1;
b+=1;
}
printf("=========================================================\n");
}
#else
flags = sm->getIndoorFlag();
if( flags != 0 )
{
/* From WoWdev:
Flag Meaning
0x1 Always set
0x4 Has vertex colors (MOCV chunk)
0x8 Outdoor
0x200 Has lights (MOLR chunk)
0x800 Has doodads (MODR chunk)
0x1000 Has water (MLIQ chunk)
0x2000 Indoor
0x40000 Show skybox
**********************
0x8000 seems to be set in the areas in citys (while it has the indoor flag, its not
an indoor area
*/
if( flags & 0x2000 && !(flags & 0x8000) )
return true;
}
#endif
}
}
return false;
}
bool MapTree::isOutDoors(const Vector3& pos)
{
Vector3 dir = Vector3(0,-1,0);
Ray ray = Ray::fromOriginAndDirection(pos, dir); // direction with length of 1
unsigned int flags;
AABSPTree<ModelContainer*>::RayIntersectionIterator MITR;
AABSPTree<ModelContainer*>::RayIntersectionIterator MITREND;
RayIntersectionIterator<TreeNode, SubModel> SMITR;
RayIntersectionIterator<TreeNode, SubModel> SMITREND;
ModelContainer * mc;
SubModel * sm;
MITR = iTree->beginRayIntersection( ray, MAX_CAN_FALL_DISTANCE );
MITREND = iTree->endRayIntersection();
for(; MITR != MITREND; ++MITR)
{
mc = ((ModelContainer*)*MITR);
Ray relativeRay = Ray::fromOriginAndDirection(ray.origin - mc->getBasePosition(), ray.direction);
SMITR = mc->beginRayIntersection( relativeRay, MAX_CAN_FALL_DISTANCE );
SMITREND = mc->endRayIntersection();
for( ; SMITR != SMITREND; ++SMITR )
{
sm = ((SubModel*)&(*SMITR));
#if 0
if( sm->getIndoorFlag() != 0 )
{
unsigned int i = sm->getIndoorFlag();
printf("=========================================================\n");
printf("Model indoor flags: %u\n", sm->getIndoorFlag());
unsigned int z, b;
for(z = 1, b = 1; b < 32;)
{
if(i & z)
printf(" Bit %u (0x%.8X or %u) is set!\n", b, z, z);
z <<= 1;
b+=1;
}
printf("=========================================================\n");
}
#else
flags = sm->getIndoorFlag();
if( flags != 0 )
{
/* From WoWdev:
Flag Meaning
0x1 Always set
0x4 Has vertex colors (MOCV chunk)
0x8 Outdoor
0x200 Has lights (MOLR chunk)
0x800 Has doodads (MODR chunk)
0x1000 Has water (MLIQ chunk)
0x2000 Indoor
0x40000 Show skybox
**********************
0x8000 seems to be set in the areas in citys (while it has the indoor flag, its not
an indoor area
*/
if( !(flags & 0x8) )
return false;
}
#endif
}
}
return true;
}
//=========================================================
bool MapTree::loadMap(const std::string& pDirFileName, unsigned int pMapTileIdent)
{
bool result = true;
size_t len = iBasePath.length() + pDirFileName.length();
char *filenameBuffer = new char[len+1];
if(!hasDirFile(pDirFileName))
{
FilesInDir filesInDir;
result = false;
sprintf(filenameBuffer, "%s%s", iBasePath.c_str(), pDirFileName.c_str());
FILE* df = fopen(filenameBuffer, "rb");
if(df)
{
char lineBuffer[FILENAMEBUFFER_SIZE];
result = true;
bool newModelLoaded = false;
while(result && (fgets(lineBuffer, FILENAMEBUFFER_SIZE-1, df) != 0))
{
std::string name = std::string(lineBuffer);
chomp(name);
if(name.length() >1)
{
filesInDir.append(name);
ManagedModelContainer *mc;
if(!isAlreadyLoaded(name))
{
std::string fname = iBasePath;
fname.append(name);
mc = new ManagedModelContainer();
result = mc->readFile(fname.c_str());
if(result)
{
addModelConatiner(name, mc);
newModelLoaded = true;
}
else
delete mc;
}
else
{
mc = getModelContainer(name);
}
mc->incRefCount();
}
}
if(result && newModelLoaded)
{
iTree->balance();
}
if(result && ferror(df) != 0)
{
result = false;
}
fclose(df);
if(result)
{
filesInDir.incRefCount();
addDirFile(pDirFileName, filesInDir);
setLoadedMapTile(pMapTileIdent);
}
}
}
else
{
// Already loaded, so just inc. the ref count if mapTileIdent is new
if(!containsLoadedMapTile(pMapTileIdent))
{
setLoadedMapTile(pMapTileIdent);
FilesInDir& filesInDir = getDirFiles(pDirFileName);
filesInDir.incRefCount();
}
}
delete [] filenameBuffer;
return (result);
}
//=========================================================
void MapTree::unloadMap(const std::string& dirFileName, unsigned int pMapTileIdent)
{
if(hasDirFile(dirFileName) && containsLoadedMapTile(pMapTileIdent))
{
if(containsLoadedMapTile(pMapTileIdent))
removeLoadedMapTile(pMapTileIdent);
FilesInDir& filesInDir = getDirFiles(dirFileName);
filesInDir.decRefCount();
if(filesInDir.getRefCount() <= 0)
{
Array<std::string> fileNames = filesInDir.getFiles();
bool treeChanged = false;
for(int i=0; i<fileNames.size(); ++i)
{
std::string name = fileNames[i];
ManagedModelContainer* mc = getModelContainer(name);
mc->decRefCount();
if(mc->getRefCount() <= 0)
{
iLoadedModelContainer.remove(name);
iTree->remove(mc);
delete mc;
treeChanged = true;
}
}
iLoadedDirFiles.remove(dirFileName);
if(treeChanged)
{
iTree->balance();
}
}
}
}
//=========================================================
//=========================================================
void MapTree::addModelConatiner(const std::string& pName, ManagedModelContainer *pMc)
{
iLoadedModelContainer.set(pName, pMc);
iTree->insert(pMc);
}
//=========================================================
//=========================================================
//=========================================================
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
] | [
[
[
1,
534
],
[
536,
697
],
[
699,
867
],
[
870,
909
]
],
[
[
535,
535
],
[
698,
698
],
[
868,
869
]
]
] |
a24872d96dda8b350fec68e2c6eb9f00bd162d64 | 37334008977a7a644cbbc2f2a828bc1d150c0638 | /win32/MD/Tools/SCD_RAM_GEN/scd_ram_gen/scd_ram_genDlg.h | 56084c8b19c3477f5d873b7bc48ce090870ad4bb | [] | no_license | titanlab/neo-myth-plugins | 91e797d69620981edf229c6186805bf0a49f0cc2 | de41771c9772a5f02f165d4f36fb1ec6f134a29a | refs/heads/master | 2021-09-08T12:17:24.494573 | 2011-11-19T15:17:42 | 2011-11-19T15:17:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,475 | h | // scd_ram_genDlg.h : header file
//
#if !defined(AFX_SCD_RAM_GENDLG_H__DE9B6FF5_AAEB_403C_A06F_82FB951A181D__INCLUDED_)
#define AFX_SCD_RAM_GENDLG_H__DE9B6FF5_AAEB_403C_A06F_82FB951A181D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////
// CScd_ram_genDlg dialog
class CScd_ram_genDlg : public CDialog
{
// Construction
public:
CScd_ram_genDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CScd_ram_genDlg)
enum { IDD = IDD_SCD_RAM_GEN_DIALOG };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CScd_ram_genDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CScd_ram_genDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
virtual void OnOK();
afx_msg void OnSystem();
afx_msg void OnButton1();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SCD_RAM_GENDLG_H__DE9B6FF5_AAEB_403C_A06F_82FB951A181D__INCLUDED_)
| [
"conleon1988@bb221dbb-59eb-094c-fa1a-8ce0a11b4692"
] | [
[
[
1,
52
]
]
] |
441f14df0b1be0eef53e9a370d8715e62d35894c | f0c08b3ddefc91f1fa342f637b0e947a9a892556 | /branches/develop/cppreflect/src/NonCopyable.cpp | 01b02de52276663ca968c16774771f4291a864e7 | [] | no_license | BackupTheBerlios/coffeestore-svn | 1db0f60ddb85ccbbdfeb9b3271a687b23e29fc8f | ddee83284fe9875bf0d04e6b7da7a2113e85a040 | refs/heads/master | 2021-01-01T05:30:22.345767 | 2009-10-11T08:55:35 | 2009-10-11T08:55:35 | 40,725,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 94 | cpp | #include "NonCopyable.hpp"
namespace reflect {
NonCopyable::NonCopyable()
{
}
}
| [
"fabioppp@e591b805-c13a-0410-8b2d-a75de64125fb"
] | [
[
[
1,
10
]
]
] |
5c866a3d1f21c9afc192cbb5a3b7849c594057db | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian-r6/MapContainer.cpp | 88e36ccefb1f5b67d96e7576b21d106c5806635f | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,313 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// INCLUDE FILES
#include "MapContainer.h"
#include "wayfinder.hrh"
#include "WayFinderConstants.h"
#include "GuidePicture.h"
#include "MapView.h"
/* For the bitmap enum. */
#include "wficons.mbg"
#include "RsgInclude.h"
#include "memlog.h"
#include "WayFinderAppUi.h"
#include "debuggingdefines.h"
#include "CellDataDrawer.h"
#include "Dialogs.h"
#if defined NAV2_CLIENT_SERIES60_V2 || defined NAV2_CLIENT_SERIES60_V3
#include <aknsdrawutils.h>
#endif
const TInt cScreenWidth = 176;
const TInt cNormalScreenHeight = 144;
const TInt cFullScreenHeight = 208;
const TInt cFullScreenOffset = 5;
const TInt cFullMapWidth = 186; // Width + 2*offset
const TInt cFullMapHeight = 218; // Height + 2*offset
/* const TInt cZoomInWidth = 470; */
/* const TInt cZoomInHeight = 510; */
/* const TInt cZoomOutWidth = 282; */
/* const TInt cZoomOutHeight = 306; */
_LIT( KGifPosition, "position.gif" );
// Enumarations
enum TControls
{
ENormalMap,
EFullScreenMap,
EPositionSprite1,
EPositionSprite2,
EPositionSprite3,
EPositionSprite4,
ETurnPicture,
#ifdef DEBUG_CELL
ECellData,
#endif
ENumberControls
};
// ================= MEMBER FUNCTIONS =======================
// ---------------------------------------------------------
// CMapContainer::ConstructL(const TRect& aRect)
// EPOC two phased constructor
// ---------------------------------------------------------
//
void CMapContainer::ConstructL( const TRect& aRect,
CMapView* aView,
CGuidePicture* aNormalMap,
TBool aHasRoute )
{
CreateWindowL();
iView = aView;
iWidth = cScreenWidth;
iHeight = cNormalScreenHeight;
iNormalRect = aRect;
SetRect(aRect);
if( aNormalMap == NULL ){
iNormalMap = new (ELeave) CGuidePicture( iLog );
LOGNEW(iNormalMap, CGuidePicture);
iNormalMap->ConstructL( TRect( TPoint(0,0), TSize( cScreenWidth, cNormalScreenHeight ) ), this );
iNormalMap->SetShow( ETrue );
iNormalMap->SetClear( EFalse );
} else {
iNormalMap = aNormalMap;
iNormalMap->SetPictureContainer( this );
iNormalMap->SetShow( ETrue );
}
iFullScreenMap = new (ELeave) CGuidePicture( iLog );
LOGNEW(iFullScreenMap, CGuidePicture);
iFullScreenMap->ConstructL( TRect( TPoint(0,0), TSize( cFullMapWidth, cFullMapHeight ) ), this );
iFullScreenMap->SetShow( EFalse );
iFullScreenMap->SetClear( EFalse );
GuiDataStore* gds = iView->GetGuiDataStore();
HBufC* wfmbmname = gds->iWayfinderMBMFilename;
/* Create new position image for 22.5 degree angles. */
iPositionSprite22 = new (ELeave) CGuidePicture( iLog );
LOGNEW(iPositionSprite22, CGuidePicture);
iPositionSprite22->ConstructL( TRect( TPoint(0,0), TSize( 21, 21 ) ), this );
iPositionSprite22->OpenBitmapFromMbm(*wfmbmname, EMbmWficonsBbb4_r);
iPositionSprite22->OpenBitmapMaskFromMbm(*wfmbmname, EMbmWficonsBbb4);
iPositionSprite22->SetShow( EFalse );
iPositionSprite22->SetClear( EFalse );
iOldDir22 = 0;
/* Create new position image for 45 degree angles. */
iPositionSprite45 = new (ELeave) CGuidePicture( iLog );
LOGNEW(iPositionSprite45, CGuidePicture);
iPositionSprite45->ConstructL( TRect( TPoint(0,0), TSize( 21, 21 ) ), this );
iPositionSprite45->OpenBitmapFromMbm(*wfmbmname, EMbmWficonsBbb1_r);
iPositionSprite45->OpenBitmapMaskFromMbm(*wfmbmname, EMbmWficonsBbb1);
iPositionSprite45->SetShow( EFalse );
iPositionSprite45->SetClear( EFalse );
iOldDir45 = 0;
/* Create new position image for 67.5 degree angles. */
iPositionSprite67 = new (ELeave) CGuidePicture( iLog );
LOGNEW(iPositionSprite67, CGuidePicture);
iPositionSprite67->ConstructL( TRect( TPoint(0,0), TSize( 21, 21 ) ), this );
iPositionSprite67->OpenBitmapFromMbm(*wfmbmname, EMbmWficonsBbb3_r);
iPositionSprite67->OpenBitmapMaskFromMbm(*wfmbmname, EMbmWficonsBbb3);
iPositionSprite67->SetShow( EFalse );
iPositionSprite67->SetClear( EFalse );
iOldDir67 = 3;
/* Create new position image for 90 degree angles. */
iPositionSprite90 = new (ELeave) CGuidePicture( iLog );
LOGNEW(iPositionSprite90, CGuidePicture);
iPositionSprite90->ConstructL( TRect( TPoint(0,0), TSize( 21, 21 ) ), this );
iPositionSprite90->OpenBitmapFromMbm(*wfmbmname, EMbmWficonsBbb2_r);
iPositionSprite90->OpenBitmapMaskFromMbm(*wfmbmname, EMbmWficonsBbb2);
iPositionSprite90->SetShow( EFalse );
iPositionSprite90->SetClear( EFalse );
iOldDir90 = 0;
#ifdef DEBUG_CELL
iCellDataDrawer = new(ELeave) CCellDataDrawer();
LOGNEW(iCellDataDrawer, CCellDataDrawer);
iCellDataDrawer->ConstructL(TRect(TPoint(0,0), TSize( cScreenWidth, cNormalScreenHeight )));
#endif
iCenterOffsetX = 10;
iCenterOffsetY = 10;
iTurnPicture = new (ELeave) CGuidePicture( iLog );
LOGNEW(iTurnPicture, CGuidePicture);
iTurnPicture->ConstructL( TRect( TPoint( 133, 1 ), TSize( 42, 36 ) ), this );
if( aView->IsGpsAllowed() ){
iTurnPicture->SetShow( aHasRoute );
}
else{
iTurnPicture->SetShow( EFalse );
}
iTurnPicture->SetClear( EFalse );
iOffset.iX = 0;
iOffset.iY = 0;
iMaxOffsetX = cScreenWidth-cFullMapWidth;
iMaxOffsetY = cFullScreenHeight-cFullMapHeight;
iHeading = 0;
ActivateL();
}
// Destructor
CMapContainer::~CMapContainer()
{
//iNormalMap is deleted in the view
LOGDEL(iFullScreenMap);
delete iFullScreenMap;
LOGDEL(iPositionSprite22);
delete iPositionSprite22;
LOGDEL(iPositionSprite45);
delete iPositionSprite45;
LOGDEL(iPositionSprite90);
delete iPositionSprite90;
LOGDEL(iPositionSprite67);
delete iPositionSprite67;
LOGDEL(iTurnPicture);
delete iTurnPicture;
#ifdef DEBUG_CELL
LOGDEL(iCellDataDrawer);
delete iCellDataDrawer;
#endif
}
TInt CMapContainer::GetStaticOffset()
{
return cFullScreenOffset;
}
void CMapContainer::GetStaticSize( TUint16 &aX, TUint16 &aY )
{
aX = cScreenWidth;
aY = cNormalScreenHeight;
}
CGuidePicture* CMapContainer::GetNormalMapPtr()
{
return iNormalMap;
}
void CMapContainer::SetMapImage( TDesC &aMapName )
{
if( iIsFullScreen ){
iFullScreenMap->OpenGif( aMapName );
}
else{
iNormalMap->OpenGif( aMapName );
}
DrawNow();
}
void CMapContainer::SetMapImage( HBufC8* aMapImage )
{
if( iIsFullScreen ){
iFullScreenMap->OpenDesc( aMapImage );
} else{
iNormalMap->OpenDesc( aMapImage );
}
DrawNow();
}
void CMapContainer::SetFullScreen( TBool aFullScreen )
{
iIsFullScreen = aFullScreen;
if( aFullScreen ){
SetExtentToWholeScreen();
iWidth = cFullMapWidth;
iHeight = cFullMapHeight;
}
else{
SetRect( iNormalRect );
iWidth = cScreenWidth;
iHeight = cNormalScreenHeight;
}
iFullScreenMap->SetShow( aFullScreen );
iNormalMap->SetShow( !aFullScreen );
}
TBool CMapContainer::IsFullScreen()
{
return iIsFullScreen;
}
TBool CMapContainer::SetScreenOffset( TInt &aX, TInt &aY, TInt aOffset )
{
TBool outOfBounds = EFalse;
if( aX > aOffset || aX < (iMaxOffsetX - aOffset) ||
aY > aOffset || aY < (iMaxOffsetY - aOffset) )
outOfBounds = ETrue;
iFullScreenMap->SetScreenOffset( aX, aY );
iPosition.iX += aX-iOffset.iX;
iPosition.iY += aY-iOffset.iY;
iPositionSprite22->SetScreenOffset( iPosition.iX, iPosition.iY);
iPositionSprite45->SetScreenOffset( iPosition.iX, iPosition.iY);
iPositionSprite67->SetScreenOffset( iPosition.iX, iPosition.iY);
iPositionSprite90->SetScreenOffset( iPosition.iX, iPosition.iY);
iOffset.iX = aX;
iOffset.iY = aY;
return outOfBounds;
}
void CMapContainer::GetMaxOffset( TInt &aX, TInt &aY )
{
aX = iMaxOffsetX;
aY = iMaxOffsetY;
}
void CMapContainer::GetPixelSize( TUint16 &aX, TUint16 &aY )
{
aX = iWidth;
aY = iHeight;
}
void CMapContainer::GetScreenSize( TUint16 &aX, TUint16 &aY )
{
aX = cScreenWidth;
if( iIsFullScreen )
aY = cFullScreenHeight;
else
aY = cNormalScreenHeight;
}
void CMapContainer::CloseMapFile()
{
if( iIsFullScreen ){
iFullScreenMap->CloseImage();
}
else{
iNormalMap->CloseImage();
}
}
const TInt CMapContainer::GetNormalScreenHeight()
{
return cNormalScreenHeight;
}
/* aHeading is no longer set!!! */
TBool CMapContainer::SetPixelPosition( TBool aShow, TInt aX, TInt aY,
TInt /* aHeading */, TInt aRealHeading )
{
TBool rotated = EFalse;
TBool rotated2 = EFalse;
if( aShow ) {
CGuidePicture* curImage;
/* Make sure that the angle is between 0 and 255. */
if (aRealHeading < 0) {
aRealHeading += 256;
}
#define USE_POSITION_IMAGES
#ifdef USE_POSITION_IMAGES
/* Divide by 16 to get values in the range 0 to 15. */
/* Add 8 to the base value to get true rounded values. */
/* This means that the value 0 in newdir means an angle */
/* of 8-16 degrees, 1 in newdir means 16-24, ... */
/* and 15 in newdir means 248-8. */
TInt newdir = ((aRealHeading+8)%256) / 16;
TInt* olddir;
switch (newdir % 4) {
case 0:
/* Even 64 degree angles. (0, 64, 128, 192) */
curImage = iPositionSprite90;
iPositionSprite22->SetShow( EFalse );
iPositionSprite45->SetShow( EFalse );
iPositionSprite67->SetShow( EFalse );
iPositionSprite90->SetShow( ETrue );
olddir = &iOldDir90;
break;
case 1:
/* 16 degree angles. (16, 80, 144, 208) */
curImage = iPositionSprite22;
iPositionSprite22->SetShow( ETrue );
iPositionSprite45->SetShow( EFalse );
iPositionSprite67->SetShow( EFalse );
iPositionSprite90->SetShow( EFalse );
olddir = &iOldDir22;
break;
case 2:
/* 32 degree angles. (32, 96, 160, 224) */
curImage = iPositionSprite45;
iPositionSprite22->SetShow( EFalse );
iPositionSprite45->SetShow( ETrue );
iPositionSprite67->SetShow( EFalse );
iPositionSprite90->SetShow( EFalse );
olddir = &iOldDir45;
break;
case 3:
/* 48 degree angles. (48, 112, 176, 240) */
curImage = iPositionSprite67;
iPositionSprite22->SetShow( EFalse );
iPositionSprite45->SetShow( EFalse );
iPositionSprite67->SetShow( ETrue );
iPositionSprite90->SetShow( EFalse );
olddir = &iOldDir67;
break;
default:
iPositionSprite22->SetShow( ETrue );
iPositionSprite45->SetShow( ETrue );
iPositionSprite67->SetShow( ETrue );
iPositionSprite90->SetShow( ETrue );
return EFalse;
break;
}
/* Check rotation. */
TInt newdir2 = newdir / 4;
CGuidePicture::TImageRotateAngle rotation = CGuidePicture::ENoRotation;
TInt foo = newdir2-(*olddir);
if (foo < 0) {
/* Negative rotation. */
/* Convert the rotation in counter clockwise direction */
/* to the appropriate number of rotations in the */
/* clockwise direction. */
foo += 4;
}
switch (foo) {
case 0:
/* No rotation needed. */
break;
case 1:
/* Need rotation 90 degrees. */
rotation = CGuidePicture::E90Degrees;
break;
case 2:
/* Need rotation 180 degrees. */
rotation = CGuidePicture::E180Degrees;
break;
case 3:
/* Need rotation 270 degrees. */
rotation = CGuidePicture::E270Degrees;
break;
default:
/* This is an impossible value! */
return EFalse;
break;
}
if (curImage->IsReady() && rotation != CGuidePicture::ENoRotation) {
/* Need to rotate. */
rotated2 = curImage->RotateImageClockwiseL( rotation );
*olddir = newdir2;
}
iPosition.iX = aX;
iPosition.iY = iHeight-aY;
iPosition.iX -= iCenterOffsetX;
iPosition.iY -= iCenterOffsetY;
iPositionSprite22->SetScreenOffset( iPosition.iX, iPosition.iY);
iPositionSprite45->SetScreenOffset( iPosition.iX, iPosition.iY);
iPositionSprite67->SetScreenOffset( iPosition.iX, iPosition.iY);
iPositionSprite90->SetScreenOffset( iPosition.iX, iPosition.iY);
} else {
iPositionSprite22->SetShow( EFalse );
iPositionSprite45->SetShow( EFalse );
iPositionSprite67->SetShow( EFalse );
iPositionSprite90->SetShow( EFalse );
}
#else
/* Draw the position indicator as a vector triangle. */
#endif
return rotated;
}
void CMapContainer::SetTurnPictureL( TInt aMbmIndex )
{
if( aMbmIndex >= 0 ){
/*HBufC* mbmName = iView->GetMbmName();
CleanupStack::PushL(mbmName);*/
iTurnPicture->SetShow( ETrue );
iTurnPicture->OpenBitmapFromMbm( iView->GetMbmName(), aMbmIndex );
//CleanupStack::PopAndDestroy (mbmName);
}
else{
iTurnPicture->SetShow( EFalse );
}
}
/*void CMapContainer::SetTurnPicture( TPictures aTurn,
TDesC &aFullPath,
TBool aRightTraffic )
{
TBuf<256> aFileName ( aFullPath );
iTurnPicture->SetShow( ETrue );
switch( aTurn )
{
case E3WayLeft:
case E3WayTeeLeft:
case E4WayLeft:
case ELeftArrow:
case ERdbLeft:
aFileName.Append(KGifSmallLeftArrow);
break;
case E3WayRight:
case E3WayTeeRight:
case E4WayRight:
case ERdbRight:
case ERightArrow:
aFileName.Append(KGifSmallRightArrow);
break;
case E4WayStraight:
case EHighWayStraight:
case EStraight:
case EStraightArrow:
case ERdbStraight:
aFileName.Append(KGifSmallStraightArrow);
break;
case EEnterHighWay:
case EEnterMainRoad:
if( aRightTraffic ){
aFileName.Append(KGifSmallKeepLeft);
}
else{
aFileName.Append(KGifSmallKeepRight);
}
break;
case EExitHighWayLeft:
case EExitMainRoadLeft:
case EKeepLeft:
aFileName.Append(KGifSmallKeepLeft);
break;
case EExitHighWay:
case EExitMainRoad:
if( aRightTraffic ){
aFileName.Append(KGifSmallKeepRight);
}
else{
aFileName.Append(KGifSmallKeepLeft);
}
break;
case EExitHighWayRight:
case EExitMainRoadRight:
case EKeepRight:
aFileName.Append(KGifSmallKeepRight);
break;
case EFerry:
aFileName.Append(KGifSmallFerry);
break;
case EFinishArrow:
case EFinishFlag:
aFileName.Append(KGifSmallFlag);
break;
case EMultiWayRdb:
if (aRightTraffic) {
aFileName.Append(KGifSmallMultiWayRdb);
} else {
aFileName.Append(KGifSmallMultiWayRdbLeft);
}
break;
case EPark:
aFileName.Append(KGifSmallPark);
break;
case ERdbUTurn:
case EUTurn:
if (aRightTraffic) {
aFileName.Append(KGifSmallUTurn);
} else {
aFileName.Append(KGifSmallUTurnLeft);
}
break;
default:
iTurnPicture->SetShow( EFalse );
break;
}
iTurnPicture->OpenGif(aFileName);
}*/
void CMapContainer::HideTurnPicture()
{
iTurnPicture->SetShow( EFalse );
}
void CMapContainer::PictureError( TInt aError )
{
iView->PictureError( aError );
}
void CMapContainer::ScalingDone()
{
DrawNow();
}
// ----------------------------------------------------------------------------
// TKeyResponse CGuideContainer::OfferKeyEventL( const TKeyEvent&,
// TEventCode )
// Handles the key events.
// ----------------------------------------------------------------------------
//
TKeyResponse CMapContainer::OfferKeyEventL( const TKeyEvent& aKeyEvent,
TEventCode aType )
{
if ( aType != EEventKey ){ // Is not key event?
return EKeyWasNotConsumed;
}
if ( aKeyEvent.iScanCode == EStdKeyDevice3 ){
iView->HandleCommandL( EWayFinderCmdMapReroute );
return EKeyWasConsumed;
}
else{
if( iIsFullScreen ){
switch (aKeyEvent.iScanCode)
{
case EStdKeyUpArrow:
iView->HandleCommandL(EWayFinderCmdMapMoveUp);
break;
case EStdKeyDownArrow:
iView->HandleCommandL(EWayFinderCmdMapMoveDown);
break;
case EStdKeyLeftArrow:
iView->HandleCommandL(EWayFinderCmdMapMoveLeft);
break;
case EStdKeyRightArrow:
iView->HandleCommandL(EWayFinderCmdMapMoveRight);
break;
}
return EKeyWasConsumed;
}
else
return EKeyWasNotConsumed;
}
}
// ---------------------------------------------------------
// CMapContainer::SizeChanged()
// Called by framework when the view size is changed
// ---------------------------------------------------------
//
void CMapContainer::SizeChanged()
{
}
// ---------------------------------------------------------
// CMapContainer::CountComponentControls() const
// ---------------------------------------------------------
//
TInt CMapContainer::CountComponentControls() const
{
return ENumberControls; // return nbr of controls inside this container
}
// ---------------------------------------------------------
// CMapContainer::ComponentControl(TInt aIndex) const
// ---------------------------------------------------------
//
CCoeControl* CMapContainer::ComponentControl(TInt aIndex) const
{
switch ( aIndex )
{
case ENormalMap:
return iNormalMap;
case EFullScreenMap:
return iFullScreenMap;
case EPositionSprite1:
return iPositionSprite22;
case EPositionSprite2:
return iPositionSprite45;
case EPositionSprite3:
return iPositionSprite67;
case EPositionSprite4:
return iPositionSprite90;
case ETurnPicture:
return iTurnPicture;
#ifdef DEBUG_CELL
case ECellData:
return iCellDataDrawer;
#endif
default:
Assert(false);
return NULL;
}
}
// ---------------------------------------------------------
// CMapContainer::Draw(const TRect& aRect) const
// ---------------------------------------------------------
//
void CMapContainer::Draw(const TRect& aRect) const
{
CWindowGc& gc = SystemGc();
gc.SetPenStyle(CGraphicsContext::ENullPen);
gc.SetBrushColor( TRgb( KBackgroundRed, KBackgroundGreen, KBackgroundBlue ) );
gc.SetBrushStyle(CGraphicsContext::ESolidBrush);
gc.DrawRect(aRect);
}
// ---------------------------------------------------------
// CMapContainer::HandleControlEventL(
// CCoeControl* aControl,TCoeEvent aEventType)
// ---------------------------------------------------------
//
void CMapContainer::HandleControlEventL( CCoeControl* /*aControl*/,
TCoeEvent /*aEventType*/)
{
// TODO: Add your control event handler code here
}
// End of File
| [
"[email protected]"
] | [
[
[
1,
685
]
]
] |
a9dc91f7d2b9f11aaf2af470c957560526e3aba8 | d68d288de8b1643d92af2d339f1a3a8dcfc37015 | /Poker.Equity/AgnosticHand.h | e2cf511171eb35b116a629a418285290be2dd65a | [] | no_license | tonetheman/poker-code | c8574084be9a85edfbc439fe16ace7eca9f64445 | 50e0e43b859aa23dd4d4eb5a802c7fc95c6e77d6 | refs/heads/master | 2016-09-01T22:30:58.854343 | 2009-04-20T12:25:20 | 2009-04-20T12:25:20 | 180,739 | 7 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,116 | h | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009 James Devlin
//
// DISCLAIMER OF WARRANTY
//
// This source code is provided "as is" and without warranties as to performance
// or merchantability. The author and/or distributors of this source code may
// have made statements about this source code. Any such statements do not
// constitute warranties and shall not be relied on by the user in deciding
// whether to use this source code.
//
// This source code is provided without any express or implied warranties
// whatsoever. Because of the diversity of conditions and hardware under which
// this source code may be used, no warranty of fitness for a particular purpose
// is offered. The user is advised to test the source code thoroughly before
// relying on it. The user must assume the entire risk of using the source code.
//
///////////////////////////////////////////////////////////////////////////////
#pragma once
///////////////////////////////////////////////////////////////////////////////
//
// An "agnostic hand" is a Texas Hold'em starting hand devoid of specific
// suit information -- for example, "AKs" or "T9o" or "33". A given agnostic
// hand boils down to N *specific* hands, for example, AKs consists of:
//
// - AsKs
// - AhKh
// - AdKd
// - AcKc
//
// An agnostic hand can also include range information. For example:
//
// - A2s+
// - 77+
// - JJ-88
// - T8o-64o
//
///////////////////////////////////////////////////////////////////////////////
class AgnosticHand
{
public:
static int Instantiate(const char* handText, const char* deadCards, vector<StdDeck_CardMask>& hands);
static int Instantiate(const char* handText, StdDeck_CardMask deadCards, vector<StdDeck_CardMask>& hands);
private:
static int InstantiateRandom(StdDeck_CardMask deadCards, vector<StdDeck_CardMask>& specificHands);
static bool IsSuited(const char*);
static bool IsOffSuit(const char*);
static bool IsInclusive(const char*);
static bool IsPair(const char*);
};
| [
"agcc@agcc-ubuntu.(none)"
] | [
[
[
1,
55
]
]
] |
e7788e299d26c52d0bd5c8fedd5d6265ab2edb7c | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Shared/symbian-r6/TimeOutTimer.cpp | 5309f1e861b385528a2e59f107e5f455035920d5 | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,798 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "TimeOutTimer.h"
#include "TimeOutNotify.h"
#define ILOG_POINTER memLog
//#include "memlog.h"
CTimeOutTimer* CTimeOutTimer::NewL(const TInt aPriority,
class MTimeOutNotify& aTimeOutNotify)
//,isab::Log* memLog)
{
CTimeOutTimer* self = CTimeOutTimer::NewLC(aPriority,aTimeOutNotify);//,memLog);
CleanupStack::Pop(self);
return self;
}
CTimeOutTimer* CTimeOutTimer::NewLC(const TInt aPriority,
MTimeOutNotify& aTimeOutNotify)
//,isab::Log* memLog)
{
CTimeOutTimer* self = new (ELeave) CTimeOutTimer(aPriority, aTimeOutNotify);
// LOGNEW(self, CTimeOutTimer);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
CTimeOutTimer::CTimeOutTimer(const TInt aPriority, MTimeOutNotify& aTimeOutNotify)
: CTimer(aPriority), iNotify(aTimeOutNotify)
{
}
CTimeOutTimer::~CTimeOutTimer()
{
Cancel();
}
void CTimeOutTimer::ConstructL()
{
CTimer::ConstructL();
CActiveScheduler::Add(this);
}
void CTimeOutTimer::RunL()
{
// Timer request has completed, so notify the timer's owner
iNotify.TimerExpired();
}
| [
"[email protected]"
] | [
[
[
1,
63
]
]
] |
d077ee02e3ca4433cd53a04246894648ff5b7c48 | 4ab40b7fa3d15e68457fd2b9100e0d331f013591 | /mirrorworld/Objects/MWWall.h | 4c57f576d45062f006af3b1444b91fd5fee5539e | [] | no_license | yzhou61/mirrorworld | f5d2c221f3f8376cfb0bffd0a3accbe9bb1caa21 | 33653244e5599d7d04e8a9d8072d32ecc55355b3 | refs/heads/master | 2021-01-19T20:18:44.546599 | 2010-03-19T22:40:42 | 2010-03-19T22:40:42 | 32,120,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | h | //////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
#ifndef _MW_WALL_H_
#define _MW_WALL_H_
#include "MWStaticObject.h"
namespace MirrorWorld {
class Wall : public StaticObject
{
public:
Wall(unsigned int id) : StaticObject(id, true, false) { }
~Wall() {}
Ogre::String name() const { return "Wall"; }
}; // End of Wall
class WallMaker : public ObjectMaker
{
public:
WallMaker(){}
~WallMaker(){}
Wall* create(unsigned int id) const
{ Wall* wall = new Wall(id); wall->setPhyMaterial(m_pPhyMatID); return wall; }
void setupEngine(Ogre::SceneManager* sceneMgr, OgreNewt::World* world = NULL);
}; // End of WallMaker
} // End fo MirrorWorld
#endif | [
"cxyzs7@2e672104-186a-11df-85bb-b9a83fee2cb1",
"yzhou61@2e672104-186a-11df-85bb-b9a83fee2cb1"
] | [
[
[
1,
12
],
[
14,
30
]
],
[
[
13,
13
]
]
] |
ebeef38c152adf6bd4347888ebd1e028cf03f465 | 77aa13a51685597585abf89b5ad30f9ef4011bde | /dep/src/boost/boost/functional/detail/float_functions.hpp | 4edd7d7b92fffd7db389fcb4fb1861aec034f416 | [] | no_license | Zic/Xeon-MMORPG-Emulator | 2f195d04bfd0988a9165a52b7a3756c04b3f146c | 4473a22e6dd4ec3c9b867d60915841731869a050 | refs/heads/master | 2021-01-01T16:19:35.213330 | 2009-05-13T18:12:36 | 2009-05-14T03:10:17 | 200,849 | 8 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 4,775 | hpp |
// Copyright 2005-2008 Daniel James.
// 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)
#if !defined(BOOST_FUNCTIONAL_DETAIL_FLOAT_FUNCTIONS_HPP)
#define BOOST_FUNCTIONAL_DETAIL_FLOAT_FUNCTIONS_HPP
#include <boost/config/no_tr1/cmath.hpp>
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
// The C++ standard requires that the C float functions are overloarded
// for float, double and long double in the std namespace, but some of the older
// library implementations don't support this. On some that don't, the C99
// float functions (frexpf, frexpl, etc.) are available.
//
// Some of this is based on guess work. If I don't know any better I assume that
// the standard C++ overloaded functions are available. If they're not then this
// means that the argument is cast to a double and back, which is inefficient
// and will give pretty bad results for long doubles - so if you know better
// let me know.
// STLport:
#if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)
# if (defined(__GNUC__) && __GNUC__ < 3 && (defined(linux) || defined(__linux) || defined(__linux__))) || defined(__DMC__)
# define BOOST_HASH_USE_C99_FLOAT_FUNCS
# elif defined(BOOST_MSVC) && BOOST_MSVC < 1300
# define BOOST_HASH_USE_C99_FLOAT_FUNCS
# else
# define BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS
# endif
// Roguewave:
//
// On borland 5.51, with roguewave 2.1.1 the standard C++ overloads aren't
// defined, but for the same version of roguewave on sunpro they are.
#elif defined(_RWSTD_VER)
# if defined(__BORLANDC__)
# define BOOST_HASH_USE_C99_FLOAT_FUNCS
# define BOOST_HASH_C99_NO_FLOAT_FUNCS
# elif defined(__DECCXX)
# define BOOST_HASH_USE_C99_FLOAT_FUNCS
# else
# define BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS
# endif
// libstdc++ (gcc 3.0 onwards, I think)
#elif defined(__GLIBCPP__) || defined(__GLIBCXX__)
# define BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS
// SGI:
#elif defined(__STL_CONFIG_H)
# if defined(linux) || defined(__linux) || defined(__linux__)
# define BOOST_HASH_USE_C99_FLOAT_FUNCS
# else
# define BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS
# endif
// Dinkumware.
#elif (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER)
// Some versions of Visual C++ don't seem to have the C++ overloads but they
// all seem to have the c99 float overloads
# if defined(BOOST_MSVC)
# define BOOST_HASH_USE_C99_FLOAT_FUNCS
// On other platforms the C++ overloads seem to have been introduced sometime
// before 402.
# elif defined(_CPPLIB_VER) && (_CPPLIB_VER >= 402)
# define BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS
# else
# define BOOST_HASH_USE_C99_FLOAT_FUNCS
# endif
// Digital Mars
#elif defined(__DMC__)
# define BOOST_HASH_USE_C99_FLOAT_FUNCS
// Use overloaded float functions by default.
#else
# define BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS
#endif
namespace boost
{
namespace hash_detail
{
inline float call_ldexp(float v, int exp)
{
using namespace std;
#if defined(BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS) || \
defined(BOOST_HASH_C99_NO_FLOAT_FUNCS)
return ldexp(v, exp);
#else
return ldexpf(v, exp);
#endif
}
inline double call_ldexp(double v, int exp)
{
using namespace std;
return ldexp(v, exp);
}
inline long double call_ldexp(long double v, int exp)
{
using namespace std;
#if defined(BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS)
return ldexp(v, exp);
#else
return ldexpl(v, exp);
#endif
}
inline float call_frexp(float v, int* exp)
{
using namespace std;
#if defined(BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS) || \
defined(BOOST_HASH_C99_NO_FLOAT_FUNCS)
return frexp(v, exp);
#else
return frexpf(v, exp);
#endif
}
inline double call_frexp(double v, int* exp)
{
using namespace std;
return frexp(v, exp);
}
inline long double call_frexp(long double v, int* exp)
{
using namespace std;
#if defined(BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS)
return frexp(v, exp);
#else
return frexpl(v, exp);
#endif
}
}
}
#if defined(BOOST_HASH_USE_C99_FLOAT_FUNCS)
#undef BOOST_HASH_USE_C99_FLOAT_FUNCS
#endif
#if defined(BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS)
#undef BOOST_HASH_USE_OVERLOAD_FLOAT_FUNCS
#endif
#if defined(BOOST_HASH_C99_NO_FLOAT_FUNCS)
#undef BOOST_HASH_C99_NO_FLOAT_FUNCS
#endif
#endif
| [
"pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88"
] | [
[
[
1,
158
]
]
] |
c87de938f040f7f5e6dcfee9dacfe50ce35e1579 | 04826a84fc97880275e36ccea83a718c6ee1d3d1 | /src/rtorrent/rsystem.h | aad3fa077cf7d68544aec77bd70d825af199fb5a | [] | no_license | fuCtor/rwin | 2a6f707a528b69cdb061dc7a703fee009d564a7b | de238b0ae2f383c47e10aec1ca5bd925da961590 | refs/heads/master | 2021-01-19T18:00:12.926878 | 2009-03-03T13:34:17 | 2009-03-03T13:34:17 | 141,932 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | h | #ifndef RSYSTEM_H
#define RSYSTEM_H
#include <QObject>
#include "ritorrent.h"
class RSystem : public RITorrent
{
Q_OBJECT
public:
RSystem(QObject *parent);
~RSystem();
QString getVersion();
int getPid();
QString getCwd();
void setCwd(QString cwd);
private:
QMap<QString,QVariant> value;
private slots:
void update(){};
void done( QString method, QString id, QVariant res );
};
#endif // RSYSTEM_H
| [
"[email protected]"
] | [
[
[
1,
29
]
]
] |
6e2f4fd0fe7beaf13379e76a97816a1ed06b0d55 | 5851a831bcc95145bf501b40e90e224d08fa4ac9 | /src/plugins/backup-plugin/ui_backup.cpp | 8c5d073b72cac04031a8abd367c8a062adbd8d60 | [] | no_license | jemyzhang/Cashup | a80091921a2e74f24db045dd731f7bf43c09011a | f4e768a7454bfa437ad9842172de817fa8da71e2 | refs/heads/master | 2021-01-13T01:35:51.871352 | 2010-03-06T14:26:55 | 2010-03-06T14:26:55 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,897 | cpp | #include "ui_backup.h"
#include <list>
#include <cMzCommon.h>
using namespace cMzCommon;
#include <pluginbase.h>
#include "resource.h"
#include <db-engine.h>
#pragma comment(lib,"db-engine.lib")
#include <commondef.h>
#define MZ_IDC_TOOLBAR_ACCOUNTS 101
#define MZ_IDC_BACKUP_LIST 102
#define IDC_PPM_CANCEL 108
#define IDC_PPM_DEL 109
#define IDC_PPM_RECOVER 110
MZ_IMPLEMENT_DYNAMIC(Ui_BackupWnd)
#ifdef _DEBUG
#define BACKUP_PARENT_DIR0 L"\\Disk\\User"
#define BACKUP_PARENT_DIR1 L"\\Disk\\User\\Backup"
#define BACKUP_DIR L"\\Disk\\User\\Backup\\M8Cash"
#else
#define BACKUP_PARENT_DIR0 L"\\Disk\\User"
#define BACKUP_PARENT_DIR1 L"\\Disk\\User\\Backup"
#define BACKUP_DIR L"\\Disk\\User\\Backup\\M8Cash"
#endif
extern HINSTANCE instHandle;
BOOL Ui_BackupWnd::OnInitDialog() {
// Must all the Init of parent class first!
if (!Ui_BaseWnd::OnInitDialog()) {
return FALSE;
}
// Then init the controls & other things in the window
int y = 0;
//m_Caption1.SetPos(0,y,GetWidth(),MZM_HEIGHT_CAPTION);
//m_Caption1.SetText(PluginGetLngResString(IDS_STR_BACKUP_RESTORE).C_Str());
//AddUiWin(&m_Caption1);
//y+=MZM_HEIGHT_CAPTION;
m_List.SetPos(0, y, GetWidth(), GetHeight() - MZM_HEIGHT_CAPTION);
m_List.SetID(MZ_IDC_BACKUP_LIST);
m_List.EnableScrollBarV(true);
m_List.EnableNotifyMessage(true);
AddUiWin(&m_List);
::PostMessage(GetParent(),MZ_MW_REQ_CHANGE_TITLE,IDS_MODULE_NAME,(LPARAM)instHandle);
DateTime::waitms(1);
// m_Toolbar.SetPos(0, GetHeight() - MZM_HEIGHT_TEXT_TOOLBAR, GetWidth(), MZM_HEIGHT_TEXT_TOOLBAR);
//m_Toolbar.SetButton(0, true, true, PluginGetLngResString(IDS_STR_RETURN).C_Str());
// m_Toolbar.EnableLeftArrow(true);
//m_Toolbar.SetButton(1, true, false, PluginGetLngResString(IDS_STR_OPERATE).C_Str());
//m_Toolbar.SetButton(2, true, true, PluginGetLngResString(IDS_STR_BACKUP).C_Str());
// m_Toolbar.SetID(MZ_IDC_TOOLBAR_ACCOUNTS);
// AddUiWin(&m_Toolbar);
return TRUE;
}
void Ui_BackupWnd::OnMzCommand(WPARAM wParam, LPARAM lParam) {
UINT_PTR id = LOWORD(wParam);
switch (id) {
case MZ_IDC_TOOLBAR_ACCOUNTS:
{
int nIndex = lParam;
if (nIndex == 0) { //返回
// exit the modal dialog
EndModal(ID_CANCEL);
return;
}
if (nIndex == 1) { //操作
// pop out a PopupMenu:
CPopupMenu ppm;
struct PopupMenuItemProp pmip;
pmip.itemCr = MZC_BUTTON_PELLUCID;
pmip.itemRetID = IDC_PPM_CANCEL;
pmip.str = PluginGetLngResString(IDS_STR_CANCEL).C_Str();
ppm.AddItem(pmip);
pmip.itemCr = MZC_BUTTON_PELLUCID;
pmip.itemRetID = IDC_PPM_DEL;
pmip.str = PluginGetLngResString(IDS_STR_DELETE).C_Str();
ppm.AddItem(pmip);
pmip.itemCr = MZC_BUTTON_PELLUCID;
pmip.itemRetID = IDC_PPM_RECOVER;
pmip.str = PluginGetLngResString(IDS_STR_RESTORE).C_Str();
ppm.AddItem(pmip);
RECT rc = MzGetWorkArea();
rc.top = rc.bottom - ppm.GetHeight();
ppm.Create(rc.left,rc.top,RECT_WIDTH(rc),RECT_HEIGHT(rc),m_hWnd,0,WS_POPUP);
int nID = ppm.DoModal();
if(nID == IDC_PPM_RECOVER){ //恢复
//弹出警告
if(MzMessageBoxEx(m_hWnd,PluginGetLngResString(IDS_STR_WARN_RESTORE).C_Str(),NULL,MZ_YESNO) != 1){
return;
}
//断开数据库
releaseDatabaseObject();
//恢复数据库
int nIndex = m_List.GetSelectedIndex();
if(nIndex == -1) return;
BOOL nRet = brecover(m_List.GetItem(nIndex)->Text);
if(nRet){
//弹出警告
//退出界面
EndModal(ID_CASCADE_EXIT);
}
}else if(nID == IDC_PPM_DEL){ //删除
//删除目录
int nIndex = m_List.GetSelectedIndex();
if(nIndex == -1) return;
BOOL nRet = bdelete(m_List.GetItem(nIndex)->Text);
if(nRet){
MzAutoMsgBoxEx(m_hWnd,PluginGetLngResString(IDS_STR_DELETE_S).C_Str());
updateList();
}
}else{
return;
}
}
if (nIndex == 2) { //备份
BOOL nRet = bbackup();
if (nRet) {
MzAutoMsgBoxEx(m_hWnd,PluginGetLngResString(IDS_STR_BACKUP_S).C_Str());
updateList();
}
return;
}
}
}
}
LRESULT Ui_BackupWnd::MzDefWndProc(UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case MZ_WM_MOUSE_NOTIFY:
{
int nID = LOWORD(wParam);
int nNotify = HIWORD(wParam);
int x = LOWORD(lParam);
int y = HIWORD(lParam);
if (nID == MZ_IDC_BACKUP_LIST && nNotify == MZ_MN_LBUTTONDOWN) {
if (!m_List.IsMouseDownAtScrolling() && !m_List.IsMouseMoved()) {
int nIndex = m_List.CalcIndexOfPos(x, y);
m_List.SetSelectedIndex(nIndex);
m_List.Invalidate();
// m_Toolbar.SetButton(1, true, true, PluginGetLngResString(IDS_STR_OPERATE).C_Str());
//m_Toolbar.Invalidate();
}
break;
}
if (nID == MZ_IDC_BACKUP_LIST && nNotify == MZ_MN_MOUSEMOVE) {
m_List.SetSelectedIndex(-1);
m_List.Invalidate();
// m_Toolbar.SetButton(1, true, false, PluginGetLngResString(IDS_STR_OPERATE).C_Str());
//m_Toolbar.Invalidate();
break;
}
}
}
return Ui_BaseWnd::MzDefWndProc(message, wParam, lParam);
}
void Ui_BackupWnd::updateList(){
m_List.RemoveAll();
//获取所有文件夹
list<CMzString> _dirs;
int nDir = File::ListDirectory(BACKUP_DIR,_dirs);
if(nDir == 0){
return; //no list
}
//排序目录
list<SYSTEMTIME> dirtimes;
list<CMzString>::iterator i = _dirs.begin();
for(; i != _dirs.end();i++){
CMzString dir = *i;
SYSTEMTIME s;
swscanf(dir.C_Str(),L"%04d%02d%02d%02d%02d%02d",
&s.wYear,&s.wMonth,&s.wDay,&s.wHour,&s.wMinute,&s.wSecond);
if(s.wYear == 0 || s.wMonth == 0 || s.wDay == 0 ||
s.wYear > 2100 || s.wMonth > 12 || s.wDay > 31 ||
s.wHour > 23 || s.wMinute > 59 || s.wSecond > 59){ //无效
continue;
}
if(dirtimes.size() == 0){
dirtimes.push_back(s);
}else{
list<SYSTEMTIME>::iterator it = dirtimes.begin();
for(;it != dirtimes.end(); it++){
SYSTEMTIME tm = *it;
if(DateTime::compareDate(s,tm)>0){
dirtimes.insert(it,s);
break;
}
}
if(it == dirtimes.end()){
dirtimes.push_back(s);
}
}
}
ListItem li;
list<SYSTEMTIME>::iterator it = dirtimes.begin();
for(; it != dirtimes.end(); it++){
SYSTEMTIME tm = *it;
wchar_t dispname[32];
wsprintf(dispname,L"%04d-%02d-%02d %02d:%02d:%02d",
tm.wYear,tm.wMonth,tm.wDay,tm.wHour,tm.wMinute,tm.wSecond);
li.Text = dispname;
m_List.AddItem(li);
}
m_List.Invalidate();
}
//恢复前必须断开数据库连接
BOOL Ui_BackupWnd::brecover(CMzString &itemname){
BOOL nRet = false;
SYSTEMTIME s;
swscanf(itemname.C_Str(),L"%04d-%02d-%02d %02d:%02d:%02d",
&s.wYear,&s.wMonth,&s.wDay,&s.wHour,&s.wMinute,&s.wSecond);
wchar_t dispname[32];
wsprintf(dispname,L"%04d%02d%02d%02d%02d%02d",
s.wYear,s.wMonth,s.wDay,s.wHour,s.wMinute,s.wSecond);
CMzString fpath = BACKUP_DIR;
fpath = fpath + L"\\";
fpath = fpath + dispname;
//获取当前目录
wchar_t currpath[320];
File::GetCurrentPath(currpath);
//准备文件
list<CMzString> sfile;
sfile.push_back(L"cash.db");
sfile.push_back(L"m8cash.ini");
sfile.push_back(L"reminder.ini");
nRet = File::BackupFiles(fpath,currpath,sfile);
return nRet;
}
BOOL Ui_BackupWnd::bdelete(CMzString &itemname){
BOOL nRet = false;
SYSTEMTIME s;
swscanf(itemname.C_Str(),L"%04d-%02d-%02d %02d:%02d:%02d",
&s.wYear,&s.wMonth,&s.wDay,&s.wHour,&s.wMinute,&s.wSecond);
wchar_t dispname[32];
wsprintf(dispname,L"%04d%02d%02d%02d%02d%02d",
s.wYear,s.wMonth,s.wDay,s.wHour,s.wMinute,s.wSecond);
CMzString fpath = BACKUP_DIR;
fpath = fpath + L"\\";
fpath = fpath + dispname;
nRet = File::DelDirectory(fpath.C_Str());
return nRet;
}
BOOL Ui_BackupWnd::bbackup(){
BOOL nRet = false;
//检查备份目录是否存在
nRet = File::DirectoryExists_New(BACKUP_PARENT_DIR0);
nRet = File::DirectoryExists_New(BACKUP_PARENT_DIR1);
//如果不存在则新建该目录
nRet = File::DirectoryExists_New(BACKUP_DIR);
//根据日期创建备份目录
CMzString dir = File::CreateDirectoryByDate(BACKUP_DIR,nRet);
//准备文件
list<CMzString> s;
s.push_back(L"cash.db");
s.push_back(L"m8cash.ini");
s.push_back(L"reminder.ini");
//获取当前目录
wchar_t currpath[320];
File::GetCurrentPath(currpath);
//备份数据
File::BackupFiles(currpath,dir,s);
return nRet;
} | [
"jemyzhang@e7c2eee8-530d-454e-acc3-bb8019a9d48c"
] | [
[
[
1,
291
]
]
] |
1499072b0a43576c3aafd22581f84e0c7546cb54 | 1cc5720e245ca0d8083b0f12806a5c8b13b5cf98 | /v100/ok/10029/p3.cpp | 80e241297d21a54c95a988b313717f63531769c4 | [] | no_license | Emerson21/uva-problems | 399d82d93b563e3018921eaff12ca545415fd782 | 3079bdd1cd17087cf54b08c60e2d52dbd0118556 | refs/heads/master | 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,937 | cpp | /*
* 0221 9236665
* 19:00
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char lista[26000][18];
int passou[26000], len[26000];
int n = 0;
int comp(const void *a, const void *b) {
return strcmp((char *)a,(char *)b);
}
int busca(char *a, int ini, int fim) {
int meio = (ini+fim)/2;
if (ini > fim)
return -1;
int k = strcmp(lista[meio],a);
if (k == 0)
return meio;
else if (k < 0)
return busca(a, meio+1, fim);
else
return busca(a, ini, meio-1);
}
int main() {
int i,j,k,l,m, tam, u,z;
char zor[20];
while(scanf("%s",lista[n])==1) {
n++;
}
qsort(lista, n, sizeof(lista[0]), comp);
for (i = 0; i < n; i++) {
passou[i] = 1;
len[i] = strlen(lista[i]);
}
m = 1;
z = n-1;
for(i=0;i!=z;i++) {
if(passou[i] > m) m = passou[i];
tam = len[i];
for(j=0;j<=tam;j++) zor[j] = lista[i][j];
// altera esta linha
for(j=0;j!=tam;j++) {
for(zor[j]++;zor[j]<='z';zor[j]++) {
if((l=busca(zor,i,n-1))!=-1) {
if(passou[l]<passou[i]+1) passou[l]=passou[i] + 1;
}
}
zor[j] = lista[i][j];
}
// remove o desta posicao
for(j=tam-1;j!=-1;j--) {
zor[j] = lista[i][j+1];
if((l=busca(zor,i,n-1))!=-1 && passou[l]<passou[i]+1)
passou[l]=passou[i] + 1;
}
// adiciona um nesta posicao
zor[tam+1] = '\0';
for(j=0;j!=tam;j++) zor[j+1] = lista[i][j];
for(j=0;j!=tam;j++) {
for(zor[j]=zor[j+1];zor[j]<='z';zor[j]++) {
if((l=busca(zor,i,n-1))!=-1) {
if(passou[l]<passou[i]+1) passou[l]=passou[i] + 1;
}
}
zor[j] = lista[i][j];
}
// adiciona na ultima posicao
for(zor[tam]='a';zor[tam]<='z';zor[tam]++) {
if((l=busca(zor,i,n-1))!=-1) {
if(passou[l]<passou[i]+1) passou[l]=passou[i] + 1;
}
}
}
printf("%d\n",m);
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
99
]
]
] |
c021b9bb57dd9c04f3f79b6597dd7f45de504bc5 | 073dfce42b384c9438734daa8ee2b575ff100cc9 | /RCF/src/RCF/ServerStub.cpp | e6713424eb1366c3a46e97bc0990dceb874735ba | [] | no_license | r0ssar00/iTunesSpeechBridge | a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf | 71a27a52e66f90ade339b2b8a7572b53577e2aaf | refs/heads/master | 2020-12-24T17:45:17.838301 | 2009-08-24T22:04:48 | 2009-08-24T22:04:48 | 285,393 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,561 | cpp |
//******************************************************************************
// RCF - Remote Call Framework
// Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved.
// Consult your license for conditions of use.
// Version: 1.1
// Contact: jarl.lindrud <at> gmail.com
//******************************************************************************
#include <RCF/ServerStub.hpp>
#include <iterator>
#include <RCF/RcfClient.hpp>
namespace RCF {
void ServerStub::invoke(
const std::string & subInterface,
int fnId,
RcfSession & session)
{
// no mutex here, since there is never anyone writing to mInvokeFunctorMap
RCF_VERIFY(
mInvokeFunctorMap.find(subInterface) != mInvokeFunctorMap.end(),
Exception(RcfError_UnknownInterface))
(subInterface)(fnId)(mInvokeFunctorMap.size())(mMergedStubs.size());
mInvokeFunctorMap[subInterface](fnId, session);
}
void ServerStub::merge(RcfClientPtr rcfClientPtr)
{
InvokeFunctorMap &invokeFunctorMap =
rcfClientPtr->getServerStub().mInvokeFunctorMap;
std::copy(
invokeFunctorMap.begin(),
invokeFunctorMap.end(),
std::insert_iterator<InvokeFunctorMap>(
mInvokeFunctorMap,
mInvokeFunctorMap.begin()));
invokeFunctorMap.clear();
mMergedStubs.push_back(rcfClientPtr);
}
} // namespace RCF
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
66448c65c7e3858e6f9550a33384a3dfa6a8761f | 8a223ca4416c60f4ad302bc045a182af8b07c2a5 | /Orders-ListeningFakeProblem-Cpp/Orders-Untouchable-Cpp/src/Money.cpp | 9205f59657e0e2b7f81d50c3dca36e557aa325ae | [] | no_license | sinojelly/sinojelly | 8a773afd0fcbae73b1552a217ed9cee68fc48624 | ee40852647c6a474a7add8efb22eb763a3be12ff | refs/heads/master | 2016-09-06T18:13:28.796998 | 2010-03-06T13:22:12 | 2010-03-06T13:22:12 | 33,052,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,820 | cpp | /// ***************************************************************************
/// Copyright (c) 2009, Industrial Logic, Inc., All Rights Reserved.
///
/// This code is the exclusive property of Industrial Logic, Inc. It may ONLY be
/// used by students during Industrial Logic's workshops or by individuals
/// who are being coached by Industrial Logic on a project.
///
/// This code may NOT be copied or used for any other purpose without the prior
/// written consent of Industrial Logic, Inc.
/// ****************************************************************************
#include "Money.h"
#include <sstream>
#include <iomanip>
using namespace std;
const double Money::hundred(100.0);
Money::Money() : m_value(0.0)
{
}
Money::Money(int amount) : m_value(amount)
{
}
Money::Money(double amount) : m_value(amount)
{
}
Money::Money(const Money& v) : m_value(v.m_value)
{
}
double Money::value() const
{
return m_value;
}
Money Money::add(const Money& augend) const
{
return Money(m_value + augend.m_value);
}
Money Money::times(const Money amount) const
{
return Money(m_value * amount.m_value);
}
Money Money::times(double amount) const
{
return Money(m_value * amount);
}
Money Money::percentOf(const Money& amount) const
{
return Money(m_value * amount.m_value / hundred);
}
Money Money::zero()
{
Money zero(0.0);
return zero;
}
int Money::compareTo(const Money& o) const
{
if (m_value < o.m_value)
return -1;
if (m_value > o.m_value)
return 1;
return 0;
}
bool Money::equals(const Money& obj) const
{
return m_value == obj.m_value;
}
std::string Money::toString() const
{
stringstream ss (stringstream::in | stringstream::out);
ss << setprecision(2);
ss << m_value;
return ss.str();
}
| [
"chenguodong@localhost"
] | [
[
[
1,
88
]
]
] |
62df9a86e8d0e35e1dc5490b31c75df53c1ccd49 | c429fffcfe1128eeaa44f880bdcb1673633792d2 | /dwmaxx/CSecondaryWindowRepresentation.cpp | b81377ce00e10c9a9f18e7d9e5085d01e8effa76 | [] | no_license | steeve/dwmaxx | 7362ef753a71d707880b8cdefe65a5688a516f8d | 0de4addc3dc8056dc478949b7efdbb5b67048d60 | refs/heads/master | 2021-01-10T20:13:15.161814 | 2008-02-18T02:48:15 | 2008-02-18T02:48:15 | 1,367,113 | 10 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 971 | cpp | #include "stdafx.h"
#include "CSecondaryWindowRepresentation.h"
#include "patch.h"
#include "udwm_rva.h"
int CSecondaryWindowRepresentation::SetOpacity(double newValue)
{
return ((int)UDWM_CallMethodEBX(this, rva_CSecondaryWindowRepresentation_SetOpacity, newValue));
}
long CSecondaryWindowRepresentation::SetTransform3D(D3DXMATRIX *matrix)
{
return ((int)UDWM_CallMethodEAX(this, rva_CSecondaryWindowRepresentation_SetTransform3D, matrix));
}
long CSecondaryWindowRepresentation::Create(int Flags, ISecondaryWindowRepresentationChangedListener *listener, CWindowData *windowData, CSecondaryWindowRepresentation **windowRepresentation)
{
return ((long)UDWM_CallFunction(rva_CSecondaryWindowRepresentation_Create, Flags, listener, windowData, windowRepresentation));
}
long CSecondaryWindowRepresentation::GetModel3D(CResource **resource)
{
return ((long)UDWM_CallMethodEDI(this, rva_CSecondaryWindowRepresentation_GetModel3D, resource));
} | [
"siwuzzz@d84ac079-a144-0410-96e0-5f9b019a5953"
] | [
[
[
1,
24
]
]
] |
7f7095f99a26ec88f8837ae0a5886971e50a2917 | 535d66763ae4d6957b7ca38f1c940720ed34fcfe | /common/common.cpp | a0a23fc1e882d27f060ec73ea43eaacfd7f7cac4 | [] | no_license | beru/pngquant_gui | b038ed2d47417beb9b310274b236d96f7585d922 | f883848b1fd14c5c30fdc0683739f3cbfa412499 | refs/heads/master | 2021-01-01T18:07:45.246457 | 2011-10-16T14:06:38 | 2011-10-16T14:06:38 | 2,585,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,714 | cpp | #include "stdafx.h"
#include "common.h"
bool ReadFileText(LPCTSTR filePath, std::string& text)
{
FILE* file = _tfopen(filePath, _T("rb"));
if (!file)
return false;
fseek(file, 0, SEEK_END);
int length = ftell(file);
fseek(file, 0, SEEK_SET);
text = std::string(length, ' ');
fread(&text[0], 1, length, file);
fclose(file);
return true;
}
std::string ToMultiByte(const wchar_t* val)
{
int length( ::WideCharToMultiByte( CP_ACP, 0, val, -1, NULL, 0, NULL, NULL ) );
std::string result( length - 1, 0 );
::WideCharToMultiByte( CP_ACP, 0, &val[ 0 ], -1, &result[ 0 ], length, NULL, NULL );
return result;
}
std::wstring ToWideChar(const char* val)
{
int length( ::MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, &val[ 0 ], -1, NULL, 0 ) );
std::wstring result( length - 1, 0 );
::MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, &val[ 0 ], -1, &result[ 0 ], length );
return result;
}
std::basic_string<TCHAR> ToT(const char* str)
{
#ifdef UNICODE
return ToWideChar(str);
#else
return str;
#endif
}
std::basic_string<TCHAR> ToT(const std::string& str)
{
return ToT(str.c_str());
}
std::basic_string<TCHAR> ToT(const wchar_t* str)
{
#ifdef UNICODE
return str;
#else
return ToMultiByte(str);
#endif
}
std::basic_string<TCHAR> ToT(const std::wstring& str)
{
return ToT(str.c_str());
}
bool IsFileExist(const TCHAR* path)
{
WIN32_FIND_DATA findData;
HANDLE hResult = ::FindFirstFile(path, &findData);
bool ret = hResult != INVALID_HANDLE_VALUE;
::FindClose(hResult);
return ret;
}
size_t GetFileSize(FILE* file)
{
fseek(file, 0, SEEK_END);
int length = ftell(file);
fseek(file, 0, SEEK_SET);
return length;
}
| [
"[email protected]"
] | [
[
[
1,
77
]
]
] |
d73d86acf160b501c2b43f6251d2a42e83b52384 | e580637678397200ed79532cd34ef78983e9aacd | /Grapplon/Planet.h | 087002c5707f723cb3a0a37eccf3b5ed181b9e0c | [] | no_license | TimToxopeus/grapplon2 | 03520bf6b5feb2c6fcb0c5ddb135abe55d3f344b | 60f0564bdeda7d4c6e1b97148b5d060ab84c8bd5 | refs/heads/master | 2021-01-10T21:11:59.438625 | 2008-07-13T06:49:06 | 2008-07-13T06:49:06 | 41,954,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | #pragma once
#include "BaseObject.h"
#include "PlanetaryData.h"
#include <time.h>
class CAnimatedTexture;
class CParticleEmitter;
class CPlayerObject;
class CPlanet : public CBaseObject
{
protected:
CParticleEmitter *m_pEmitter;
float m_fRespawnTime;
CAnimatedTexture *m_pOrbit;
CAnimatedTexture *m_pGlow;
public:
CPlanet(PlanetaryData &data, int index = 1);
virtual ~CPlanet();
CPlanet* m_pOrbitOwner;
float m_fOrbitAngle;
float m_fOrbitLength;
float m_fOrbitSpeed;
float m_fRotation;
bool m_bIsInOrbit;
dJointID orbitJoint;
float m_fDamageMult;
int m_iTempRadius;
//void SetOrbitJoint( dJointID joint ) { m_oPhysicsData.planetData->orbitJoint = joint; }
virtual void Update( float fTime );
virtual void Render();
};
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
12
],
[
14,
20
],
[
22,
39
]
],
[
[
13,
13
],
[
21,
21
]
]
] |
b971dc6cf9a96e5b9d530c813afdfb0f235f69ba | c3a0cf3d0c023cbdb9a1ab8295aa1231543d83e7 | /sln/src/GameMgr.cpp | 47d7c1873eb2f3abc580b319250def87838ceee1 | [] | no_license | yakergong/seedcup2008 | 2596cdb5fe404ef8628366cdd2f8003141625264 | e57b92cf576900ba6cb5e0c0f6661bba3e7f75d7 | refs/heads/master | 2016-09-05T11:06:12.717346 | 2008-12-19T13:04:28 | 2008-12-19T13:04:28 | 32,268,668 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,252 | cpp | #include "GameMgr.h"
#include "ConfigMgr.h"
#include "FbgRenderer.h"
using namespace std;
GameMgr GameMgr::instance_;
bool GameMgr::Init(bool idleMode,int startLevel, string mode )
{
isIdleMode_ = idleMode;
gameOver_ = false;
paused_ = false;
ConfigMgr config;
if( config.GetIntegerValue(mode + ".speed_up_mode"))
speedUpMode_ = true;
else
speedUpMode_ = false;
int gameNum;
int team_num = config.GetIntegerValue("global.team_num");
if(config.GetIntegerValue(mode + ".single_mode"))
gameNum = 1;
else
gameNum = team_num;
for(int i = 0; i < gameNum; ++i)
{
FbgGame *game = new FbgGame(i, idleMode, startLevel, mode);
game->setState(GAMEPLAY);
game->setPaused(paused_);
game->setSpeedUpMode(speedUpMode_);
gameVec_.push_back(game);
}
if(mode == "show_log")
normalDelay_ = config.GetIntegerValue("global.show_delay");
else
normalDelay_ = config.GetIntegerValue("global.normal_delay");
tinyDelay_ = config.GetIntegerValue("global.tiny_delay");
fps_ = config.GetIntegerValue("global.frame_per_second");
downHeldSpeed_ = config.GetIntegerValue("global.down_held_speed");
frameIndex_ = 0;
ResetMod();
newLevelPause_ = config.GetIntegerValue(mode + ".new_level_pause");
return true;
}
GameMgr::GameMgr()
{
}
GameMgr::~GameMgr()
{
Destroy();
}
void GameMgr::Loop()
{
SDL_Event event;
while( !gameOver_ )
{
int startTime = SDL_GetTicks();
FbgRenderer::Instance().draw();
// Event Handling
while (SDL_PollEvent(&event))
{
if( CheckKeyEvent(event) )
continue;
for(int i = 0; i < (int)gameVec_.size(); ++i)
gameVec_[i]->processEvent(event);
}
// 演示模式下每关暂停
bool startFlag = true;
for(int i = 0; i < (int)gameVec_.size(); ++i)
if(gameVec_[i]->getPaused() == false)
startFlag = false;
if(startFlag && newLevelPause_ && !paused_)
for(int i = 0; i < (int)gameVec_.size(); ++i)
gameVec_[i]->startNewLevel();
// 调节速度
if(gameVec_[0]->getDownHeld())
{
int newMod = mod_/downHeldSpeed_;
if(newMod < 1)
newMod = 1;
int times = 1;
if( speedUpMode_ )
times = int(float(1000/fps_)/float(tinyDelay_));
if(times < 1)
times = 1;
if(frameIndex_%newMod == 0)
DropBlockFunc(times);
}
else
{
int times = 1;
if( speedUpMode_ )
times = int(float(1000/fps_)/float(tinyDelay_));
if(times < 1)
times = 1;
if(frameIndex_ % mod_ == 0)
DropBlockFunc(times);
}
++frameIndex_;
// 保持帧率为fps_
int endTime = SDL_GetTicks();
int timePerFrame = 1000/fps_;
if(endTime - startTime < timePerFrame)
{
SDL_Delay(timePerFrame - (endTime -startTime));
}
}
}
vector< FbgGame * >& GameMgr::GetGameVec()
{
return gameVec_;
}
bool GameMgr::CheckKeyEvent( SDL_Event &event )
{
if( event.type == SDL_QUIT )
{
gameOver_ = true;
return true;
}
if(event.type == SDL_KEYDOWN)
{
SDLKey key = event.key.keysym.sym;
if(key == SDLK_ESCAPE)
{
gameOver_ = true;
return true;
}
else if(key == SDLK_F2)
{
paused_ = !paused_;
for(int i = 0; i < (int)gameVec_.size(); ++i)
gameVec_[i]->setPaused(paused_);
}
else if(key == SDLK_F3)
{
speedUpMode_ = !speedUpMode_;
ResetMod();
for(int i = 0; i < (int)gameVec_.size(); ++i)
gameVec_[i]->setSpeedUpMode(speedUpMode_);
}
}
return false;
}
bool GameMgr::IsGameOver()
{
return gameOver_;
}
GameMgr& GameMgr::Instance()
{
return instance_;
}
void GameMgr::Destroy()
{
for(int i = 0; i < (int)gameVec_.size(); ++i)
{
delete gameVec_[i];
gameVec_[i] = NULL;
}
}
void GameMgr::DropBlockFunc(int times)
{
SDL_Event event;
SDL_UserEvent userEvent;
userEvent.type = SDL_USEREVENT;
userEvent.code = FBG_EVENT_DROP;
userEvent.data1 = NULL;
userEvent.data2 = NULL;
event.type = SDL_USEREVENT;
event.user = userEvent;
for(int i = 0; i < times; ++i)
SDL_PushEvent(&event);
}
void GameMgr::ResetMod()
{
if(speedUpMode_)
mod_ = tinyDelay_/fps_;
else
mod_ = normalDelay_/fps_;
if(mod_ < 1)
mod_ = 1;
} | [
"yakergong@c3067968-ca50-11dd-8ca8-e3ff79f713b6"
] | [
[
[
1,
212
]
]
] |
386f4889ab36ead2aa3d9944e6a4a5f9ee126bf8 | 6b75de27b75015e5622bfcedbee0bf65e1c6755d | /stack/表达式求值/表达式求值4/stack.h | ac69019cf3aeb7da91e712c5aad51dfbab1bd31e | [] | no_license | xhbang/data_structure | 6e4ac9170715c0e45b78f8a1b66c838f4031a638 | df2ff9994c2d7969788f53d90291608ac5b1ef2b | refs/heads/master | 2020-04-04T02:07:18.620014 | 2011-12-05T09:39:34 | 2011-12-05T09:39:34 | 2,393,408 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,781 | h | //*****stack.h
#ifndef _STACK_H
#define _STACK_H
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int Status;
template<class QElemType>
class stack
{
public:
void InitStack();
void DestroyStack();
void ClearStack();
Status StackEmpty();
Status StackLength();
int GetTop(QElemType & e);
void Push(QElemType e);
int Pop(QElemType & e);
private:
struct SqStack{
QElemType *base;
QElemType *top;
int stacksize;
}S;
};
//******stack.cpp------
template<class QElemType>
void stack<QElemType>::InitStack()
{
S.base = (QElemType *)malloc(STACK_INIT_SIZE * sizeof(QElemType));
if(!S.base) exit(0);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
template <class QElemType>
void stack<QElemType>::DestroyStack()
{
free(S.base);
}
template <class QElemType>
void stack<QElemType>::ClearStack()
{
S.top = S.base;
}
template <class QElemType>
Status stack<QElemType>::StackEmpty()
{
if(S.top == S.base) return 1;
else return 0;
}
template <class QElemType>
Status stack<QElemType>::StackLength()
{
return (S.top - S.base);
}
template <class QElemType>
int stack<QElemType>::GetTop(QElemType & e)
{
if(S.top != S.base)
{
e = *(S.top - 1);
return 1;
}
else return 0;
}
template <class QElemType>
void stack<QElemType>::Push(QElemType e)
{
if(S.top - S.base >= S.stacksize)
{
S.base = (QElemType *)realloc(S.base,(S.stacksize + STACKINCREMENT) * sizeof(QElemType));
if(!S.base) exit(0);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
}
template <class QElemType>
int stack<QElemType>::Pop(QElemType & e)
{
if(S.top == S.base) return 0;
else
e = * --S.top;
return 1;
}
//**********stack.cpp
#endif //stack.h **** | [
"[email protected]"
] | [
[
[
1,
88
]
]
] |
4ac8acf128507c5333c3072bbd74624d54ca80ca | 87f20a21fe39a6ead52d5ac15b2dd745ceaa15c8 | /MiniGame.cpp | 2c41edaeef9e0a206525249a9a38d870a2c32755 | [] | no_license | Phildo/Planet-Wars | a0ba13f75de84af2b8619af4617eeeb212f4ec67 | b3dce6e93b63152106173d4858a120cd8ea55129 | refs/heads/master | 2021-01-17T14:52:50.899870 | 2011-12-21T23:00:58 | 2011-12-21T23:00:58 | 2,921,506 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,278 | cpp | #include "MiniGame.h"
MiniGame::MiniGame(Node * planet, Ship * attackerShip, Ship * defenderShip)
{
node = planet;
attacker = attackerShip;
defender = defenderShip;
lanes = new Lane*[NUM_LANES];
for(int i = 0; i < NUM_LANES; i++)
{
lanes[i] = new Lane();
}
selectedALane = 0;
selectedDLane = NUM_LANES-1;
lanes[selectedALane]->setSelected(true, true);
lanes[selectedDLane]->setSelected(true, false);
Lane::setWinMini = false;
Lane::winMini = false;
}
void MiniGame::changeLane(int direction, bool attacker)
{
if(attacker)
{
if(direction == LEFT && selectedALane != 0)
selectLane(selectedALane-1, true);
else if(direction == RIGHT && selectedALane != 4)
selectLane(selectedALane+1, true);
}
else
{
if(direction == LEFT && selectedDLane != 0)
selectLane(selectedDLane-1, false);
else if(direction == RIGHT && selectedDLane != 4)
selectLane(selectedDLane+1, false);
}
}
void MiniGame::selectLane(int lane, bool attacker)
{
if(attacker)
{
lanes[selectedALane]->setSelected(false, true);
selectedALane = lane;
lanes[selectedALane]->setSelected(true, true);
}
else
{
lanes[selectedDLane]->setSelected(false, false);
selectedDLane = lane;
lanes[selectedDLane]->setSelected(true, false);
}
}
void MiniGame::deployUnit(Ship * s, int type) {
Unit * u = s->deployUnit(type);
if(u != Model::getSelf()->nullUnit)
{
if(attacker == s)
lanes[selectedALane]->deployUnit(u, true);
else
lanes[selectedDLane]->deployUnit(u, false);
}
}
void MiniGame::update() {
if(attacker->numWaterUnits + attacker->numEarthUnits + attacker->numWindUnits + attacker->numFireUnits == 0 &&
lanes[0]->attackerIndex == 0 &&
lanes[1]->attackerIndex == 0 &&
lanes[2]->attackerIndex == 0 &&
lanes[3]->attackerIndex == 0 &&
lanes[4]->attackerIndex == 0)
attacker->health -= 10000;
if(defender->numWaterUnits + defender->numEarthUnits + defender->numWindUnits + defender->numFireUnits == 0 &&
lanes[0]->defenderIndex == 0 &&
lanes[1]->defenderIndex == 0 &&
lanes[2]->defenderIndex == 0 &&
lanes[3]->defenderIndex == 0 &&
lanes[4]->defenderIndex == 0)
defender->health -= 10000;
if(attacker->health <= 0)
{
Lane::winMini = true;
Lane::attackerWin = false;
}
if(defender->health <= 0)
{
Lane::winMini = true;
Lane::attackerWin = true;
}
for(int i = 0; i < NUM_LANES; i++)
{
lanes[i]->tick();
}
}
void MiniGame::drawGame() {
//Draw Lanes
for(int i = 0; i < NUM_LANES; i++)
{
glPushMatrix();
glTranslated((double)((LANE_WIDTH*i)-(LANE_WIDTH*(int)(NUM_LANES/2))), 0.0, 0.0);
lanes[i]->draw();
glPopMatrix();
}
glPushMatrix();
if(attacker->owner == Model::getSelf()->playerArray[0])
glColor3f(1.0, 0.0, 0.0);
else
glColor3f(0.0, 0.0, 1.0);
glTranslatef(0.0, 0.0, LANE_LENGTH/2);
glBegin(GL_QUADS);
glVertex3d(-.5*(LANE_WIDTH*NUM_LANES), -100.0, 0.0);
glVertex3d(.5*(LANE_WIDTH*NUM_LANES), -100.0, 0.0);
glVertex3d(.5*(LANE_WIDTH*NUM_LANES), -100.0, -300.0);
glVertex3d(-.5*(LANE_WIDTH*NUM_LANES), -100.0, -300.0);
glEnd();
glPopMatrix();
glPushMatrix();
if(defender->owner == Model::getSelf()->playerArray[0])
glColor3f(1.0, 0.0, 0.0);
else
glColor3f(0.0, 0.0, 1.0);
glTranslatef(0.0, 0.0, LANE_LENGTH/-2);
glBegin(GL_QUADS);
glVertex3d(-.5*(LANE_WIDTH*NUM_LANES), -100.0, 0.0);
glVertex3d(.5*(LANE_WIDTH*NUM_LANES), -100.0, 0.0);
glVertex3d(.5*(LANE_WIDTH*NUM_LANES), -100.0, 300.0);
glVertex3d(-.5*(LANE_WIDTH*NUM_LANES), -100.0, 300.0);
glEnd();
glPopMatrix();
//Draw Health
glColor3f(0.0, 1.0, 0.0);
glPushMatrix();
glTranslated(0.0, 500.0, -5000.0);
glBegin(GL_QUADS);
glVertex3f(-1* NUM_LANES * LANE_WIDTH / 2, 0.0, -100.0);
glVertex3f(-1* NUM_LANES * LANE_WIDTH / 2, 0.0, 100.0);
glVertex3f((-1* NUM_LANES * LANE_WIDTH / 2) + (NUM_LANES * LANE_WIDTH * ((float)defender->health/(float)SHIP_HEALTH)), 0.0, 100.0);
glVertex3f((-1* NUM_LANES * LANE_WIDTH / 2) + (NUM_LANES * LANE_WIDTH * ((float)defender->health/(float)SHIP_HEALTH)), 0.0, -100.0);
glEnd();
glPopMatrix();
glPushMatrix();
glTranslated(0.0, 500.0, 5000.0);
glBegin(GL_QUADS);
glVertex3f(-1* NUM_LANES * LANE_WIDTH / 2, 0.0, -100.0);
glVertex3f(-1* NUM_LANES * LANE_WIDTH / 2, 0.0, 100.0);
glVertex3f((-1* NUM_LANES * LANE_WIDTH / 2) + (NUM_LANES * LANE_WIDTH * ((float)attacker->health/(float)SHIP_HEALTH)), 0.0, 100.0);
glVertex3f((-1* NUM_LANES * LANE_WIDTH / 2) + (NUM_LANES * LANE_WIDTH * ((float)attacker->health/(float)SHIP_HEALTH)), 0.0, -100.0);
glEnd();
glPopMatrix();
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
2
],
[
4,
5
],
[
8,
13
],
[
20,
21
],
[
23,
23
],
[
39,
40
],
[
42,
42
],
[
56,
57
],
[
60,
61
],
[
66,
69
],
[
98,
113
],
[
170,
173
]
],
[
[
3,
3
],
[
6,
7
],
[
14,
19
],
[
22,
22
],
[
24,
38
],
[
41,
41
],
[
43,
55
],
[
58,
59
],
[
62,
65
],
[
70,
97
],
[
114,
169
]
]
] |
6c9236f9a99d2aa614400e8495e06b84d1a8cafe | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Samples/MorphableTerrain/MyWindow.cpp | adc0ac23216e035922f407c426ea1a785c3cfd6a | [] | 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,068 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: MyWindow.cpp
Version: 0.01
---------------------------------------------------------------------------
*/
#include "MyWindow.h"
MyWindow::MyWindow():
GUIWindow(WND_TRANSPARENT)
{
this->setWidth(700);
this->setHeight(500);
this->setPosition(50, 50);
this->setVisible(true);
addControls();
}
//----------------------------------------------------------------------
void MyWindow::addControls()
{
lblMessage.setCaption(L"Morphable terrain demo:\n - press 'H' to hide this menu\n - press 'Q', 'W' to control blend factor\n - use mouse wheel to zoom in and out\n - move mouse to rotate around the scene");
lblMessage.setPosition(Vector2(0, 0));
lblMessage.setFontSize(24);
lblMessage.setTextColour(Colour::COLOUR_WHITE);
this->addControl(&lblMessage);
}
//---------------------------------------------------------------------- | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
37
]
]
] |
3bcbf2cccd044204d5d8c31cfebc115e55ba3809 | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvmesh/render/NvTriStripVertexCache.cpp | 7827d6568235a529f9da37c6915b4fbe7b48d5c1 | [] | no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 40 | cpp |
#include "NvTriStripVertexCache.h"
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
] | [
[
[
1,
3
]
]
] |
8dbe97c85029ad8025844e2d1e47aab8906edad1 | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvmesh/tools/baker/GeometryImage.h | 15763ba219e425e703256bd4e16b562e97f2032b | [] | no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,172 | h | // Copyright NVIDIA Corporation 2006 -- Denis Kovacs <[email protected]>
#ifndef NV_GEOMETRYIMAGE_H
#define NV_GEOMETRYIMAGE_H
#include <nvimage/FloatImage.h>
#include <nvimage/HoleFilling.h>
#include <nvmath/Vector.h>
namespace nv
{
class GeometryImage
{
public:
enum Flags
{
PositionFlag = 0x01,
NormalFlag = 0x02,
DisplacementFlag = 0x04,
VectorDisplacementFlag = 0x08,
CurvatureFlag = 0x10,
OcclusionFlag = 0x20,
BentNormalFlag = 0x40
};
GeometryImage(uint flags, Vector2 extents)
{
setupFlags(flags);
m_geometryImage = new FloatImage();
m_geometryImage->allocate(m_componentCount, (uint)extents.x(), (uint)extents.y());
m_geometryImage->clear(0.0f);
}
// GeometryImage takes ownership of the given image.
GeometryImage(uint flags, FloatImage * img)
{
setupFlags(flags);
m_geometryImage = img;
}
~GeometryImage()
{
delete m_geometryImage;
}
inline FloatImage * img()
{
return m_geometryImage;
}
inline int width() const { return m_geometryImage->width(); }
inline int height() const { return m_geometryImage->height(); }
inline int componentNum() const {
return m_geometryImage->componentNum();
}
inline int coverageChannel() const { return m_coverageChannel; }
inline int positionChannel(uint channel = 0) const {
nvDebugCheck(channel < 3); return m_positionChannel + channel;
}
inline int normalChannel(uint channel = 0) const {
nvDebugCheck(channel < 3); return m_normalChannel + channel;
}
inline int displacementChannel(uint channel = 0) const {
nvDebugCheck(channel < 3); return m_displacementChannel + channel;
}
inline int curvatureChannel() const { return m_curvatureChannel; }
inline int occlusionChannel() const { return m_occlusionChannel; }
inline int bentNormalChannel(uint channel = 0) const {
nvDebugCheck(channel < 3); return m_bentNormalChannel + channel;
}
inline const float pixel(int x, int y, int c) const
{
return m_geometryImage->pixel(x, y, c);
}
inline void setPixel(float f, int x, int y, int c)
{
m_geometryImage->setPixel(f, x, y, c);
}
inline void addPixel(float f, int x, int y, int c)
{
m_geometryImage->addPixel(f, x, y, c);
}
inline void setPixel(Vector3 v, int x, int y, int c)
{
m_geometryImage->setPixel(v.x(), x, y, c+0);
m_geometryImage->setPixel(v.y(), x, y, c+1);
m_geometryImage->setPixel(v.z(), x, y, c+2);
}
inline void addPixel(Vector3 v, int x, int y, int c)
{
m_geometryImage->addPixel(v.x(), x, y, c+0);
m_geometryImage->addPixel(v.y(), x, y, c+1);
m_geometryImage->addPixel(v.z(), x, y, c+2);
}
Vector3 position(int x, int y) const
{
return Vector3(
pixel(x, y, positionChannel(0)),
pixel(x, y, positionChannel(1)),
pixel(x, y, positionChannel(2)));
}
Vector3 normal(int x, int y) const
{
return Vector3(
pixel(x, y, normalChannel(0)),
pixel(x, y, normalChannel(1)),
pixel(x, y, normalChannel(2)));
}
Vector3 bentNormal(int x, int y) const
{
return Vector3(
pixel(x, y, bentNormalChannel(0)),
pixel(x, y, bentNormalChannel(1)),
pixel(x, y, bentNormalChannel(2)));
}
GeometryImage * fastDownSample() const
{
return new GeometryImage( m_flags,
m_geometryImage->fastDownSample() );
}
// normalize pixels by coverage
void fillSubpixels(BitMap * bmap, float threshold)
{
nvDebugCheck(bmap != NULL);
nvDebugCheck(threshold >= 0.0f && threshold < 1.0f);
uint w = width();
uint h = height();
uint c = componentNum(); // do coverage last.
uint coverageCh = coverageChannel();
float * coverage = img()->channel(coverageCh);
// clear insignificant coverage
for (uint i = 0; i < h*w; i++)
{
if (coverage[i] < threshold) {
coverage[i] = 0.0f;
bmap->clearBitAt(i);
}
}
// normalize pixels (including coverage)
for (uint k = 0; k <= c; k++)
{
if (k == coverageCh) continue; // skip coverage until the end
uint ch = k;
if (ch == c) ch = coverageCh; // normalize coverage a the end
float * channel = img()->channel(ch);
for (uint i = 0; i < h*w; i++)
{
if (coverage[i] > 0.0f) {
//nvDebugCheck(!isZero(channel[i]));
channel[i] /= coverage[i];
}
}
}
}
BitMap * getBitMaskFromCoverage() const
{
uint w = width();
uint h = height();
BitMap * bm = new BitMap(w, h);
bm->clearAll();
float * coverage = m_geometryImage->channel(coverageChannel());
// clear insignificant coverage
for (uint i = 0; i< h*w; i++)
{
if (coverage[i] != 0.0) bm->setBitAt(i);
}
return bm;
}
void setNormalMap(FloatImage * nmap)
{
uint w = width();
uint h = height();
uint size = w * h;
nvCheck(nmap->width() == w && nmap->height() == h);
uint xoffset = size * normalChannel(0);
uint yoffset = size * normalChannel(1);
uint zoffset = size * normalChannel(2);
uint coffset = size * coverageChannel();
for (uint i = 0; i < size; i++)
{
Vector3 normal = Vector3(
nmap->pixel(i),
nmap->pixel(i + size),
nmap->pixel(i + size * 2));
float len = length(normal);
if (len > 0.1f)
{
m_geometryImage->setPixel(normal.x(), i + xoffset);
m_geometryImage->setPixel(normal.y(), i + yoffset);
m_geometryImage->setPixel(normal.z(), i + zoffset);
m_geometryImage->setPixel(clamp(len, 0.0f, 1.0f), i + coffset);
}
}
}
private:
void setupFlags(uint flags)
{
m_flags = flags;
m_componentCount = 1;
m_coverageChannel = 0;
m_positionChannel = -1;
m_normalChannel = -1;
m_displacementChannel = -1;
m_curvatureChannel = -1;
m_occlusionChannel = -1;
m_bentNormalChannel = -1;
if (flags & PositionFlag)
{
m_positionChannel = m_componentCount;
m_componentCount += 3;
}
if (flags & NormalFlag)
{
m_normalChannel = m_componentCount;
m_componentCount += 3;
}
if (flags & VectorDisplacementFlag)
{
m_displacementChannel = m_componentCount;
m_componentCount += 3;
}
else if (flags & DisplacementFlag)
{
m_displacementChannel = m_componentCount;
m_componentCount++;
}
if (flags & CurvatureFlag)
{
m_curvatureChannel = m_componentCount;
m_componentCount++;
}
if (flags & OcclusionFlag)
{
m_occlusionChannel = m_componentCount;
m_componentCount++;
}
if (flags & NormalFlag)
{
m_bentNormalChannel = m_componentCount;
m_componentCount += 3;
}
}
private:
FloatImage * m_geometryImage;
uint m_flags;
uint m_componentCount;
int m_coverageChannel;
int m_positionChannel;
int m_normalChannel;
int m_displacementChannel;
int m_curvatureChannel;
int m_occlusionChannel;
int m_bentNormalChannel;
};
} // nv
#endif // NV_GEOMETRYIMAGE_H
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
] | [
[
[
1,
303
]
]
] |
9eb63e6a433f87a8520568c06b00f1e062396aaa | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/config/test/has_tr1_hash_pass.cpp | 14f0a16a93ba481cd2ae1a5158a20f942c905691 | [
"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 | 1,010 | cpp | // This file was automatically generated on Sat Feb 19 12:29:55 2005
// by libs/config/tools/generate.cpp
// Copyright John Maddock 2002-4.
// Use, modification and distribution are 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)
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_HAS_TR1_HASH
// This file should compile, if it does not then
// BOOST_HAS_TR1_HASH should not be defined.
// See file boost_has_tr1_hash.ipp for details
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifdef BOOST_HAS_TR1_HASH
#include "boost_has_tr1_hash.ipp"
#else
namespace boost_has_tr1_hash = empty_boost;
#endif
int main( int, char *[] )
{
return boost_has_tr1_hash::test();
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
34
]
]
] |
253e0e77611d23cd4f48a4da57a53594d52bb4e4 | 1c4a1cd805be8bc6f32b0a616de751ad75509e8d | /jacknero/src/pku_src/2262/.svn/text-base/3573397_AC_188MS_1264K.cpp.svn-base | 2bd3604e894a3ac54ae41cbcffbd93ebf0838834 | [] | no_license | jacknero/mycode | 30313261d7e059832613f26fa453abf7fcde88a0 | 44783a744bb5a78cee403d50eb6b4a384daccf57 | refs/heads/master | 2016-09-06T18:47:12.947474 | 2010-05-02T10:16:30 | 2010-05-02T10:16:30 | 180,950 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | #include <iostream>
#include <cstdio>
using namespace std;
int main()
{
bool prime[1000001]={false,};
int i,j, n;
for(i=3;i<=1000000;i++) {
if(prime[i]==false) for(j=i<<1;j<=1000000;j+=i) prime[j]=true;
}
for(;;) {
cin >> n;
if(n==0) break;
for(i=3;i<=n/2;i++) {
if(prime[i]==false && prime[n-i]==false) {
printf("%d = %d + %d\n", n,i,n-i);
break;
}
}
if(i>n/2) puts("Goldbach's conjecture is wrong.");
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
30
]
]
] |
|
94b157bf6dd8f3b0cda1115009e1e6e26ceb639d | 23b2ab84309de65b42333c87e0de088503e2cb36 | /src/gui/addclasswizard.h | 79fac0367208b73839a83ae4503fc30a735b4b0b | [] | no_license | fyrestone/simple-pms | 74a771d83979690eac231a82f1c457d7b6c55f41 | 1917d5c4e14bf7829707bacb9cc2452b49d6cc2b | refs/heads/master | 2021-01-10T20:36:39.403902 | 2011-04-16T15:38:12 | 2011-04-16T15:38:12 | 32,192,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | h | #ifndef ADDCLASSWIZARD_H
#define ADDCLASSWIZARD_H
#include <QWizard>
namespace Ui {
class AddClassWizard;
}
class AddClassWizard : public QWizard
{
Q_OBJECT
public:
explicit AddClassWizard(QWidget *parent = 0);
~AddClassWizard();
private:
Ui::AddClassWizard *ui;
};
#endif // ADDCLASSWIZARD_H
| [
"[email protected]@95127988-2b6b-df20-625d-5ecc0e46e2bb"
] | [
[
[
1,
22
]
]
] |
427ce278d22780fb3dfac711d6fb356c688e50fd | 5dc78c30093221b4d2ce0e522d96b0f676f0c59a | /src/modules/audio/openal/Audio.h | a7175807a65b89604c9dd852a1dceb894f7140b1 | [
"Zlib"
] | permissive | JackDanger/love | f03219b6cca452530bf590ca22825170c2b2eae1 | 596c98c88bde046f01d6898fda8b46013804aad6 | refs/heads/master | 2021-01-13T02:32:12.708770 | 2009-07-22T17:21:13 | 2009-07-22T17:21:13 | 142,595 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,531 | h | /**
* Copyright (c) 2006-2009 LOVE Development 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.
**/
#ifndef LOVE_AUDIO_OPENAL_AUDIO_H
#define LOVE_AUDIO_OPENAL_AUDIO_H
// STD
#include <queue>
#include <map>
#include <iostream>
#include <cmath>
// SDL
#include <SDL.h>
// OpenAL
#include <AL/alc.h>
#include <AL/al.h>
// LOVE
#include <audio/Audio.h>
#include <common/config.h>
#include <common/constants.h>
#include <sound/SoundData.h>
#include "Sound.h"
#include "Music.h"
#include "Source.h"
#include "Pool.h"
namespace love
{
namespace audio
{
namespace openal
{
class Audio : public love::audio::Audio
{
private:
// The OpenAL device.
ALCdevice * device;
// The OpenAL context.
ALCcontext * context;
SDL_Thread * thread;
// The Pool.
Pool * pool;
static int run(void * unused);
public:
Audio();
~Audio();
// Implements Module.
const char * getName() const;
// Implements Audio.
love::audio::Sound * newSound(love::sound::SoundData * data);
love::audio::Music * newMusic(love::sound::Decoder * decoder);
love::audio::Source * newSource();
int getNumSources() const;
int getMaxSources() const;
void play(love::audio::Source * source);
void play(love::audio::Sound * sound);
void play(love::audio::Music * music);
void play();
void stop(love::audio::Source * source);
void stop();
void pause(love::audio::Source * source);
void pause();
void resume(love::audio::Source * source);
void resume();
void rewind(love::audio::Source * source);
void rewind();
void setVolume(float volume);
float getVolume() const;
}; // Audio
} // openal
} // audio
} // love
#endif // LOVE_AUDIO_OPENAL_AUDIO_H
| [
"prerude@3494dbca-881a-0410-bd34-8ecbaf855390"
] | [
[
[
1,
106
]
]
] |
ba0cbc69c8316f22e2543f74f80b392631fbe16e | d9da783f4bf071364d500e27ad6c0f807d413eca | /stdc++/Main.cpp | 08c44d7513dc70297db133fd0cd07f3f9feb82db | [
"WTFPL"
] | permissive | Kaedenn/CodeMines | 9ad9b2e345582a388e625abad445e52853124cfb | a526d96c643bc1442bea25776cee5c912aabb2fc | refs/heads/master | 2020-04-06T07:11:57.959356 | 2011-12-27T19:56:30 | 2011-12-27T19:56:30 | 3,058,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,634 | cpp | // Main.cpp
/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
#include "InputOutput.hpp"
int main(int argc, char* argv[]) {
if (argc > 1) {
if (std::string(argv[1]) == "-listcommands") {
std::cout << "quit -quits the game" << '\n'
<< "restart -restarts the current game" << '\n'
<< "setmines # -replace # with a number of mines between 1 and" << '\n'
<< " 519 to change the number of mines. This also" << '\n'
<< " restarts the level." << '\n'
<< "mark $ -replace $ with the desired tile to 'mark' or" << '\n'
<< " 'flag' the selected tile." << '\n'
<< "flag $ -exactly the same as 'mark $'" << '\n'
<< "log $- -Takes a snapshot of the current output and" << '\n'
<< " it in 'codesmineslog.txt'" << '\n'
<< "longcat, desu, dontpanic, cassie, dragon, tigger, mario," << '\n'
<< "sexysexy, :v:, xyzzy, yzzyx" << std::endl;
}
}
try {
CM::InputOutput game(&std::cin, std::cout);
game.InitializeGame();
game.RunGameLoop();
} catch (...) {
std::cout << "Fatal error detected. The program will close now.";
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
39
]
]
] |
e24e144492571bb38a81d0d1620efffa93b3d096 | 0f457762985248f4f6f06e29429955b3fd2c969a | /irrlicht/src/proto_SA/HeroPlayer.cpp | 1dbbcfff35871de43826fc7f96d97da87a086f61 | [] | no_license | tk8812/ukgtut | f19e14449c7e75a0aca89d194caedb9a6769bb2e | 3146ac405794777e779c2bbb0b735b0acd9a3f1e | refs/heads/master | 2021-01-01T16:55:07.417628 | 2010-11-15T16:02:53 | 2010-11-15T16:02:53 | 37,515,002 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 7,380 | cpp | #include "CSAApp.h"
#include "ChsBullet.h"
#include "HeroPlayer.h"
/*
해결해야할문제점
1. 캐릭터 컨트롤러의 터널링문제 - 사양이 낮은 곳에서 터널링이발생할수있다.
해결방법은 이동방향으로 광선 검사를 수행해서 근접물체가 있으면 움직임을 멈추게 해야한다.
if( 캐릭컨트롤러의 이동방향 앞으로 물체가 근접했는가? == false)
m_pChracterAnimator->controlStep_Walker(WalkVelocity);
*/
CHeroPlayer::CHeroPlayer()
{
m_strTypeName = "CHeroPlayer";
int i;
for(i=0;i<irr::KEY_KEY_CODES_COUNT;i++)
{
m_Key[i] = false;
}
SetStatus(FSM_READY);
}
CHeroPlayer::~CHeroPlayer(void)
{
}
bool CHeroPlayer::Init(irr::scene::ISceneNode *pNode)
{
if(CPlayer::Init(pNode))
{
irr::scene::CBulletObjectAnimatorParams physicsParams;
irr::scene::ISceneManager *pSmgr = CSAApp::GetPtr()->m_pSmgr;
irr::IrrlichtDevice *pDevice = CSAApp::GetPtr()->m_pDevice;
irr::scene::CBulletAnimatorManager* pBulletPhysicsFactory = CSAApp::GetPtr()->m_pBulletPhysicsFactory;
irr::scene::CBulletWorldAnimator* pWorldAnimator = CSAApp::GetPtr()->m_pWorldAnimator;
m_pTrigerNode = pSmgr->getSceneNodeFromName("usr/triger");
{
irr::scene::ISceneNode *eyeNode = (irr::scene::jz3d::CCollusionMngNode *)pSmgr->getSceneNodeFromName("eye",m_pNode);
irr::scene::ISceneNode *BodyNode = (irr::scene::jz3d::CCollusionMngNode *)pSmgr->getSceneNodeFromName("body",m_pNode);
m_pCollMngNode = (irr::scene::jz3d::CCollusionMngNode *)pSmgr->getSceneNodeFromName("col_main",m_pNode);//캐릭터볼륨얻기(이동제어용)
//m_pCollMngNode_Kick = (irr::scene::jz3d::CCollusionMngNode *)pSmgr->getSceneNodeFromName("col_kick",m_pNode); //발차기 충돌정보
//m_pCollMngNode_Body = (irr::scene::jz3d::CCollusionMngNode *)pSmgr->getSceneNodeFromName("col_body",m_pNode); //몸통 충돌정보
physicsParams.mass = 70.f; //70kg
physicsParams.gravity = core::vector3df(0, 0, 0);
physicsParams.friction = 10.f; //마찰값
//현재 카메라얻기
irr::scene::ISceneNode *pCamNode = pSmgr->getActiveCamera();
irr::scene::CBulletFpsCamAnimator *pAnim = pBulletPhysicsFactory->createBulletFpsCamAnimator(
pSmgr,
pCamNode,
pDevice->getCursorControl(),
pWorldAnimator->getID(),
m_pCollMngNode->getGeometryInfo(),
&physicsParams
);
pCamNode->addAnimator(pAnim);
m_pChracterAnimator = pAnim;
pAnim->drop();
//카메라에 캐릭터 노드 붙이기
m_pNode->setParent(pCamNode);
BodyNode->setPosition(BodyNode->getPosition() - eyeNode->getPosition()); //눈을 기준으로 무기의 위치 잡아주기
m_pChracterAnimator->setLocalPosition(eyeNode->getPosition());//눈의 위치 재조정
}
return true;
}
return false;
}
void CHeroPlayer::Update(irr::f32 fDelta)
{
irr::scene::ISceneManager *pSmgr = CSAApp::GetPtr()->m_pSmgr;
irr::IrrlichtDevice *pDevice = CSAApp::GetPtr()->m_pDevice;
irr::scene::CBulletAnimatorManager* pBulletPhysicsFactory = CSAApp::GetPtr()->m_pBulletPhysicsFactory;
irr::scene::CBulletWorldAnimator* pWorldAnimator = CSAApp::GetPtr()->m_pWorldAnimator;
m_pChracterAnimator->setMoveSpeed( 1.1f * 1800.f * fDelta ); // 시속 18키로 정도
switch(GetStatus())
{
case CHeroPlayer::FSM_READY:
{
//시작위치 지정
m_pNode->setVisible(true);
irr::core::vector3df pos_Spwan = pSmgr->getSceneNodeFromName("start",m_pTrigerNode)->getAbsolutePosition();
m_pChracterAnimator->setPosition(pos_Spwan);
m_pChracterAnimator->zeroForces();
//m_pChracterAnimator->setLocalPosition(irr::core::vector3df(0,5,0));
//m_pChracterAnimator->setMoveSpeed(1.1f);
SetStatus(FSM_STAND);
}
break;
case CHeroPlayer::FSM_STAND:
{
if(GetStep() == 0)
{
m_pNode->changeAction("stand");
IncStep();
}
else
{
if( m_Key[irr::KEY_LBUTTON] )
{
irr::scene::ISceneManager *pSmgr = pDevice->getSceneManager();
irr::core::position2di mpos = pDevice->getCursorControl()->getPosition();
irr::core::line3df Ray;
irr::core::vector3df vAim;
Ray = pDevice->getSceneManager()->getSceneCollisionManager()->getRayFromScreenCoordinates(mpos);
vAim = Ray.getVector();
vAim.normalize();
ChsBullet *pBullet = new ChsBullet();
ChsBullet::Params param_bullet;
param_bullet.Energy = 100.f;
param_bullet.mass = .1f;
param_bullet.vAim = vAim;
param_bullet.vInitPos = getPosition() + (irr::core::vector3df(0,5,0) + vAim * 3); //총구 위치 적용된 발사시작위치
pBullet->Init(¶m_bullet); //총알 초기화
m_mapBullets[pBullet->m_pAnim->getRigidBody()] = SP_IFSMObject(pBullet);
m_Key[irr::KEY_LBUTTON] = false;
}
}
}
break;
}
//탄도 충돌 검출
{
btDynamicsWorld *pWorld = pWorldAnimator->getWorld();
int num = pWorld->getDispatcher()->getNumManifolds();
for(int i=0;i<num;i++)
{
btPersistentManifold *contactManifold = pWorld->getDispatcher()->getManifoldByIndexInternal(i);
if(contactManifold->getNumContacts() > 0)
{
btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
//충돌한 오브잭트 찾기
ChsBullet *pBullet = NULL;
if(m_mapBullets.count(obB) != 0)
{
pBullet = (ChsBullet *)m_mapBullets[obB].get();
}
if(m_mapBullets.count(obA) != 0)
{
pBullet = (ChsBullet *)m_mapBullets[obA].get();
}
if(pBullet)
{
pBullet->Signal("hit",NULL);
btCollisionObject *pTar = CSAApp::Get().m_spZombie1->m_pcloBody; //몸통 물리 충돌오브잭트 얻기
//해당타겟이 명중인지?
if(obA == pTar || obB == pTar)
{
CSAApp::Get().m_spZombie1->Signal("hit",pBullet);
}
std::cout << "current bullet num :" << m_mapBullets.size() << std::endl;
}
}
}
//총알 컨테이너 관리
{
std::map<btCollisionObject *,SP_IFSMObject>::iterator it = m_mapBullets.begin();
while(it != m_mapBullets.end())
{
if(it->second->isDie())
{
m_mapBullets.erase(it++);
if(m_mapBullets.empty())
break;
}
else
{
it->second->Update(fDelta);
it++;
}
}
}
}
}
void CHeroPlayer::Signal(std::string strSignal, void *pParam)
{
}
bool CHeroPlayer::OnEvent(const irr::SEvent &event)
{
switch(event.EventType)
{
case irr::EET_GUI_EVENT:
{
}
break;
case irr::EET_KEY_INPUT_EVENT:
{
if(event.KeyInput.PressedDown)
{
m_Key[event.KeyInput.Key] = true;
}
else
{
m_Key[event.KeyInput.Key] = false;
}
}
break;
case irr::EET_MOUSE_INPUT_EVENT:
{
if(event.MouseInput.Event == irr::EMIE_LMOUSE_PRESSED_DOWN)
{
m_Key[irr::KEY_LBUTTON] = true;
}
else if(event.MouseInput.Event == irr::EMIE_LMOUSE_LEFT_UP)
{
m_Key[irr::KEY_LBUTTON] = false;
}
}
break;
case irr::EET_USER_EVENT:
break;
}
return false;
}
| [
"gbox3d@58f0f68e-7603-11de-abb5-1d1887d8974b"
] | [
[
[
1,
276
]
]
] |
221a7c8ad14dfa408df7a39922bbfbb76e8a9d16 | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/branches/chrome/chrome/src/cpp/include/breakpad/src/processor/stackwalker_amd64.h | cdde4a67e1e58e15c2f592e5e8445e7b9cbbee67 | [
"Apache-2.0"
] | permissive | vdt/selenium | 137bcad58b7184690b8785859d77da0cd9f745a0 | 30e5e122b068aadf31bcd010d00a58afd8075217 | refs/heads/master | 2020-12-27T21:35:06.461381 | 2009-08-18T15:56:32 | 2009-08-18T15:56:32 | 13,650,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,331 | h | // Copyright (c) 2007, Google Inc.
// 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 Google Inc. 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
// 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.
// stackwalker_amd64.h: amd64-specific stackwalker.
//
// Provides stack frames given amd64 register context and a memory region
// corresponding to a amd64 stack.
//
// Author: Mark Mentovai, Ted Mielczarek
#ifndef PROCESSOR_STACKWALKER_AMD64_H__
#define PROCESSOR_STACKWALKER_AMD64_H__
#include "google_breakpad/common/breakpad_types.h"
#include "google_breakpad/common/minidump_format.h"
#include "google_breakpad/processor/stackwalker.h"
namespace google_breakpad {
class CodeModules;
class StackwalkerAMD64 : public Stackwalker {
public:
// context is a amd64 context object that gives access to amd64-specific
// register state corresponding to the innermost called frame to be
// included in the stack. The other arguments are passed directly through
// to the base Stackwalker constructor.
StackwalkerAMD64(const SystemInfo *system_info,
const MDRawContextAMD64 *context,
MemoryRegion *memory,
const CodeModules *modules,
SymbolSupplier *supplier,
SourceLineResolverInterface *resolver);
private:
// Implementation of Stackwalker, using amd64 context (stack pointer in %rsp,
// stack base in %rbp) and stack conventions (saved stack pointer at 0(%rbp))
virtual StackFrame* GetContextFrame();
virtual StackFrame* GetCallerFrame(
const CallStack *stack,
const vector< linked_ptr<StackFrameInfo> > &stack_frame_info);
// Stores the CPU context corresponding to the innermost stack frame to
// be returned by GetContextFrame.
const MDRawContextAMD64 *context_;
};
} // namespace google_breakpad
#endif // PROCESSOR_STACKWALKER_AMD64_H__
| [
"noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9"
] | [
[
[
1,
80
]
]
] |
957db4346c0e04e78705e7f1bf10524103c43322 | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /aluminizer/LockScan.cpp | 80bf71e2e75799b255858aeb7a0a2c65605971cb | [
"LicenseRef-scancode-public-domain"
] | permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,045 | cpp | #ifdef PRECOMPILED_HEADER
#include "common.h"
#endif
#include "ScanObject.h"
#include "ExpSCAN.h"
using namespace std;
LockScan::LockScan(ExpSCAN* scanPage, vector<scan_variable*> scan_variables, LockParams* lp, ScanSource* ss) :
ContinuousScan(scanPage, scan_variables),
pCenterChannel( new ConstantChannel("center", false) ),
pLockParams(lp),
num_new_points(0),
ss(ss)
{
data_feed.AddChannel(pCenterChannel);
}
void LockScan::UseValidData()
{
ContinuousScan::UseValidData();
if (validData.size() > 0)
pLockParams->RespondToMeasurement();
//take 3 data points before signaling OnIdle
if (++num_new_points == GetNumToTake())
{
num_new_points = 0;
setRunStatus(ExperimentBase::IDLE);
}
else
setRunStatus(ExperimentBase::NEED_MORE_DATA);
}
string LockScan::GetPlotLabel()
{
return pLockParams->GetLockVariableName() + " = " + to_string<double>(pLockParams->GetCenter(), 2);
}
LockInScan::LockInScan(ExpSCAN* scanPage, vector<scan_variable*> scan_variables, LockInParams* lp, ScanSource* ss) :
LockScan(scanPage, scan_variables, lp, ss),
pLockInParams(lp),
iCurrentPoint(0),
flipLeftRight(0),
nLeft(0),
nRight(0),
nCenter(0),
measurements(3),
pcAdjustments( new ConstantChannel("adjustments", false) )
{
data_feed.AddChannel(pcAdjustments);
data_feed.AddChannel(pcLeftSignal = new ConstantChannel("Left", true, 3));
data_feed.AddChannel(pcCenterSignal = new ConstantChannel("Center", true, 3));
data_feed.AddChannel(pcRightSignal = new ConstantChannel("Right", true, 3));
//is this the same output as in SetOutput ???
// pLockInParams->SetCenter( pLockInParams->GetOutput() );
}
void LockInScan::AcquireDataPoint()
{
//pLockInParams->SetOutput( pLockInParams->GetCenter() + ModulationState(iCurrentPoint) );
pLockInParams->modulateOutput( ModulationState(iCurrentPoint) );
if ( iCurrentPoint == LeftIndex())
nLeft++;
if ( iCurrentPoint == RightIndex())
nRight++;
if ( iCurrentPoint == CenterIndex())
nCenter++;
/*
if( (nLeft == nRight) && (nLeft % 10 == 0))
{
//flipLeftRight = 1 - flipLeftRight;
for(size_t i = 0; i < measurements.size(); i++)
measurements[i].counts = -1;
}
*/
pCenterChannel->SetCurrentData( pLockInParams->GetCenter() );
pcAdjustments->SetCurrentData( pLockInParams->GetOutput() );
return ContinuousScan::AcquireDataPoint();
}
void LockInScan::UpdateLockSignalChannels()
{
double counts = pLockInParams->GetSignal();
//update array of measurements with latest data
measurements[iCurrentPoint].x = pLockInParams->GetOutput();
measurements[iCurrentPoint].counts = counts;
if (iCurrentPoint == LeftIndex()) pcLeftSignal->SetCurrentData(counts);
if (iCurrentPoint == RightIndex()) pcRightSignal->SetCurrentData(counts);
if (iCurrentPoint == CenterIndex()) pcCenterSignal->SetCurrentData(counts);
}
void LockInScan::UseValidData()
{
ContinuousScan::UseValidData();
if (validData.size() > 0)
{
if (!pLockInParams->UpdateMeasurements(measurements))
{
UpdateLockSignalChannels();
pLockInParams->RespondToMeasurements(this, measurements, iCurrentPoint);
}
else
{
double err, dX;
pLockInParams->getErrorSignal(&err, &dX);
printf("error = %6.4f dX = %12.9f\r\n", err, dX);
pLockInParams->RespondToMeasurements(this, err, dX);
}
}
if ( ++num_new_points == GetNumToTake() )
{
num_new_points = 0;
setRunStatus(ExperimentBase::IDLE);
}
else
setRunStatus(ExperimentBase::NEED_MORE_DATA);
}
void LockInScan::NextDataPoint()
{
iCurrentPoint = (iCurrentPoint + 1) % measurements.size();
ContinuousScan::NextDataPoint();
}
void LockInScan::DefaultExperimentState()
{
pLockInParams->modulateOutput( 0 );
}
void LockInScan::ClearMeasurements()
{
for (size_t i = 0; i < measurements.size(); i++)
measurements[i].counts = -1;
}
double LockInScan::ModulationState(int i)
{
int multiplier = 0;
if (i == LeftIndex())
multiplier = -1;
if (i == RightIndex())
multiplier = 1;
if (flipLeftRight)
multiplier *= -1;
return multiplier * pLockInParams->GetModulation();
}
void LockInParams::RespondToMeasurements(LockInScan* pScan, const measurements_t& m, size_t i)
{
if ((int)i == pScan->RightIndex() || (int)i == pScan->LeftIndex())
{
for (size_t j = 0; j < m.size(); j++)
if (m[j].counts == -1)
return;
error_signal = m.at(pScan->RightIndex()).counts - m.at(pScan->LeftIndex()).counts;
deltaX = m.at(pScan->RightIndex()).x - m.at(pScan->LeftIndex()).x;
if (MakeCorrection())
ShiftCenterNormalized(GetGain() * error_signal / 2);
}
}
void LockInParams::RespondToMeasurements(LockInScan*, double err, double dX)
{
error_signal = err;
deltaX = dX;
if (MakeCorrection())
ShiftCenterNormalized(GetGain() * error_signal / 2);
}
ExperimentBase::run_status LockScan::DataPoint()
{
return ContinuousScan::DataPoint();
}
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
] | [
[
[
1,
205
]
]
] |
0b97c2130868824a46b713965cbab15e685f6b7c | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Utilities/VisualDebugger/Viewer/Dynamics/Constraint/Drawer/hkpPrimitiveDrawer.h | dc4378e979cae01782bc5cf62f9e17d585e26e75 | [] | 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,154 | 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 HK_PRIMITIVEDRAWER_H
#define HK_PRIMITIVEDRAWER_H
#include <Common/Base/hkBase.h>
//#include <hkutilities/hkHavok2Common.h>
//#include <hkdynamics/constraint/hkpConstraintInstance.h>
//#include <hkdynamics/constraint/hkRigidConstraint.h>
//#include <hkvisualize/type/hkColor.h>
//#include <hkvisualize/hkDebugDisplayHandler.h>
/// Base class for constraint viewers
class hkDebugDisplayHandler;
class hkpPrimitiveDrawer
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_VDB, hkpPrimitiveDrawer );
protected:
hkDebugDisplayHandler* m_displayHandler;
public:
hkpPrimitiveDrawer();
/// Sets the display handler
void setDisplayHandler(hkDebugDisplayHandler* displayHandler);
/// Displays an oriented point.
void displayOrientedPoint(const hkVector4& position,const hkRotation& rot,hkReal size, int color, int id, int tag);
/// Displays an arrow.
void displayArrow (const hkVector4& startPos, const hkVector4& arrowDirection, const hkVector4& perpDirection, int color, hkReal scale, int id, int tag);
/// Displays a cone.
void displayCone (hkReal cone_angle, const hkVector4& startPos, const hkVector4& coneAaxis, const hkVector4& perpVector, int numSegments, int color, hkReal coneSize, int id, int tag);
/// Displays a plane.
void displayPlane(const hkVector4& startPos, const hkVector4& planeNormal, const hkVector4& vectorOnPlane, int color, hkReal scale, int id, int tag);
/// Draws a semi circle.
/// \center The position of the center in world space.
/// \normal The axis about which the circle is drawn.
/// \param startPerp An orthogonal axis to the normal which defines the start of the sweep.
void drawSemiCircle(const hkVector4& center, hkVector4& normal,
hkVector4& startPerp, hkReal thetaMin, hkReal thetaMax,
hkReal radius,int numSegments, int color, int id, int tag);
};
#endif // HK_PRIMITIVEDRAWER_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,
74
]
]
] |
d815452e136ea37cc35d4dcd9ef2471076daa896 | c7fd308ee062c23e1b036b84bbf890c3f7e74fc4 | /Tarea9_Texturas/main.cpp | 0045fa95748947a1a4eeb3f3ee43afd425021537 | [] | no_license | truenite/truenite-opengl | 805881d06a5f6ef31c32235fb407b9a381a59ed9 | 157b0e147899f95445aed8f0d635848118fce8b6 | refs/heads/master | 2021-01-10T01:59:35.796094 | 2011-05-06T02:03:16 | 2011-05-06T02:03:16 | 53,160,700 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 6,723 | cpp | /***************************************************
Materia: Gráficas Computacionales
Tarea: 9 Texturas
Fecha: 3 de abril de 2011
Autor 1: 1162205 Diego Alfonso Garcia Mendiburu
***************************************************/
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#define MINTRIANGULOS 10
#define MAXTRIANGULOS 100
#define IMAGESIZE 512
float MAXALTURA = .2;
char textura[] ="Madera.ppm";
char altura[] = "espiral.ppm";
float rotationX=0.0;
float rotationY=0.0;
float prevX=0.0;
float prevY=0.0;
bool mouseDown=false;
float viewer[]= {0.0, 0.0, 1.0};
GLuint texName=0;
unsigned char woodtexture[IMAGESIZE][IMAGESIZE][3];
unsigned char woodHeight[IMAGESIZE][IMAGESIZE][3];
int numFilas = 100;
int heightSize;
void calcAltura(){
int w, h, d;
char *c;
FILE *fp;
int i, j, k;
fp = fopen(altura,"rb");
fscanf(fp,"%s ", &c);
fscanf(fp,"%d %d %d ", &w, &h, &d) ;
//heightSize = w;
for (i = 0 ; i < w ; i++)
for (j = 0 ; j < h ; j++)
for (k = 0 ; k < 3 ; k++)
fscanf(fp,"%c",&(woodHeight[i][j][k])) ;
fclose(fp);
}
float getAltura(int v){
if(v == 255)
return (GLfloat) MAXALTURA;
else
return (GLfloat)(v * MAXALTURA) / 255.0;
}
void initTexture(){
/* First, read this simple ppm file in */
int w, h, d;
char *c;
FILE *fp;
int i, j, k;
fp = fopen(textura,"rb");
fscanf(fp,"%s ", &c);
fscanf(fp,"%d %d %d ", &w, &h, &d) ;
for (i = 0 ; i < w ; i++)
for (j = 0 ; j < h ; j++)
for (k = 0 ; k < 3 ; k++)
fscanf(fp,"%c",&(woodtexture[i][j][k])) ;
fclose(fp) ;
/* Now, set up all the stuff for texturing, per page 368 */
glGenTextures(1, &texName) ;
//glBindTexture(GL_TEXTURE_2D, texName) ;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) ;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) ;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) ;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) ;
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB, IMAGESIZE, IMAGESIZE, 0, GL_RGB,
GL_UNSIGNED_BYTE, woodtexture);
}
void specialKey(int c, int x, int y){
if(c == GLUT_KEY_UP) {
if(MAXALTURA < 1)
MAXALTURA += 0.02;
}
if(c == GLUT_KEY_DOWN) {
if(MAXALTURA > 0)
MAXALTURA -= 0.02;
}
glutPostRedisplay();
}
void key(unsigned char key, int x, int y)
{
if(key == '+' && numFilas < MAXTRIANGULOS) {
numFilas += 1;
//numFilas *= 2;
printf("Numero de filas %d \n", numFilas);
}
if(key == '-' && numFilas > MINTRIANGULOS) {
numFilas -= 1;
//numFilas /= 2;
printf("Numero de filas %d \n", numFilas);
}
if(key == 'x') viewer[0]-= 0.1;
if(key == 'X') viewer[0]+= 0.1;
if(key == 'y') viewer[1]-= 0.1;
if(key == 'Y') viewer[1]+= 0.1;
if(key == 'z') viewer[2]-= 0.1;
if(key == 'Z') viewer[2]+= 0.1;
glutPostRedisplay();
}
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor3f(1,1,1);
gluLookAt(viewer[0],viewer[1],viewer[2],0,0,0,0,1,0);
glRotatef(rotationX,1,0,0);
glRotatef(rotationY,0,1,0);
//glTranslatef(1.0,1.0,0);
//glRotatef(90,0,0,1);
//glTranslatef(.5,.5,0);
float posActualX, posActualY, posActualZ;
posActualX = posActualY = posActualZ = 0.0;
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
for(int i = 0; i < numFilas; i++){
for(int j = 0; j < numFilas; j++){
//glBegin(GL_POLYGON);
glBegin(GL_TRIANGLES);
//Vertice 1
glTexCoord2f(posActualX, posActualY);
int im = IMAGESIZE / numFilas;
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * i][im * j][0]));
//printf("[%d,%d,%d]\n", i, j, im * i);
posActualX += 1/(GLfloat)numFilas;
//Vertice 2
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * i][im * (j+1)][0]));
posActualY += 1/(GLfloat)numFilas;
//Vertice 3
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * (i+1)][im * (j+1)][0]));
//Vertice 4
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * (i+1)][im * (j+1)][0]));
posActualX -= 1/(GLfloat)numFilas;
//Vertice 5
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * (i+1)][im * j][0]));
posActualY -= 1/(GLfloat)numFilas;
//Vertice 6
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * i][im * j][0]));
posActualX += 1/(GLfloat)numFilas;
glEnd();
}
posActualY += 1/(GLfloat)numFilas;
posActualX = 0;
}
//
glutSwapBuffers();
}
void initializeGL(void)
{
glEnable(GL_DEPTH_TEST);
glClearColor(0,0,0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-0.5, 1.5, -0.5, 1.5, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D) ;
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) ;
glBindTexture(GL_TEXTURE_2D, texName) ;
initTexture();
calcAltura();
}
void mouse(int button, int state, int x, int y){
printf("pica\n");
if(button == GLUT_LEFT_BUTTON && state==GLUT_DOWN){
mouseDown = true;
prevX = x - rotationY;
prevY = y - rotationX;
}else{
mouseDown = false;
}
}
void mouseMotion(int x, int y){
printf("moviendo\n");
if(mouseDown){
rotationX = y - prevY;
rotationY = x - prevX;
glutPostRedisplay();
}
}
main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(500,500);
glutInitWindowPosition(100, 150);
glutCreateWindow("Usando una imagen como textura");
glutKeyboardFunc(key);
glutSpecialFunc(specialKey);
glutDisplayFunc(myDisplay);
glutMouseFunc(mouse);
glutMotionFunc(mouseMotion);
initializeGL();
glutMainLoop();
}
| [
"[email protected]"
] | [
[
[
1,
267
]
]
] |
9db037108a91d0e52f28c71e67e27a8dc53363f6 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/__ffl_dump/source/ffl_dump_mini.cpp | a5ecf7f8137fd902fc3d33f176588876e6d9198b | [] | no_license | 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 | UHC | C++ | false | false | 2,583 | cpp | #include "../include/ffl_dump_mini.h"
#include "../include/ffl_c_string.h"
#include <tchar.h>
void ffl_dump_mini::dump( const ffl_tchar_t * name, ffl_dump_param_t * param )
{
if( param != NULL && name != NULL )
{
HANDLE file = ::CreateFile( name,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
NULL );
if( file != INVALID_HANDLE_VALUE )
{
write( file, param );
::CloseHandle( file );
file = INVALID_HANDLE_VALUE;
}
}
return;
}
void ffl_dump_mini::write( HANDLE file, ffl_dump_param_t * param )
{
if( file != INVALID_HANDLE_VALUE && param != NULL )
{
HMODULE dbghelp = find_dll();
if( dbghelp != NULL )
{
typedef BOOL (WINAPI * mini_dump_write_dump_f)( HANDLE,
DWORD,
HANDLE,
MINIDUMP_TYPE,
const PMINIDUMP_EXCEPTION_INFORMATION,
const PMINIDUMP_USER_STREAM_INFORMATION,
const PMINIDUMP_CALLBACK_INFORMATION );
mini_dump_write_dump_f dump_f = (mini_dump_write_dump_f) ::GetProcAddress( dbghelp, "MiniDumpWriteDump" );
if( dump_f != NULL )
{
int dump_type = MiniDumpNormal;// | MiniDumpWithHandleData;
if( param->level == ffl_dump_level_medium )
{
dump_type |= MiniDumpWithDataSegs;
}
if( param->level == ffl_dump_level_heavy )
{
dump_type |= MiniDumpWithFullMemory;
}
MINIDUMP_EXCEPTION_INFORMATION info;
info.ThreadId = param->dump_thread_id;
info.ExceptionPointers = param->exception_ptr;
info.ClientPointers = FALSE;
dump_f( ::GetCurrentProcess(),
::GetCurrentProcessId(),
file,
static_cast< MINIDUMP_TYPE >( dump_type ),
param->exception_ptr ? &info : NULL,
NULL,
NULL );
}
::FreeLibrary( dbghelp );
dbghelp = NULL;
}
}
return;
}
HMODULE ffl_dump_mini::find_dll()
{
static const ffl_tchar_t dll_name[] = FFL_T( "dbghelp.dll" );
HMODULE dbghelp = NULL;
ffl_tchar_t path[MAX_PATH] = { 0, };
// 실행파일이 있는 곳의 dbghelp.dll을 먼저 로드한다.
if( ::GetModuleFileName( NULL, path, FFL_COUNTOF( path ) ) != 0 )
{
ffl_tchar_t * slash = NULL;
if( (slash = ::_tcsrchr( path, FFL_T( '\\' ) )) != NULL )
{
size_t count = FFL_COUNTOF( path ) - (slash-path);
ffl_strncpy( slash + 1, count - 1, dll_name, FFL_COUNTOF( dll_name ) );
dbghelp = ::LoadLibrary( path );
}
}
// 실패하면 기본 dll을 로드한다.
if( dbghelp == NULL )
{
dbghelp = ::LoadLibrary( dll_name );
}
return dbghelp;
} | [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
107
]
]
] |
5b7fbd641ba7d815e1b76748d5903a61d2569427 | 629e4fdc23cb90c0144457e994d1cbb7c6ab8a93 | /lib/system/random.cpp | fc12b0928c783499b815d2b1149119398dbc0609 | [] | no_license | akin666/ice | 4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2 | 7cfd26a246f13675e3057ff226c17d95a958d465 | refs/heads/master | 2022-11-06T23:51:57.273730 | 2011-12-06T22:32:53 | 2011-12-06T22:32:53 | 276,095,011 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 769 | cpp | /*
* random.cpp
*
* Created on: 3.4.2010
* Author: akin
*/
#include "random"
#include <iostream>
#include <cstdlib>
#include <ctime>
namespace ice
{
Random *Random::sm_singleton = NULL;
Random::Random() {
srand( time(NULL) );
}
Random::~Random() {
}
Random& Random::get() {
if( sm_singleton == NULL ) {
sm_singleton = new Random();
}
return *sm_singleton;
}
float Random::getFloat() {
// returns 32bit integer, change into float directly. should be random. TRULY
// [0.0f,1.0f]
return rand()/(RAND_MAX+1.f);
}
unsigned char Random::getUChar() {
return (unsigned char)(getFloat()*0xFF);
}
char Random::getChar() {
return (char)(getFloat()*0xFF);
}
int Random::getInt() {
return rand();
}
}
| [
"akin@lich",
"akin@localhost"
] | [
[
[
1,
7
],
[
9,
48
]
],
[
[
8,
8
]
]
] |
5d9670b4cd28d45c407f9e3775bdef70f0a5631a | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/Include/CHumanoid.h | 641e01166e59a6302e0c0dc4bdfee45f7094cca9 | [] | 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 | ISO-8859-10 | C++ | false | false | 2,817 | h | /*!
@file
@author Pablo Nuņez
@date 13/2009
@module
*//*
This file is part of the Nebula Engine.
Nebula Engine is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Nebula Engine 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Nebula Engine. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CHUMANOID_H_
#define _CHUMANOID_H_
#include "EnginePrerequisites.h"
#include "ItemBoxWindow.h"
#include "Tooltip.h"
namespace Nebula {
using namespace Ogre;
class IGameComponent;
class ToolTip;
class ItemBoxWindow;
//class GuiManager;
//enum WindowPosition;
struct NebulaDllPrivate CHumanoidDesc
{
CHumanoidDesc()
{
}
std::string name;
};
class NebulaDllPrivate CHumanoid : public IGameComponent
{
public:
CHumanoid();
CHumanoid(const CHumanoidDesc&);
~CHumanoid();
void update();
void setup();
void notifyStartDrop(wraps::BaseLayout * _sender, wraps::DDItemInfo _info, bool & _result);
void notifyRequestDrop(wraps::BaseLayout * _sender, wraps::DDItemInfo _info, bool & _result);
void notifyEndDrop(wraps::BaseLayout * _sender, wraps::DDItemInfo _info, bool _result);
void notifyNotifyItem(wraps::BaseLayout * _sender, const MyGUI::IBNotifyItemData & _info);
void notifyDropState(wraps::BaseLayout * _sender, MyGUI::DDItemState _state);
void notifyToolTip(wraps::BaseLayout * _sender, const MyGUI::ToolTipInfo & _info, ItemData * _data);
void notifyMouseButtonClick(MyGUI::WidgetPtr _sender, int _left, int _top, MyGUI::MouseButton _id);
void notifyMouseSetFocus(MyGUI::WidgetPtr _sender, MyGUI::WidgetPtr _old);
void notifyMouseLostFocus(MyGUI::WidgetPtr _sender, MyGUI::WidgetPtr _new);
void hideCharacterPaper();
void showCharacterPaper();
void createCharacterPaper(Vector2 imageSize,std::string resourceName); //, WindowPosition align
void destroyCharacterPaper();
void create();
CHumanoidDesc& getDescription() {
return mDesc;
}
void callLuaFunction(const std::string func );
virtual const std::string& componentID() const {
return mComponentID;
}
private:
std::string mComponentID;
ItemBoxWindow * mCharacterBox;
ToolTip * mToolTip;
MyGUI::StaticImagePtr mCharacterImage;
CHumanoidDesc mDesc;
};
} //end namespace
#endif
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
] | [
[
[
1,
103
]
]
] |
ef197a036d94693a17366785c278cb3e0dbce3b5 | 96fefafdfbb413a56e0a2444fcc1a7056afef757 | /mq2telnet/ISXEQTelnet.cpp | 59cdd3c16fe99dbc1821e3306847136534b680bd | [] | no_license | kevrgithub/peqtgc-mq2-sod | ffc105aedbfef16060769bb7a6fa6609d775b1fa | d0b7ec010bc64c3f0ac9dc32129a62277b8d42c0 | refs/heads/master | 2021-01-18T18:57:16.627137 | 2011-03-06T13:05:41 | 2011-03-06T13:05:41 | 32,849,784 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 11,847 | cpp | //
// ISXEQTelnet
//
#pragma warning(disable:4996)
#include "../ISXEQClient.h"
#include "ISXEQTelnet.h"
// The mandatory pre-setup function. Our name is "ISXEQTelnet", and the class is ISXEQTelnet.
// This sets up a "ModulePath" variable which contains the path to this module in case we want it,
// and a "PluginLog" variable, which contains the path and filename of what we should use for our
// debug logging if we need it. It also sets up a variable "pExtension" which is the pointer to
// our instanced class.
ISXPreSetup("ISXEQTelnet",ISXEQTelnet);
// Basic LavishScript datatypes, these get retrieved on startup by our initialize function, so we can
// use them in our Top-Level Objects or custom datatypes
LSType *pStringType=0;
LSType *pIntType=0;
LSType *pBoolType=0;
LSType *pFloatType=0;
LSType *pTimeType=0;
LSType *pByteType=0;
ISInterface *pISInterface=0;
HISXSERVICE hPulseService=0;
HISXSERVICE hMemoryService=0;
HISXSERVICE hServicesService=0;
HISXSERVICE hEQChatService=0;
HISXSERVICE hEQUIService=0;
HISXSERVICE hEQGamestateService=0;
HISXSERVICE hEQSpawnService=0;
HISXSERVICE hEQZoneService=0;
// Forward declarations of callbacks
void __cdecl PulseService(bool Broadcast, unsigned int MSG, void *lpData);
void __cdecl MemoryService(bool Broadcast, unsigned int MSG, void *lpData);
void __cdecl ServicesService(bool Broadcast, unsigned int MSG, void *lpData);
// Initialize is called by Inner Space when the extension should initialize.
bool ISXEQTelnet::Initialize(ISInterface *p_ISInterface)
{ pISInterface=p_ISInterface;
// retrieve basic ISData types
pStringType=pISInterface->FindLSType("string");
pIntType=pISInterface->FindLSType("int");
pBoolType=pISInterface->FindLSType("bool");
pFloatType=pISInterface->FindLSType("float");
pTimeType=pISInterface->FindLSType("time");
pByteType=pISInterface->FindLSType("byte");
pISInterface->OpenSettings(XMLFileName);
LoadSettings();
ConnectServices();
RegisterCommands();
RegisterAliases();
RegisterDataTypes();
RegisterTopLevelObjects();
RegisterServices();
WriteChatf("ISXEQTelnet Loaded");
return true;
}
// shutdown sequence
void ISXEQTelnet::Shutdown()
{
// save settings, if you changed them and want to save them now. You should normally save
// changes immediately.
//pISInterface->SaveSettings(XMLFileName);
pISInterface->UnloadSettings(XMLFileName);
DisconnectServices();
UnRegisterServices();
UnRegisterTopLevelObjects();
UnRegisterDataTypes();
UnRegisterAliases();
UnRegisterCommands();
}
void ISXEQTelnet::ConnectServices()
{
// connect to any services. Here we connect to "Pulse" which receives a
// message every frame (after the frame is displayed) and "Memory" which
// wraps "detours" and memory modifications
hPulseService=pISInterface->ConnectService(this,"Pulse",PulseService);
hMemoryService=pISInterface->ConnectService(this,"Memory",MemoryService);
hServicesService=pISInterface->ConnectService(this,"Services",ServicesService);
}
void ISXEQTelnet::RegisterCommands()
{
// add any commands
// pISInterface->AddCommand("MyCommand",MyCommand,true,false);
}
void ISXEQTelnet::RegisterAliases()
{
// add any aliases
}
void ISXEQTelnet::RegisterDataTypes()
{
// add any datatypes
// pMyType = new MyType;
// pISInterface->AddLSType(*pMyType);
}
void ISXEQTelnet::RegisterTopLevelObjects()
{
// add any Top-Level Objects
// pISInterface->AddTopLevelObject("MapSpawn",tloMapSpawn);
}
void ISXEQTelnet::RegisterServices()
{
// register any services. Here we demonstrate a service that does not use a
// callback
// set up a 1-way service (broadcast only)
// hISXEQTelnetService=pISInterface->RegisterService(this,"ISXEQTelnet Service",0);
// broadcast a message, which is worthless at this point because nobody will receive it
// (nobody has had a chance to connect)
// pISInterface->ServiceBroadcast(this,hISXEQTelnetService,ISXSERVICE_MSG+1,0);
}
void ISXEQTelnet::DisconnectServices()
{
// gracefully disconnect from services
if (hPulseService)
pISInterface->DisconnectService(this,hPulseService);
if (hMemoryService)
{
pISInterface->DisconnectService(this,hMemoryService);
// memory modifications are automatically undone when disconnecting
// also, since this service accepts messages from clients we should reset our handle to
// 0 to make sure we dont try to continue using it
hMemoryService=0;
}
if (hServicesService)
pISInterface->DisconnectService(this,hServicesService);
}
void ISXEQTelnet::UnRegisterCommands()
{
// remove commands
// pISInterface->RemoveCommand("MyCommand");
}
void ISXEQTelnet::UnRegisterAliases()
{
// remove aliases
}
void ISXEQTelnet::UnRegisterDataTypes()
{
// remove data types
//if (pMyType)
//{
// pISInterface->RemoveLSType(*pMyType);
// delete pMyType;
//}
}
void ISXEQTelnet::UnRegisterTopLevelObjects()
{
// remove Top-Level Objects
// pISInterface->RemoveTopLevelObject("MapSpawn");
}
void ISXEQTelnet::UnRegisterServices()
{
// shutdown our own services
// if (hISXEQTelnetService)
// pISInterface->ShutdownService(this,hISXEQTelnetService);
}
void ISXEQTelnet::LoadSettings()
{
// IS provides easy methods of reading and writing settings of all types (bool, int, string, float, etc)
bool BoolSetting=true;
char StringSetting[512]={0};
int IntSetting=15;
float FloatSetting=25.3f;
if (!pISInterface->GetSettingi(XMLFileName,"My Section","My Int Setting",IntSetting))
{
// int setting did not exist, should we modify the xml?
// It returned false, so IntSetting is still our default value of 15. Let's
// use that from here, and store it in the xml
pISInterface->SetSettingi(XMLFileName,"My Section","My Int Setting",IntSetting);
}
if (!pISInterface->GetSettingb(XMLFileName,"My Section","My Bool Setting",BoolSetting))
{
// bool setting did not exist, should we modify the xml?
// It returned false, so BoolSetting is still our default value of true. Let's
// use that from here, and store it.
// Bool settings are stored as integers, so just use SetSettingi
pISInterface->SetSettingi(XMLFileName,"My Section","My Bool Setting",BoolSetting);
}
if (!pISInterface->GetSettingf(XMLFileName,"My Section","My Float Setting",FloatSetting))
{
// float setting did not exist, should we modify the xml?
// It returned false, so FloatSetting is still our default value of 25.3. Let's
// use that from here, and store it.
pISInterface->SetSettingf(XMLFileName,"My Section","My Float Setting",FloatSetting);
}
if (!pISInterface->GetSetting(XMLFileName,"My Section","My String Setting",StringSetting,sizeof(StringSetting)))
{
// string setting did not exist, should we modify the xml?
// It returned false, so StringSetting is still our default empty string.
// Let's set it to a new default, "ISXEQTelnet", and store it.
strcpy(StringSetting,"ISXEQTelnet");
pISInterface->SetSetting(XMLFileName,"My Section","My String Setting",StringSetting);
}
// save settings if we changed them
pISInterface->SaveSettings(XMLFileName);
}
void __cdecl PulseService(bool Broadcast, unsigned int MSG, void *lpData)
{
if (MSG==PULSE_PULSE)
{
// Same as OnPulse
}
}
void __cdecl MemoryService(bool Broadcast, unsigned int MSG, void *lpData)
{
// no messages are currently associated with this service (other than
// system messages such as client disconnect), so do nothing.
}
void __cdecl EQUIService(bool Broadcast, unsigned int MSG, void *lpData)
{
switch(MSG)
{
case UISERVICE_CLEANUP:
// same as OnCleanUI
break;
case UISERVICE_RELOAD:
// same as OnReloadUI
break;
}
}
void __cdecl EQGamestateService(bool Broadcast, unsigned int MSG, void *lpData)
{
#define GameState ((unsigned int)lpData)
if (MSG==GAMESTATESERVICE_CHANGED)
{
// same as SetGameState
}
#undef GameState
}
void __cdecl EQSpawnService(bool Broadcast, unsigned int MSG, void *lpData)
{
switch(MSG)
{
#define pSpawn ((PSPAWNINFO)lpData)
case SPAWNSERVICE_ADDSPAWN:
// same as OnAddSpawn
break;
case SPAWNSERVICE_REMOVESPAWN:
// same as OnRemoveSpawn
break;
#undef pSpawn
#define pGroundItem ((PGROUNDITEM)lpData)
case SPAWNSERVICE_ADDITEM:
// same as OnAddGroundItem
break;
case SPAWNSERVICE_REMOVEITEM:
// same as OnRemoveGroundItem
break;
#undef pGroundItem
}
}
void __cdecl EQZoneService(bool Broadcast, unsigned int MSG, void *lpData)
{
switch(MSG)
{
case ZONESERVICE_BEGINZONE:
// same as OnBeginZone
break;
case ZONESERVICE_ENDZONE:
// same as OnEndZone
break;
case ZONESERVICE_ZONED:
// same as OnZoned
break;
}
}
void __cdecl EQChatService(bool Broadcast, unsigned int MSG, void *lpData)
{
switch(MSG)
{
case CHATSERVICE_OUTGOING:
// same as OnWriteChatColor
break;
case CHATSERVICE_INCOMING:
// same as OnIncomingChat
break;
}
}
// This uses the Services service to connect to ISXEQ services
void __cdecl ServicesService(bool Broadcast, unsigned int MSG, void *lpData)
{
#define Name ((char*)lpData)
switch(MSG)
{
case SERVICES_ADDED:
if (!stricmp(Name,"EQ UI Service"))
{
hEQUIService=pISInterface->ConnectService(pExtension,Name,EQUIService);
}
else if (!stricmp(Name,"EQ Gamestate Service"))
{
hEQGamestateService=pISInterface->ConnectService(pExtension,Name,EQGamestateService);
}
else if (!stricmp(Name,"EQ Spawn Service"))
{
hEQSpawnService=pISInterface->ConnectService(pExtension,Name,EQSpawnService);
}
else if (!stricmp(Name,"EQ Zone Service"))
{
hEQZoneService=pISInterface->ConnectService(pExtension,Name,EQZoneService);
}
else if (!stricmp(Name,"EQ Chat Service"))
{
hEQChatService=pISInterface->ConnectService(pExtension,Name,EQChatService);
}
break;
case SERVICES_REMOVED:
if (!stricmp(Name,"EQ UI Service"))
{
if (hEQUIService)
{
pISInterface->DisconnectService(pExtension,hEQUIService);
hEQUIService=0;
}
}
else if (!stricmp(Name,"EQ Gamestate Service"))
{
if (hEQGamestateService)
{
pISInterface->DisconnectService(pExtension,hEQGamestateService);
hEQGamestateService=0;
}
}
else if (!stricmp(Name,"EQ Spawn Service"))
{
if (hEQSpawnService)
{
pISInterface->DisconnectService(pExtension,hEQSpawnService);
hEQSpawnService=0;
}
}
else if (!stricmp(Name,"EQ Zone Service"))
{
if (hEQZoneService)
{
pISInterface->DisconnectService(pExtension,hEQZoneService);
hEQZoneService=0;
}
}
else if (!stricmp(Name,"EQ Chat Service"))
{
if (hEQChatService)
{
pISInterface->DisconnectService(pExtension,hEQChatService);
hEQChatService=0;
}
}
break;
}
#undef Name
}
int MyCommand(int argc, char *argv[])
{
// IS Commands work just like console programs. argc is the argument (aka parameter) count,
// argv is an array containing them. The name of the command is always the first argument.
if (argc<2)
{
// This command requires arguments
WriteChatf("Syntax: %s <text>",argv[0]);
return 0;
}
char FullText[8192]={0};
pISInterface->GetArgs(1,argc,argv,FullText); // this gets the rest of the arguments, from 1 to argc
WriteChatf("You passed the following text to the command:");
WriteChatf("%s",FullText);
// For most commands, you need to deal with only one argument at a time, instead of the entire line.
for (int i = 1 ; i < argc ; i++)
{
WriteChatf("argv[%d]=\"%s\"",i,argv[i]);
}
// return 0 or greater for normal conditions, or return -1 for an error that should stop
// a script.
return 0;
}
| [
"[email protected]@39408780-f958-9dab-a28b-4b240efc9052"
] | [
[
[
1,
413
]
]
] |
e883e627a0a1cda929f91c8b279a08cf525d4829 | ef1ad93a27524000ba8f99fcdf217136ceebb3c1 | /main.cpp | 64abad0702191f48465f77205c9c7a73c5be062a | [] | no_license | capnjj/taiga-wizard | 1c2ade791544a02b694fd4da312e70aef560fd23 | ea3835bd64cbe57e0ce22af9ced262b5ff3f00fd | refs/heads/master | 2021-01-18T05:15:13.284903 | 2010-08-27T14:52:49 | 2010-08-27T14:52:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 657 | cpp | #include <QtGui/QApplication>
#include "dialog.h"
#include <QFont>
#include <QString>
#include <QDir>
#include <QMessageBox>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString styleSheet;
if(QDir::separator()=='/') // for checking if were in windows of linux
styleSheet = "QLabel{font: \"SansSerif\"; font-size: 10px } QGroupBox{font: bold \"SansSerif\"; font-size: 14px }";
else
styleSheet = "QLabel{font: \"SansSerif\"; font-size: 12px } QGroupBox{font: bold \"SansSerif\"; font-size: 14px }";
a.setStyleSheet(styleSheet);
Dialog w;
w.show();
return a.exec();
}
| [
"[email protected]"
] | [
[
[
1,
21
]
]
] |
ebf50cd2fc59ed563cb1e42e2d0f2e5ee84b4ef2 | 016774685beb74919bb4245d4d626708228e745e | /lib/Collide/ozcollide/vec2f.cpp | 2872aa9d8924ec69238d11caa7f786249f8e8176 | [] | no_license | sutuglon/Motor | 10ec08954d45565675c9b53f642f52f404cb5d4d | 16f667b181b1516dc83adc0710f8f5a63b00cc75 | refs/heads/master | 2020-12-24T16:59:23.348677 | 2011-12-20T20:44:19 | 2011-12-20T20:44:19 | 1,925,770 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 992 | cpp | /*
OZCollide - Collision Detection Library
Copyright (C) 2006 Igor Kravtchenko
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact the author: [email protected]
*/
#include <ozcollide/ozcollide.h>
#ifndef OZCOLLIDE_PCH
#include <ozcollide/vec2f.h>
#endif
ENTER_NAMESPACE_OZCOLLIDE
LEAVE_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
30
]
]
] |
4f4587211145261e4703ac48629ac3644d2f64b9 | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/include/Ngl/Manager/IEntityPairVisitor.h | d0b4aa9c5ceb7f5e27bebdd28df5edd01cb40a3a | [] | no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,270 | h | /*******************************************************************************/
/**
* @file IEntityPairVisitor.h.
*
* @brief ペア訪問者インターフェース定義.
*
* @date 2008/07/16.
*
* @version 1.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#ifndef _NGL_IENTITYPAIRVISITOR_H_
#define _NGL_IENTITYPAIRVISITOR_H_
namespace Ngl{
/**
* @interface IEntityPairVisitor.
* @brief ペア訪問者インターフェース.
* @tparam Entity 訪問する要素.
*/
template <class Entity>
class IEntityPairVisitor
{
public:
/*=========================================================================*/
/**
* @brief デストラクタ
*
* @param[in] なし.
*/
virtual ~IEntityPairVisitor(){}
/*=========================================================================*/
/**
* @brief 訪問する
*
* @param[in] entity1 訪問する要素その1.
* @param[in] entity2 訪問する要素その2.
* @return なし.
*/
virtual void visit( Entity entity1, Entity entity2 ) = 0;
};
} // namespace Ngl
#endif
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
] | [
[
[
1,
55
]
]
] |
ccb8111ee39b494db72446ba06d87aeeacbd1ec2 | f9351a01f0e2dec478e5b60c6ec6445dcd1421ec | /itl/src/itl/setgentor.hpp | c2a82a9539ce9a1870ea9ed0f26b357a4a822841 | [
"BSL-1.0"
] | permissive | WolfgangSt/itl | e43ed68933f554c952ddfadefef0e466612f542c | 6609324171a96565cabcf755154ed81943f07d36 | refs/heads/master | 2016-09-05T20:35:36.628316 | 2008-11-04T11:44:44 | 2008-11-04T11:44:44 | 327,076 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,764 | hpp | /*----------------------------------------------------------------------------+
Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin
+-----------------------------------------------------------------------------+
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+----------------------------------------------------------------------------*/
/* ------------------------------------------------------------------
class SetGentorT
A random generator for Sets.
--------------------------------------------------------------------*/
#ifndef __SETGENTOR_H_JOFA_000724__
#define __SETGENTOR_H_JOFA_000724__
#include <itl/gentorit.hpp>
#include <itl/numbergentor.hpp>
#include <itl/itl_list.hpp>
namespace itl
{
template <class SetTV>
class SetGentorT: public RandomGentorAT<SetTV>
{
public:
typedef typename SetTV::value_type ValueTypeTD;
typedef typename SetTV::key_type DomainTD;
typedef list<ValueTypeTD> SampleTypeTD;
typedef RandomGentorAT<DomainTD> DomainGentorT;
typedef DomainGentorT* DomainGentorPT;
SetGentorT(): p_domainGentor(NULL) {}
~SetGentorT() {}
virtual void some(SetTV& x);
void last(SetTV& x)const;
void last_permuted(SetTV& x)const;
void setDomainGentor(RandomGentorAT<DomainTD>* gentor)
{
if(p_domainGentor)
delete p_domainGentor;
p_domainGentor = gentor;
}
void setRangeOfSampleSize(int lwb, int upb)
{ m_sampleSizeRange = rightopen_interval(lwb,upb); }
void setRangeOfSampleSize(const interval<int>& szRange)
{ J_ASSERT(szRange.is_rightopen()); m_sampleSizeRange = szRange; }
DomainGentorPT domainGentor()const { return p_domainGentor; }
private:
RandomGentorAT<DomainTD>* p_domainGentor;
interval<int> m_sampleSizeRange;
SampleTypeTD m_sample;
int m_sampleSize;
};
template <class SetTV>
void SetGentorT<SetTV>::some(SetTV& x)
{
NumberGentorT<int> intGentor;
x.clear();
m_sample.clear();
m_sampleSize = intGentor(m_sampleSizeRange);
for(int i=0; i<m_sampleSize; i++)
{
DomainTD key;
//CL m_domainGentor->some(key);
domainGentor()->some(key);
x += key;
m_sample.push_back(key);
}
}
template <class SetTV>
void SetGentorT<SetTV>::last(SetTV& x)const
{
x.clear();
const_FORALL(typename SampleTypeTD, it, m_sample)
x += *it;
}
template <class SetTV>
void SetGentorT<SetTV>::last_permuted(SetTV& x)const
{
x.clear();
SampleTypeTD perm;
NumberGentorT<int> intGentor;
const_FORALL(typename SampleTypeTD, it, m_sample)
{
if( 0==intGentor(2) ) perm.push_back(*it);
else perm.push_front(*it);
}
const_FORALL(typename SampleTypeTD, pit, perm)
x += *pit;
}
/*
template <class SetTV>
void SetGentorT<SetTV>::lastSample(SampleTypeTD& sam)const
{ sam = m_sample; }
template <class SetTV>
void SetGentorT<SetTV>::lastSample_permuted(SampleTypeTD& sam)
{
NumberGentorT<unsigned> intGentor;
x.clear();
int coin = intGentor.some(2); // gives 0 or 1
const_FORALL(typename SampleTypeTD, it, m_sample)
{
if( 0==intGentor.some(2) ) sam.push_back(*it);
else sam.push_front(*it);
}
}
*/
} // namespace itl
#endif
| [
"jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a"
] | [
[
[
1,
151
]
]
] |
add10a12371a9286c822cfdbc4760bfd979af64c | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.6/cbear.berlios.de/windows/com/exception.hpp | 6b37b954fddb58e278f2859e5fc4ce42aeae376c | [
"MIT"
] | permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,486 | hpp | /*
The MIT License
Copyright (c) 2005 C Bear (http://cbear.berlios.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CBEAR_BERLIOS_DE_COM_EXCEPTION_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_COM_EXCEPTION_HPP_INCLUDED
#include <sstream>
#include <boost/preprocessor/wstringize.hpp>
#include <cbear.berlios.de/base/exception.hpp>
#include <cbear.berlios.de/base/integer.hpp>
#include <cbear.berlios.de/base/lexical_cast.hpp>
#include <cbear.berlios.de/locale/cast.hpp>
#include <cbear.berlios.de/windows/com/uint.hpp>
#include <cbear.berlios.de/windows/com/hresult.hpp>
#include <cbear.berlios.de/windows/com/bstr.hpp>
#include <cbear.berlios.de/windows/com/uuid.hpp>
#include <cbear.berlios.de/windows/com/pointer.hpp>
#include <cbear.berlios.de/windows/com/ulong.hpp>
#include <cbear.berlios.de/pp/cat.hpp>
#include <cbear.berlios.de/pp/widen.hpp>
namespace cbear_berlios_de
{
namespace windows
{
namespace com
{
template<class Base>
class pointer_content<Base, ::IErrorInfo>:
public pointer_content<Base, ::IUnknown>
{
public:
bstr_t GetDescription() const
{
bstr_t Result;
this->reference().GetDescription(com::internal<out>(Result));
return Result;
}
com::uuid GetGUID() const
{
com::uuid Result;
this->reference().GetGUID(Result.c_out());
return Result;
}
dword_t GetHelpContext() const
{
dword_t Result;
this->reference().GetHelpContext(com::internal<out>(Result));
return Result;
}
bstr_t GetHelpFile() const
{
bstr_t Result;
this->reference().GetHelpFile(com::internal<out>(Result));
return Result;
}
bstr_t GetSource() const
{
bstr_t Result;
this->reference().GetSource(com::internal<out>(Result));
return Result;
}
};
typedef pointer< ::IErrorInfo> ierrorinfo;
template<class Base>
class pointer_content<Base, ::ICreateErrorInfo>:
public pointer_content<Base, ::IUnknown>
{
public:
void SetDescription(lpcwstr_t X) const
{
this->reference().SetDescription(
const_cast<lpwstr_t::internal_type>(const_cast<wchar_t *>(X.get())));
}
void SetGUID(const com::uuid &X) const
{
this->reference().SetGUID(*X.c_in());
}
void SetHelpContext(dword_t X) const
{
this->reference().SetHelpContext(X);
}
void SetHelpFile(lpcwstr_t X) const
{
this->reference().SetHelpFile(const_cast<wchar_t *>(X.get()));
}
void SetSource(lpcwstr_t X) const
{
this->reference().SetSource(const_cast<wchar_t *>(X.get()));
}
};
typedef pointer< ::ICreateErrorInfo> icreateerrorinfo;
class exception:
public std::exception,
public stream::wvirtual_write
{
public:
const char *what() const throw()
{
return "::cbear_berlios_de::windows::com::exception";
}
// hresult.
hresult result() const throw() { return this->Result; }
// error info.
const ierrorinfo &errorinfo() const throw() { return this->ErrorInfo; }
// print.
template<class Stream>
void write(Stream &O) const
{
O <<
L"cbear_berlios_de::com::exception(0x" <<
base::hex(base::unsigned_(this->Result.internal())) <<
L"):\n";
if(this->ErrorInfo)
{
O <<
L"Description: " << this->ErrorInfo.GetDescription() << L"\n" <<
L"GUID: " << this->ErrorInfo.GetGUID() << L"\n" <<
L"Help Context: " << this->ErrorInfo.GetHelpContext() << L"\n" <<
L"Help File: " << this->ErrorInfo.GetHelpFile() << L"\n" <<
L"Source: " << this->ErrorInfo.GetSource() << L"\n";
}
}
// It throws an exception initialized by a system COM error info.
static void throw_unless(hresult Value)
{
if(!Value.failed()) return;
ierrorinfo ErrorInfo;
::GetErrorInfo(0, com::internal<out>(ErrorInfo));
throw exception(Value, ErrorInfo);
}
// It throws an exception initialized by system COM error info.
static void throw_unless(::HRESULT Value)
{
throw_unless(hresult(Value));
}
static const hresult user()
{
return hresult(true, hresult::facility_type::itf, hresult::code_type::min);
}
private:
friend class create_exception;
hresult Result;
ierrorinfo ErrorInfo;
exception(
hresult Result = user(), const ierrorinfo &ErrorInfo = ierrorinfo()):
Result(Result), ErrorInfo(ErrorInfo)
{
}
hresult set() const
{
if(this->ErrorInfo) ::SetErrorInfo(0, com::internal<in>(this->ErrorInfo));
return this->Result;
}
void detail_write(cbear_berlios_de::stream::wvirtual_write::stream &S) const
{
this->write(S);
}
};
class create_exception: public com::exception
{
public:
create_exception(const hresult &X = user()): com::exception(X)
{
::CreateErrorInfo(com::internal<out>(this->CreateErrorInfo));
this->com::exception::ErrorInfo = *CreateErrorInfo.
query_interface<ierrorinfo::interface_t>();
}
const create_exception &Description(lpcwstr_t X) const
{
this->CreateErrorInfo.SetDescription(X);
return *this;
}
const create_exception &Guid(const com::uuid &X) const
{
this->CreateErrorInfo.SetGUID(X);
return *this;
}
const create_exception &HelpContext(dword_t X) const
{
this->CreateErrorInfo.SetHelpContext(X);
return *this;
}
const create_exception &HelpFile(lpcwstr_t X) const
{
this->CreateErrorInfo.SetHelpFile(X);
return *this;
}
const create_exception &Source(lpcwstr_t X) const
{
this->CreateErrorInfo.SetSource(X);
return *this;
}
// It catchs all exceptions and sets system COM error info.
static hresult catch_()
{
try
{
try
{
throw;
}
catch(const com::exception &B)
{
return B.set();
}
catch(const ::cbear_berlios_de::stream::wvirtual_write &W)
{
//std::wostringstream O;
//O << W;
return create_exception().Description(base::to_stream<bstr_t>(W)).set();
}
catch(const ::std::exception &S)
{
return create_exception().
Description(locale::cast<bstr_t>(std::string(S.what()))).
set();
}
}
catch(...)
{
return hresult::e_fail;
}
}
private:
icreateerrorinfo CreateErrorInfo;
};
}
}
}
#define CBEAR_BERLIOS_DE_WINDOWS_COM_EXCEPTION_THROW(Message) \
throw ::cbear_berlios_de::windows::com::create_exception(). \
Description(Message). \
Source(CBEAR_BERLIOS_DE_PP_CAT6( \
L"File: ", CBEAR_BERLIOS_DE_PP_WIDEN(__FILE__), \
L", Line: ", BOOST_PP_WSTRINGIZE(__LINE__), \
L", Function: ", CBEAR_BERLIOS_DE_PP_WIDEN(__FUNCTION__)))
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
] | [
[
[
1,
289
]
]
] |
a941649199e281ab35b0488e394f73178443ed35 | 90834e9db9d61688c796d0a30e77dd3acc2a9492 | /SauerbratenRemote/src/engine/decal.cpp | 59810e96d735b41e539b68681f9aa01dad30b6ba | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Zlib"
] | permissive | zot/Plexus-original | 1a79894797ca209af566bb67f72d6164869d7742 | f9c3c66c697066e63ea0509c5ff9a8d6b27e369a | refs/heads/master | 2020-09-20T21:51:57.194398 | 2009-04-21T12:45:19 | 2009-04-21T12:45:19 | 224,598,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,530 | cpp | #include "pch.h"
#include "engine.h"
struct decalvert
{
vec pos;
float u, v;
bvec color;
uchar alpha;
};
struct decalinfo
{
int millis;
bvec color;
ushort startvert, endvert;
};
enum
{
DF_RND4 = 1<<0,
DF_ROTATE = 1<<1,
DF_INVMOD = 1<<2,
DF_OVERBRIGHT = 1<<3,
DF_ADD = 1<<4
};
VARFP(maxdecaltris, 1, 1024, 16384, initdecals());
VARP(decalfade, 1000, 10000, 60000);
VAR(dbgdec, 0, 0, 1);
struct decalrenderer
{
const char *texname;
int flags, fadeintime, fadeouttime, timetolive;
Texture *tex;
decalinfo *decals;
int maxdecals, startdecal, enddecal;
decalvert *verts;
int maxverts, startvert, endvert, availverts;
decalrenderer(const char *texname, int flags = 0, int fadeintime = 0, int fadeouttime = 1000, int timetolive = -1)
: texname(texname), flags(flags),
fadeintime(fadeintime), fadeouttime(fadeouttime), timetolive(timetolive),
tex(NULL),
decals(NULL), maxdecals(0), startdecal(0), enddecal(0),
verts(NULL), maxverts(0), startvert(0), endvert(0), availverts(0),
decalu(0), decalv(0)
{
}
void init(int tris)
{
if(decals)
{
DELETEA(decals);
maxdecals = startdecal = enddecal = 0;
}
if(verts)
{
DELETEA(verts);
maxverts = startvert = endvert = availverts = 0;
}
decals = new decalinfo[tris];
maxdecals = tris;
tex = textureload(texname);
maxverts = tris*3 + 3;
availverts = maxverts - 3;
verts = new decalvert[maxverts];
}
int hasdecals()
{
return enddecal < startdecal ? maxdecals - (startdecal - enddecal) : enddecal - startdecal;
}
void cleardecals()
{
startdecal = enddecal = 0;
startvert = endvert = 0;
availverts = maxverts - 3;
}
int freedecal()
{
if(startdecal==enddecal) return 0;
decalinfo &d = decals[startdecal];
startdecal++;
if(startdecal >= maxdecals) startdecal = 0;
int removed = d.endvert < d.startvert ? maxverts - (d.startvert - d.endvert) : d.endvert - d.startvert;
startvert = d.endvert;
if(startvert==endvert) startvert = endvert = 0;
availverts += removed;
return removed;
}
void fadedecal(decalinfo &d, uchar alpha)
{
bvec color;
if(flags&DF_OVERBRIGHT)
{
if(renderpath!=R_FIXEDFUNCTION || hasTE) color = bvec(128, 128, 128);
else color = bvec(alpha, alpha, alpha);
}
else
{
color = d.color;
if(flags&(DF_ADD|DF_INVMOD)) loopk(3) color[k] = uchar((int(color[k])*int(alpha))>>8);
}
decalvert *vert = &verts[d.startvert],
*end = &verts[d.endvert < d.startvert ? maxverts : d.endvert];
while(vert < end)
{
vert->color = color;
vert->alpha = alpha;
vert++;
}
if(d.endvert < d.startvert)
{
vert = verts;
end = &verts[d.endvert];
while(vert < end)
{
vert->color = color;
vert->alpha = alpha;
vert++;
}
}
}
void clearfadeddecals()
{
int threshold = lastmillis - (timetolive>=0 ? timetolive : decalfade) - fadeouttime;
decalinfo *d = &decals[startdecal],
*end = &decals[enddecal < startdecal ? maxdecals : enddecal];
while(d < end && d->millis <= threshold) d++;
if(d >= end && enddecal < startdecal)
{
d = decals;
end = &decals[enddecal];
while(d < end && d->millis <= threshold) d++;
}
startdecal = d - decals;
if(startdecal!=enddecal) startvert = decals[startdecal].startvert;
else startvert = endvert = 0;
availverts = endvert < startvert ? startvert - endvert - 3 : maxverts - 3 - (endvert - startvert);
}
void fadeindecals()
{
if(!fadeintime) return;
decalinfo *d = &decals[enddecal],
*end = &decals[enddecal < startdecal ? 0 : startdecal];
while(d > end)
{
d--;
int fade = lastmillis - d->millis;
if(fade >= fadeintime) return;
fadedecal(*d, (fade<<8)/fadeintime);
}
if(enddecal < startdecal)
{
d = &decals[maxdecals];
end = &decals[startdecal];
while(d > end)
{
d--;
int fade = lastmillis - d->millis;
if(fade >= fadeintime) return;
fadedecal(*d, (fade<<8)/fadeintime);
}
}
}
void fadeoutdecals()
{
decalinfo *d = &decals[startdecal],
*end = &decals[enddecal < startdecal ? maxdecals : enddecal];
int offset = (timetolive>=0 ? timetolive : decalfade) + fadeouttime - lastmillis;
while(d < end)
{
int fade = d->millis + offset;
if(fade >= fadeouttime) return;
fadedecal(*d, (fade<<8)/fadeouttime);
d++;
}
if(enddecal < startdecal)
{
d = decals;
end = &decals[enddecal];
while(d < end)
{
int fade = d->millis + offset;
if(fade >= fadeouttime) return;
fadedecal(*d, (fade<<8)/fadeouttime);
d++;
}
}
}
static void setuprenderstate()
{
enablepolygonoffset(GL_POLYGON_OFFSET_FILL);
glDepthMask(GL_FALSE);
glEnable(GL_BLEND);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
}
static void cleanuprenderstate()
{
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
disablepolygonoffset(GL_POLYGON_OFFSET_FILL);
}
void render()
{
if(startvert==endvert) return;
float oldfogc[4];
if(flags&(DF_ADD|DF_INVMOD|DF_OVERBRIGHT))
{
glGetFloatv(GL_FOG_COLOR, oldfogc);
static float zerofog[4] = { 0, 0, 0, 1 }, grayfog[4] = { 0.5f, 0.5f, 0.5f, 1 };
glFogfv(GL_FOG_COLOR, flags&DF_OVERBRIGHT && (renderpath!=R_FIXEDFUNCTION || hasTE) ? grayfog : zerofog);
}
if(flags&DF_OVERBRIGHT)
{
if(renderpath!=R_FIXEDFUNCTION)
{
glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
static Shader *overbrightdecalshader = NULL;
if(!overbrightdecalshader) overbrightdecalshader = lookupshaderbyname("overbrightdecal");
overbrightdecalshader->set();
}
else if(hasTE)
{
glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
setuptmu(0, "T , C @ Ca");
}
else glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA);
}
else
{
if(flags&DF_INVMOD) glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
else if(flags&DF_ADD) glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
else glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
foggedshader->set();
}
glBindTexture(GL_TEXTURE_2D, tex->id);
glVertexPointer(3, GL_FLOAT, sizeof(decalvert), &verts->pos);
glTexCoordPointer(2, GL_FLOAT, sizeof(decalvert), &verts->u);
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(decalvert), &verts->color);
int count = endvert < startvert ? maxverts - startvert : endvert - startvert;
glDrawArrays(GL_TRIANGLES, startvert, count);
if(endvert < startvert)
{
count += endvert;
glDrawArrays(GL_TRIANGLES, 0, endvert);
}
xtravertsva += count;
if(flags&(DF_ADD|DF_INVMOD|DF_OVERBRIGHT)) glFogfv(GL_FOG_COLOR, oldfogc);
if(flags&DF_OVERBRIGHT && hasTE) resettmu(0);
}
decalinfo &newdecal()
{
decalinfo &d = decals[enddecal];
int next = enddecal + 1;
if(next>=maxdecals) next = 0;
if(next==startdecal) freedecal();
enddecal = next;
return d;
}
static int decalclip(const vec *in, int numin, const plane &c, vec *out)
{
int numout = 0;
const vec *n = in;
float idist = c.dist(*n), ndist = idist;
loopi(numin-1)
{
const vec &p = *n;
float pdist = ndist;
ndist = c.dist(*++n);
if(pdist>=0) out[numout++] = p;
if((pdist>0 && ndist<0) || (pdist<0 && ndist>0))
(out[numout++] = *n).sub(p).mul(pdist / (pdist - ndist)).add(p);
}
if(ndist>=0) out[numout++] = *n;
if((ndist>0 && idist<0) || (ndist<0 && idist>0))
(out[numout++] = *in).sub(*n).mul(ndist / (ndist - idist)).add(*n);
return numout;
}
ivec bborigin, bbsize;
vec decalcenter, decalnormal, decaltangent, decalbitangent;
float decalradius, decalu, decalv;
bvec decalcolor;
void adddecal(const vec ¢er, const vec &dir, float radius, const bvec &color, int info)
{
int isz = int(ceil(radius));
bborigin = ivec(center).sub(isz);
bbsize = ivec(isz*2, isz*2, isz*2);
decalcolor = color;
decalcenter = center;
decalradius = radius;
decalnormal = dir;
#if 0
decaltangent.orthogonal(dir);
#else
decaltangent = vec(dir.z, -dir.x, dir.y);
decaltangent.sub(vec(dir).mul(decaltangent.dot(dir)));
#endif
if(flags&DF_ROTATE) decaltangent.rotate(rnd(360)*RAD, dir);
decaltangent.normalize();
decalbitangent.cross(decaltangent, dir);
if(flags&DF_RND4)
{
decalu = 0.5f*(info&1);
decalv = 0.5f*((info>>1)&1);
}
ushort dstart = endvert;
gendecaltris(worldroot, ivec(0, 0, 0), hdr.worldsize>>1);
if(dbgdec)
{
int nverts = endvert < dstart ? endvert + maxverts - dstart : endvert - dstart;
conoutf(CON_DEBUG, "tris = %d, verts = %d, total tris = %d", nverts/3, nverts, (maxverts - 3 - availverts)/3);
}
if(endvert==dstart) return;
decalinfo &d = newdecal();
d.color = color;
d.millis = lastmillis;
d.startvert = dstart;
d.endvert = endvert;
}
void gendecaltris(cube &cu, int orient, vec *v, bool solid)
{
int f[4], faces = 0;
loopk(4) f[k] = solid ? fv[orient][k] : faceverts(cu, orient, k);
vec p(v[f[0]]), surfaces[2];
if(solid)
{
surfaces[0] = vec(0, 0, 0);
surfaces[0][dimension(orient)] = 2*dimcoord(orient) - 1;
faces = 1 | 4;
}
else
{
vec e(v[f[2]]);
e.sub(p);
surfaces[0].cross(vec(v[f[1]]).sub(p), e);
float mag1 = surfaces[0].squaredlen();
if(mag1) { surfaces[0].div(sqrtf(mag1)); faces |= 1; }
surfaces[1].cross(e, vec(v[f[3]]).sub(p));
float mag2 = surfaces[1].squaredlen();
if(mag2)
{
surfaces[1].div(sqrtf(mag2));
faces |= (!faces || faceconvexity(cu, orient) ? 2 : 4);
}
}
p.sub(decalcenter);
loopl(2) if(faces&(1<<l))
{
const vec &n = surfaces[l];
float facing = n.dot(decalnormal);
if(facing<=0) continue;
#if 0
// intersect ray along decal normal with plane
float dist = n.dot(p) / facing;
if(fabs(dist) > decalradius) continue;
vec pcenter = vec(decalnormal).mul(dist).add(decalcenter);
#else
// travel back along plane normal from the decal center
float dist = n.dot(p);
if(fabs(dist) > decalradius) continue;
vec pcenter = vec(n).mul(dist).add(decalcenter);
#endif
vec ft, fb;
ft.orthogonal(n);
ft.normalize();
fb.cross(ft, n);
vec pt = vec(ft).mul(ft.dot(decaltangent)).add(vec(fb).mul(fb.dot(decaltangent))).normalize(),
pb = vec(ft).mul(ft.dot(decalbitangent)).add(vec(fb).mul(fb.dot(decalbitangent))).normalize();
// orthonormalize projected bitangent to prevent streaking
pb.sub(vec(pt).mul(pt.dot(pb))).normalize();
vec v1[8] = { v[f[0]], v[f[l+1]], v[f[l+2]] }, v2[8];
int numv = 3;
if(faces&4) { v1[3] = v[f[3]]; numv = 4; }
float ptc = pt.dot(pcenter), pbc = pb.dot(pcenter);
numv = decalclip(v1, numv, plane(pt, decalradius - ptc), v2);
if(numv<3) continue;
numv = decalclip(v2, numv, plane(vec(pt).neg(), decalradius + ptc), v1);
if(numv<3) continue;
numv = decalclip(v1, numv, plane(pb, decalradius - pbc), v2);
if(numv<3) continue;
numv = decalclip(v2, numv, plane(vec(pb).neg(), decalradius + pbc), v1);
if(numv<3) continue;
float tsz = flags&DF_RND4 ? 0.5f : 1.0f, scale = tsz*0.5f/decalradius,
tu = decalu + tsz*0.5f - ptc*scale, tv = decalv + tsz*0.5f - pbc*scale;
pt.mul(scale); pb.mul(scale);
decalvert dv1 = { v1[0], pt.dot(v1[0]) + tu, pb.dot(v1[0]) + tv, decalcolor, 255 },
dv2 = { v1[1], pt.dot(v1[1]) + tu, pb.dot(v1[1]) + tv, decalcolor, 255 };
int totalverts = 3*(numv-2);
if(totalverts > maxverts-3) return;
while(availverts < totalverts)
{
if(!freedecal()) return;
}
availverts -= totalverts;
loopk(numv-2)
{
verts[endvert++] = dv1;
verts[endvert++] = dv2;
dv2.pos = v1[k+2];
dv2.u = pt.dot(v1[k+2]) + tu;
dv2.v = pb.dot(v1[k+2]) + tv;
verts[endvert++] = dv2;
if(endvert>=maxverts) endvert = 0;
}
}
}
void gendecaltris(cube *cu, const ivec &o, int size, uchar *vismasks = NULL, uchar avoid = 0)
{
loopoctabox(o, size, bborigin, bbsize)
{
ivec co(i, o.x, o.y, o.z, size);
if(cu[i].children)
{
uchar visclip = cu[i].vismask & cu[i].clipmask & ~avoid;
if(visclip)
{
uchar vertused = fvmasks[visclip];
vec v[8];
loopj(8) if(vertused&(1<<j)) calcvert(cu[i], co.x, co.y, co.z, size, v[j], j, true);
loopj(6) if(visclip&(1<<j)) gendecaltris(cu[i], j, v, true);
}
if(cu[i].vismask & ~avoid) gendecaltris(cu[i].children, co, size>>1, cu[i].vismasks, avoid | visclip);
}
else if(vismasks)
{
uchar vismask = vismasks[i] & ~avoid;
if(!vismask) continue;
uchar vertused = fvmasks[vismask];
bool solid = cu[i].ext && isclipped(cu[i].ext->material&MATF_VOLUME);
vec v[8];
loopj(8) if(vertused&(1<<j)) calcvert(cu[i], co.x, co.y, co.z, size, v[j], j, solid);
loopj(6) if(vismask&(1<<j)) gendecaltris(cu[i], j, v, solid || (flataxisface(cu[i], j) && faceedges(cu[i], j)==F_SOLID));
}
else
{
bool solid = cu[i].ext && isclipped(cu[i].ext->material&MATF_VOLUME);
uchar vismask = 0;
loopj(6) if(!(avoid&(1<<j)) && (solid ? visiblematerial(cu[i], j, co.x, co.y, co.z, size)==MATSURF_VISIBLE : cu[i].texture[j]!=DEFAULT_SKY && visibleface(cu[i], j, co.x, co.y, co.z, size))) vismask |= 1<<j;
if(!vismask) continue;
uchar vertused = fvmasks[vismask];
vec v[8];
loopj(8) if(vertused&(1<<j)) calcvert(cu[i], co.x, co.y, co.z, size, v[j], j, solid);
loopj(6) if(vismask&(1<<j)) gendecaltris(cu[i], j, v, solid || (flataxisface(cu[i], j) && faceedges(cu[i], j)==F_SOLID));
}
}
}
};
decalrenderer decals[] =
{
decalrenderer("packages/particles/scorch.png", DF_ROTATE, 500),
decalrenderer("packages/particles/blood.png", DF_RND4|DF_ROTATE|DF_INVMOD),
decalrenderer("<decal>packages/particles/bullet.png", DF_OVERBRIGHT)
};
void initdecals()
{
loopi(sizeof(decals)/sizeof(decals[0])) decals[i].init(maxdecaltris);
}
void cleardecals()
{
loopi(sizeof(decals)/sizeof(decals[0])) decals[i].cleardecals();
}
VARNP(decals, showdecals, 0, 1, 1);
void renderdecals(int time)
{
bool rendered = false;
loopi(sizeof(decals)/sizeof(decals[0]))
{
decalrenderer &d = decals[i];
if(time)
{
d.clearfadeddecals();
d.fadeindecals();
d.fadeoutdecals();
}
if(!showdecals || !d.hasdecals()) continue;
if(!rendered)
{
rendered = true;
decalrenderer::setuprenderstate();
}
d.render();
}
if(!rendered) return;
decalrenderer::cleanuprenderstate();
}
VARP(maxdecaldistance, 1, 512, 10000);
void adddecal(int type, const vec ¢er, const vec &surface, float radius, const bvec &color, int info)
{
if(!showdecals || type<0 || (size_t)type>=sizeof(decals)/sizeof(decals[0]) || center.dist(camera1->o) - radius > maxdecaldistance) return;
decalrenderer &d = decals[type];
d.adddecal(center, surface, radius, color, info);
}
| [
"bill@sheba.(none)"
] | [
[
[
1,
541
]
]
] |
20d062509c30876de2a041115feb002cd3b06854 | 9a5db9951432056bb5cd4cf3c32362a4e17008b7 | /FacesCapture/branches/ShangHai/Damany.Library/CameraWrappers/AssemblyInfo.cpp | 52b2204f03bb959918f06857294ef2ef6bda5631 | [] | no_license | miaozhendaoren/appcollection | 65b0ede264e74e60b68ca74cf70fb24222543278 | f8b85af93f787fa897af90e8361569a36ff65d35 | refs/heads/master | 2021-05-30T19:27:21.142158 | 2011-06-27T03:49:22 | 2011-06-27T03:49:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,356 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("CameraWrappers")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("Damany")];
[assembly:AssemblyProductAttribute("CameraWrappers")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) Damany 2010")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"shenbinsc@cbf8b9f2-3a65-11de-be05-5f7a86268029"
] | [
[
[
1,
40
]
]
] |
17f1df1cbe7b73d9c91898f5135d4f9e5c213a5a | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/chromium/src/EditorClientImpl.h | 7ab4761ff9d4d2128bccbf393be3aaa25701b361 | [
"BSD-2-Clause"
] | permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,167 | h | /*
* Copyright (C) 2009 Google Inc. 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 Google Inc. 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
* 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.
*/
#ifndef EditorClientImpl_h
#define EditorClientImpl_h
#include "EditorClient.h"
#include "Timer.h"
#include <wtf/Deque.h>
namespace WebCore {
class HTMLInputElement;
}
namespace WebKit {
class WebViewImpl;
class EditorClientImpl : public WebCore::EditorClient {
public:
EditorClientImpl(WebViewImpl* webView);
virtual ~EditorClientImpl();
virtual void pageDestroyed();
virtual bool shouldShowDeleteInterface(WebCore::HTMLElement*);
virtual bool smartInsertDeleteEnabled();
virtual bool isSelectTrailingWhitespaceEnabled();
virtual bool isContinuousSpellCheckingEnabled();
virtual void toggleContinuousSpellChecking();
virtual bool isGrammarCheckingEnabled();
virtual void toggleGrammarChecking();
virtual int spellCheckerDocumentTag();
virtual bool isEditable();
virtual bool shouldBeginEditing(WebCore::Range*);
virtual bool shouldEndEditing(WebCore::Range*);
virtual bool shouldInsertNode(WebCore::Node*, WebCore::Range*, WebCore::EditorInsertAction);
virtual bool shouldInsertText(const WTF::String&, WebCore::Range*, WebCore::EditorInsertAction);
virtual bool shouldDeleteRange(WebCore::Range*);
virtual bool shouldChangeSelectedRange(WebCore::Range* fromRange,
WebCore::Range* toRange,
WebCore::EAffinity,
bool stillSelecting);
virtual bool shouldApplyStyle(WebCore::CSSStyleDeclaration*, WebCore::Range*);
virtual bool shouldMoveRangeAfterDelete(WebCore::Range*, WebCore::Range*);
virtual void didBeginEditing();
virtual void respondToChangedContents();
virtual void respondToChangedSelection();
virtual void didEndEditing();
virtual void didWriteSelectionToPasteboard();
virtual void didSetSelectionTypesForPasteboard();
virtual void registerCommandForUndo(PassRefPtr<WebCore::EditCommand>);
virtual void registerCommandForRedo(PassRefPtr<WebCore::EditCommand>);
virtual void clearUndoRedoOperations();
virtual bool canUndo() const;
virtual bool canRedo() const;
virtual void undo();
virtual void redo();
virtual const char* interpretKeyEvent(const WebCore::KeyboardEvent*);
virtual bool handleEditingKeyboardEvent(WebCore::KeyboardEvent*);
virtual void handleKeyboardEvent(WebCore::KeyboardEvent*);
virtual void handleInputMethodKeydown(WebCore::KeyboardEvent*);
virtual void textFieldDidBeginEditing(WebCore::Element*);
virtual void textFieldDidEndEditing(WebCore::Element*);
virtual void textDidChangeInTextField(WebCore::Element*);
virtual bool doTextFieldCommandFromEvent(WebCore::Element*, WebCore::KeyboardEvent*);
virtual void textWillBeDeletedInTextField(WebCore::Element*);
virtual void textDidChangeInTextArea(WebCore::Element*);
virtual void ignoreWordInSpellDocument(const WTF::String&);
virtual void learnWord(const WTF::String&);
virtual void checkSpellingOfString(const UChar*, int length,
int* misspellingLocation,
int* misspellingLength);
virtual void checkGrammarOfString(const UChar*, int length,
WTF::Vector<WebCore::GrammarDetail>&,
int* badGrammarLocation,
int* badGrammarLength);
virtual WTF::String getAutoCorrectSuggestionForMisspelledWord(const WTF::String&);
virtual void updateSpellingUIWithGrammarString(const WTF::String&, const WebCore::GrammarDetail&);
virtual void updateSpellingUIWithMisspelledWord(const WTF::String&);
virtual void showSpellingUI(bool show);
virtual bool spellingUIIsShowing();
virtual void getGuessesForWord(const WTF::String& word,
WTF::Vector<WTF::String>& guesses);
virtual void willSetInputMethodState();
virtual void setInputMethodState(bool enabled);
// Shows the form autofill popup for |node| if it is an HTMLInputElement and
// it is empty. This is called when you press the up or down arrow in a
// text-field or when clicking an already focused text-field.
// Returns true if the autofill popup has been scheduled to be shown, false
// otherwise.
virtual bool showFormAutofillForNode(WebCore::Node*);
// Notification that the text changed due to acceptance of a suggestion
// provided by an Autocomplete popup. Having a separate callback in this
// case is a simple way to break the cycle that would otherwise occur if
// textDidChangeInTextField was called.
virtual void onAutocompleteSuggestionAccepted(WebCore::HTMLInputElement*);
private:
void modifySelection(WebCore::Frame*, WebCore::KeyboardEvent*);
// Triggers autofill for an input element if applicable. This can be form
// autofill (via a popup-menu) or password autofill depending on the
// input element. If |formAutofillOnly| is true, password autofill is not
// triggered.
// |autofillOnEmptyValue| indicates whether the autofill should be shown
// when the text-field is empty.
// If |requiresCaretAtEnd| is true, the autofill popup is only shown if the
// caret is located at the end of the entered text.
// Returns true if the autofill popup has been scheduled to be shown, false
// otherwise.
bool autofill(WebCore::HTMLInputElement*,
bool formAutofillOnly, bool autofillOnEmptyValue,
bool requiresCaretAtEnd);
// Called to process the autofill described by m_autofillArgs.
// This method is invoked asynchronously if the caret position is not
// reflecting the last text change yet, and we need it to decide whether or
// not to show the autofill popup.
void doAutofill(WebCore::Timer<EditorClientImpl>*);
void cancelPendingAutofill();
// Returns whether or not the focused control needs spell-checking.
// Currently, this function just retrieves the focused node and determines
// whether or not it is a <textarea> element or an element whose
// contenteditable attribute is true.
// FIXME: Bug 740540: This code just implements the default behavior
// proposed in this issue. We should also retrieve "spellcheck" attributes
// for text fields and create a flag to over-write the default behavior.
bool shouldSpellcheckByDefault();
WebViewImpl* m_webView;
bool m_inRedo;
typedef Deque<RefPtr<WebCore::EditCommand> > EditCommandStack;
EditCommandStack m_undoStack;
EditCommandStack m_redoStack;
// Whether the last entered key was a backspace.
bool m_backspaceOrDeletePressed;
// This flag is set to false if spell check for this editor is manually
// turned off. The default setting is SpellCheckAutomatic.
enum {
SpellCheckAutomatic,
SpellCheckForcedOn,
SpellCheckForcedOff
};
int m_spellCheckThisFieldStatus;
// Used to delay autofill processing.
WebCore::Timer<EditorClientImpl> m_autofillTimer;
struct AutofillArgs {
RefPtr<WebCore::HTMLInputElement> inputElement;
bool autofillFormOnly;
bool autofillOnEmptyValue;
bool requireCaretAtEnd;
bool backspaceOrDeletePressed;
};
OwnPtr<AutofillArgs> m_autofillArgs;
};
} // namespace WebKit
#endif
| [
"[email protected]"
] | [
[
[
1,
196
]
]
] |
b1858afb0bef39795096e25345a5d6a2242ff382 | 14447604061a3ded605cd609b44fec3979d9b1cc | /Cacoon/MainFrm.h | b1edba4653b2d89c84b8204f7494102786853928 | [] | no_license | sinsoku/cacoon | 459e441aacf4dc01311a6b5cd7eae2425fbf4c3f | 36e81b689b53505c2d8117ff60ce8e4012d6eae6 | refs/heads/master | 2020-05-30T23:34:08.361671 | 2010-12-03T17:44:20 | 2010-12-03T17:44:20 | 809,470 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,562 | h |
// MainFrm.h : MainFrame クラスのインターフェイス
//
#pragma once
class MainFrame : public CFrameWndEx
{
private:
CMenu m_TaskTrayMenu;
NOTIFYICONDATA m_stNtfyIcon;
protected: // シリアル化からのみ作成します。
MainFrame();
DECLARE_DYNCREATE(MainFrame)
// 属性
public:
// 操作
public:
// オーバーライド
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual BOOL LoadFrame(UINT nIDResource, DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, CWnd* pParentWnd = NULL, CCreateContext* pContext = NULL);
// 実装
public:
virtual ~MainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // コントロール バー用メンバー
CMFCMenuBar m_wndMenuBar;
CMFCToolBar m_wndToolBar;
CMFCStatusBar m_wndStatusBar;
CMFCToolBarImages m_UserImages;
// 生成された、メッセージ割り当て関数
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnViewCustomize();
afx_msg LRESULT OnToolbarCreateNew(WPARAM wp, LPARAM lp);
afx_msg void OnApplicationLook(UINT id);
afx_msg void OnUpdateApplicationLook(CCmdUI* pCmdUI);
afx_msg void OnWindowPosChanging(WINDOWPOS * lpwndpos);
afx_msg void OnCommandMenu_1();
afx_msg void OnCommandMenu_2();
afx_msg void OnCommandMenu_3();
DECLARE_MESSAGE_MAP()
public:
void OnDestroy(void);
virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
};
| [
"[email protected]"
] | [
[
[
1,
60
]
]
] |
23c3a0198585b57cb05244aa0018f839e80b3e7d | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/BaseRefVectorOf.hpp | 43fa91cf044d602cb75faa0bcc53cd1101fc5ae0 | [] | 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 | 5,770 | hpp | /*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(ABSTRACTVECTOROF_HPP)
#define ABSTRACTVECTOROF_HPP
#include <xercesc/util/ArrayIndexOutOfBoundsException.hpp>
#include <xercesc/util/XMLEnumerator.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/framework/MemoryManager.hpp>
XERCES_CPP_NAMESPACE_BEGIN
/**
* Abstract base class for the xerces internal representation of Vector.
*
* The destructor is abstract, forcing each of RefVectorOf and
* RefArrayVectorOf to implement their own appropriate one.
*
*/
template <class TElem> class BaseRefVectorOf : public XMemory
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
BaseRefVectorOf
(
const unsigned int maxElems
, const bool adoptElems = true
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
virtual ~BaseRefVectorOf();
// -----------------------------------------------------------------------
// Element management
// -----------------------------------------------------------------------
void addElement(TElem* const toAdd);
virtual void setElementAt(TElem* const toSet, const unsigned int setAt);
void insertElementAt(TElem* const toInsert, const unsigned int insertAt);
TElem* orphanElementAt(const unsigned int orphanAt);
virtual void removeAllElements();
virtual void removeElementAt(const unsigned int removeAt);
virtual void removeLastElement();
bool containsElement(const TElem* const toCheck);
virtual void cleanup();
void reinitialize();
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
unsigned int curCapacity() const;
const TElem* elementAt(const unsigned int getAt) const;
TElem* elementAt(const unsigned int getAt);
unsigned int size() const;
MemoryManager* getMemoryManager() const;
// -----------------------------------------------------------------------
// Miscellaneous
// -----------------------------------------------------------------------
void ensureExtraCapacity(const unsigned int length);
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
BaseRefVectorOf(const BaseRefVectorOf<TElem>& copy);
BaseRefVectorOf& operator=(const BaseRefVectorOf<TElem>& copy);
protected:
// -----------------------------------------------------------------------
// Data members
// -----------------------------------------------------------------------
bool fAdoptedElems;
unsigned int fCurCount;
unsigned int fMaxCount;
TElem** fElemList;
MemoryManager* fMemoryManager;
};
//
// An enumerator for a vector. It derives from the basic enumerator
// class, so that value vectors can be generically enumerated.
//
template <class TElem> class BaseRefVectorEnumerator : public XMLEnumerator<TElem>, public XMemory
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
BaseRefVectorEnumerator
(
BaseRefVectorOf<TElem>* const toEnum
, const bool adopt = false
);
virtual ~BaseRefVectorEnumerator();
BaseRefVectorEnumerator(const BaseRefVectorEnumerator<TElem>& copy);
// -----------------------------------------------------------------------
// Enum interface
// -----------------------------------------------------------------------
bool hasMoreElements() const;
TElem& nextElement();
void Reset();
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
BaseRefVectorEnumerator& operator=(const BaseRefVectorEnumerator<TElem>& copy);
// -----------------------------------------------------------------------
// Data Members
//
// fAdopted
// Indicates whether we have adopted the passed vector. If so then
// we delete the vector when we are destroyed.
//
// fCurIndex
// This is the current index into the vector.
//
// fToEnum
// The reference vector being enumerated.
// -----------------------------------------------------------------------
bool fAdopted;
unsigned int fCurIndex;
BaseRefVectorOf<TElem>* fToEnum;
};
XERCES_CPP_NAMESPACE_END
#if !defined(XERCES_TMPLSINC)
#include <xercesc/util/BaseRefVectorOf.c>
#endif
#endif
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
152
]
]
] |
c102e0f32cf62744a312848d14b4b7d4d48b4f03 | 9fb229975cc6bd01eb38c3e96849d0c36985fa1e | /Tools/Unify/UnifyWriter.cpp | 9f2a39be31fff4611f5353ef5af62ad33d6ef7f7 | [] | no_license | Danewalker/ahr | 3758bf3219f407ed813c2bbed5d1d86291b9237d | 2af9fd5a866c98ef1f95f4d1c3d9b192fee785a6 | refs/heads/master | 2016-09-13T08:03:43.040624 | 2010-07-21T15:44:41 | 2010-07-21T15:44:41 | 56,323,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,916 | cpp | #pragma warning(disable:4786)
#include "unify.h"
#include "unifywriter.h"
#include "util.h"
#ifdef WIN32
#include "windows.h"
#endif
namespace Unify {
void CUnifyWriter::Write(const char * filename, Unify::CNode* root, bool brief){
m_Brief=brief;
m_Tab=0;
m_File.open(filename,std::ios::out);
if( (m_File.rdstate() & std::ios::failbit ) != 0 ){
MessageBox(0,"Can't open file for writing.\nMake sure it is not read-only.\n","Alice error",MB_OK);
}else{
WriteNode(root);
m_File.close();
}
}
void CUnifyWriter::WriteNode(Unify::CNode* node){
bool compact=false;
bool empty=false;
std::string tab (m_Tab,'\t');
/*if(node->GetChildCount()==0 && node->GetParameterCount()<=4)compact=true;
if(node->GetParameterCount()==0)compact=false;*/
// If node is a block, compact it
Unify::CParameter * param;
param=node->GetParameter("class");
if(param){
if(param->GetString()=="block"){
compact=true;
if( node->GetParameter("type")->GetString()=="empty"
&& node->GetParameter("flags")->GetString()=="" )
{
empty=true;
}
}
}
if(!m_Brief)empty=false;
if(node&&!empty){
m_File << std::endl<<tab << "(";
param=node->GetParameter("class");
if(param){
WriteParameter("class",param);
}
param=node->GetParameter("name");
if(param){
WriteParameter("name",param);
}
Unify::CNode::ParameterIterator it=node->ParameterBegin();
for(int i=0;i<node->GetParameterCount();i++){
if((*it).first!="class" && (*it).first !="name"){
if(!compact)
m_File << std::endl;
if(!compact)
m_File << tab ;
WriteParameter((*it).first,((*it).second));
}
it++;
}
for(i=0;i<node->GetChildCount();i++){
m_Tab++;
WriteNode(node->GetChild(i));
m_Tab--;
}
if(!compact){
m_File << std::endl << tab << ")";
}else{
m_File << ")";
}
}
}
void CUnifyWriter::WriteParameter(const std::string& name, Unify::CParameter* param) {
if(param){
WriteToken(name.c_str());
m_File << " ";
bool first=true;
for(int i=0;i<param->GetValueCount();i++){
if(first){
first=false;
}else{
m_File<<",";
}
WriteToken(param->GetValue(i)->GetString());
}
m_File << " ";
}
}
void CUnifyWriter::WriteToken(const std::string& str2 ){
bool quote=false;
std::string str=str2;
EscapeString(str);
if(str.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.+-")!=std::string::npos)
quote=true;
if(str=="")
quote=true;
if(quote)
m_File << "\"" ;
//!PATCH (Need to escape quotes)
m_File << str ;
if(quote)
m_File << "\"" ;
}
void CUnifyWriter::EscapeString(std::string& str){
Util::Replace(str,"\\","\\\\");
Util::Replace(str,"\r\n","\\n");
Util::Replace(str,"\t","\\t");
Util::Replace(str,"\"","\\\"");
}
} | [
"jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae"
] | [
[
[
1,
144
]
]
] |
7b3a11b130cda3b4ebe4928aa7f04d2e22c34094 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Applications/Miscellaneous/DrawImplicitSurface/RayTracer.inl | c797b430d5664358fcf10f54688911265c4b0dcd | [] | no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,107 | inl | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
//----------------------------------------------------------------------------
inline Vector3f& RayTracer::Location ()
{
return m_kLocation;
}
//----------------------------------------------------------------------------
inline Vector3f& RayTracer::Direction ()
{
return m_kDirection;
}
//----------------------------------------------------------------------------
inline Vector3f& RayTracer::Up ()
{
return m_kUp;
}
//----------------------------------------------------------------------------
inline Vector3f& RayTracer::Right ()
{
return m_kRight;
}
//----------------------------------------------------------------------------
inline float& RayTracer::Near ()
{
return m_fNear;
}
//----------------------------------------------------------------------------
inline float& RayTracer::Far ()
{
return m_fFar;
}
//----------------------------------------------------------------------------
inline float& RayTracer::HalfWidth ()
{
return m_fHalfWidth;
}
//----------------------------------------------------------------------------
inline float& RayTracer::HalfHeight ()
{
return m_fHalfHeight;
}
//----------------------------------------------------------------------------
inline int RayTracer::GetWidth () const
{
return m_iWidth;
}
//----------------------------------------------------------------------------
inline int RayTracer::GetHeight () const
{
return m_iHeight;
}
//----------------------------------------------------------------------------
inline const float* RayTracer::GetImage () const
{
return m_afImage;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
a8bfd8d6fd9884216c99b383d46e2e3dc7184ed2 | cd69369374074a7b4c4f42e970ee95847558e9f0 | /Nova Versao, em Visual Studio 2010/Consulta.h | f275d42ad100477090d9708c132973a611e50bb8 | [] | no_license | miaosun/aeda-trab1 | 4e6b8ce3de8bb7e85e13670595012a5977258a2a | 1ec5e2edec383572c452545ed52e45fb26df6097 | refs/heads/master | 2021-01-25T03:40:21.146657 | 2010-12-25T03:35:28 | 2010-12-25T03:35:28 | 33,734,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | h | ///////////////////////////////////////////////////////////
// Consulta.h
// Implementation of the Class Consulta
// Created on: 24-Out-2010 20:04:07
// Original author: Answer
///////////////////////////////////////////////////////////
#if !defined(EA_58523BA4_83E1_4418_9232_D55F12BD24FC__INCLUDED_)
#define EA_58523BA4_83E1_4418_9232_D55F12BD24FC__INCLUDED_
#include "Marcacao.h"
class Consulta : public Marcacao
{
public:
Consulta();
virtual ~Consulta();
Consulta(string data, string hora, string tipo);
string toString();
vector<string> imprime();
vector<string> editMarcacao();
/////////////////////////////
//
void setSala(string sala);
};
#endif // !defined(EA_58523BA4_83E1_4418_9232_D55F12BD24FC__INCLUDED_)
| [
"miaosun88@9ca0f86a-2074-76d8-43a5-19cf18205b40"
] | [
[
[
1,
30
]
]
] |
cb1a3c2ab83785d8d9c76ba034032534ee4adca7 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /Sockets/Lock.h | 66e95abeadf5885db421c608b6a29a5f3dace6ec | [] | 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 | 1,715 | h | /** \file Lock.h
** \date 2005-08-22
** \author [email protected]
**/
/*
Copyright (C) 2005-2009 Anders Hedstrom
This library is made available under the terms of the GNU GPL, with
the additional exemption that compiling, linking, and/or using OpenSSL
is allowed.
If you would like to use this library in a closed-source application,
a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
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.
*/
#ifndef _SOCKETS_Lock_H
#define _SOCKETS_Lock_H
#include "sockets-config.h"
#ifdef SOCKETS_NAMESPACE
namespace SOCKETS_NAMESPACE {
#endif
class IMutex;
/** IMutex encapsulation class.
\ingroup threading */
class Lock
{
public:
Lock(const IMutex&);
~Lock();
private:
const IMutex& m_mutex;
};
//#define LOCK(refIMutex) Lock _lock(refIMutex);
#ifdef SOCKETS_NAMESPACE
}
#endif
#endif // _SOCKETS_Lock_H
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
] | [
[
[
1,
61
]
]
] |
2efe8ebb3a9e6f1875545cbc4e3e931a4a89bc63 | 4813a54584f8e8a8a2d541291a08b244640a7f77 | /libxl/include/fs.h | 54e7a55d6c98b4c34b88e669ae815cea1989dbe7 | [] | no_license | cyberscorpio/libxl | fcc0c67390dd8eae4bb7d36f6a459ffed368183a | 8d27566f45234af214a7a1e19c455e9721073e8c | refs/heads/master | 2021-01-19T16:56:51.990977 | 2010-06-30T08:18:41 | 2010-06-30T08:18:41 | 38,444,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,401 | h | /**
* @brief wrapper for file system relative calls
*/
#ifndef XL_FS_H
#define XL_FS_H
#include "common.h"
#include "string.h"
#include "interfaces.h"
XL_BEGIN
bool file_existsA (const string &filename);
bool file_existsW (const wstring &filename);
inline bool file_exists (const tstring &filename) {
#ifdef UNICODE
return file_existsW(filename);
#else
return file_existsA(filename);
#endif
}
string file_get_absolute_nameA (const string &filename);
wstring file_get_absolute_nameW (const wstring &filename);
inline tstring file_get_absolute_name (const tstring &filename) {
#ifdef UNICODE
return file_get_absolute_nameW(filename);
#else
return file_get_absolute_nameA(filename);
#endif
}
__int64 file_get_length (FILE *);
__int64 file_get_lengthA (const string &filename);
__int64 file_get_lengthW (const wstring &filename);
inline __int64 file_get_length (const tstring &filename) {
#ifdef UNICODE
return file_get_lengthW(filename);
#else
return file_get_lengthA(filename);
#endif
}
string file_get_directoryA (const string &filename, bool mustExist = false);
wstring file_get_directoryW (const wstring &filename, bool mustExist = false);
/**
* return the director contains the file, not include the last '\\'.
* for example, if pass c:\windows\system32\drivers\etc\hosts, it will return
* c:\windows\system32\drivers\etc
*/
inline tstring file_get_directory (const tstring &filename, bool mustExist = false) {
#ifdef UNICODE
return file_get_directoryW(filename, mustExist);
#else
return file_get_directoryA(filename, mustExist);
#endif
}
string file_get_nameA (const string &filename, bool mustExist = false);
wstring file_get_nameW (const wstring &filename, bool mustExist = false);
inline tstring file_get_name (const tstring &filename, bool mustExist = false) {
#ifdef UNICODE
return file_get_nameW(filename, mustExist);
#else
return file_get_nameA(filename, mustExist);
#endif
}
//////////////////////////////////////////////////////////////////////////
// file_put_contents and file_get_contents are borrowed from PHP, they are very handy functions.
/**
* @brief write the total std::string into the file.
* @return the count of bytes written. -1 indicate an error.
*/
int file_put_contentsA (const string &filename, const std::string &data);
int file_put_contentsW (const wstring &filename, const std::string &data);
inline int file_put_contents (const tstring &filename, const std::string &data) {
#ifdef UNICODE
return file_put_contentsW(filename, data);
#else
return file_put_contentsA(filename, data);
#endif
}
/**
* @brief read the total file contents into a std::string.
* @param offset if set offset, read the file content from offset.
* @note don't get content of a very large file.
*/
bool file_get_contentsA (const string &filename, std::string &data, size_t offset = 0, ILongTimeRunCallback *callback = NULL);
bool file_get_contentsW (const wstring &filename, std::string &data, size_t offset = 0, ILongTimeRunCallback *callback = NULL);
inline bool file_get_contents (const tstring &filename, std::string &data, size_t offset = 0, ILongTimeRunCallback *callback = NULL) {
#ifdef UNICODE
return file_get_contentsW(filename, data, offset, callback);
#else
return file_get_contentsA(filename, data, offset, callback);
#endif
}
XL_END
#endif
| [
"[email protected]",
"doudehou@59b6eb50-eb15-11de-b362-3513cf04e977"
] | [
[
[
1,
7
],
[
9,
11
],
[
21,
31
],
[
43,
67
],
[
70,
73
],
[
83,
88
],
[
98,
103
]
],
[
[
8,
8
],
[
12,
20
],
[
32,
42
],
[
68,
69
],
[
74,
82
],
[
89,
97
]
]
] |
59ec71b2dcc274f5497365be2b0d6206987945d4 | 347fdd4d3b75c3ab0ecca61cf3671d2e6888e0d1 | /addons/vaOpenal/include/vaOpenal/Sound.h | 3d6fff331151d4e2f7c7ce0e1871221391786280 | [] | no_license | sanyaade/VirtualAwesome | 29688648aa3f191cdd756c826b5c84f6f841b93f | 05f3db98500366be1e79da16f5e353e366aed01f | refs/heads/master | 2020-12-01T03:03:51.561884 | 2010-11-08T00:17:44 | 2010-11-08T00:17:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,642 | h | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2009 Laurent Gomila ([email protected])
//
// 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.
//
////////////////////////////////////////////////////////////
#ifndef VAOPENAL_SOUND
#define VAOPENAL_SOUND
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <osg/Vec3>
#include <vaOpenal/Resource.h>
#include <vaOpenal/AudioResource.h>
#include <cstdlib>
namespace vaOpenal {
class SoundBuffer;
////////////////////////////////////////////////////////////
/// Sound defines the properties of a sound such as position,
/// volume, pitch, etc.
////////////////////////////////////////////////////////////
class Sound : public AudioResource
{
public :
////////////////////////////////////////////////////////////
/// Enumeration of the sound states
////////////////////////////////////////////////////////////
enum SoundStatus
{
Stopped, ///< Sound is not playing
Paused, ///< Sound is paused
Playing ///< Sound is playing
};
////////////////////////////////////////////////////////////
/// Default constructor
///
////////////////////////////////////////////////////////////
Sound();
////////////////////////////////////////////////////////////
/// Construct the sound from its parameters
///
/// \param Buffer : Sound buffer to play (NULL by default)
/// \param Loop : Loop flag (false by default)
/// \param Pitch : Value of the pitch (1 by default)
/// \param Volume : Volume (100 by default)
/// \param Position : Position (0, 0, 0 by default)
///
////////////////////////////////////////////////////////////
Sound(const SoundBuffer& Buffer, bool Loop = false, float Pitch = 1.f, float Volume = 100.f, const osg::Vec3f& Position = osg::Vec3f(0, 0, 0));
////////////////////////////////////////////////////////////
/// Copy constructor
///
/// \param Copy : Instance to copy
///
////////////////////////////////////////////////////////////
Sound(const Sound& Copy);
////////////////////////////////////////////////////////////
/// Destructor
///
////////////////////////////////////////////////////////////
~Sound();
////////////////////////////////////////////////////////////
/// Play the sound
///
////////////////////////////////////////////////////////////
void Play();
////////////////////////////////////////////////////////////
/// Pause the sound
///
////////////////////////////////////////////////////////////
void Pause();
////////////////////////////////////////////////////////////
/// Stop the sound
///
////////////////////////////////////////////////////////////
void Stop();
////////////////////////////////////////////////////////////
/// Set the source buffer
///
/// \param Buffer : New sound buffer to bind to the sound
///
////////////////////////////////////////////////////////////
void SetBuffer(const SoundBuffer& Buffer);
////////////////////////////////////////////////////////////
/// Set the sound loop state.
/// This parameter is disabled by default
///
/// \param Loop : True to play in loop, false to play once
///
////////////////////////////////////////////////////////////
void SetLoop(bool Loop);
////////////////////////////////////////////////////////////
/// Set the sound pitch.
/// The default pitch is 1
///
/// \param Pitch : New pitch
///
////////////////////////////////////////////////////////////
void SetPitch(float Pitch);
////////////////////////////////////////////////////////////
/// Set the sound volume.
/// The default volume is 100
///
/// \param Volume : Volume (in range [0, 100])
///
////////////////////////////////////////////////////////////
void SetVolume(float Volume);
////////////////////////////////////////////////////////////
/// Set the sound position (take 3 values).
/// The default position is (0, 0, 0)
///
/// \param X, Y, Z : Position of the sound in the world
///
////////////////////////////////////////////////////////////
void SetPosition(float X, float Y, float Z);
////////////////////////////////////////////////////////////
/// Set the sound position (take a 3D vector).
/// The default position is (0, 0, 0)
///
/// \param Position : Position of the sound in the world
///
////////////////////////////////////////////////////////////
void SetPosition(const osg::Vec3f& Position);
////////////////////////////////////////////////////////////
/// Make the sound's position relative to the listener's
/// position, or absolute.
/// The default value is false (absolute)
///
/// \param Relative : True to set the position relative, false to set it absolute
///
////////////////////////////////////////////////////////////
void SetRelativeToListener(bool Relative);
////////////////////////////////////////////////////////////
/// Set the minimum distance - closer than this distance,
/// the listener will hear the sound at its maximum volume.
/// The default minimum distance is 1.0
///
/// \param MinDistance : New minimum distance for the sound
///
////////////////////////////////////////////////////////////
void SetMinDistance(float MinDistance);
////////////////////////////////////////////////////////////
/// Set the attenuation factor - the higher the attenuation, the
/// more the sound will be attenuated with distance from listener.
/// The default attenuation factor 1.0
///
/// \param Attenuation : New attenuation factor for the sound
///
////////////////////////////////////////////////////////////
void SetAttenuation(float Attenuation);
////////////////////////////////////////////////////////////
/// Set the current playing position of the sound
///
/// \param TimeOffset : New playing position, expressed in seconds
///
////////////////////////////////////////////////////////////
void SetPlayingOffset(float TimeOffset);
////////////////////////////////////////////////////////////
/// Get the source buffer
///
/// \return Sound buffer bound to the sound (can be NULL)
///
////////////////////////////////////////////////////////////
const SoundBuffer* GetBuffer() const;
////////////////////////////////////////////////////////////
/// Tell whether or not the sound is looping
///
/// \return True if the sound is looping, false otherwise
///
////////////////////////////////////////////////////////////
bool GetLoop() const;
////////////////////////////////////////////////////////////
/// Get the pitch
///
/// \return Pitch value
///
////////////////////////////////////////////////////////////
float GetPitch() const;
////////////////////////////////////////////////////////////
/// Get the volume
///
/// \return Volume value (in range [1, 100])
///
////////////////////////////////////////////////////////////
float GetVolume() const;
////////////////////////////////////////////////////////////
/// Get the sound position
///
/// \return Position of the sound in the world
///
////////////////////////////////////////////////////////////
osg::Vec3f GetPosition() const;
////////////////////////////////////////////////////////////
/// Tell if the sound's position is relative to the listener's
/// position, or if it's absolute
///
/// \return True if the position is relative, false if it's absolute
///
////////////////////////////////////////////////////////////
bool IsRelativeToListener() const;
////////////////////////////////////////////////////////////
/// Get the minimum distance
///
/// \return Minimum distance for the sound
///
////////////////////////////////////////////////////////////
float GetMinDistance() const;
////////////////////////////////////////////////////////////
/// Get the attenuation factor
///
/// \return Attenuation factor of the sound
///
////////////////////////////////////////////////////////////
float GetAttenuation() const;
////////////////////////////////////////////////////////////
/// Get the status of the sound (stopped, paused, playing)
///
/// \return Current status of the sound
///
////////////////////////////////////////////////////////////
SoundStatus GetStatus() const;
////////////////////////////////////////////////////////////
/// Get the current playing position of the sound
///
/// \return Current playing position, expressed in seconds
///
////////////////////////////////////////////////////////////
float GetPlayingOffset() const;
////////////////////////////////////////////////////////////
/// Assign the sound to an Effect Slot
///
/// \param uiSlotID : ID of the aux. effect slot to be used
///
////////////////////////////////////////////////////////////
void AssignEffect(unsigned int uiEffectSlot, unsigned int uiSlotID);
////////////////////////////////////////////////////////////
/// Remove the sound from an Effect Slot
///
/// \param uiSlotID : ID of the aux. effect slot to be removed from
///
////////////////////////////////////////////////////////////
void RemoveEffect(unsigned int uiSlotID);
////////////////////////////////////////////////////////////
/// Assignment operator
///
/// \param Other : Instance to assign
///
/// \return Reference to the sound
///
////////////////////////////////////////////////////////////
Sound& operator =(const Sound& Other);
private :
friend class SoundStream;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
unsigned int mySource; ///< OpenAL source identifier
ResourcePtr<SoundBuffer> myBuffer; ///< Sound buffer bound to the source
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
319
]
]
] |
43f552b717c9280c76e35cb805bcb9929d57722e | 63df4630a247625d202fa4a0df2e564b79ce7066 | /iv_util.h | 47eff8c5b88e249f097cafb3ffce56a37e39d711 | [] | no_license | ivan4869/nsbdump | 59e809486ef643c2a2aedff09904da0fd031de8b | cb680afb570deba49b3091bd56f44f1b6bf7d2f0 | refs/heads/master | 2021-01-10T10:24:33.206817 | 2011-04-25T13:04:29 | 2011-04-25T13:04:29 | 36,677,554 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,624 | h | #ifndef IV_UTIL_H_
#define IV_UTIL_H_
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <utility>
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <direct.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>
#include <errno.h>
#include <share.h>
using std::pair;
using std::make_pair;
using std::string;
using std::vector;
using std::map;
using std::set;
using std::cerr;
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
namespace iv{
inline void errexit(const string msg)
{
cerr << msg << endl;
exit (-1);
return;
}
inline void todo(const string msg)
{
cerr << msg << endl;
return ;
}
int open_or_exit(const string fname, int flag, int pmod=_S_IREAD);
void make_path(string filename, const char *drive=NULL, const char *dir=NULL, const char *ext=NULL);
int write_file(string filename, const unsigned char *buff, unsigned len);
int writetail(int fd, const void *buff, unsigned count);
long long writef2f(int fd_dest, int fd_src);
long long filecat(int fd_dest, int fd_src);
int write(int fd, const void *buff, unsigned count);
int read(int fd, void *buff, unsigned count);
int close(int fd);
inline long long lseek(int fd, long long offset, int seek_set=SEEK_SET){
return _lseeki64(fd, offset, seek_set);
}
inline long long tell(int fd) { return _telli64(fd); }
inline int eof(int fd) { return _eof(fd); }
}
#endif
| [
"ivan4869@2d210990-551f-8c42-1311-29a641925cc6"
] | [
[
[
1,
64
]
]
] |
c64c955b26aed01a59af1f2a0909ae55dff5fc7f | 54cacc105d6bacdcfc37b10d57016bdd67067383 | /trunk/source/math/geom/Polygon.h | ee815e86ebdb3013443635bb3a41ba65a3e50f54 | [] | no_license | galek/hesperus | 4eb10e05945c6134901cc677c991b74ce6c8ac1e | dabe7ce1bb65ac5aaad144933d0b395556c1adc4 | refs/heads/master | 2020-12-31T05:40:04.121180 | 2009-12-06T17:38:49 | 2009-12-06T17:38:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,810 | h | /***
* hesperus: Polygon.h
* Copyright Stuart Golodetz, 2008. All rights reserved.
***/
#ifndef H_HESP_POLYGON
#define H_HESP_POLYGON
#include <vector>
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
#include <source/math/vectors/Vector3.h>
namespace hesp {
/**
This class template allows users to create convex, planar polygons with a vertex type and
auxiliary data type of their choosing. For instance, they can create textured polygons by
specifying a vertex type with (u,v) texture coordinates and an auxiliary data type referencing
the texture itself.
*/
template <typename Vert, typename AuxData>
class Polygon
{
//#################### FRIENDS ####################
friend class Polygon;
//#################### TYPEDEFS ####################
public:
// Expose the template arguments so that they can easily be used by client code.
typedef Vert Vert;
typedef AuxData AuxData;
typedef shared_ptr<Polygon> Polygon_Ptr;
//#################### PRIVATE VARIABLES ####################
private:
std::vector<Vert> m_vertices;
Vector3d m_normal;
AuxData m_auxData;
//#################### CONSTRUCTORS ####################
public:
Polygon(const std::vector<Vert>& vertices, const AuxData& auxData);
template <typename OtherAuxData> Polygon(const Polygon<Vert,OtherAuxData>& otherPoly, const AuxData& auxData);
//#################### PUBLIC METHODS ####################
public:
AuxData& auxiliary_data();
const AuxData& auxiliary_data() const;
Polygon_Ptr flipped_winding() const;
const Vector3d& normal() const;
const Vert& vertex(int i) const;
int vertex_count() const;
//#################### PRIVATE METHODS ####################
private:
void calculate_normal();
};
}
#include "Polygon.tpp"
#endif
| [
"[email protected]"
] | [
[
[
1,
67
]
]
] |
6128eebf858de424fc54797a3fec37db2b897693 | aab4c401149d8cdee10094d4fb4de98f490be3b6 | /include/controlers/mouse.h | 7e41a4624f867497fcd641c0f8b6d433eb1ad14c | [] | no_license | soulik/quads | a7a49e32dcd137fd32fd45b60fa26b5c0747bd03 | ce440c5d35448908fd936797bff0cb7a9ff78b6e | refs/heads/master | 2016-09-08T00:18:28.704939 | 2008-09-01T14:18:42 | 2008-09-01T14:18:42 | 32,122,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 641 | h | #ifndef MOUSE_H_
#define MOUSE_H_
#include "objects/qPoint.h"
#include "qDebug.h"
class cMouse: public qDebug {
qPointi position;
qPointi _position;
qPointi rel_pos;
unsigned char buttons;
unsigned char _buttons;
public:
cMouse();
void update();
qPointi getPos();
qPointi getPos2();
qPointi getRelPos();
unsigned char getButtons();
unsigned char getPrevButtons();
void setPos(int x, int y);
void setRelPos(int x, int y);
void synchronizePosition();
void setButtons(unsigned int state);
void setButton(unsigned int button, unsigned char state);
virtual ~cMouse();
};
#endif /*MOUSE_H_*/
| [
"soulik42@89f801e3-d555-0410-a9c1-35b9be595399"
] | [
[
[
1,
31
]
]
] |
a46f27b4ac1ab4a00de081fd76188f15dac46b0c | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/xpressive/detail/utility/algorithm.hpp | 2858e96634c1510ceebea881f5ea0394d88ab207 | [
"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 | 2,792 | hpp | ///////////////////////////////////////////////////////////////////////////////
// algorithm.hpp
//
// Copyright 2004 Eric Niebler. 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)
#ifndef BOOST_XPRESSIVE_DETAIL_UTILITY_ALGORITHM_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_DETAIL_UTILITY_ALGORITHM_HPP_EAN_10_04_2005
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <climits>
#include <algorithm>
#include <boost/iterator/iterator_traits.hpp>
namespace boost { namespace xpressive { namespace detail
{
///////////////////////////////////////////////////////////////////////////////
// any
//
template<typename InIter, typename Pred>
inline bool any(InIter begin, InIter end, Pred pred)
{
return end != std::find_if(begin, end, pred);
}
///////////////////////////////////////////////////////////////////////////////
// find_nth_if
//
template<typename FwdIter, typename Diff, typename Pred>
FwdIter find_nth_if(FwdIter begin, FwdIter end, Diff count, Pred pred)
{
for(; begin != end; ++begin)
{
if(pred(*begin) && 0 == count--)
{
return begin;
}
}
return end;
}
///////////////////////////////////////////////////////////////////////////////
// toi
//
template<typename InIter, typename Traits>
int toi(InIter &begin, InIter end, Traits const &traits, int radix = 10, int max = INT_MAX)
{
int i = 0, c = 0;
for(; begin != end && -1 != (c = traits.value(*begin, radix)); ++begin)
{
if(max < ((i *= radix) += c))
return i / radix;
}
return i;
}
///////////////////////////////////////////////////////////////////////////////
// advance_to
//
template<typename BidiIter, typename Diff>
inline bool advance_to_impl(BidiIter & iter, Diff diff, BidiIter end, std::bidirectional_iterator_tag)
{
for(; 0 < diff && iter != end; --diff)
++iter;
for(; 0 > diff && iter != end; ++diff)
--iter;
return 0 == diff;
}
template<typename RandIter, typename Diff>
inline bool advance_to_impl(RandIter & iter, Diff diff, RandIter end, std::random_access_iterator_tag)
{
if(0 < diff)
{
if((end - iter) < diff)
return false;
}
else if(0 > diff)
{
if((iter - end) < -diff)
return false;
}
iter += diff;
return true;
}
template<typename Iter, typename Diff>
inline bool advance_to(Iter & iter, Diff diff, Iter end)
{
return detail::advance_to_impl(iter, diff, end, typename iterator_category<Iter>::type());
}
}}}
#endif
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
102
]
]
] |
3f50829bdae8598dcdb9839f84e88db23e3c7173 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/web/favourites_api/src/FavouritesDbTestObserver.cpp | 07dddc1c3511d7129d294f9f4a2afef82e76af42 | [] | 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,169 | cpp | /*
* Copyright (c) 2000 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: Implementation of class CFavouritesDbTestObserver
*
*/
// INCLUDE FILES
#include <FavouritesDb.h>
#include "FavouritesDbTestObserver.h"
//#include "FavouritesDbTester.h"
#include "ActiveFavouritesDbNotifier.h"
// CONSTANTS
// ================= MEMBER FUNCTIONS =======================
// ---------------------------------------------------------
// CFavouritesDbTestObserver::CFavouritesDbTestObserver
// ---------------------------------------------------------
//
CFavouritesDbTestObserver::CFavouritesDbTestObserver
( CFavouritesBCTest& aTester )
: CActive( EPriorityLow ), iTester( &aTester )
{
// Observer has lower priority than the notifier; to make sure we don't
// miss notification.
CActiveScheduler::Add( this );
}
// ---------------------------------------------------------
// CFavouritesDbTestObserver::~CFavouritesDbTestObserver
// ---------------------------------------------------------
//
CFavouritesDbTestObserver::~CFavouritesDbTestObserver()
{
Cancel();
delete iNotifier;
// iTester->iDb.Close();
}
// ---------------------------------------------------------
// CFavouritesDbTestObserver::RunL
// ---------------------------------------------------------
//
void CFavouritesDbTestObserver::RunL()
{
CActiveScheduler::Stop();
}
// ---------------------------------------------------------
// CFavouritesDbTestObserver::DoCancel
// ---------------------------------------------------------
//
void CFavouritesDbTestObserver::DoCancel()
{
if ( iNotifier )
{
iNotifier->Cancel();
}
}
// ---------------------------------------------------------
// CFavouritesDbTestObserver::HandleFavouritesDbEventL
// ---------------------------------------------------------
//
void CFavouritesDbTestObserver::HandleFavouritesDbEventL
( RDbNotifier::TEvent aEvent )
{
iLastEvent = aEvent;
iEventCount++;
}
// ---------------------------------------------------------
// CFavouritesDbTestObserver::Start
// ---------------------------------------------------------
//
void CFavouritesDbTestObserver::Start()
{
iStep = -1; // First call to Next will increment it to 1.
iLastEvent = 666;
iEventCount = 0;
Next();
}
// ---------------------------------------------------------
// CFavouritesDbTestObserver::Next
// ---------------------------------------------------------
//
void CFavouritesDbTestObserver::Next()
{
iStep++;
iStatus = KRequestPending;
SetActive();
TRequestStatus *status = &iStatus;
User::RequestComplete( status, KErrNone ); // Invoke RunL()
}
| [
"none@none"
] | [
[
[
1,
110
]
]
] |
c913d6778ac8364d88147f1b1a2c0b5e60888fbb | 13f30850677b4b805aeddbad39cd9369d7234929 | / astrocytes --username [email protected]/CT_tutorial/MyGraph/str.cpp | 85f30d39e7e0a7d6179ac1f3595f4dd4e3fa9491 | [] | 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 | 2,216 | cpp | #include "str.h"
namespace str
{
std::string replace(std::string target, std::string that, std::string with)
{
while(1)
{
std::string::size_type where1 = target.find(that);
if(where1 != std::string::npos)
{
target.replace(target.begin() + where1, target.begin() + where1 + that.size(), with.begin(), with.end());
}else break;
}
return target;
}
std::string ReplaceInString(std::string s,StringPairs& repl)
{
if(repl.size())
{
for(int i=0;i<repl.size();i++)
{
s = replace(s, repl[i].first, repl[i].second);
}
}else
return s;
return s;
}
void ReplaceInFile(std::string fn,std::string nfn,StringPairs& repl)
{
char buf[10000];
std::ifstream fs(fn.c_str(),std::ios::in | std::ios::binary);
std::ofstream fs1(nfn.c_str(),std::ios::out | std::ios::binary);
while(!fs.eof())
{
fs.getline(buf,1000);
std::string ss(buf);
std::string res = ReplaceInString(ss,repl);
if(res.size()>1)
{
fs1.write(res.c_str(),res.size()-1);
fs1 << std::endl;
}
}
fs.close();
fs1.close();
}
void AddPair(StringPairs& arr, std::string a, std::string b)
{
arr.push_back(std::pair<std::string,std::string>(a,b));
}
std::vector<std::string> split(const std::string& source, std::string delim)
{
std::vector<std::string> result;
int cur1=0,cur2;
while(1)
{
cur1 = source.find_first_not_of(delim, cur1);
if(cur1==-1)break;
cur2 = source.find_first_of(delim, cur1);
if(cur2==-1)cur2=source.length();
result.push_back(source.substr(cur1,cur2-cur1));
cur1=cur2+1;
}
return result;
}
float ToFloat(std::string s)
{
return (float)atof(s.c_str());
}
int ToInt(std::string s)
{
return atoi(s.c_str());
}
std::string ToString(int val)
{
char buf[100];
_itoa(val,buf,10);
return std::string(buf);
}
std::string ToString(float val)
{
char buf[100];
sprintf_s(buf,100,"%f",val);
return std::string(buf);
}
std::string ToString(vec3 val)
{
char buf[200];
sprintf_s(buf,200,"%f %f %f",val.x,val.y,val.z);
return std::string(buf);
}
}; | [
"[email protected]"
] | [
[
[
1,
117
]
]
] |
4cf2bc31bf38599891d9bf306c60f3c7860fcb88 | 971b000b9e6c4bf91d28f3723923a678520f5bcf | /doc/TextOdfDebug/ZipDebugMain.cpp | c437c18c56ceec87ae7ed893cb8348c69a60bbbc | [] | no_license | google-code-export/fop-miniscribus | 14ce53d21893ce1821386a94d42485ee0465121f | 966a9ca7097268c18e690aa0ea4b24b308475af9 | refs/heads/master | 2020-12-24T17:08:51.551987 | 2011-09-02T07:55:05 | 2011-09-02T07:55:05 | 32,133,292 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,922 | cpp | #include "ZipDebugMain.h"
//
/* Save file as ZipDebugMain.cpp */
/* incomming class name ZipDebugMain */
//
ZipDebugMain::ZipDebugMain( QWidget* parent )
: QMainWindow( parent )
{
setupUi( this );
setWindowTitle(tr("Zip or OpenOffice file debug"));
setAcceptDrops (true);
textEdit->setAcceptDrops (true);
textEdit->installEventFilter(this);
}
bool ZipDebugMain::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::DragEnter) {
QDragEnterEvent *ev = static_cast<QDragEnterEvent *>(event);
const QMimeData *md = ev->mimeData();
if ( md->hasUrls() ) {
QList<QUrl> urls = md->urls();
for ( int i = 0; i < urls.size(); ++i ) {
QUrl gettyurl(urls.at(i));
if (gettyurl.scheme() == "file") {
QFileInfo fi(gettyurl.toLocalFile());
openFile( fi.absoluteFilePath() );
return true;
}
}
}
return false;
}
return false;
}
void ZipDebugMain::on_openzip_triggered()
{
QString file = QFileDialog::getOpenFileName(this, tr( "Choose a zip or a oo file to open" ),"" , "*" );
if ( file.isEmpty() ) {
return;
}
openFile(file);
}
void ZipDebugMain::openFile( const QString file )
{
lineEdit->setText ( file );
QMap<QString,QByteArray> filist = unzipstream(file);
tabWidget->clear();
QByteArray base = filist["content.xml"];
if (base.size() > 0) {
drawTab(base,"content.xml");
}
QMapIterator<QString,QByteArray> i(filist);
while (i.hasNext()) {
i.next();
QFileInfo fi(i.key());
const QString ext = fi.completeSuffix().toLower();
if (ext == "xml" && i.key() != "content.xml") {
drawTab(i.value(),fi.fileName());
}
}
Ooo = new OOReader(file);
connect(Ooo, SIGNAL(ready()), this, SLOT(drawDoc()));
}
void ZipDebugMain::drawDoc()
{
if (Ooo) {
drawDoc(Ooo->document());
}
}
void ZipDebugMain::drawDoc( QTextDocument *doc )
{
XMLTextEdit *de = new XMLTextEdit;
de->setPlainText(Ooo->debugStyle());
tabWidget->addTab(de,tr("Style"));
QWidget *tabi = new QWidget();
tabi->setObjectName("result");
QGridLayout *grid = new QGridLayout(tabi);
QTextEdit *t = new QTextEdit(tabi);
t->setDocument ( doc );
t->setAcceptDrops (true);
t->installEventFilter(this);
t->setObjectName("document");
grid->addWidget(t, 0, 0, 1, 1);
tabWidget->addTab(tabi,tr("Document_Debug"));
const int last = tabWidget->count() - 1;
tabWidget->setCurrentIndex(last);
t->setLineWrapColumnOrWidth(t->lineWrapColumnOrWidth());
}
void ZipDebugMain::drawTab( QByteArray dat , const QString file )
{
QWidget *tabi = new QWidget();
tabi->setObjectName(file);
QGridLayout *grid = new QGridLayout(tabi);
XMLTextEdit *t = new XMLTextEdit(tabi);
ReadWriteBuf *buf = new ReadWriteBuf();
buf->write(dat);
////QDomDocument
if (buf->isValid()) {
const QString text = QString::fromUtf8(buf->Dom().toByteArray(1).constData());
t->setPlainText(text);
}
t->setAcceptDrops (true);
t->installEventFilter(this);
t->setObjectName(file);
grid->addWidget(t, 0, 0, 1, 1);
tabWidget->addTab(tabi,file);
}
| [
"ppkciz@9af58faf-7e3e-0410-b956-55d145112073"
] | [
[
[
1,
147
]
]
] |
f598ff6ed511010333369b23115c7f9860a9a4aa | 6253ab92ce2e85b4db9393aa630bde24655bd9b4 | /operational/PathSmoother/PathSmoother/boundary.h | 4e32ffb81e16e85f3195bb04c5dd213832e5f3ab | [] | no_license | Aand1/cornell-urban-challenge | 94fd4df18fd4b6cc6e12d30ed8eed280826d4aed | 779daae8703fe68e7c6256932883de32a309a119 | refs/heads/master | 2021-01-18T11:57:48.267384 | 2008-10-01T06:43:18 | 2008-10-01T06:43:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | h | #include "shape.h"
#include "shared_ptr.h"
#ifndef _BOUNDARY_H
#define _BOUNDARY_H
#ifdef __cplusplus_cli
#pragma managed(push,off)
#endif
enum bound_side {
side_left,
side_right,
side_path,
};
class boundary {
private:
shared_ptr<shape> _shape;
bound_side _side;
double _desired_spacing;
double _min_spacing;
double _alpha_s;
bool _check_small_obs;
int _index;
public:
boundary(shared_ptr<shape> shape, bound_side side, double desired_spacing, double min_spacing, double alpha_s, int index, bool check_small_obs)
: _shape(shape), _side(side), _desired_spacing(desired_spacing), _min_spacing(min_spacing), _alpha_s(alpha_s), _index(index), _check_small_obs(check_small_obs) {}
shared_ptr<const shape> shape() const { return const_ptr(_shape); }
bound_side side() const { return _side; }
double desired_spacing() const { return _desired_spacing; }
double min_spacing() const { return _min_spacing; }
bool check_small_obs() const { return _check_small_obs; }
double alpha_s() const { return _alpha_s; }
int index() const { return _index; }
};
#ifdef __cplusplus_cli
#pragma managed(pop)
#endif
#endif | [
"anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5"
] | [
[
[
1,
48
]
]
] |
1f31b9e26ff344aefc1ffc3a492d9c8d306d8ac7 | 60ef79535d316aaeb4efc4f79d700fcb1c87586f | /CUGBLinker/tinystr.cpp | 30d0a331008e6932e96d8c4f08067a8cc195110b | [] | no_license | dinglx/cugblinker | 9b4cc5e129268cf3b2c14c99cd43a322c3f3487b | f4a2ee5bdecf41ec8ba91c63cf1923672964eae1 | refs/heads/master | 2021-01-16T00:27:54.122346 | 2009-12-16T17:00:50 | 2009-12-16T17:00:50 | 32,516,245 | 0 | 0 | null | null | null | null | MacCentralEurope | C++ | false | false | 2,624 | cpp | /*
www.sourceforge.net/projects/tinyxml
Original file by Yves Berquin.
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.
*/
/*
* THIS FILE WAS ALTERED BY Tyge LÝvset, 7. April 2005.
*/
#include "stdafx.h"
#ifndef TIXML_USE_STL
#include "tinystr.h"
// Error value for find primitive
const TiXmlString::size_type TiXmlString::npos = static_cast< TiXmlString::size_type >(-1);
// Null rep.
TiXmlString::Rep TiXmlString::nullrep_ = { 0, 0, { '\0' } };
void TiXmlString::reserve (size_type cap)
{
if (cap > capacity())
{
TiXmlString tmp;
tmp.init(length(), cap);
memcpy(tmp.start(), data(), length());
swap(tmp);
}
}
TiXmlString& TiXmlString::assign(const char* str, size_type len)
{
size_type cap = capacity();
if (len > cap || cap > 3*(len + 8))
{
TiXmlString tmp;
tmp.init(len);
memcpy(tmp.start(), str, len);
swap(tmp);
}
else
{
memmove(start(), str, len);
set_size(len);
}
return *this;
}
TiXmlString& TiXmlString::append(const char* str, size_type len)
{
size_type newsize = length() + len;
if (newsize > capacity())
{
reserve (newsize + capacity());
}
memmove(finish(), str, len);
set_size(newsize);
return *this;
}
TiXmlString operator + (const TiXmlString & a, const TiXmlString & b)
{
TiXmlString tmp;
tmp.reserve(a.length() + b.length());
tmp += a;
tmp += b;
return tmp;
}
TiXmlString operator + (const TiXmlString & a, const char* b)
{
TiXmlString tmp;
TiXmlString::size_type b_len = static_cast<TiXmlString::size_type>( strlen(b) );
tmp.reserve(a.length() + b_len);
tmp += a;
tmp.append(b, b_len);
return tmp;
}
TiXmlString operator + (const char* a, const TiXmlString & b)
{
TiXmlString tmp;
TiXmlString::size_type a_len = static_cast<TiXmlString::size_type>( strlen(a) );
tmp.reserve(a_len + b.length());
tmp.append(a, a_len);
tmp += b;
return tmp;
}
#endif // TIXML_USE_STL
| [
"dlx1986@4ddcaae0-7081-11de-ae35-f3f989a3c448"
] | [
[
[
1,
117
]
]
] |
2d7437d9e8c17d4d200c2ee22298cd7d1c729cb5 | c70941413b8f7bf90173533115c148411c868bad | /plugins/FreeTypePlugin/include/vtxftParser.h | 2fcaf71e0e5896b634f9f8f6045f317824752f60 | [] | no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,124 | h | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __vtxftParser_H__
#define __vtxftParser_H__
#include "vtxfreetype.h"
#include "vtxFontParser.h"
#include "vtxVector2.h"
namespace vtx { namespace ft {
//-----------------------------------------------------------------------
class vtxftExport FreeTypeParser : public FontParser
{
public:
FreeTypeParser();
virtual ~FreeTypeParser();
const StringList& getExtensions() const;
FontResource* parse(FileStream* stream);
const float getEmSize() const;
GlyphResource* getCurrentGlyph() const;
protected:
float mEmSize;
GlyphResource* mCurrentGlyph;
//void* mFreeType;
};
//-----------------------------------------------------------------------
}}
#endif
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
] | [
[
[
1,
58
]
]
] |
3be590f354baca1397b1aac0d8300b4a6798a563 | 72071dfcccdab286fce3b0d4483d9e075f0a2ae3 | /StatKeeper.cpp | a8db55065b9a5c1680b2babf35389ba73010a521 | [] | no_license | rickumali/RicksTetris | bc824d25ca6403cd12891aa2eae59fc5c6c41a9c | 76128d72f0cfb75ff4d619784c70fec9562d5c71 | refs/heads/master | 2016-09-06T04:27:15.587789 | 2011-12-23T18:17:10 | 2011-12-23T18:17:10 | 3,043,175 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,018 | cpp | #include "StatKeeper.h"
#include "Constants.h"
#include <iostream>
using std::cout;
using std::endl;
StatKeeper::StatKeeper() {
}
void StatKeeper::clear_counters() {
for (int i=0; i<7; i++)
shape_count[i] = 0;
}
void StatKeeper::increment_shape_count(int shape) {
// This takes a shape constant (from Constants.h), and increments the counter
if (shape < 1 || shape > 7)
return;
shape--;
shape_count[shape]++;
}
int StatKeeper::get_shape_count(int shape) {
shape--;
return(shape_count[shape]);
}
void StatKeeper::dump_stats() {
cout << "SQUARE: " << get_shape_count(SQUARE) << endl;
cout << "PYRAMID: " << get_shape_count(PYRAMID) << endl;
cout << "LEFT_SLANT: " << get_shape_count(LEFT_SLANT) << endl;
cout << "RIGHT_SLANT: " << get_shape_count(RIGHT_SLANT) << endl;
cout << "LONG_ROW: " << get_shape_count(LONG_ROW) << endl;
cout << "LEFT_ELL: " << get_shape_count(LEFT_ELL) << endl;
cout << "RIGHT_ELL: " << get_shape_count(RIGHT_ELL) << endl;
}
| [
"[email protected]"
] | [
[
[
1,
37
]
]
] |
779fb1d01b1237bc4c9ad99e69d0125452aeb149 | 600065575d74f6ff18107510c527fce4830b98a2 | /vdubauo/src/vdub.cpp | a6de1b27a649bd7b283361e00b72b31d90b1bcc1 | [] | no_license | chattama/vdubauo | ba129a57ac893367588ec02acf784f92d33d7d92 | 0bca13001debe98192c4a09a9ad38ed475775376 | refs/heads/master | 2021-01-20T11:19:18.169404 | 2009-07-17T05:13:17 | 2009-07-17T05:13:17 | 253,281 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,570 | cpp |
#include "vdub.h"
#include "debug.h"
//////////////////////////////////////////////////////////////////////////////
const VDPluginInfo *const kPlugins[] = {
NULL,
};
extern "C" __declspec(dllexport) const VDPluginInfo *const *VDXAPIENTRY VDGetPluginInfo() {
return kPlugins;
}
//////////////////////////////////////////////////////////////////////////////
VDubFrameServer::VDubFrameServer(const char *sname) {
lstrcpy(m_sname, sname);
GetDubServerInterface = NULL;
vdsvrlnk = NULL;
ivdsl = NULL;
ivdac = NULL;
vFormat = NULL;
aFormat = NULL;
InitializeCriticalSection(&cs);
}
VDubFrameServer::~VDubFrameServer() {
DeleteCriticalSection(&cs);
if (ivdac)
ivdsl->FrameServerDisconnect(ivdac);
if (vdsvrlnk)
FreeLibrary(vdsvrlnk);
}
BOOL VDubFrameServer::Init() {
BOOL final = TRUE;
try {
vdsvrlnk = LoadLibrary("vdsvrlnk.dll");
if (!vdsvrlnk) throw (BOOL)FALSE;
GetDubServerInterface = (GetDubServerInterfaceProc) GetProcAddress(vdsvrlnk, "GetDubServerInterface");
if (!GetDubServerInterface) throw (BOOL)FALSE;
ivdsl = GetDubServerInterface();
if (!ivdsl) throw (BOOL)FALSE;
ivdac = ivdsl->FrameServerConnect(m_sname);
if (!ivdac) throw (BOOL)FALSE;
fHasAudio = ivdac->hasAudio();
if (!ivdac->readStreamInfo(&vStreamInfo, FALSE, &vSampleFirst, &vSampleLast))
throw (BOOL)FALSE;
if ((vFormatLen = ivdac->readFormat(NULL, FALSE))<=0)
throw (BOOL)FALSE;
if (!(vFormat = (BITMAPINFOHEADER *)malloc(vFormatLen)))
throw (HRESULT)E_OUTOFMEMORY;
if (ivdac->readFormat(vFormat, FALSE)<=0)
throw (BOOL)FALSE;
if (fHasAudio) {
if (!ivdac->readStreamInfo(&aStreamInfo, TRUE, &aSampleFirst, &aSampleLast))
throw (BOOL)FALSE;
if ((aFormatLen = ivdac->readFormat(NULL, TRUE))<=0)
throw (BOOL)FALSE;
if (!(aFormat = (WAVEFORMATEX *)malloc(aFormatLen)))
throw (HRESULT)E_OUTOFMEMORY;
if (ivdac->readFormat(aFormat, TRUE)<=0)
throw (BOOL)FALSE;
}
} catch (BOOL res) {
final = res;
}
return final;
}
int VDubFrameServer::GetVideo(int sample, void *buf) {
lock();
int r = ivdac->readVideo(sample, buf);
unlock();
return r;
}
int VDubFrameServer::GetAudio(int start, int length, int *readed, void *buf, long size) {
long rb = 0;
lock();
int r = ivdac->readAudio(start, length, buf, size, &rb, (long*)readed);
unlock();
return r;
}
void VDubFrameServer::lock() {
EnterCriticalSection(&cs);
}
void VDubFrameServer::unlock() {
LeaveCriticalSection(&cs);
}
| [
"[email protected]"
] | [
[
[
1,
108
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.