code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
#ifndef _MyTimer
#define _MyTimer
#include <ctime>
class MyTimer
{
private:
clock_t start_time;
clock_t end_time;
bool isActive;
public:
MyTimer()
{
start_time = 0;
end_time = 0;
isActive = false;
}
void Start(void)
{
start_time = clock();
isActive = true;
}
void SetActive(bool active)
{
isActive = active;
}
double getDiff(void)
{
if(isActive)
{
double res = (clock() - start_time) / (double)CLOCKS_PER_SEC;
if(res < 40)
return res;
else
return 40;
}
else
return 0;
}
};
#endif
| C++ |
#include <SDL.h>
#include "CApp.h"
#undef main
int main(int argc, char *argv[])
{
CApp app;
return app.OnExecute();
}
| C++ |
#ifndef SDL_LOAD_H
#define SDL_LOAD_H
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <cstring>
#include <string>
#endif // SDL_LOAD_H
| C++ |
#ifndef CAPP_H
#define CAPP_H
#include <stdlib.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <math.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include "Player1UDPs.h"
#include "Player2UDPc.h"
#include "MyTimer.h"
#include <netdb.h> //ubunta
#include <unistd.h>
using namespace std;
class CApp
{
private:
fstream log;
bool Running;
SDL_Event Event;
SDL_Window* screen;
int ScreenWidth;
int ScreenHeight;
SDL_Renderer* render;
SDL_Texture* background;
int Zone1;
int Zone2;
//параметры и режимы игры
int Mode; //0 - меню, 1 - тренировка, 2 - создать, 3 - подключится
//меню
SDL_Texture* trainingText;
SDL_Rect trainingRect;
SDL_Texture* createText;
SDL_Rect createRect;
SDL_Texture* connectText;
SDL_Rect connectRect;
SDL_Texture* ExitText;
SDL_Rect ExitRect;
//создать
Player1UDPs server;
SDL_Texture* waitingText;
SDL_Rect waitingRect;
//подключится
Player2UDPc client;
SDL_Texture* inputText;
SDL_Rect inputRect;
SDL_Texture* inputipText;
SDL_Rect inputipRect;
//счет
SDL_Color font_color;
SDL_Texture* score1Text;
SDL_Rect score1Rect;
SDL_Texture* score2Text;
SDL_Rect score2Rect;
int score1;
int score2;
//мяч
SDL_Rect ballRect;
SDL_Texture* ballText;
int ballSpeedX;
int ballSpeedY;
double ballSpeed;
MyTimer timer;
//игроки
SDL_Rect stick1Rect;
SDL_Rect stick2Rect;
SDL_Texture* stick1Text;
SDL_Texture* stick2Text;
public:
CApp()
{
remove("logs/log.txt");
log.open("logs/log.txt", fstream::in | fstream::out | fstream::app);
Running = true;
screen = NULL;
render = NULL;
background = NULL;
font_color = {0, 255, 255};
ScreenWidth = 800;
ScreenHeight = 400;
Zone1 = 290;
Zone2 = 510;
//параметры игры
Mode = 0;
//кнопки меню и надписи
trainingRect.w = 150;
trainingRect.h = 80;
trainingRect.x = 325;
trainingRect.y = 10;
createRect.w = 150;
createRect.h = 80;
createRect.x = 325;
createRect.y = 110;
connectRect.w = 150;
connectRect.h = 80;
connectRect.x = 325;
connectRect.y = 210;
ExitRect.w = 150;
ExitRect.h = 80;
ExitRect.x = 325;
ExitRect.y = 310;
DefaultConfig();
}
void DefaultConfig(void)
{
//Ввод вывод текста
waitingRect.w = 200;
waitingRect.h = 60;
waitingRect.x = 300;
waitingRect.y = 130;
inputRect.w = 200;
inputRect.h = 40;
inputRect.x = 300;
inputRect.y = 190;
inputipRect.w = 40;
inputipRect.h = 60;
inputipRect.x = 385;
inputipRect.y = 240;
//счет
score1Rect.w = 50;
score1Rect.h = 100;
score1Rect.x = 300;
score1Rect.y = 150;
score2Rect.w = 50;
score2Rect.h = 100;
score2Rect.x = 450;
score2Rect.y = 150;
score1 = 0;
score2 = 0;
//мяч
ballRect.w = ballRect.h = 20;
ballRect.x = 400 - ballRect.w/2;
ballRect.y = 200 - ballRect.h/2 +5;
ballSpeedX = 5;
ballSpeedY = 5;
ballSpeed = sqrt(pow(ballSpeedX, 2) + pow(ballSpeedY, 2));
//бруски
stick1Rect.w = stick2Rect.w = 80;
stick1Rect.h = stick2Rect.h = 80;
stick1Rect.x = 0;
stick2Rect.x = ScreenWidth - stick2Rect.w;
stick1Rect.y= stick2Rect.y = ScreenHeight/2 - stick1Rect.h/2;
}
void SticksContactWithBall(SDL_Rect &stick)
{
if(sqrt(pow(stick.x + stick.w/2 - ballRect.x - ballRect.w/2, 2)
+ pow(stick.y + stick.h/2 - ballRect.y - ballRect.h/2, 2)) <= stick.w/2 + ballRect.w/2)
{
float diffX = abs(ballRect.x + ballRect.w/2 - stick.x - stick.w/2);
float diffY = abs(ballRect.y + ballRect.h/2 - stick.y - stick.h/2);
float diffS = sqrt(pow(diffX, 2) + pow(diffY, 2));
if (ballRect.x + ballRect.w/2 >= stick.x + stick.w/2
&& ballRect.y + ballRect.h/2 >= stick.y + stick.h/2)
{
ballSpeedX = diffX * ballSpeed / diffS;
ballSpeedY = diffY * ballSpeed / diffS;
}
else if (ballRect.x + ballRect.w/2 >= stick.x + stick.w/2
&& ballRect.y + ballRect.h/2 <= stick.y + stick.h/2)
{
ballSpeedX = diffX * ballSpeed / diffS;
ballSpeedY = -diffY * ballSpeed / diffS;
}
else if (ballRect.x + ballRect.w/2 <= stick.x + stick.w/2
&& ballRect.y + ballRect.h/2 <= stick.y + stick.h/2)
{
ballSpeedX = -diffX * ballSpeed / diffS;
ballSpeedY = -diffY * ballSpeed / diffS;
}
else if (ballRect.x + ballRect.w/2 <= stick.x + stick.w/2
&& ballRect.y + ballRect.h/2 >= stick.y + stick.h/2)
{
ballSpeedX = -diffX * ballSpeed / diffS;
ballSpeedY = diffY * ballSpeed / diffS;
}
}
}
SDL_Texture* SDL_LoadTexture(SDL_Renderer* renderer, const char *path)
{
SDL_Surface* Surf = IMG_Load(path);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, Surf);
SDL_FreeSurface(Surf);
return texture;
}
SDL_Texture* SDL_SetFontTexture(SDL_Renderer* renderer, std::string message, SDL_Color color)
{
TTF_Font* font = TTF_OpenFont("font/SourceSansPro-Black.ttf", 100);
const char* msg = message.c_str();
SDL_Surface* surf = TTF_RenderText_Solid(font, msg, color);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surf);
SDL_FreeSurface(surf);
TTF_CloseFont(font);
return texture;
}
SDL_Texture* ChangeScore(SDL_Texture* scoreText, int score) //изменяет текст в текстурах со счетом
{
std::stringstream ss;
ss.seekp(0);
ss << score;
SDL_DestroyTexture(scoreText);
scoreText = SDL_SetFontTexture(render, ss.str(), font_color);
return scoreText;
}
char* SDL_InputString(void) //ввод строки
{
std::string str="";
SDL_Event mevent;
bool print = true;
while(print)
{
while (SDL_PollEvent(&mevent))
{
if(mevent.type == SDL_KEYDOWN)
{
if(mevent.key.keysym.sym == SDLK_ESCAPE)
return NULL;
if(mevent.key.keysym.sym == SDLK_RETURN)
{
print = false;
break;
}
else
{
if(mevent.key.keysym.sym == SDLK_BACKSPACE)
{
if(str.length()>0)
str.erase(str.length()-1);
}
else
str += SDL_GetScancodeName(mevent.key.keysym.scancode)[0];
inputipRect.w = str.length()*30;
inputipRect.x = 400 - inputipRect.w/2;
SDL_DestroyTexture(inputipText);
inputipText = SDL_SetFontTexture(render, str, font_color);
SDL_RenderClear(render);
SDL_RenderCopy(render, background, NULL, NULL);
//SDL_ShowCursor(true);
SDL_RenderCopy(render, trainingText, NULL, &trainingRect);
SDL_RenderCopy(render, createText, NULL, &createRect);
SDL_RenderCopy(render, connectText, NULL, &connectRect);
SDL_RenderCopy(render, ExitText, NULL, &ExitRect);
SDL_RenderCopy(render, inputText, NULL, &inputRect);
SDL_RenderCopy(render, inputipText, NULL, &inputipRect);
SDL_RenderPresent(render);
}
}
}
}
char *res = new char[str.length()+1];
std::copy(str.begin(), str.end(), res);
res[str.length()]='\0';
return res;
}
int OnExecute()
{
if(OnInit() == false)
return -1;
while(Running)
{
usleep(7500);
while(SDL_PollEvent(&Event))
{
OnEvent(&Event);
}
OnLoop();
OnRender();
}
OnCleanup();
return 0;
}
bool OnInit()
{
log << "Application started.\n";
if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
return false;
log << "SDL_Init completed.\n";
if(TTF_Init() < 0)
{
log << SDL_GetError() << endl;
return false;
}
log << "TTF_Init completed.\n";
if((screen = SDL_CreateWindow("MyApplication", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, ScreenWidth, ScreenHeight, SDL_WINDOW_OPENGL)) == NULL)
{
log << SDL_GetError() << endl;
return false;
}
log << "Window created.\n";
if((render = SDL_CreateRenderer(screen, -1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)) == NULL)
{
log << SDL_GetError() << endl;
return false;
}
log << "Renderer created.\n";
//Загрузка текстур
score1Text = SDL_SetFontTexture(render, "0", font_color);
score2Text = SDL_SetFontTexture(render, "0", font_color);
inputText = SDL_SetFontTexture(render, "Input IP address:", font_color);
background = SDL_LoadTexture(render,"images/field.png");
ballText = SDL_LoadTexture(render, "images/ball.png");
stick1Text = SDL_LoadTexture(render, "images/stick1.png");
stick2Text = SDL_LoadTexture(render, "images/stick2.png");
trainingText = SDL_LoadTexture(render, "buttons/training.png");
createText = SDL_LoadTexture(render, "buttons/create.png");
connectText = SDL_LoadTexture(render, "buttons/connect.png");
ExitText = SDL_LoadTexture(render, "buttons/exit.png");
SDL_Log("All textures loaded.\n");
return true;
}
void OnEvent(SDL_Event* Event)
{
switch(Event->type)
{
case SDL_MOUSEMOTION:
{
if(Mode == 1 || Mode == 2)
{
if(Event->motion.x < Zone1 - stick1Rect.w + 40)
{
stick1Rect.x = Event->motion.x - stick1Rect.w/2;
}
else
{
stick1Rect.x = Zone1 - stick1Rect.w*3/2 + 40;
// SDL_WarpMouseInWindow(screen, stick1Rect.x + stick1Rect.w/2, stick1Rect.y + stick1Rect.h/2);
}
if(Event->motion.y > stick1Rect.h/2 -3 && Event->motion.y < ScreenHeight - stick1Rect.h/2 +3)
{
stick1Rect.y = Event->motion.y - stick1Rect.h/2;
}
else
{
if(Event->motion.y < 200) stick1Rect.y = 0;
else stick1Rect.y = ScreenHeight - stick1Rect.h;
// SDL_WarpMouseInWindow(screen, stick1Rect.x + stick1Rect.w/2, stick1Rect.y + stick1Rect.h/2);
}
}
if(Mode == 3)
{
if(Event->motion.x > Zone2 + 40)
{
stick2Rect.x = Event->motion.x - stick2Rect.w/2;
}
else
{
stick2Rect.x = Zone2;
// SDL_WarpMouseInWindow(screen, stick2Rect.x + stick2Rect.w/2, stick2Rect.y + stick2Rect.h/2);
}
if(Event->motion.y > stick2Rect.h/2 -3 && Event->motion.y < ScreenHeight - stick2Rect.h/2 +3)
{
stick2Rect.y = Event->motion.y - stick2Rect.h/2;
}
else
{
if(Event->motion.y < 200) stick2Rect.y = 0;
else stick2Rect.y = ScreenHeight - stick2Rect.h;
// SDL_WarpMouseInWindow(screen, stick2Rect.x + stick2Rect.w/2, stick2Rect.y + stick2Rect.h/2);
}
}
break;
}
case SDL_MOUSEBUTTONDOWN:
{
if(Mode == 0)
{
if(Event->button.button == SDL_BUTTON_LEFT)
{
if(Event->button.x > trainingRect.x && Event->button.x < trainingRect.x + trainingRect.w
&& Event->button.y > trainingRect.y && Event->button.y < trainingRect.y + trainingRect.h)
{
log << "Training choosen.\n";
Mode = 1;
timer.SetActive(true);
timer.Start();
}
if(Event->button.x > createRect.x && Event->button.x < createRect.x + createRect.w
&& Event->button.y > createRect.y && Event->button.y < createRect.y + createRect.h)
{
log << "Create choosen.\n";
Mode = 2;
sockaddr_in address;
char* hostname = new char[50];
gethostname(hostname, 50);
hostent *host=gethostbyname(hostname);
int ip_n = 0;
while(host->h_addr_list[ip_n]!=NULL) ip_n++;
char ip_res[100] = "";
std::cout << std::endl << ip_n << std::endl;
for(int i = 0; i < ip_n; i++)
{
memcpy(&address.sin_addr, host->h_addr_list[i], host->h_length);
char* ip = inet_ntoa(address.sin_addr);
strcpy(ip_res, strcat(ip_res, " "));
strcpy(ip_res, strcat(ip_res, ip));
waitingRect.w *= 1.5;
waitingRect.x = 400 - waitingRect.w/2;
}
waitingText = SDL_SetFontTexture(render, ip_res, font_color);
SDL_RenderCopy(render, waitingText, NULL, &waitingRect);
SDL_RenderPresent(render);
server.StartServer();
SDL_DestroyTexture(waitingText);
server.Receive();
server.Send(stick1Rect.x, stick1Rect.y, 0, 0, 0, 0);
timer.SetActive(true);
timer.Start();
}
if(Event->button.x > connectRect.x && Event->button.x < connectRect.x + connectRect.w
&& Event->button.y > connectRect.y && Event->button.y < connectRect.y + connectRect.h)
{
log << "Join choosen.\n";
Mode = 3;
SDL_RenderClear(render);
SDL_RenderCopy(render, background, NULL, NULL);
// SDL_ShowCursor(true);
SDL_RenderCopy(render, trainingText, NULL, &trainingRect);
SDL_RenderCopy(render, createText, NULL, &createRect);
SDL_RenderCopy(render, connectText, NULL, &connectRect);
SDL_RenderCopy(render, ExitText, NULL, &ExitRect);
SDL_RenderCopy(render, inputText, NULL, &inputRect);
SDL_RenderPresent(render);
char* ip = SDL_InputString();
log << "Server's IP: " << ip << endl;
if(ip!=NULL)
client.InitAddress(ip);
else
Mode = 0;
free(ip);
}
if(Event->button.x > ExitRect.x && Event->button.x < ExitRect.x + ExitRect.w
&& Event->button.y > ExitRect.y && Event->button.y < ExitRect.y + ExitRect.h)
{
log << "Button Exit pressed.\n";
Running = false;
}
}
}
break;
}
case SDL_KEYDOWN:
{
if(Event->key.keysym.sym == SDLK_ESCAPE)
{
if(Mode == 1)
{
log << "Escape pressed. Training stoped\n";
Mode = 0;
DefaultConfig();
}
if(Mode == 2)
{
log << "Escape pressed. Server shutdown.\n";
server.Send(400, 150, 0, 0, 0, 0);
server.Close();
DefaultConfig();
Mode = 0;
}
if(Mode == 3)
{
log << "Escape pressed. Client shutdown.\n";
client.Send(400, 150, 0, 0, 0, 0);
client.Close();
DefaultConfig();
Mode = 0;
}
}
break;
}
case SDL_QUIT:
{
if(Mode == 2)
{
log << "Quit pressed. Server shutdown.\n";
server.Send(400, 150, 0, 0, 0, 0);
server.Close();
}
if(Mode == 3)
{
log << "Quit pressed. Client shutdown.\n";
client.Send(400, 150, 0, 0, 0, 0);
client.Close();
}
Running = false;
break;
}
}
}
void OnLoop()
{
if(Mode == 1 || Mode == 2) //если Training или Host, то координаты мяча высчитываются тут
{
/*Движения мяча*/
ballRect.x += (ballSpeedX + ballSpeedX*(int)timer.getDiff()/20);
ballRect.y += (ballSpeedY + ballSpeedY*(int)timer.getDiff()/20);
if(ballRect.x < -ballRect.w)
{
if(Mode == 1)
{
Mode = 0;
DefaultConfig();
return;
}
else
{
/*гол игроку1*/
score2++;
/*if(score2 == 10)
{
log << "Player2 won the game.\n";
server.Send(400, 150, 0, 0, 0, 0);
server.Close();
}*/
score2Text = ChangeScore(score2Text, score2);
ballRect.x = 400 - ballRect.w/2;
ballRect.y = 200 - ballRect.h/2 +5;
ballSpeedX = -ballSpeedX;
timer.Start();
}
}
int modoffset; //для отскока
if(Mode == 1) //от стены
modoffset = ballRect.w; //во время training
else
modoffset = 0;
if(ballRect.x > ScreenWidth - modoffset)
{
if(Mode == 1)
ballSpeedX = -ballSpeedX;
else
{
/*гол игроку2*/
score1++;
/*if(score1 == 10)
{
log << "Player1 won the game.\n";
server.Send(400, 150, 0, 0, 0, 0);
server.Close();
}*/
score1Text = ChangeScore(score1Text, score1);
ballRect.x = 400 - ballRect.w/2;
ballRect.y = 200 - ballRect.h/2 +5;
ballSpeedX = -ballSpeedX;
timer.Start();
}
}
if (ballRect.y < 0)
ballSpeedY = abs(ballSpeedY);
if(ballRect.y > ScreenHeight - ballRect.h)
ballSpeedY = -abs(ballSpeedY);
/*Отскок мяча от брусков*/
//от бруска1
SticksContactWithBall(stick1Rect);
if(Mode != 1)
{
//от бруска2
SticksContactWithBall(stick2Rect);
}
}
/*Движение оппонента и отправка координат*/
if(Mode == 2) //Отправляешь свои координаты и координаты мяча
{
int* XY = server.Receive();
log << "Received data from client.\n";
if(XY[0] == 400)
{
log << "Client left the game.\n";
Mode = 0;
server.Close();
DefaultConfig();
}
stick2Rect.x = XY[0];
stick2Rect.y = XY[1];
server.Send((short)stick1Rect.x, (short)stick1Rect.y, (short)ballRect.x, (short)ballRect.y, score1, score2);
log << "Sent data to client.\n";
}
if(Mode == 3) //получаешь координаты, положение мяча и счет от хоста
{
client.Send((short) stick2Rect.x, (short)stick2Rect.y, 0, 0, 0, 0);
log << "Sent data to server.\n";
int* XY = client.Receive();
log << "Received data from server.\n";
if(XY[0] == 400)
{
log << "Server left the game\n";
Mode = 0;
client.Close();
DefaultConfig();
}
stick1Rect.x = XY[0];
stick1Rect.y = XY[1];
ballRect.x = XY[2];
ballRect.y = XY[3];
score1 = XY[4];
score2 = XY[5];
score1Text = ChangeScore(score1Text, score1);
score2Text = ChangeScore(score2Text, score2);
}
}
void OnRender()
{
SDL_RenderClear(render);
SDL_RenderCopy(render, background, NULL, NULL);
if(Mode == 0)
{
//SDL_ShowCursor(true);
SDL_RenderCopy(render, trainingText, NULL, &trainingRect);
SDL_RenderCopy(render, createText, NULL, &createRect);
SDL_RenderCopy(render, connectText, NULL, &connectRect);
SDL_RenderCopy(render, ExitText, NULL, &ExitRect);
}
else
if(Mode > 0)
{
//SDL_ShowCursor(false);
if(Mode != 1)
{
SDL_RenderCopy(render, score1Text, NULL, &score1Rect);
SDL_RenderCopy(render, score2Text, NULL, &score2Rect);
}
SDL_RenderCopy(render, ballText, NULL, &ballRect);
SDL_RenderCopy(render, stick1Text, NULL, &stick1Rect);
if(Mode != 1)
SDL_RenderCopy(render, stick2Text, NULL, &stick2Rect);
}
SDL_RenderPresent(render);
}
void OnCleanup()
{
SDL_DestroyTexture(score1Text);
SDL_DestroyTexture(score2Text);
SDL_DestroyTexture(inputText);
SDL_DestroyTexture(background);
SDL_DestroyTexture(ballText);
SDL_DestroyTexture(stick1Text);
SDL_DestroyTexture(stick2Text);
SDL_DestroyTexture(trainingText);
SDL_DestroyTexture(createText);
SDL_DestroyTexture(connectText);
SDL_DestroyTexture(ExitText);
SDL_DestroyRenderer(render);
log.close();
TTF_Quit();
SDL_Quit();
}
};
#endif // CAPP_H
| C++ |
#ifndef _MyTimer
#define _MyTimer
#include <ctime>
class MyTimer
{
private:
clock_t start_time;
clock_t end_time;
bool isActive;
public:
MyTimer()
{
start_time = 0;
end_time = 0;
isActive = false;
}
void Start(void)
{
start_time = clock();
isActive = true;
}
void SetActive(bool active)
{
isActive = active;
}
double getDiff(void)
{
if(isActive)
{
double res = (clock() - start_time) / (double)CLOCKS_PER_SEC;
if(res < 40)
return res;
else
return 40;
}
else
return 0;
}
};
#endif
| C++ |
#include <SDL2/SDL.h>
#include "CApp.h"
#undef main
int main(int argc, char *argv[])
{
CApp app;
return app.OnExecute();
}
| C++ |
#ifndef PLAYER1UDPS_H
#define PLAYER1UDPS_H
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
/*****************************************
Согласование отправки данных:
Всего передается 12 байт.
№ Байта | Что там
1, 2 | Координата бруска по Х
2, 3 | Координата бруска по Y
5, 6 | Координата мяча по Х
7, 8 | Координата мяча по Y
9, 10 | Кол-во забитых мячей игроком1
11, 12 | Кол-во забитых мячей игроком2
*****************************************/
class Player1UDPs
{
private:
//WSADATA wsd;
u_int s;
sockaddr_in address;
sockaddr_in remaddr;
bool isWorking;
public:
Player1UDPs()
{
isWorking = false;
}
void Close(void)
{
// WSACleanup();
close(s);
}
void StartServer()
{
/*int iRes = 0;
iRes = WSAStartup(MAKEWORD(2, 2), &wsd);
if (iRes != NO_ERROR)
return;*/
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
return;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);//inet_addr("127.0.0.1");
address.sin_port = htons(5020);
if ((bind(s, (struct sockaddr*)&address, sizeof(address))) < 0)
{
close(s);
return;
}
isWorking = true;
}
void Send(short x, short y, short bx, short by, short score1, short score2)
{
if(!isWorking) return;
short msg[6];
msg[0]=x;
msg[1]=y;
msg[2]=bx;
msg[3]=by;
msg[4]=score1;
msg[5]=score2;
sendto(s, (char*)msg, 12, 0, (sockaddr*)&remaddr, sizeof(remaddr));
}
int* Receive(void)
{
if(!isWorking) return NULL;
char msg[12];
int remaddr_len = sizeof(remaddr);
recvfrom(s, msg, 12, 0, (sockaddr*)&remaddr, (socklen_t*)&remaddr_len);
short* sxy = (short*) msg;
int *xy = new int[6];
xy[0]=(int)sxy[0]; xy[1]=(int)sxy[1];
xy[2]=(int)sxy[2]; xy[3]=(int)sxy[3];
xy[4]=(int)sxy[4]; xy[5]=(int)sxy[5];
return xy;
}
};
#endif // PLAYER1UDPS_H
| C++ |
#ifndef PLAYER2UDPC_H
#define PLAYER2UDPC_H
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
/*****************************************
Согласование отправки данных:
Всего передается 12 байт.
№ Байта | Что там
1, 2 | Координата бруска по Х
2, 3 | Координата бруска по Y
5, 6 | Координата мяча по Х
7, 8 | Координата мяча по Y
9, 10 | Кол-во забитых мячей игроком1
11, 12 | Кол-во забитых мячей игроком2
*****************************************/
class Player2UDPc
{
private:
// WSADATA wsd;
u_int s;
sockaddr_in address;
sockaddr_in remaddr;
bool isWorking;
public:
Player2UDPc()
{
isWorking = false;
}
void Close(void)
{
// WSACleanup();
close(s);
}
void InitAddress(char* ip)
{
/* int iRes = 0;
iRes = WSAStartup(MAKEWORD(2, 2), &wsd);
if (iRes != NO_ERROR)
return;*/
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
return;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(ip);
address.sin_port = htons(5020);
isWorking = true;
}
void Send(short x, short y, short bx, short by, short score1, short score2)
{
if(!isWorking) return;
short msg[6];
msg[0]=x;
msg[1]=y;
msg[2]=bx;
msg[3]=by;
msg[4]=score1;
msg[5]=score2;
sendto(s, (char*)msg, 12, 0, (sockaddr*)&address, sizeof(address));
}
int* Receive(void)
{
if(!isWorking) return NULL;
char msg[12];
int remaddr_len = sizeof(remaddr);
recvfrom(s, msg, 12, 0, (sockaddr*)&remaddr, (socklen_t*)&remaddr_len);
short* sxy = (short*) msg;
int* xy = new int[6];
xy[0]=(int)sxy[0]; xy[1]=(int)sxy[1];
xy[2]=(int)sxy[2]; xy[3]=(int)sxy[3];
xy[4]=(int)sxy[4]; xy[5]=(int)sxy[5];
return xy;
}
};
#endif // PLAYER2UDPC_H
| C++ |
// stdafx.cpp : source file that includes just the standard includes
// myNOD.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| C++ |
// myNOD.cpp : Defines the entry pounsigned int for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <ctime>
using namespace std;
///////////////////////// RECURSIBE NOD //////////////////////////
unsigned int nod(unsigned int x, unsigned int y){
if (y == 0)
return x;
return nod(y, x % y);
}
///////////////////////// RECURSIBE NOD //////////////////////////
unsigned int nodMinus(unsigned int a, unsigned int b) {
while (a != b) {
if (a > b) a -= b;
else b -= a;
}
return a;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int k = 0;
unsigned int nodMy(unsigned int a, unsigned int b)
{
if (a >= b)
{
k = b;
}
else
{
k = a;
}
if (a % 2 == 0 && b % 2 == 0)
{
while (a%k != 0 || b%k != 0)
{
k = k - 2;
}
}
else
{
if (a % 5 == 0 && b % 5 == 0)
{
while (a%k != 0 || b%k != 0)
{
k = k - 5
;
}
}
else
{
while (a%k != 0 || b%k != 0)
{
k = k - 1;
}
}
}
return(k);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
clock_t start;
clock_t end;
unsigned int testArray[] = {242343243,34324234234,432432423,434324234,21321321,31232
,42343242442,42343242343244
,0 };
unsigned int a, b;
//cout << "Enter a,b\n";
///c//in >> a;
///// cin >> b;
unsigned int size,i=0;
while (testArray[i])
{
size = testArray[i];
a = testArray[i];
b = testArray[i+1];
cout << "///////// A= " << a;
cout << " ///////// B= " << b;
cout << "\n";
start = clock();
cout << "NOD with divide: " << nod(a, b) << " Output";
end = clock();
cout << "TIME: " << (end - start) / CLOCKS_PER_SEC << "\n";
start = clock();
cout << "Nod with minus: " << nodMinus(a, b) << " Output";
end = clock();
cout << "TIME: " << (end - start) / CLOCKS_PER_SEC << "\n";
start = clock();
cout << "Nod my: " << nodMy(a, b) << " Output";
end = clock();
cout << "TIME: " << (end - start) / CLOCKS_PER_SEC << "\n";
i +=2;
}
}
| C++ |
// stdafx.cpp : source file that includes just the standard includes
// meraList.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| C++ |
#include "stdafx.h"
#include "SimpleList.h"
///////////////////////////////////////////////////////////////////////
int SimpleList::getLength(){
return length;
}
bool SimpleList::hasNext(){
return (length > curIterator) ? true : false;
}
SimpleList::SimpleList()
{
}
SimpleList::~SimpleList()
{
}
///////////////////////////////////////////////////////////////////////
void SimpleList::append(int element){
SimpleListElement* myElement = new SimpleListElement;
myElement -> value = element;
if (length == 0 ){
firstAdress = myElement;
lastAdress = myElement;
myElement -> nextAdress = myElement;
currIteratorAdress = myElement;
}
else{
SimpleListElement* myTemp = lastAdress;
myTemp ->nextAdress = myElement;
myElement->prevAdress = lastAdress;
lastAdress = myElement;
}
length++;
}
int SimpleList::getValue(){
tempCur = *currIteratorAdress;
if ( tempCur.nextAdress != NULL)
currIteratorAdress = tempCur.nextAdress;
curIterator++;
return tempCur.value;
}
int SimpleList::getValueByNumberOrderByBeginning(int number){
currIteratorAdress = firstAdress;
for (int i = 0; i < number; i++){
tempCur = *currIteratorAdress;
if (tempCur.nextAdress != NULL) currIteratorAdress = tempCur.nextAdress;
curIterator++;
}
currIteratorAdress = firstAdress;
return tempCur.value;
}
int SimpleList::getValueByNumberOrderByEnd(int number){
currIteratorAdress = lastAdress;
for (int i = length; i > length - number; i--){
tempCur = *currIteratorAdress;
if (tempCur.prevAdress != NULL) currIteratorAdress = tempCur.prevAdress;
curIterator++;
}
currIteratorAdress = firstAdress;
return tempCur.value;
}
void SimpleList::pop(int number){
currIteratorAdress = firstAdress;
for (int i = 1; i < number+2; i++){
tempCur = *currIteratorAdress;
if (i == number -1) { forDeletingPrevElement = currIteratorAdress; }
if (i == (number+1) ) forDeletingNextElement = currIteratorAdress;
if (tempCur.nextAdress != NULL) currIteratorAdress = tempCur.nextAdress;
}
// Magic :)
SimpleListElement* myTempDel = forDeletingPrevElement;
myTempDel->nextAdress = forDeletingNextElement;
SimpleListElement* myTempDel2 = myTempDel->nextAdress;
myTempDel2->prevAdress = forDeletingPrevElement;
int result = myTempDel -> value;
currIteratorAdress = firstAdress;
length --;
}
void SimpleList::appendAfter(int element,int position){
currIteratorAdress = firstAdress;//
position++;
SimpleListElement* myElement = new SimpleListElement;
myElement->value = element;
if (length > 0){
//////////////////// MAGIC ///////////
for (int i = 1; i < position + 2; i++){
tempCur = *currIteratorAdress;
if (i == position - 1) { forDeletingPrevElement = currIteratorAdress; }
if (i == (position )) forDeletingNextElement = currIteratorAdress;
if (tempCur.nextAdress != NULL) currIteratorAdress = tempCur.nextAdress;
}
// Magic :)
SimpleListElement* myTempDel = forDeletingPrevElement;
myTempDel->nextAdress = myElement;
SimpleListElement* myTempDel2 = forDeletingNextElement;
myTempDel2->prevAdress = myElement;
myElement->prevAdress = myTempDel;
myElement->nextAdress = myTempDel2;
length++;
}
}
| C++ |
#pragma once
class SimpleListIterator
{
public:
SimpleListIterator();
~SimpleListIterator();
bool hasNext();
};
| C++ |
#include "stdafx.h"
#include "SimpleListIterator.h"
SimpleListIterator::SimpleListIterator()
{
}
SimpleListIterator::~SimpleListIterator()
{
}
bool SimpleListIterator::hasNext(){
return 0;
}
| C++ |
#pragma once
struct SimpleListElement
{
int value;
SimpleListElement* nextAdress=NULL;
SimpleListElement* prevAdress = NULL;
};
class SimpleList
{
private:
int length=0;
SimpleListElement* firstAdress;
SimpleListElement* lastAdress;
SimpleListElement tempCur;
SimpleListElement myTemp;
SimpleListElement myElement ;
SimpleListElement* prevElement;
SimpleListElement* forDeletingPrevElement;
SimpleListElement* forDeletingNextElement;
int curIterator=0;
SimpleListElement* currIteratorAdress=NULL;
public:
bool hasNext();
int getValue();
SimpleList();
~SimpleList();
int getLength();
void SimpleList::pop(int a); // From beginning
int SimpleList::getValueByNumberOrderByBeginning(int number);
int SimpleList::getValueByNumberOrderByEnd(int number);
void append(int el);
void appendToBeginning(int a);
void appendAfter(int a,int b);
};
| C++ |
#include "stdafx.h"
#include "SimpleList.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
SimpleList myList = *new SimpleList();
myList.append(1);
myList.append(2);
myList.append(3);
myList.append(4); // will be poped
myList.append(5);
myList.append(6);
myList.append(7);
myList.append(8);
myList.append(9);
myList.append(10);
myList.append(11);
myList.append(12);
myList.appendAfter(100, 6);
myList.append(44);
myList.appendAfter(1000, 8);
cout << "\nPop <4> element: ";
myList.pop(4);
cout << "\n";
cout << "I'm printing all SimpleList :) \n";
while (myList.hasNext() )
{
cout << "\n " << myList.getValue();
}
cout << "\n\n In the SimpleList there are " << myList.getLength() << " elements\n";
cout << " <4> From beginning: " << myList.getValueByNumberOrderByBeginning(4) << "\n";
cout << " <6> From end: " << myList.getValueByNumberOrderByEnd(6) << "\n";
return 0;
}
| C++ |
// stdafx.cpp : source file that includes just the standard includes
// myNOD.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| C++ |
// myNOD.cpp : Defines the entry pounsigned int for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <ctime>
using namespace std;
///////////////////////// RECURSIBE NOD //////////////////////////
unsigned int nod(unsigned int x, unsigned int y){
if (y == 0)
return x;
return nod(y, x % y);
}
///////////////////////// RECURSIBE NOD //////////////////////////
unsigned int nodMinus(unsigned int a, unsigned int b) {
while (a != b) {
if (a > b) a -= b;
else b -= a;
}
return a;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int k = 0;
unsigned int nodMy(unsigned int a, unsigned int b)
{
if (a >= b)
{
k = b;
}
else
{
k = a;
}
if (a % 2 == 0 && b % 2 == 0)
{
while (a%k != 0 || b%k != 0)
{
k = k - 2;
}
}
else
{
if (a % 5 == 0 && b % 5 == 0)
{
while (a%k != 0 || b%k != 0)
{
k = k - 5
;
}
}
else
{
while (a%k != 0 || b%k != 0)
{
k = k - 1;
}
}
}
return(k);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
clock_t start;
clock_t end;
unsigned int testArray[] = {242343243,34324234234,432432423,434324234,21321321,31232
,42343242442,42343242343244
,0 };
unsigned int a, b;
//cout << "Enter a,b\n";
///c//in >> a;
///// cin >> b;
unsigned int size,i=0;
while (testArray[i])
{
size = testArray[i];
a = testArray[i];
b = testArray[i+1];
cout << "///////// A= " << a;
cout << " ///////// B= " << b;
cout << "\n";
start = clock();
cout << "NOD with divide: " << nod(a, b) << " Output";
end = clock();
cout << "TIME: " << (end - start) / CLOCKS_PER_SEC << "\n";
start = clock();
cout << "Nod with minus: " << nodMinus(a, b) << " Output";
end = clock();
cout << "TIME: " << (end - start) / CLOCKS_PER_SEC << "\n";
start = clock();
cout << "Nod my: " << nodMy(a, b) << " Output";
end = clock();
cout << "TIME: " << (end - start) / CLOCKS_PER_SEC << "\n";
i +=2;
}
}
| C++ |
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void shakeSort(int *a, const int n)
{
int l, r, i, k, buf;
k = l = 0;
r = n - 2;
while(l <= r)
{
for(i = l; i <= r; i++)
if (a[i] > a[i+1])
{
buf = a[i]; a[i] = a[i+1]; a[i+1] = buf;
k = i;
}
r = k - 1;
for(i = r; i >= l; i--)
if (a[i] > a[i+1])
{
buf = a[i]; a[i] = a[i+1]; a[i+1] = buf;
k = i;
}
l = k + 1;
}
} | C++ |
#pragma once
void buble1 (int a[],int size);
#include "stdafx.h"
#include <iostream>
using namespace std;
| C++ |
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void shakeSort(int *a, const int n);
| C++ |
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int* makeArray (int size)
{
int *a = new int[size];
//////////////////////////////////
srand ( (unsigned int)time(NULL) );
for (int i = 0; i < size; i++)
{
// a[i]=(rand() % 100) * (rand() % 10) + rand() % 1000;
a[i]=(rand() % 100000);
}
return a;
} | C++ |
#include "stdafx.h"
#include <iostream>
using namespace std;
void buble1 (int a[],int size)
{
////
for (int i = 0; i < size; i++)
{
for (int j = size - 1; j > i; j--)
{
if (a[j] < a[j - 1])
{
swap (a[j], a[j - 1]);
}
}
}
//for (int i = 0; i < size; i++)
// {
/// cout << a[i] << ' ';
/// }
} | C++ |
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void quickSort(int*a,int l, int r);
| C++ |
#include "stdafx.h"
#include <iostream>
using namespace std;
void buble2( int a[], int size )
{
int max;
int temp = size - 1;
for ( int i = 0; i < size; i++, temp-- )
{
max = 0;
for ( int j = 0; j <= temp; j++ )
if ( a[ j ] > a[ max ] )
max = j;
swap ( a[ max ], a[ temp ] );
}
} | C++ |
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void quickSort(int* s_arr, int first, int last)
{
int i = first, j = last, x = s_arr[(first + last) / 2];
do {
while (s_arr[i] < x) i++;
while (s_arr[j] > x) j--;
if(i <= j) {
if (i < j) swap(s_arr[i], s_arr[j]);
i++;
j--;
}
} while (i <= j);
if (i < last)
quickSort(s_arr, i, last);
if (first < j)
quickSort(s_arr, first,j);
} | C++ |
#pragma once
void buble2 (int a[],int size);
#include "stdafx.h"
#include <iostream>
using namespace std;
| C++ |
// stdafx.cpp : source file that includes just the standard includes
// heapMera.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| C++ |
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
static void siftDown(int *a, int i, int j);
int* makeArray(int size)
{
int *a = new int[size];
//////////////////////////////////
srand((unsigned int)time(NULL));
for (int i = 0; i < size; i++)
{
// a[i]=(rand() % 100) * (rand() % 10) + rand() % 1000;
a[i] = (rand() % 100000);
}
return a;
}
/////////////////////////////////////////////////////////////////////////////////////////////
static void HeapSort(int * a,int size)
{
int i;
int temp;
for (i = (size / 2) - 1; i >= 0; i--)
{
siftDown(a, i, size);
}
for (i = size - 1; i >= 1; i--)
{
temp = a[0];
a[0] = a[i];
a[i] = temp;
siftDown(a, 0, i - 1);
}
}
static void siftDown(int *a, int i, int j)
{
bool done = false;
int maxChild;
int temp;
while ((i * 2 < j) && (!done))
{
if (i * 2 == j)
maxChild = i * 2;
else if (a[i * 2] > a[i * 2 + 1])
maxChild = i * 2;
else
maxChild = i * 2 + 1;
if (a[i] < a[maxChild])
{
temp = a[i];
a[i] = a[maxChild];
a[maxChild] = temp;
i = maxChild;
}
else
{
done = true;
}
}
}
///////////////////////////////////////
int _tmain(int argc, _TCHAR* argv[])
{
const int size = 40;
int *a = makeArray(size);
HeapSort(a, size);
for (int i = 0; i < size; i++){
std::cout << a[i] << "\n";
}
return 0;
}
| C++ |
#include "Sort.h"
#include <stdlib.h>
void shSwap(int* Arr, int i)
{
int temp;
temp = Arr[i];
Arr[i] = Arr[i - 1];
Arr[i - 1] = temp;
}
void ShakerSort(int* Arr, int Start, int N)
{
int Left, Right;
Left = Start;
Right = N - 1;
do
{
for (int i = Right; i >= Left; i--)
{
if (Arr[i - 1] > Arr[i])
{
shSwap(Arr, i);
}
}
Left = Left + 1;
for (int i = Left; i <= Right; i++)
{
if (Arr[i - 1] > Arr[i])
{
shSwap(Arr, i);
}
}
Right = Right - 1;
} while (Left <= Right);
}
void swap(int* a, int* b)
{
int buf = *a;
*a = *b;
*b = buf;
}
void NaiveSort(int* arr, int length)
{
int i, j;
for (i = length - 1; i > 0; i--)
{
for (j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
}
}
void BubbleSort(int* arr, int length)
{
int i, j, flag;
for (i = length - 1; i > 0; i--)
{
flag = 0;
for (j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
{
swap(&arr[j], &arr[j + 1]);
flag = 1;
}
}
if (!flag) return;
}
}
int _cmp_int(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
void qsort_common(int* arr, int length)
{
qsort(arr, length, sizeof(int), _cmp_int);
}
void ShakerSort_common(int* arr, int length)
{
ShakerSort(arr,0, length);
} | C++ |
#include "Sort.h"
#include <stdlib.h>
void shSwap(int* Arr, int i)
{
int temp;
temp = Arr[i];
Arr[i] = Arr[i - 1];
Arr[i - 1] = temp;
}
void ShakerSort(int* Arr, int Start, int N)
{
int Left, Right;
Left = Start;
Right = N - 1;
do
{
for (int i = Right; i >= Left; i--)
{
if (Arr[i - 1] > Arr[i])
{
shSwap(Arr, i);
}
}
Left = Left + 1;
for (int i = Left; i <= Right; i++)
{
if (Arr[i - 1] > Arr[i])
{
shSwap(Arr, i);
}
}
Right = Right - 1;
} while (Left <= Right);
}
void swap(int* a, int* b)
{
int buf = *a;
*a = *b;
*b = buf;
}
void NaiveSort(int* arr, int length)
{
int i, j;
for (i = length - 1; i > 0; i--)
{
for (j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
}
}
void BubbleSort(int* arr, int length)
{
int i, j, flag;
for (i = length - 1; i > 0; i--)
{
flag = 0;
for (j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
{
swap(&arr[j], &arr[j + 1]);
flag = 1;
}
}
if (!flag) return;
}
}
int _cmp_int(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
void qsort_common(int* arr, int length)
{
qsort(arr, length, sizeof(int), _cmp_int);
}
void ShakerSort_common(int* arr, int length)
{
ShakerSort(arr,0, length);
}
| C++ |
#include "stdafx.h"
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include <iostream>
#include <windows.h>
#include<locale.h>
#include<malloc.h>
#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
void merge(int *mas,int a,int c)
{
int *rez=(int*)malloc(sizeof(int)*(c+1));
if(a<c)
{
int x=(a+c)/2;
merge(mas,a,x); merge(mas,x+1,c);
int n1=a,n2=x+1;
for (int i=a;i<=c;i++)
{
if ((n1<x+1)&&((n2>c)||mas[n1]<mas[n2]))
{
rez[i]=mas[n1];n1++;
}
else
{
rez[i]=mas[n2];
n2++;
}
}
for (int i=a;i<=c;i++)
{
mas[i]=rez[i];
}
}
free(rez);
};
int main(int argc, char* args[])
{
srand(time(NULL));
int a=0,c=5;
int mas[6];
for (int i=0;i<=c;i++)
{
mas[i]=0+rand()%10;
printf("%d ",mas[i]);
}
merge(mas,a,c);
printf("\n");
for (int i=0;i<=c;i++)
{
printf("%d ",mas[i]);
}
//int* mas=(int*)malloc(sizeof(6*int));
return 0;
} | C++ |
// fact.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int a, b;
printf("vvedite 2 chisla ");
scanf("%d",&a);
scanf("%d",&b);
//if (a>b)
//{
a=a-b;
b=b+a;
a=b-a;
/*}
if (b>a)
{
b=b-a;
a=a+b;
b=a-b;
}*/
printf("zamena, %d, %d\n", a, b);
return 0;
}
| C++ |
#include "stdafx.h"
#include <stdio.h>
#include <cstdlib>
int main()
{
int i, j;
int k;
int arr[200000];
srand(5);
for (int i=0; i<=(199999); i++)
arr[i]=rand()%1000;
printf("%d, ",arr[i]);
printf( "\n");
for (int i=0; i<=(199998); i++)
for (int j=0; j<=(199998); j++)
if (arr[j]>arr[j+1])
{
k=arr[j];
arr[j]=arr[j+1];
arr[j+1]=k;
}
for (int i=0; i<=9; i++)
printf("%d, ",arr[i]);
return 0;
}
| C++ |
// heapSort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
using namespace std;
void heapifier (int *arr, int i, int size)
{int done=0;
int c,k=0;
int maxChild;
//int temp;
while((i*2<size)&&(!done))
{
if (i*2==size)
maxChild=i*2;
else
{if (arr[i*2]>arr[i*2+1])
maxChild=i*2;
else maxChild=i*2+1;
}
if (arr[i]<arr[maxChild])
{
c=arr[i];
arr[i]=arr[maxChild];
arr[maxChild]=c;
i=maxChild;
}
else done=1;
}
for(int k=0; k<size;k++)
{
printf("%d ",arr[k]);
}
printf("\n");
}
void heapsort (int *arr, int size)
{
int i;
int c;
for (i=(size/2)-1;i>=0;i--)
{
heapifier(arr,i,size);
}
for (i=size-1;i>=1;i--)
{
c=arr[0];
arr[0]=arr[i];
arr[i]=c;
heapifier(arr,0,i-1);
}
}
int _tmain(int argc, _TCHAR* argv[])
{int n;
int arr[10];
printf("vvedite kolichestvo elementov");
cin>>n;
srand((unsigned) time(NULL));
for(int i=0;i<n;i++)
{
arr[i]=rand()%100;
printf("%d ", arr[i]);
}
printf("\n");
heapsort (arr, n);
for(int i=0; i<n;i++)
{
printf("%d ", arr[i]);
}
return 0;
}
| C++ |
// sv_sp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
using namespace std;
struct Link
{
int x;
struct Link*next;
} *head,*end;
Link *creat(int n)
{Link *head,*end ;
if (n)head=new Link;
head->x=n;
end=head;
n--;
while (n>0)
{
end->next=new Link;
end=end->next;
end->x=n;
end->next=NULL;
n--;
}
return head;
}
Link *creat_unsort(int n)
{Link *head,*end ;
srand((unsigned) time(NULL));
if (n)head=new Link;
head->x=n;
end=head;
n--;
while (n>0)
{
end->next=new Link;
end=end->next;
end->x=rand()%n;
end->next=NULL;
n--;
}
return head;
}
void print(Link *end)
{
while (end->next)
{
cout<<end->x<<'\t';
//printf("%d\n",end->x);
end=end->next;
}
cout<<end->x;
}
void add(Link *head, int x, int y)
{Link *v,*p=head;
while (p->next)
{
if (p->x==y)
{
v=new struct Link;
v->x=x;
v->next=p->next;
p->next=v;
return;
}
else p=p->next;
}
}
int count(struct Link *head, int k)
{struct Link*pr=head;
while (pr)
{k++;
pr=pr->next;
}
return k;
}
/*int access(struct Link *head, int i)
{
struct Link *point=head;
while(i)
{
i--;
point=point->next;
}
return point;
}*/
struct Link *del(Link *b,int x)
{
Link *d;
if (b->x==x)
{
d=b;
b=b->next;
delete d;
return b;
}
Link *p=b;
while (p->next)
{
if (p->next->x==x)
{
d=p->next;
p->next=p->next->next;
delete d;
return b;
}
p=p->next;
}
return b;
}
int main()
{
{
struct Link *head;*end;
int n,x,y,m,i;
//struct Link *ipointer;
m=0;
//printf("vvedite n");
//scanf("%d",&n);
cin>>n;
cin>>x;
cin>>y;
printf("vvedite iscomoe pole");
cin>>i;
head=creat(n);
//ipointer=access(head,i);
m=count(head,m);
printf("%d\n",m);
//printf("%d\n", ipointer);
add(head,x,y);
print(head);
printf("\n");
m=0;
m=count(head,m);
printf("%d\n",m);
del(head,y);
print(head);
printf("\n");
m=0;
m=count(head,m);
printf("%d\n",m);
//getch();
}
return 0;
}
| C++ |
// Factorial.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
int factorial(int n)
{
if (n<=1)
return 1;
else
return n*factorial(n-1);
}
int _tmain(int argc, _TCHAR* argv[])
{
int n,nr;
printf("vvedite n ");
scanf("%d",&n);
nr=factorial(n);
printf("%d",nr);
return 0;
}
| C++ |
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
void Swap(int elem1, int elem2)
{int c;
c=elem1;
elem1=elem2;
elem2=c;
}
void ShakerSort(int arr[], int beg, int n)
{
int L, R;
L= beg;
R=n-1;
while (L<=R)
{
for (int i=R; i>L; i--)
{
if (arr[i]<arr[i - 1])
Swap(arr[i], arr[i-1]);
}
L= L+ 1;
for (int i = L; i < R; i++)
{
if (arr[i] > arr[i + 1])
Swap(arr[i], arr[i + 1]);
}
R= R- 1;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[100];
int i;
int n;
srand((unsigned) time(NULL));
printf("vvedite razmer massiva");
cin>>n;
for (i=0;i<n;i++)
{
arr[i]=rand()%100;
printf("%d ",arr[i]);
}
ShakerSort(arr,0,n);
for (i=0;i<n;i++);
printf("%d ",arr[i]);
return 0;
}
| C++ |
// hanoy.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
void hanoy(int num, char a, char b, char c, int &s)
{
if (num>0)
{
hanoy(num-1, a,c, b,s);
printf("%c--->%c\n ", a, c);
s++;
hanoy(num-1,b, a, c,s);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char a, b, c;
int num;
int s=0;
printf("number of rings=");
scanf("%d", &num);
a='A';
b='B';
c='C';
hanoy(num, a, b, c,s);
printf("%d\n, shagov", s);
return 0;
}
| C++ |
//5 functions of D-LIST!!!!!!!!!!!!!!!!!!!!
//append_to_end is very simpler than in s-list!!!
//but create_elem became more difficult
#include <iostream>
#include <stdlib.h>
using namespace std;
struct Elem
{
Elem* next;
Elem* prev;
int value;
};
struct List
{
Elem* head;
Elem* tail;
int len;
};
//I don't know how, but everything works fine without typedef
List* create_list()
{
List* list = (List*) malloc (sizeof(List));
list->head=0;
list->len=0;
return list;
}
Elem* create_elem(List* list, int val) //need list for testing about fill!!!
{
Elem* elem = (Elem*) malloc (sizeof(Elem));
elem->next=0;
elem->value=val;
//now will be dawn work with prev
if (list->head!=0) //if list is not empty
{
elem->prev=list->tail; //set tail
list->tail->next=elem; //connect with previos element
list->tail=elem; //move tail
}
else //if list is empty
{
elem->prev=0; //previous element not exist, then prev=NULL
list->head=list->tail=elem;
}
return elem;
}
void append_to_begin(List* list, Elem* elem) //as in s-list!
{
elem->next=list->head;
list->head=elem;
list->len++;
}
void append_to_end(List* list, Elem* elem) //very much better than in s-list!!!!!!!!!!!
{
list->tail->next=elem;
list->tail=elem;
list->len++;
}
void insert_after(List* list, Elem* elem, int x) //as in s-list, but it could be written differently
{
Elem* d=list->head;
for(int i=1;i<x;i++) //go to x from head
d=d->next; //
elem->next=d->next;
d->next=elem;
list->len++;
}
void print(List* list) //as in s-list!
{
Elem* d=list->head;
for(int i=1;i<=(list->len);i++)
{
cout<<d->value<<" ";
d=d->next;
}
cout<<endl;
}
void give_freedom(List* list) //as in s-list!
{
Elem* d=0;
for(int i=1;i<=list->len;i++)
{
d=list->head->next;
free(list->head);
list->head=d;
}
free(list);
}
int main()
{
List* spisok=create_list();
for(int i=2;i<=10000;i+=i)
{
Elem* d=create_elem(spisok, i);
append_to_end(spisok, d);
}
print(spisok);
cout<<"length1="<<spisok->len<<endl; //I didn't make function for this
Elem* d=create_elem(spisok, 228);
insert_after(spisok, d, 10);
print(spisok);
cout<<"length2="<<spisok->len<<endl;
give_freedom(spisok);
return 0;
} | C++ |
//rnd i can make later
#include <iostream>
using namespace std;
#define maxn 100
int a[maxn];
int n;
void merge(int l, int r) {
if (r == l)
return;
if (r - l == 1) {
if (a[r] < a[l])
swap(a[r], a[l]);
return;
}
int m = (r + l) / 2;
merge(l, m);
merge(m + 1, r);
int buf[maxn];
int xl = l;
int xr = m + 1;
int cur = 0;
while (r - l + 1 != cur) {
if (xl > m)
buf[cur++] = a[xr++];
else if (xr > r)
buf[cur++] = a[xl++];
else if (a[xl] > a[xr])
buf[cur++] = a[xr++];
else buf[cur++] = a[xl++];
}
for (int i = 0; i < cur; i++)
a[i + l] = buf[i];
}
int main() {
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
merge(0, n - 1);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout<<endl;
return 0;
} | C++ |
//xchg in d-list with sentinel
//2 situations (elements are near / elements are far)
//if you read this code, so soon I'll create the list-sort ^_^
#include <iostream>
#include <stdlib.h>
#include <iomanip> //for setw
using namespace std;
struct Elem
{
Elem* next;
Elem* prev;
int value;
};
struct List
{
Elem* head;
Elem* tail;
int len;
};
//I don't know how, but everything works fine without typedef
List* create_list()
{
List* list = (List*) malloc (sizeof(List));
list->head=0;
list->len=0;
return list;
}
Elem* create_elem(List* list, int val) //need list for testing about fill!!!
{
Elem* elem = (Elem*) malloc (sizeof(Elem));
elem->next=0;
elem->value=val;
//now will be dawn work with prev
if (list->head!=0) //if list is not empty
{
elem->prev=list->tail; //set tail
list->tail->next=elem; //connect with previos element
list->tail=elem; //move tail
}
else //if list is empty
{
elem->prev=0; //previous element not exist, then prev=NULL
list->head=list->tail=elem;
}
return elem;
}
void append_to_begin(List* list, Elem* elem) //as in s-list!
{
elem->next=list->head;
list->head=elem;
list->len++;
}
void append_to_end(List* list, Elem* elem) //very much better than in s-list!!!!!!!!!!!
{
list->tail->next=elem;
list->tail=elem;
list->len++;
}
void insert_after(List* list, Elem* elem, int x) //as in s-list, but it could be written differently
{
Elem* d=list->head;
for(int i=1;i<x;i++) //go to x from head
d=d->next; //
elem->next=d->next;
d->next=elem;
list->len++;
}
void print(List* list) //as in s-list!
{
Elem* d=list->head;
for(int i=1;i<=(list->len);i++)
{
cout<<setw(10)<<d->value;
d=d->next;
}
cout<<endl;
cout<<endl;
}
void give_freedom(List* list) //as in s-list!
{
Elem* d=0;
for(int i=1;i<=list->len;i++)
{
d=list->head->next;
free(list->head);
list->head=d;
}
free(list);
}
///////////////////////////////////////////////////////////////
List* xchg(List* list, int a, int b)
{
Elem* curr=list->head->prev; //sentinel
Elem* min=list->head->prev; //sentinel
Elem* precurr=0;
Elem* postcurr=0;
Elem* premin=0;
Elem* postmin=0;
for(int i=1; i<=a; i++) //set curr and min from a and b
curr=curr->next;
for(int i=1; i<=b; i++)
min=min->next;
if (a>b) //protection of fools
{
a+=b;
b=a-b;
a-=b;
}
if (abs(a-b)>1) //elements are far
{
precurr=curr->prev;
postcurr=curr->next;
premin=min->prev;
postmin=min->next;
precurr->next=min; //8 changes of pointers
postcurr->prev=min;
premin->next=curr;
postmin->prev=curr;
curr->next=postmin;
curr->prev=premin;
min->next=postcurr;
min->prev=precurr;
}
else //elements are near
{
precurr=curr->prev;
postmin=min->next;
precurr->next=min; //6 changes of pointers
postmin->prev=curr;
curr->next=postmin;
curr->prev=min;
min->next=curr;
min->prev=precurr;
}
if (a==1) // !!!!!!!!!!!!! head and tail recovery !!!!!!!!!!!!!!!
list->head=min; //I could not think of this for a long time:(
if (b==list->len) //
list->tail=curr; //
return list;
}
int main()
{
List* spisok=create_list();
for(int i=2;i<=10000;i+=i)
{
Elem* d=create_elem(spisok, i);
append_to_end(spisok, d);
}
Elem* sentinel = (Elem*) malloc (sizeof(Elem)); //creating the sentinel!
sentinel->next=spisok->head; //
sentinel->prev=spisok->tail; //
sentinel->value=666; //
spisok->head->prev=sentinel; //
spisok->tail->next=sentinel; //
//cout<<spisok->head->prev->value<<endl; //look to sentinel!
print(spisok);
spisok=xchg(spisok, 3, 5);
print(spisok);
//cout<<spisok->len<<endl;
give_freedom(spisok);
return 0;
} | C++ |
//for adequate results in the diagram, for all the functions used by sleep(3)
#include <stdio.h>
#include<conio.h>
#include<time.h>
#include<windows.h>
#include<iostream>
#include <stdlib.h>
//#include <math.h> //for operations on long long
using namespace std;
void Sleep(BYTE time) //because the usual sleep not working:(
{
Sleep((DWORD)time*1000);
return;
}
void sub(long long a, long long b) //this is VYCHITANIE
{
long t1,t2;
t1=clock();
while (a!=b)
if (a>b)
a=a-b;
else
b=b-a;
//unsigned int i=3000;
//sleep(i);
Sleep((BYTE)3);
t2=clock();
cout<<"vychitanie time - "<<t2-t1<<"ms"<<endl;
//cout<<"NOD="<<a;
}
void evcl( long long a, long long b) //this is DELENIE
{//in the comments of many experiences with double
long t1,t2;
t1=clock();
while (a!=0 && b!=0)
if (a>b)
a=a%b;
//a = fmod (a,b);
else
b=b%a;
//b = fmod (b,a);
//unsigned long i=3000;
//sleep(i);
Sleep((BYTE)3);
t2=clock();
cout<<"delenie time - "<<t2-t1<<"ms"<<endl;
//cout.setf(ios_base::fixed); //for simple display of number (for double)
//cout.precision(0); //for 0 numbers after comma
//cout<<"NOD="<<a+b;
}
void nvnst( long long a, long long b) //this is NAIVNOST'
{
long long c,max,min;
long t1,t2;
if (a>=b)
{
max=a;
min=b;
}
else
{
max=b;
min=a;
}
c=min;
t1=clock();
do
{
if (max%c==0 && min%c==0)
{
//cout<<"NOD="<<c<<endl;
break;
}
else
c--;
}
while (c>0);
Sleep((BYTE)3);
t2=clock();
cout<<"naivnost' time - "<<t2-t1<<"ms"<<endl;
}
int pain()
{
long long a,b;
cout<<endl<<"A:";
cin>>a;
cout<<"B:";
cin>>b;
nvnst(a,b);
evcl(a,b);
sub(a,b);
return 0;
}
int main()
{
pain();
pain();
pain();
pain();
pain();
cout<<endl<<"Click to exit...";
getchar();
getchar();
} | C++ |
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
unsigned long long d=0;
long func(int n)
{
return n > 0 ? d=n*func(n-1) : 1;
}
int main(int argc, char *argv[])
{
int a=atoi(argv[1]);
//printf("%d\n", func(a));
func(a);
if (d>=18446744071562067968)
cout<<"too much!"<<endl;
cout<<d<<endl;
return 0;
}
| C++ |
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
unsigned long long d;
int func(int n)
{
if (n<=2)
return 1;
if (d>14446744073709551615)
cout<<"too much!"<<endl;
return d=func(n-1)+func(n-2);
}
int main(int argc, char *argv[])
{
int a=atoi(argv[1]);
//printf("%d\n", func(a));
func(a);
cout<<d<<endl;
return 0;
}
| C++ |
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
unsigned long long d=1;
int main(int argc, char *argv[])
{
int a=atoi(argv[1]);
for (int i=1; i<=a; i++)
d*=i;
if (d>14446744073709551615)
cout<<"too much!"<<endl;
cout<<d<<endl;
return 0;
}
| C++ |
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
unsigned long long d;
int fib_n(int n)
{
if (n <= 2) return 1;
//F(n-2)
int x = 1;
//F(n-1)
int y = 1;
//F(n)
int ans = 0;
for (int i = 2; i <= n; i++)
{
ans = x + y;
x = y;
y = ans;
}
if (d>10446744073709551615)
cout<<"too much!"<<endl;
return d=ans;
}
int main(int argc, char *argv[])
{
int n=atoi(argv[1]);
fib_n(n-1);
cout<<d<<endl;
return 0;
}
| C++ |
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef unsigned long long ull;
int fib(int n)
{
ull a = 1, ta,
b = 1, tb,
c = 1, rc = 0, tc,
d = 0, rd = 1;
while (n)
{
if (n & 1)
{
tc = rc;
rc = rc*a + rd*c;
rd = tc*b + rd*d;
}
ta = a; tb = b; tc = c;
a = a*a + b*c;
b = ta*b + b*d;
c = c*ta + d*c;
d = tc*tb+ d*d;
n >>= 1;
}
return rc;
}
int main(int argc, char *argv[])
{
int n=atoi(argv[1]);
cout<<fib(n)<<endl;
return 0;
} | C++ |
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
unsigned long long d;
int a[500];
int func(int n)
{
if (n<=2)
return 1;
if (a[n]==0)
a[n]=func(n-1)+func(n-2);
if (>=18446744071562067968)
cout<<"too much!"<<endl;
return d=a[n];
}
int main(int argc, char *argv[])
{
int n=atoi(argv[1]);
//printf("%d\n", func(a));
func(n);
cout<<d<<endl;
//t:
return 0;
}
| C++ |
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
main()
{
int a=1;
int b=2;
a+=b;
b=a-b;
a-=b;
cout<<a<<","<<b<<endl;
return 0;
} | C++ |
//5 functions of s-list
#include <iostream>
#include <stdlib.h>
using namespace std;
struct Elem
{
Elem* next;
int value;
};
struct List
{
Elem* head;
int len;
};
//I don't know how, but everything works fine without typedef
List* create_list()
{
List* list = (List*) malloc (sizeof(List));
list->head=0;
list->len=0;
return list;
}
Elem* create_elem(int val)
{
Elem* elem = (Elem*) malloc (sizeof(Elem));
elem->next=0;
elem->value=val;
return elem;
}
void append_to_begin(List* list, Elem* elem)
{
elem->next=list->head;
list->head=elem;
list->len++;
}
void append_to_end(List* list, Elem* elem)
{
Elem* d=list->head;
while(d->next) //go to tail
d=d->next; //
d->next=elem;
list->len++;
}
void insert_after(List* list, Elem* elem, int x)
{
Elem* d=list->head;
for(int i=1;i<x;i++) //go to x
d=d->next; //
elem->next=d->next;
d->next=elem;
list->len++;
}
void print(List* list)
{
Elem* d=list->head;
for(int i=1;i<=(list->len);i++)
{
cout<<d->value<<" ";
d=d->next;
}
cout<<endl;
}
void give_freedom(List* list)
{
Elem* d=0;
for(int i=1;i<=list->len;i++)
{
d=list->head->next;
free(list->head);
list->head=d;
}
free(list);
}
int main()
{
List* spisok=create_list();
Elem* d=create_elem(2); //I want to put elements to tail of list
append_to_begin(spisok, d); //but I can not append_to_end while list is empty
for(int i=4;i<=10000;i+=i)
{
Elem* d=create_elem(i);
append_to_end(spisok, d);
}
print(spisok);
cout<<"length1="<<spisok->len<<endl; //I didn't make function for this
d=create_elem(228);
insert_after(spisok, d, 10);
print(spisok);
cout<<"length2="<<spisok->len<<endl;
give_freedom(spisok);
return 0;
} | C++ |
#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
void heapifier(int *a, int i, int size)
{
int done=0;
int maxChild;
while((i*2<size)&&(!done))
{
if (i*2==size)
maxChild=i*2;
else if(a[2*i]>a[2*i+1])
maxChild=i*2;
else maxChild=i*2+1;
if (a[i]<a[maxChild])
{
int temp;
temp=a[i];
a[i]=a[maxChild];
a[maxChild]=temp;
i=maxChild;
}
else done=1;
}
}
void HeapSort(int *a, int size)
{
for(int i=size/2-1;i>=0;i--)
heapifier(a,i,size);
for(int i=size-1;i>=1;i--)
{
int temp;
temp=a[0];
a[0]=a[i];
a[i]=temp;
heapifier(a,0,i-1);
}
}
int main(int argc, char* args[])
{
srand(time(NULL));
const int size=10;
int i,a[size];
for(i=0;i<size;i++)
{
a[i]=rand()%100;
printf("%d ",a[i]);
};
printf("\n");
HeapSort(a, size);
for(i=0;i<size;i++)
printf("%d ",a[i]);
} | C++ |
#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
#include "stdio.h"
int _tmain(int argc, _TCHAR* argv[])
{
int difn[5]={2000,4000,8000,10000,100000},k,label;
long n,i,j,t;
long int mas[100000];
srand(9);
for (k=0;k<5;k++) //главный цикл, который подставляет в n разные значения из массива difn
{n=difn[k];
printf("chisel: %d\n",n);
//////////////////////////////////////////////////////////////////////////////////////
for (i=0;i<n;i++) //генерирую массив случайных чисел
{
mas[i]=rand() % 10;
}
long t1=clock(); //считываю время перед циклом
for (i=1;i<n;i++) //сортирую
for (j=0;j<n-1;j++)
{
if (mas[j]>mas[j+1])
{t=mas[j];mas[j]=mas[j+1];mas[j+1]=t;}
}
long t2=clock(); //считываю время после завершения цикла
printf("sort1: %d\n",(t2-t1)); //вывожу время работы цикла
///////////////////////////////////////////////////////////////////////////////////////
for (i=0;i<n;i++)
{
mas[i]=rand() % 10;
}
t1=clock();
for (i=1;i<n;i++) //всё то же самое, но для улучшенной сортировки пузырьком
{ label=0;
for (j=0;j<n-i;j++)
{
if (mas[j]>mas[j+1])
{t=mas[j];mas[j]=mas[j+1];mas[j+1]=t;label=1;}
}
if(label==0) i=n-1;
}
t2=clock();
printf("sort2: %d\n",(t2-t1));
/////////////////////////////////////////////////////////////////////////
for (i=0;i<n;i++)
{
mas[i]=rand() % 10;
}
t1=clock();
do
{label=0;
for (i=0;i<n-2;i++)
{ if (mas[i]>mas[i+1])
{t=mas[i];mas[i]=mas[i+1];mas[i+1]=t;label=1;}
}
if(label==0) break;
for (i=n-2;i>0;i--)
{ if (mas[i]>mas[i+1])
{t=mas[i];mas[i]=mas[i+1];mas[i+1]=t;label=1;}
}}
while(label);
t2=clock();
printf("sort3: %d\n",(t2-t1));}
/////////////////////////////////////////////////////////////////////////
return 0;
}
| C++ |
#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
struct Element
{
Element* next;
int value;
};
struct LinkedList
{
Element* head;
int length;
};
LinkedList* create_list()
{
LinkedList* list = (LinkedList*)malloc(sizeof(LinkedList));
list->head=NULL;
list->length=0;
return list;
}
Element* create_elem(int value)
{
Element* elem = (Element*)malloc(sizeof(Element));
elem->next=NULL;
elem->value=value;
return elem;
}
void append_to_begin(LinkedList* list, Element* elem)
{
elem->next=list->head;
list->head=elem;
list->length++;
}
void append_to_end(LinkedList* list, Element* elem)
{
Element* el = list->head;
if(el==NULL)
{list->head=elem;}
else
{while(el->next)
el=el->next;
elem->next=NULL;
el->next=elem;}
list->length++;
}
int get_size(LinkedList* list)
{
return list->length;
}
struct Element* find_el(LinkedList* list, int pos)
{
if(pos>(list->length))
{
printf("\nelement not found\n");
return 0;
}
else
{
struct Element* el=list->head;
for(int i=1;i<pos;i++)
{
el=el->next;
}
return el;
}
}
void insert_after(LinkedList* list, int pos, Element* elem)
{
Element* el = list->head;
for(int i=1;i<pos;i++)
el=el->next;
elem->next=el->next;
el->next=elem;
list->length++;
}
void clear_el(LinkedList* list, Element* elem)
{
struct Element* el = list->head;
struct Element* prev = NULL;
for(int i=1;i<=(list->length);i++)
{
if(elem==el)
{ if(prev==NULL)
list->head=el->next;
else
prev->next=prev->next->next;
free(elem);
list->length--;
break;
}
prev=el;
el=el->next;
}
}
void clear_elem(LinkedList* list, int pos)
{
Element* el = find_el(list,pos);
clear_el(list,el);
}
void clear_list(LinkedList* list)
{
Element* temp=NULL;
Element* el = list->head;
for(int i=1;i<=list->length;i++)
{
temp=el->next;
free(el);
el=temp;
}
free(list);
}
void print_list(LinkedList* list)
{
Element* el = list->head;
for(int i=1;i<(list->length);i++)
{
printf("%d ",el->value);
el=el->next;
}
printf("%d\n",el->value);
}
int* convert_to_array(LinkedList* list)
{
int* arr = (int*)malloc(sizeof(int)*(list->length));
struct Element* el=list->head;
for(int i=0;i<(list->length);i++)
{
arr[i]=el->value;
el=el->next;
}
return arr;
}
struct Element* find_max(LinkedList* list)
{
struct Element* el=list->head;
struct Element* maxel=list->head;
int max=maxel->value;
for(int i=1;i<=(list->length);i++)
{
if(max<(el->value))
{
maxel=el;
max=el->value;
}
el=el->next;
}
return maxel;
}
struct Element* find_min(LinkedList* list)
{
struct Element* el=list->head;
struct Element* maxel=list->head;
int max=maxel->value;
for(int i=1;i<=(list->length);i++)
{
if(max>(el->value))
{
maxel=el;
max=el->value;
}
el=el->next;
}
return maxel;
}
void swap(LinkedList* list,Element* a,Element* b)
{
Element* temp;
if(a->next==NULL)
{temp=a;a=b;b=temp;}
Element* preva=list->head;
if(preva==a)
preva=NULL;
else
while(preva->next!=a)
preva=preva->next;
Element* posta=a->next;
Element* prevb=list->head;
while(prevb->next!=b)
prevb=prevb->next;
Element* postb=b->next;
if(a->next==b)
{
if(preva==NULL)
list->head=b;
else
preva->next=b;
b->next=a;
a->next=postb;
}
else
{
if(preva==NULL)
{b->next=posta;
list->head=b;}
else
{preva->next=b;
b->next=posta;}
prevb->next=a;
a->next=postb;
}
}
void sorting(LinkedList* list)
{
Element* curr=list->head;
Element* place=list->head;
Element* min=list->head;
for(int j=0;j<(list->length-1);j++)
{
for(int i=j+1;i<(list->length+1);i++)
{
if((curr->value)<(min->value))
min=curr;
curr=curr->next;
}
swap(list,place,min);
place=min->next;
curr=min->next;
min=min->next;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
struct LinkedList* klen=create_list();
srand(time(NULL));
for(int i=1;i<=10;i++)
{
struct Element* cherv=create_elem(rand()%100);
append_to_begin(klen, cherv);
}
print_list(klen);
sorting(klen);
print_list(klen);
return 0;
}
| C++ |
#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
struct Elem
{
Elem* next;
Elem* prev;
int value;
};
struct DList
{
Elem* head;
Elem* tail;
int size;
};
DList* createDList()
{
DList* dl=(DList*)malloc(sizeof(DList));
dl->head=NULL;
dl->tail=NULL;
dl->size=0;
return dl;
}
Elem* createElem(int value)
{
Elem* el=(Elem*)malloc(sizeof(Elem));
el->next=NULL;
el->prev=NULL;
el->value=value;
return el;
}
void append_to_begin(DList* list, Elem* elem)
{
if(list->tail==NULL)
list->tail=elem;
elem->next=list->head;
//elem->prev=NULL;
list->head=elem;
if(elem->next!=NULL)
elem->next->prev=elem;
if(elem->prev!=NULL)
elem->prev->next=elem;
list->size++;
}
void append_to_end(DList* list, Elem* elem)
{
if(list->head==NULL)
list->head=elem;
elem->prev=list->tail;
list->tail=elem;
if(elem->prev!=NULL)
elem->prev->next=elem;
if(elem->next!=NULL)
elem->next->prev=elem;
list->size++;
}
struct Elem* findElem(DList* list,int pos)
{
Elem* elem=list->head;
for(int i=2;i<=pos;i++)
elem=elem->next;
return elem;
}
void print_list(DList* list)
{
Elem* el = list->head;
for(int i=1;i<(list->size);i++)
{
printf("%d ",el->value);
el=el->next;
}
printf("%d\n",el->value);
}
int find_pos(DList* list, Elem* el)
{
Elem* curr=list->head;
for(int i=1;i<=list->size;i++)
{if(el==curr)
return i;
if(curr->next!=NULL)
curr=curr->next;}
}
void swap(DList* list,Elem* a,Elem* b)
{
Elem* temp;
if(find_pos(list,a)>find_pos(list,b))
{temp=a;a=b;b=temp;}
Elem* preva=a->prev;
Elem* posta=a->next;
Elem* prevb=b->prev;
Elem* postb=b->next;
if(posta==b)
{
if(preva==NULL)
list->head=b;
else
preva->next=b;
if(postb==NULL)
list->tail=a;
else
postb->prev=a;
b->prev=preva;
b->next=a;
a->prev=b;
a->next=postb;
}
else
{ if(preva==NULL)
list->head=b;
else
preva->next=b;
if(postb==NULL)
list->tail=a;
else
postb->prev=a;
b->prev=preva;
b->next=posta;
posta->prev=b;
prevb->next=a;
a->prev=prevb;
a->next=postb;
}
}
void sorting(DList* list)
{
Elem* curr=list->head;
Elem* place=list->head;
Elem* min=list->head;
for(int j=1;j<=(list->size-2);j++)
{
for(int i=j;i<=(list->size);i++)
{
if((curr->value)<(min->value))
min=curr;
if(curr!=NULL)
curr=curr->next;
}
swap(list,place,min);
if(place!=NULL)
place=min->next;
curr=min->next;
min=min->next;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
struct DList* klen=createDList();
srand(time(NULL));
for(int i=1;i<=10;i++)
{
struct Elem* cherv=createElem(rand()%100);
//struct Elem* cherv2=createElem(i);
//append_to_begin(klen, cherv2);
append_to_end(klen, cherv);
}
print_list(klen);
Elem* a=findElem(klen,1);
Elem* b=findElem(klen,6);
sorting(klen);
//swap(klen,a,b);
//swap(klen,b,a);
print_list(klen);
return 0;
} | C++ |
#include "FPPCamera.h"
FPPCamera::FPPCamera()
{
m_Up= D3DXVECTOR3(0,1,0);
m_FromEye = D3DXVECTOR3(0,0,-1);
m_At= D3DXVECTOR3(0,2,0);
m_Radius=30.0f;
D3DXQuaternionIdentity(&m_Rotation);
}
D3DXMATRIX FPPCamera::getViewMatrix()
{
D3DXVECTOR4 TmpFromEye;
D3DXVECTOR4 TmpUp;
D3DXMATRIX TmpMatrix;
D3DXMATRIX View;
D3DXMatrixRotationQuaternion(&TmpMatrix,&m_Rotation);
D3DXVec3Transform(&TmpFromEye, &m_FromEye, &TmpMatrix);
D3DXVec3Transform(&TmpUp, &m_Up, &TmpMatrix);
D3DXVECTOR3 TargetPos=m_At+(D3DXVECTOR3(TmpFromEye.x,TmpFromEye.y,TmpFromEye.z)*m_Radius);
D3DXVECTOR3 Up(TmpUp.x,TmpUp.y,TmpUp.z);
D3DXMatrixLookAtLH(&View,
&m_At,
&TargetPos,
&Up);
return View;
}
D3DXVECTOR3 FPPCamera::getEyePosition()
{
return m_At;
}
void FPPCamera::move(D3DXVECTOR3 v)
{
D3DXQUATERNION TempRot;
D3DXMATRIX TmpMatrix;
D3DXVECTOR4 TmpVec;
D3DXMatrixRotationQuaternion(&TmpMatrix,&m_Rotation);
D3DXVec3Transform(&TmpVec, &v, &TmpMatrix);
D3DXVECTOR3 vec=D3DXVECTOR3(TmpVec.x,0,TmpVec.z);
m_At+=vec;
}
void FPPCamera::RotateY(float angle)
{
D3DXQUATERNION TempRot;
D3DXVECTOR3 Axis(0,1,0);
D3DXQuaternionRotationAxis(&TempRot,&Axis,angle);
D3DXQuaternionMultiply(&m_Rotation,&m_Rotation,&TempRot);
}
void FPPCamera::RotateX(float angle)
{
D3DXQUATERNION TempRot;
D3DXVECTOR3 Axis(1,0,0);
D3DXVECTOR4 TmpAxis;
D3DXMATRIX TmpMatrix;
D3DXMatrixRotationQuaternion(&TmpMatrix,&m_Rotation);
D3DXVec3Transform(&TmpAxis, &Axis, &TmpMatrix);
Axis=D3DXVECTOR3(TmpAxis.x,TmpAxis.y,TmpAxis.z);
D3DXQuaternionRotationAxis(&TempRot,&Axis,angle);
D3DXQuaternionMultiply(&m_Rotation,&m_Rotation,&TempRot);
}
D3DXVECTOR3 FPPCamera::GetAtPosition()
{
return m_At;
}
void FPPCamera::SetAtPosition(D3DXVECTOR3 position)
{
m_At=position;
}
D3DXVECTOR3 FPPCamera::getEyeDirection()
{
D3DXMATRIX TmpMatrix;
D3DXVECTOR4 TmpVec;
D3DXMatrixRotationQuaternion(&TmpMatrix,&m_Rotation);
D3DXVec3Transform(&TmpVec, &m_FromEye, &TmpMatrix);
D3DXVECTOR3 vec=D3DXVECTOR3(TmpVec.x,TmpVec.y,TmpVec.z);
return vec;
} | C++ |
#pragma once
#include <D3DX10.h>
class RandomTexture
{
private:
ID3D10Device * m_d3dDevice;
ID3D10Texture3D * m_Texture;
ID3D10ShaderResourceView* m_TextureView;
public:
RandomTexture(ID3D10Device * device);
~RandomTexture();
ID3D10ShaderResourceView* GetRandomTexture();
}; | C++ |
#ifndef _CUDATEST
#define _CUDATEST
#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>
#include <cutil.h>
#include <fstream>
#include "vertex.h"
using namespace std;
SimpleVertex* GenerateSphere(int s, float R, ofstream &out);
#endif
| C++ |
#ifndef _DRAWABLE_OBJECT
#define _DRAWABLE_OBJECT
#include <windows.h>
#include <d3d10.h>
#include <d3dx10.h>
#include "iDrawable.h"
#include "vertex.h"
class DrawableObject : public IDrawable
{
private:
ID3D10Device * m_pd3dDevice;
ID3D10Buffer * m_pVertexBuffer;
ID3D10Buffer * m_pIndexBuffer;
D3D10_PRIMITIVE_TOPOLOGY m_Topology;
D3DXVECTOR3 m_Position;
int m_vertexBufferSize;
int m_indexBufferSize;
public:
DrawableObject(ID3D10Device * device);
void Draw();
void CreateVertexBuffer(SimpleVertex * vertices, int n);
void CreateIndexBuffer(DWORD * vertices, int n, D3D10_PRIMITIVE_TOPOLOGY topology=D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
~DrawableObject();
};
#endif
| C++ |
#ifndef lsystems
#define lsystems
#include <iostream>
#include <map>
#include <string>
using namespace std;
///L-system class (Lindermayer system)
class LSystem
{
private:
string start;
map<char,string> Rules;
public:
LSystem();
LSystem(string s, map<char,string> m);
void AddRule(char p, string s);
void RemoveRule(char p);
void SetStart(string s);
string Expand(int level);
};
#endif | C++ |
#include "drawableObject.h"
DrawableObject::DrawableObject(ID3D10Device * device)
{
m_pd3dDevice=device;
m_Position=D3DXVECTOR3(0.0f,0.0f,0.0f);
}
void DrawableObject::CreateVertexBuffer(SimpleVertex * vertices, int n)
{
if(!m_pd3dDevice) return;
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DEFAULT;
bd.ByteWidth = sizeof(SimpleVertex)*n;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = vertices;
m_pd3dDevice->CreateBuffer( &bd, &InitData, &m_pVertexBuffer );
m_vertexBufferSize=n;
}
void DrawableObject::CreateIndexBuffer( DWORD * indices, int n ,D3D10_PRIMITIVE_TOPOLOGY topology)
{
if(!m_pd3dDevice) return;
m_Topology=topology;
D3D10_BUFFER_DESC bd;
D3D10_SUBRESOURCE_DATA InitData;
//Index buffer
bd.Usage = D3D10_USAGE_DEFAULT;
bd.ByteWidth = sizeof( DWORD ) * n;
bd.BindFlags = D3D10_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
InitData.pSysMem = indices;
m_pd3dDevice->CreateBuffer( &bd, &InitData, &m_pIndexBuffer );
m_indexBufferSize=n;
}
DrawableObject::~DrawableObject()
{
if(m_pIndexBuffer) m_pIndexBuffer->Release();
if(m_pVertexBuffer) m_pVertexBuffer->Release();
}
void DrawableObject::Draw()
{
if(!m_pVertexBuffer||!m_pIndexBuffer) return;
// Set vertex buffer
UINT stride = sizeof( SimpleVertex );
UINT offset = 0;
m_pd3dDevice->IASetVertexBuffers( 0, 1, &m_pVertexBuffer, &stride, &offset );
// Set index buffer
m_pd3dDevice->IASetIndexBuffer( m_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0 );
// Set primitive topology
m_pd3dDevice->IASetPrimitiveTopology( m_Topology );
m_pd3dDevice->DrawIndexed(m_indexBufferSize, 0, 0 );
}
| C++ |
#pragma once
#include <d3dx10.h>
#include <vector>
#include <map>
#include <string>
#include "iCamera.h"
#include "drawableObject.h"
#include "shaderManager.h"
struct SceneObject
{
DrawableObject * m_Object;
D3DXMATRIX m_TranslationMatrix;
D3DXQUATERNION m_Rotation;
};
//helper class for managing objects in the scene and draw them with proper techniques
class SceneObjectManager
{
private:
ID3D10Device * m_d3dDevice;
ShaderManager * m_ShaderManager;
std::map<std::string,std::vector<SceneObject*>> m_ObjectMap;
D3DXVECTOR3 m_EyeDirection; //eye direction used to ignore invisible obejcts
D3DXVECTOR3 m_EyePosition;
public:
SceneObjectManager(ID3D10Device * device, ShaderManager * shaderManager);
~SceneObjectManager();
void AddObject(DrawableObject * object, std::string technique, D3DXVECTOR3 position, D3DXQUATERNION rotation );
void Draw();
void SetEyeParameters(ICamera * camera);
}; | C++ |
#ifndef _FPP_CAMERA
#define _FPP_CAMERA
#include <d3d10.h>
#include <d3dx10.h>
#include "iCamera.h"
class FPPCamera:public ICamera
{
private:
D3DXVECTOR3 m_FromEye;
D3DXVECTOR3 m_At;
D3DXVECTOR3 m_Up;
float m_Radius;
D3DXQUATERNION m_Rotation;
public:
FPPCamera();
D3DXMATRIX getViewMatrix();
D3DXVECTOR3 getEyePosition();
D3DXVECTOR3 getEyeDirection();
void move(D3DXVECTOR3 v);
void RotateY(float angle);
void RotateX(float angle);
D3DXVECTOR3 GetAtPosition();
void SetAtPosition(D3DXVECTOR3 position);
};
#endif | C++ |
#include "d3dApp.h"
#include "l_systems.h"
#include "camera.h"
#include "FPPCamera.h"
#include "tree.h"
#include "terrain.h"
#include "sphere.h"
#include "RandomTexture.h"
#include "terrainPlants.h"
class myApp : public D3DApp
{
public:
myApp(HINSTANCE hInstance);
~myApp();
void InitApp();
void OnResize();// reset projection/etc
void UpdateScene(float dt);
void DrawScene();
void Controls();
private:
ID3D10InputLayout* g_pVertexLayout;
Tree *tree;
Tree *tree2;
Tree *tree3;
Sphere * sphere;
Terrain * terrain;
TerrainPlants * m_TerrainPlants;
RandomTexture * m_RandomTexture;
//Textures
ID3D10ShaderResourceView * m_GrassTexture;
ID3D10ShaderResourceView * m_LeafTexture;
float m_Time;
D3DXVECTOR3 m_LightDirection; //light direction
};
myApp::myApp(HINSTANCE hInstance):D3DApp(hInstance)
{
mMainWndCaption="Proceduralne generowanie geometri. DirectX,CUDA,HLSL";
m_ShaderPath="\Shader2.fx";
mClearColor=D3DXCOLOR(120.0/255,170.0/255,230.0/255,1);
}
myApp::~myApp()
{
}
void myApp::DrawScene()
{
D3DApp::DrawScene();
// Set the input layout
md3dDevice->IASetInputLayout( g_pVertexLayout );
//draw objects form scene object manager
m_SceneObjectManager->Draw();
}
void myApp::InitApp()
{
D3DApp::initApp();
m_Camera=new FPPCamera();
m_RandomTexture= new RandomTexture(md3dDevice);
m_LightDirection=D3DXVECTOR3(1,1,1);
// Obtain the technique
m_ShaderManager->addTechnique( "Zlants" );
m_ShaderManager->addTechnique( "TreeBranch" );
m_ShaderManager->addTechnique( "TreeLeaf" );
m_ShaderManager->addTechnique( "TreeLeaf2" );
m_ShaderManager->addTechnique( "Terrain" );
m_ShaderManager->addTechnique( "Sky" );
//create grass texture
m_ShaderManager->addResourceVariable("txGrass");
D3DX10CreateShaderResourceViewFromFile( md3dDevice, "grass1.png", NULL, NULL, &m_GrassTexture, NULL );
m_ShaderManager->setResourceVariable("txGrass",m_GrassTexture);
//create leaf texture
m_ShaderManager->addResourceVariable("txLeaf");
D3DX10CreateShaderResourceViewFromFile( md3dDevice, "leaf.png", NULL, NULL, &m_GrassTexture, NULL );
m_ShaderManager->setResourceVariable("txLeaf",m_GrassTexture);
//create leaf texture
m_ShaderManager->addResourceVariable("txLeaf2");
D3DX10CreateShaderResourceViewFromFile( md3dDevice, "leaf2.png", NULL, NULL, &m_GrassTexture, NULL );
m_ShaderManager->setResourceVariable("txLeaf2",m_GrassTexture);
// Define the input layout
D3D10_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 32, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "BINORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 44, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = sizeof( layout ) / sizeof( layout[0] );
// Create the input layout
D3D10_PASS_DESC PassDesc;
m_ShaderManager->getTechniqueByName("TreeBranch")->GetPassByIndex( 0 )->GetDesc( &PassDesc );
md3dDevice->CreateInputLayout( layout, numElements, PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize, &g_pVertexLayout );
m_ShaderManager->addVectorVariable("vLightDirection");
m_ShaderManager->addResourceVariable("txRandomNumbers");
m_ShaderManager->setVectorVariable("vLightDirection", static_cast<float*>(m_LightDirection));
m_ShaderManager->setResourceVariable("txRandomNumbers", m_RandomTexture->GetRandomTexture());
LSystem S;
S.SetStart("A");
S.AddRule('A',"FFF+CF>F+B+++BF+CF/+BF+++B>F+D++BF<+DF+B+DF>+CF");
S.AddRule('B',"[<<FD++CF++C/FDF++C\\F]");
S.AddRule('C',"[<<FD/FD+<FD]");
S.AddRule('D',"[>>>F]++[>>>F]++[>>>F]++[>>>F]++[>>>F]++[>>>F]");
LSystem D;
D.SetStart("A");
D.AddRule('A',"F>F<[<F/FB][>F\\FB]");
D.AddRule('B',"[FC<FC+>FC][>>>FC/FCFC]++[>>>FCFCFC]++[>>>>FCFCFC]++[>>>FCFCFC]++[>>>>FCFCFC]++[>>FCFCFC]");
D.AddRule('C',"[>>>F]++[>>>F]++[>>>F]++[>>>F]++[>>>F]++[>>>F]");
LSystem F;
F.SetStart("A");
F.AddRule('A',"FF>FFF<[<F/FB][>F\\FB]");
F.AddRule('B',"[FC<FC+>FC][>>>FC/FCFC]++[>>>FCFCFC]++[>>>>FCFCFC]++[>>>FCFCFC]++[>>>>FCFCFC]++[>>FCFCFC]");
F.AddRule('C',"[>>>F]++[>>>F]++[>>>F]++[>>>F]++[>>>F]++[>>>F]");
tree=new Tree(md3dDevice,10);
tree->generateLSys(&S,6,4.0f);
tree->generateCuda(8,0.07f);
tree->generateLeafsCUDA(10,0.4f);
tree2=new Tree(md3dDevice,10);
tree2->generateLSys(&D,3,5.0f);
tree2->generateCuda(6,0.4f);
tree2->generateLeafsCUDA(8,0.7f);
tree3=new Tree(md3dDevice,10);
tree3->generateLSys(&F,3,7.0f);
tree3->generateCuda(6,0.7f);
tree3->generateLeafsCUDA(12,0.7f);
terrain=new Terrain(md3dDevice,20, 30);
sphere=new Sphere(md3dDevice,10,1000);
m_TerrainPlants = new TerrainPlants(md3dDevice, 500);
m_TerrainPlants->Generate(terrain,D3DXVECTOR2(0,500),D3DXVECTOR2(500,0));
D3DXQUATERNION rotation;
D3DXQuaternionIdentity(&rotation);
m_SceneObjectManager->AddObject(terrain->GetTerrain(), "Terrain",D3DXVECTOR3(0,0,0),rotation);
m_SceneObjectManager->AddObject(sphere->GetSphere(), "Sky",D3DXVECTOR3(0,0,0),rotation);
m_SceneObjectManager->AddObject(m_TerrainPlants->GetDrawableObject(),"Zlants",D3DXVECTOR3(0,0,0),rotation);
for(int i=0; i<15; i++)
{
float x= rand()%500;
float z= rand()%500;
D3DXQuaternionRotationYawPitchRoll(&rotation, (float)(rand()%100)/50,0,0);
m_SceneObjectManager->AddObject(tree->GetLeafs(), "TreeLeaf",D3DXVECTOR3(x,terrain->GetHeight(x,z),z),rotation);
m_SceneObjectManager->AddObject(tree->GetBranches(),"TreeBranch",D3DXVECTOR3(x,terrain->GetHeight(x,z),z),rotation);
}
for(int i=0; i<15; i++)
{
float x= rand()%500;
float z= rand()%500;
D3DXQuaternionRotationYawPitchRoll(&rotation, (float)(rand()%100)/50,0,0);
m_SceneObjectManager->AddObject(tree2->GetLeafs(), "TreeLeaf2",D3DXVECTOR3(x,terrain->GetHeight(x,z)-1.0f,z),rotation);
m_SceneObjectManager->AddObject(tree2->GetBranches(),"TreeBranch",D3DXVECTOR3(x,terrain->GetHeight(x,z)-1.0f,z),rotation);
}
for(int i=0; i<15; i++)
{
float x= rand()%500;
float z= rand()%500;
D3DXQuaternionRotationYawPitchRoll(&rotation, (float)(rand()%100)/50,0,0);
m_SceneObjectManager->AddObject(tree3->GetLeafs(), "TreeLeaf",D3DXVECTOR3(x,terrain->GetHeight(x,z)-1.0f,z),rotation);
m_SceneObjectManager->AddObject(tree3->GetBranches(),"TreeBranch",D3DXVECTOR3(x,terrain->GetHeight(x,z)-1.0f,z),rotation);
}
}
void myApp::OnResize()
{
D3DApp::OnResize();
}
void myApp::UpdateScene(float dt)
{
D3DApp::UpdateScene(dt);
Controls();
//update camera height
D3DXVECTOR3 position=dynamic_cast<FPPCamera*>(m_Camera)->GetAtPosition();
dynamic_cast<FPPCamera*>(m_Camera)->SetAtPosition(D3DXVECTOR3(position.x,terrain->GetHeight(position.x,position.z)+10.0f,position.z));
}
void myApp::Controls()
{
m_MouseManager->Update();
D3DXVECTOR3 mouseMovement=m_MouseManager->GetMouseMovement();
float moveMultiplier=100.0f;
//Camera rotation
if(mouseMovement.x<0)
dynamic_cast<FPPCamera*>(m_Camera)->RotateY(mouseMovement.x/moveMultiplier);
else if(mouseMovement.x>0)
dynamic_cast<FPPCamera*>(m_Camera)->RotateY(mouseMovement.x/moveMultiplier);
if(mouseMovement.y<0)
dynamic_cast<FPPCamera*>(m_Camera)->RotateX(-mouseMovement.y/moveMultiplier);
else if(mouseMovement.y>0)
dynamic_cast<FPPCamera*>(m_Camera)->RotateX(-mouseMovement.y/moveMultiplier);
//Move camera
if(m_MouseManager->MouseButtonDown(1))
dynamic_cast<FPPCamera*>(m_Camera)->move(D3DXVECTOR3(0,0,-2.0f));
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd)
{
myApp application(hInstance);
application.InitApp();
return application.Run();
} | C++ |
#ifndef _SPHERE
#define _SPHERE
#include <d3d10.h>
#include <d3dx10.h>
#include "kulaCuda.h"
#include "drawableObject.h"
class Sphere
{
private:
int m_size;
float m_scale;
ID3D10Device* pd3dDevice;
DrawableObject* m_SphereObject;
float ** m_HeightMap;
public:
Sphere(ID3D10Device* d, int m_size, float scale);
~Sphere();
HRESULT generate();
void render();
DrawableObject * GetSphere();
};
#endif | C++ |
#ifndef _CUDATEST
#define _CUDATEST
#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>
#include <cutil.h>
#include <fstream>
#include "vertex.h"
using namespace std;
SimpleVertex* generateTerrain(int s, float scale, ofstream &out);
SimpleVertex* generateTerrain(int s, float scale);
#endif
| C++ |
#pragma once
#include <dinput.h>
#include <d3dx10.h>
class MouseManager
{
private:
//Direct input stuff
LPDIRECTINPUT8 m_DirectInputObject;
LPDIRECTINPUTDEVICE8 m_MouseDevice;
DIMOUSESTATE m_MouseState;
D3DXVECTOR3 m_CurrentCoordinates;
public:
bool Init(HINSTANCE hinstance, HWND hwnd);
void Update(); //updates mouse state
D3DXVECTOR3 GetMousePosition(); //returns mouse position
D3DXVECTOR3 GetMouseMovement(); //returns distance between current and previous mouse position
bool MouseButtonDown(int button);
~MouseManager();
}; | C++ |
#ifndef _SHADER_MANAGER
#define _SHADER_MANAGER
#include <d3d10.h>
#include <d3dx10.h>
#include <Windows.h>
#include <map>
#include <string>
///A helper class for managing a shader
class ShaderManager
{
private:
ID3D10Device * m_pd3dDevice;
ID3D10Effect * m_pd3dEffect;
std::map<std::string, ID3D10EffectTechnique*> m_Techniques;
std::map<std::string, ID3D10EffectScalarVariable*> m_ScalarVariables;
std::map<std::string, ID3D10EffectVectorVariable*> m_VectorVariables;
std::map<std::string, ID3D10EffectMatrixVariable*> m_MatrixVariables;
std::map<std::string, ID3D10EffectShaderResourceVariable*> m_ResourceVariables;
public:
ShaderManager(ID3D10Device * device, std::string shaderFilePath);
~ShaderManager();
///adding variables to containers
void addScalarVariable(std::string name);
void addVectorVariable(std::string name);
void addMatrixVariable(std::string name);
void addResourceVariable(std::string name );
///getting variables
ID3D10EffectScalarVariable * getScalarVariableByName(std::string name);
ID3D10EffectVectorVariable * getVectorVariableByName(std::string name);
ID3D10EffectMatrixVariable * getMatrixVariableByName(std::string name);
ID3D10EffectShaderResourceVariable * getResourceVariableByName(std::string name);
///setting variables
void setScalarVariable(std::string name, float value);
void setVectorVariable(std::string name, float* value);
void setMatrixVariable(std::string name, float* value);
void setResourceVariable(std::string name, ID3D10ShaderResourceView* value);
///manage techniques
void addTechnique(std::string name);
ID3D10EffectTechnique* getTechniqueByName(std::string name);
};
#endif | C++ |
#ifndef _SHADER_MANAGER
#define _SHADER_MANAGER
#include <d3d10.h>
#include <d3dx10.h>
#include <Windows.h>
#include <map>
#include <string>
///A helper class for managing a shader, techniques and variables
class ShaderManager
{
private:
ID3D10Device * m_pd3dDevice;
ID3D10Effect * m_pd3dEffect;
std::map<std::string, ID3D10EffectTechnique*> m_Techniques;
std::map<std::string, ID3D10EffectScalarVariable*> m_ScalarVariables;
std::map<std::string, ID3D10EffectVectorVariable*> m_VectorVariables;
std::map<std::string, ID3D10EffectMatrixVariable*> m_MatrixVariables;
std::map<std::string, ID3D10EffectShaderResourceVariable*> m_ResourceVariables;
public:
ShaderManager(ID3D10Device * device, std::string shaderFilePath);
~ShaderManager();
///adding variables to containers
void addScalarVariable(std::string name);
void addVectorVariable(std::string name);
void addMatrixVariable(std::string name);
void addResourceVariable(std::string name );
///getting variables
ID3D10EffectScalarVariable * getScalarVariableByName(std::string name);
ID3D10EffectVectorVariable * getVectorVariableByName(std::string name);
ID3D10EffectMatrixVariable * getMatrixVariableByName(std::string name);
ID3D10EffectShaderResourceVariable * getResourceVariableByName(std::string name);
///setting variables
void setScalarVariable(std::string name, float value);
void setVectorVariable(std::string name, float* value);
void setMatrixVariable(std::string name, float* value);
void setResourceVariable(std::string name, ID3D10ShaderResourceView* value);
///manage techniques
void addTechnique(std::string name);
ID3D10EffectTechnique* getTechniqueByName(std::string name);
};
#endif | C++ |
#include "terrainPlants.h"
TerrainPlants::TerrainPlants(ID3D10Device * device, int size)
{
m_d3dDevice=device;
m_size =size;
}
TerrainPlants::~TerrainPlants()
{
if(m_d3dDevice!=NULL)
m_d3dDevice->Release();
if(m_DrawableObject!=NULL)
delete(m_DrawableObject);
}
void TerrainPlants::Generate(Terrain *terrain, D3DXVECTOR2 upperLeft, D3DXVECTOR2 lowerRight)
{
float dx=lowerRight.x-upperLeft.x;
float dy=upperLeft.y-lowerRight.y;
SimpleVertex * vertices=new SimpleVertex[m_size];
DWORD * indices=new DWORD[m_size];
for(int i=0; i<m_size; i++)
{
indices[i]=i;
float x= (float)(rand()%100)/100;
float y= (float)(rand()%100)/100;
x=upperLeft.x+x*dx;
y=upperLeft.y-y*dy;
D3DXVECTOR3 pos=D3DXVECTOR3(x,terrain->GetHeight(x,y),y);
vertices[i].Pos=pos;
vertices[i].Nor=D3DXVECTOR3(0,1,0);
}
m_DrawableObject=new DrawableObject(m_d3dDevice);
m_DrawableObject->CreateIndexBuffer(indices,m_size, D3D10_PRIMITIVE_TOPOLOGY_POINTLIST);
m_DrawableObject->CreateVertexBuffer(vertices, m_size);
}
DrawableObject * TerrainPlants::GetDrawableObject()
{
return m_DrawableObject;
}
| C++ |
//=======================================================================================
// d3dApp.cpp by Frank Luna (C) 2008 All Rights Reserved.
// Modified by Grzegorz Bartoszek 2010
//=======================================================================================
#include "d3dApp.h"
#include <sstream>
#include "camera.h"
LRESULT CALLBACK
MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static D3DApp* app = 0;
switch( msg )
{
case WM_CREATE:
{
// Get the 'this' pointer we passed to CreateWindow via the lpParam parameter.
CREATESTRUCT* cs = (CREATESTRUCT*)lParam;
app = (D3DApp*)cs->lpCreateParams;
return 0;
}
}
// Don't start processing messages until after WM_CREATE.
if( app )
return app->msgProc(msg, wParam, lParam);
else
return DefWindowProc(hwnd, msg, wParam, lParam);
}
D3DApp::D3DApp(HINSTANCE hInstance)
{
mhAppInst = hInstance;
mhMainWnd = 0;
mAppPaused = false;
mMinimized = false;
mMaximized = false;
mResizing = false;
mFrameStats = "";
md3dDevice = 0;
mSwapChain = 0;
mDepthStencilBuffer = 0;
mRenderTargetView = 0;
mDepthStencilView = 0;
mFont = 0;
mMainWndCaption = "D3D10 Application";
md3dDriverType = D3D10_DRIVER_TYPE_HARDWARE;
mClearColor = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f);
mClientWidth = 1024;
mClientHeight = 768;
}
D3DApp::~D3DApp()
{
mRenderTargetView->Release();
mDepthStencilView->Release();
mSwapChain->Release();
mDepthStencilBuffer->Release();
md3dDevice->Release();
mFont->Release();
}
HINSTANCE D3DApp::getAppInst()
{
return mhAppInst;
}
HWND D3DApp::getMainWnd()
{
return mhMainWnd;
}
int D3DApp::Run()
{
MSG msg = {0};
mTimer.reset();
while(msg.message != WM_QUIT)
{
// If there are Window messages then process them.
if(PeekMessage( &msg, 0, 0, 0, PM_REMOVE ))
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
// Otherwise, do animation/game stuff.
else
{
mTimer.tick();
if( !mAppPaused )
UpdateScene(mTimer.getDeltaTime());
else
Sleep(50);
DrawScene();
DrawFPS();
}
}
return (int)msg.wParam;
}
void D3DApp::initApp()
{
initMainWindow();
initDirect3D();
m_MouseManager=new MouseManager();
m_MouseManager->Init(mhAppInst,mhMainWnd);
m_ShaderManager=new ShaderManager(this->md3dDevice,m_ShaderPath);
m_SceneObjectManager=new SceneObjectManager(md3dDevice,m_ShaderManager);
// Obtain the variables
m_ShaderManager->addMatrixVariable( "World" );
m_ShaderManager->addMatrixVariable( "View" );
m_ShaderManager->addMatrixVariable( "Projection" );
m_ShaderManager->addVectorVariable( "vEyePos" );
m_ShaderManager->addScalarVariable("fTime");
// Initialize the projection matrix
D3DXMatrixPerspectiveFovLH( &m_Projection, ( float )D3DX_PI * 0.25f, mClientWidth / ( FLOAT )mClientHeight, 0.1f, 2000.0f );
//Set projection matrix
m_ShaderManager->setMatrixVariable("Projection", ( float* )&m_Projection );
D3DX10_FONT_DESC fontDesc;
fontDesc.Height = 24;
fontDesc.Width = 0;
fontDesc.Weight = 0;
fontDesc.MipLevels = 1;
fontDesc.Italic = false;
fontDesc.CharSet = DEFAULT_CHARSET;
fontDesc.OutputPrecision = OUT_DEFAULT_PRECIS;
fontDesc.Quality = DEFAULT_QUALITY;
fontDesc.PitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
memcpy(fontDesc.FaceName, "Times New Roman",sizeof("Times New Roman"));
D3DX10CreateFontIndirect(md3dDevice, &fontDesc, &mFont);
}
void D3DApp::OnResize()
{
// Release the old views, as they hold references to the buffers we
// will be destroying. Also release the old depth/stencil buffer.
ReleaseCOM(mRenderTargetView)
ReleaseCOM(mDepthStencilView)
ReleaseCOM(mDepthStencilBuffer)
// Resize the swap chain and recreate the render target view.
mSwapChain->ResizeBuffers(1, mClientWidth, mClientHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0);
ID3D10Texture2D* backBuffer;
mSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), reinterpret_cast<void**>(&backBuffer));
md3dDevice->CreateRenderTargetView(backBuffer, 0, &mRenderTargetView);
ReleaseCOM(backBuffer)
// Create the depth/stencil buffer and view.
D3D10_TEXTURE2D_DESC depthStencilDesc;
depthStencilDesc.Width = mClientWidth;
depthStencilDesc.Height = mClientHeight;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthStencilDesc.SampleDesc.Count = 1; // multisampling must match
depthStencilDesc.SampleDesc.Quality = 0; // swap chain values.
depthStencilDesc.Usage = D3D10_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.MiscFlags = 0;
D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
descDSV.Format = depthStencilDesc.Format;
descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
descDSV.Texture2D.MipSlice = 0;
md3dDevice->CreateTexture2D(&depthStencilDesc, 0, &mDepthStencilBuffer);
md3dDevice->CreateDepthStencilView(mDepthStencilBuffer, &descDSV, &mDepthStencilView);
// Bind the render target view and depth/stencil view to the pipeline.
md3dDevice->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView);
// Set the viewport transform.
D3D10_VIEWPORT vp;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
vp.Width = mClientWidth;
vp.Height = mClientHeight;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
md3dDevice->RSSetViewports(1, &vp);
D3D10_RASTERIZER_DESC rasterizerState;
rasterizerState.CullMode = D3D10_CULL_NONE;
rasterizerState.FillMode = D3D10_FILL_SOLID;
rasterizerState.FrontCounterClockwise = true;
rasterizerState.DepthBias = false;
rasterizerState.DepthBiasClamp = 0;
rasterizerState.SlopeScaledDepthBias = 0;
rasterizerState.DepthClipEnable = true;
rasterizerState.ScissorEnable = false;
rasterizerState.MultisampleEnable = false;
rasterizerState.AntialiasedLineEnable = true;
ID3D10RasterizerState* pRS;
md3dDevice->CreateRasterizerState( &rasterizerState, &pRS);
md3dDevice->RSSetState(pRS);
}
void D3DApp::UpdateScene(float dt)
{
// Code computes the average frames per second, and also the
// average time it takes to render one frame.
static int frameCnt = 0;
static float t_base = 0.0f;
frameCnt++;
// Compute averages over one second period.
if( (mTimer.getGameTime() - t_base) >= 1.0f )
{
float fps = (float)frameCnt; // fps = frameCnt / 1
float mspf = 1000.0f / fps;
std::ostringstream outs;
outs.precision(6);
outs << "FPS: " << fps << "\n"
<< "Milliseconds: Per Frame: " << mspf;
mFrameStats = outs.str();
// Reset for next average.
frameCnt = 0;
t_base += 1.0f;
}
//Update basic shader variables
if(m_Camera)
{
m_View=m_Camera->getViewMatrix();
m_EyePos=m_Camera->getEyePosition();
}
//View matrix and eye position
m_ShaderManager->setMatrixVariable("View", ( float* )&m_View );
m_ShaderManager->setVectorVariable("vEyePos", (float*)&m_EyePos);
m_ShaderManager->setScalarVariable("fTime", mTimer.getGameTime());
m_SceneObjectManager->SetEyeParameters(m_Camera);
}
void D3DApp::DrawScene()
{
//clear screen
md3dDevice->ClearRenderTargetView(mRenderTargetView, mClearColor);
md3dDevice->ClearDepthStencilView(mDepthStencilView, D3D10_CLEAR_DEPTH|D3D10_CLEAR_STENCIL, 1.0f, 0);
}
LRESULT D3DApp::msgProc(UINT msg, WPARAM wParam, LPARAM lParam)
{
switch( msg )
{
// WM_ACTIVATE is sent when the window is activated or deactivated.
// We pause the game when the window is deactivated and unpause it
// when it becomes active.
case WM_ACTIVATE:
if( LOWORD(wParam) == WA_INACTIVE )
{
mAppPaused = true;
mTimer.stop();
}
else
{
mAppPaused = false;
mTimer.start();
}
return 0;
// WM_SIZE is sent when the user resizes the window.
case WM_SIZE:
// Save the new client area dimensions.
mClientWidth = LOWORD(lParam);
mClientHeight = HIWORD(lParam);
if( md3dDevice )
{
if( wParam == SIZE_MINIMIZED )
{
mAppPaused = true;
mMinimized = true;
mMaximized = false;
}
else if( wParam == SIZE_MAXIMIZED )
{
mAppPaused = false;
mMinimized = false;
mMaximized = true;
OnResize();
}
else if( wParam == SIZE_RESTORED )
{
// Restoring from minimized state?
if( mMinimized )
{
mAppPaused = false;
mMinimized = false;
OnResize();
}
// Restoring from maximized state?
else if( mMaximized )
{
mAppPaused = false;
mMaximized = false;
OnResize();
}
else if( mResizing )
{
// If user is dragging the resize bars, we do not resize
// the buffers here because as the user continuously
// drags the resize bars, a stream of WM_SIZE messages are
// sent to the window, and it would be pointless (and slow)
// to resize for each WM_SIZE message received from dragging
// the resize bars. So instead, we reset after the user is
// done resizing the window and releases the resize bars, which
// sends a WM_EXITSIZEMOVE message.
}
else // API call such as SetWindowPos or mSwapChain->SetFullscreenState.
{
OnResize();
}
}
}
return 0;
// WM_EXITSIZEMOVE is sent when the user grabs the resize bars.
case WM_ENTERSIZEMOVE:
mAppPaused = true;
mResizing = true;
mTimer.stop();
return 0;
// WM_EXITSIZEMOVE is sent when the user releases the resize bars.
// Here we reset everything based on the new window dimensions.
case WM_EXITSIZEMOVE:
mAppPaused = false;
mResizing = false;
mTimer.start();
OnResize();
return 0;
// WM_DESTROY is sent when the window is being destroyed.
case WM_DESTROY:
PostQuitMessage(0);
return 0;
// The WM_MENUCHAR message is sent when a menu is active and the user presses
// a key that does not correspond to any mnemonic or accelerator key.
case WM_MENUCHAR:
// Don't beep when we alt-enter.
return MAKELRESULT(0, MNC_CLOSE);
// Catch this message so to prevent the window from becoming too small.
case WM_GETMINMAXINFO:
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 200;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 200;
return 0;
}
return DefWindowProc(mhMainWnd, msg, wParam, lParam);
}
void D3DApp::initMainWindow()
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = MainWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = mhAppInst;
wc.hIcon = LoadIcon(0, IDI_APPLICATION);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = "D3DWndClassName";
if( !RegisterClass(&wc) )
{
MessageBox(0, "RegisterClass FAILED", 0, 0);
PostQuitMessage(0);
}
// Compute window rectangle dimensions based on requested client area dimensions.
RECT R = { 0, 0, mClientWidth, mClientHeight };
AdjustWindowRect(&R, WS_OVERLAPPEDWINDOW, false);
int width = R.right - R.left;
int height = R.bottom - R.top;
mhMainWnd = CreateWindow("D3DWndClassName", mMainWndCaption.c_str(),
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, width, height, 0, 0, mhAppInst, this);
if( !mhMainWnd )
{
MessageBox(0, "CreateWindow FAILED", 0, 0);
PostQuitMessage(0);
}
ShowWindow(mhMainWnd, SW_SHOW);
UpdateWindow(mhMainWnd);
}
void D3DApp::initDirect3D()
{
// Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain.
DXGI_SWAP_CHAIN_DESC sd;
sd.BufferDesc.Width = mClientWidth;
sd.BufferDesc.Height = mClientHeight;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
// No multisampling.
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferCount = 1;
sd.OutputWindow = mhMainWnd;
sd.Windowed = true;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
sd.Flags = 0;
// Create the device.
UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
#endif
D3D10CreateDeviceAndSwapChain(
0, //default adapter
md3dDriverType,
0, // no software device
createDeviceFlags,
D3D10_SDK_VERSION,
&sd,
&mSwapChain,
&md3dDevice) ;
OnResize();
}
void D3DApp::DrawFPS()
{
//draw FPS
RECT R = {5, 5, 0, 0};
md3dDevice->OMGetDepthStencilState(&mDepthStencilState,0);
mFont->DrawText(0, mFrameStats.c_str(), -1, &R, DT_NOCLIP, D3DXCOLOR(0,0,0,1));
md3dDevice->OMSetDepthStencilState(mDepthStencilState,0);
// Present the information rendered to the back buffer to the front buffer (the screen)
mSwapChain->Present( 0, 0 );
}
| C++ |
#include "camera.h"
Camera::Camera()
{
m_Up= D3DXVECTOR3(0,1,0);
m_ToEye = D3DXVECTOR3(0,1,-1);
m_At= D3DXVECTOR3(0,4,0);
m_Radius=30.0f;
D3DXQuaternionIdentity(&m_Rotation);
}
D3DXMATRIX Camera::getViewMatrix()
{
D3DXVECTOR4 TmpToEye;
D3DXVECTOR4 TmpUp;
D3DXMATRIX TmpMatrix;
D3DXMATRIX View;
D3DXMatrixRotationQuaternion(&TmpMatrix,&m_Rotation);
D3DXVec3Transform(&TmpToEye, &m_ToEye, &TmpMatrix);
D3DXVec3Transform(&TmpUp, &m_Up, &TmpMatrix);
D3DXVECTOR3 EyePos=m_At+(D3DXVECTOR3(TmpToEye.x,TmpToEye.y,TmpToEye.z)*m_Radius);
D3DXVECTOR3 Up(TmpUp.x,TmpUp.y,TmpUp.z);
D3DXMatrixLookAtLH(&View,
&EyePos,
&m_At,
&Up);
return View;
}
D3DXVECTOR3 Camera::getEyePosition()
{
D3DXVECTOR3 eyePosition;
D3DXVECTOR4 tmpToEye;
D3DXMATRIX tmpMatrix;
D3DXMatrixRotationQuaternion(&tmpMatrix,&m_Rotation);
D3DXVec3Transform(&tmpToEye, &m_ToEye, &tmpMatrix);
D3DXVECTOR3 toEye=D3DXVECTOR3(tmpToEye.x,tmpToEye.y,tmpToEye.z)*m_Radius;
D3DXVec3Add(&eyePosition,&m_At,&toEye);
return eyePosition;
}
void Camera::move(D3DXVECTOR3 v)
{
D3DXQUATERNION TempRot;
D3DXMATRIX TmpMatrix;
D3DXVECTOR4 TmpVec;
D3DXMatrixRotationQuaternion(&TmpMatrix,&m_Rotation);
D3DXVec3Transform(&TmpVec, &v, &TmpMatrix);
D3DXVECTOR3 vec=D3DXVECTOR3(TmpVec.x,0,TmpVec.z);
m_At+=vec;
}
void Camera::RotateY(float angle)
{
D3DXQUATERNION TempRot;
D3DXVECTOR3 Axis(0,1,0);
D3DXQuaternionRotationAxis(&TempRot,&Axis,angle);
D3DXQuaternionMultiply(&m_Rotation,&m_Rotation,&TempRot);
}
void Camera::RotateX(float angle)
{
D3DXQUATERNION TempRot;
D3DXVECTOR3 Axis(1,0,0);
D3DXVECTOR4 TmpAxis;
D3DXMATRIX TmpMatrix;
D3DXMatrixRotationQuaternion(&TmpMatrix,&m_Rotation);
D3DXVec3Transform(&TmpAxis, &Axis, &TmpMatrix);
Axis=D3DXVECTOR3(TmpAxis.x,TmpAxis.y,TmpAxis.z);
D3DXQuaternionRotationAxis(&TempRot,&Axis,angle);
D3DXQuaternionMultiply(&m_Rotation,&m_Rotation,&TempRot);
}
void Camera::Zoom(float step)
{
m_Radius+=m_Radius*step;
}
D3DXVECTOR3 Camera::GetAtPosition()
{
return m_At;
}
void Camera::SetAtPosition(D3DXVECTOR3 position)
{
m_At=position;
} | C++ |
#include "shaderManager.h"
ShaderManager::ShaderManager(ID3D10Device * device, std::string shaderFilePath)
{
m_pd3dDevice=device;
// Create the effect
DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
dwShaderFlags |= D3D10_SHADER_DEBUG;
#endif
HRESULT hr=D3DX10CreateEffectFromFile( shaderFilePath.c_str(), NULL, NULL, "fx_4_0", dwShaderFlags, 0,
m_pd3dDevice, NULL, NULL, &m_pd3dEffect, NULL, NULL );
if(FAILED(hr))
MessageBox(NULL, "Error opening shader file", "Error",0);
}
void ShaderManager::addScalarVariable( std::string name )
{
if(!m_pd3dEffect)
return;
if(m_ScalarVariables[name]!=NULL)
{
MessageBox(NULL, "Variable already exists",name.c_str(),0);
return;
}
ID3D10EffectScalarVariable* variable=m_pd3dEffect->GetVariableByName( name.c_str() )->AsScalar();
m_ScalarVariables[name]=variable;
}
ID3D10EffectScalarVariable * ShaderManager::getScalarVariableByName( std::string name )
{
if(m_ScalarVariables[name]==NULL)
{
MessageBox(NULL, "Variable doesn't exist",name.c_str(),0);
return NULL;
}
ID3D10EffectScalarVariable * variable = m_ScalarVariables[name];
return variable;
}
void ShaderManager::addVectorVariable( std::string name )
{
if(!m_pd3dEffect)
return;
if(m_VectorVariables[name]!=NULL)
{
MessageBox(NULL, "Variable already exists",name.c_str(),0);
return;
}
ID3D10EffectVectorVariable* variable=m_pd3dEffect->GetVariableByName( name.c_str() )->AsVector();
m_VectorVariables[name]=variable;
}
ID3D10EffectVectorVariable * ShaderManager::getVectorVariableByName( std::string name )
{
if(m_VectorVariables[name]==NULL)
{
MessageBox(NULL, "Variable doesn't exist",name.c_str(),0);
return NULL;
}
ID3D10EffectVectorVariable * variable = m_VectorVariables[name];
return variable;
}
void ShaderManager::addMatrixVariable( std::string name )
{
if(!m_pd3dEffect)
return;
if(m_MatrixVariables[name]!=NULL)
{
MessageBox(NULL, "Variable already exists",name.c_str(),0);
return;
}
ID3D10EffectMatrixVariable* variable=m_pd3dEffect->GetVariableByName( name.c_str() )->AsMatrix();
m_MatrixVariables[name]=variable;
}
ID3D10EffectMatrixVariable * ShaderManager::getMatrixVariableByName( std::string name )
{
if(m_MatrixVariables[name]==NULL)
{
MessageBox(NULL, "Variable doesn't exist",name.c_str(),0);
return NULL;
}
ID3D10EffectMatrixVariable * variable = m_MatrixVariables[name];
return variable;
}
void ShaderManager::addResourceVariable( std::string name )
{
if(!m_pd3dEffect)
return;
if(m_ResourceVariables[name]!=NULL)
{
MessageBox(NULL, "Variable already exists",name.c_str(),0);
return;
}
ID3D10EffectShaderResourceVariable* variable=m_pd3dEffect->GetVariableByName( name.c_str() )->AsShaderResource();
m_ResourceVariables[name]=variable;
}
ID3D10EffectShaderResourceVariable * ShaderManager::getResourceVariableByName( std::string name )
{
if(m_ResourceVariables[name]==NULL)
{
MessageBox(NULL, "Variable doesn't exist",name.c_str(),0);
return NULL;
}
ID3D10EffectShaderResourceVariable * variable = m_ResourceVariables[name];
return variable;
}
void ShaderManager::setScalarVariable( std::string name, float value )
{
ID3D10EffectScalarVariable* variable=m_ScalarVariables[name];
if(variable==NULL)
{
MessageBox(NULL,"Variable doesn't exist",name.c_str(),0);
return;
}
variable->SetFloat(value);
}
void ShaderManager::setVectorVariable( std::string name, float* value )
{
ID3D10EffectVectorVariable* variable=m_VectorVariables[name];
if(variable==NULL)
{
MessageBox(NULL,"Variable doesn't exist",name.c_str(),0);
return;
}
variable->SetFloatVector(value);
}
void ShaderManager::setMatrixVariable( std::string name, float* value )
{
ID3D10EffectMatrixVariable* variable=m_MatrixVariables[name];
if(variable==NULL)
{
MessageBox(NULL,"Variable doesn't exist",name.c_str(),0);
return;
}
variable->SetMatrix(value);
}
void ShaderManager::setResourceVariable(std::string name, ID3D10ShaderResourceView* value)
{
ID3D10EffectShaderResourceVariable* variable=m_ResourceVariables[name];
if(variable==NULL)
{
MessageBox(NULL,"Variable doesn't exist",name.c_str(),0);
return;
}
variable->SetResource(value);
}
void ShaderManager::addTechnique( std::string name )
{
ID3D10EffectTechnique* technique=m_pd3dEffect->GetTechniqueByName(name.c_str());
if(!technique)
{
MessageBox(NULL,"Error adding technique", "Error", 0);
return;
}
m_Techniques[name]=technique;
}
ID3D10EffectTechnique* ShaderManager::getTechniqueByName( std::string name )
{
ID3D10EffectTechnique* technique=m_Techniques[name];
if(!technique)
{
MessageBox(NULL,"The technique doesn't exist", "Error",0);
return NULL;
}
return technique;
}
ShaderManager::~ShaderManager()
{
if(m_pd3dDevice!=NULL)
{
m_pd3dDevice->Release();
m_pd3dDevice=NULL;
}
if(m_pd3dEffect!=NULL)
{
m_pd3dEffect->Release();
m_pd3dEffect=NULL;
}
} | C++ |
#include "MouseManager.h"
bool MouseManager::Init(HINSTANCE hinstance, HWND hwnd)
{
HRESULT hr;
// Create the DirectInput object.
hr=DirectInput8Create( hinstance,
DIRECTINPUT_VERSION,
IID_IDirectInput8,
( void** )&m_DirectInputObject,
NULL );
//create mouse device
hr=m_DirectInputObject->CreateDevice(GUID_SysMouse, &m_MouseDevice, NULL);
//set data format
hr=m_MouseDevice->SetDataFormat(&c_dfDIMouse);
//set cooperative level
hr=m_MouseDevice->SetCooperativeLevel(hwnd,DISCL_FOREGROUND);
hr=m_MouseDevice->Acquire();
if(FAILED(hr))
return false;
else
return true;
}
MouseManager::~MouseManager()
{
if(m_DirectInputObject)
{
m_DirectInputObject->Release();
m_DirectInputObject=NULL;
}
if(m_MouseDevice)
{
m_MouseDevice->Unacquire();
m_MouseDevice->Release();
m_MouseDevice=NULL;
}
}
void MouseManager::Update()
{
if(DIERR_INPUTLOST == m_MouseDevice->GetDeviceState(sizeof(m_MouseState),
(LPVOID)&m_MouseState))
{
m_MouseDevice->Acquire();
}
else
{
m_CurrentCoordinates.x+=static_cast<float>(m_MouseState.lX);
m_CurrentCoordinates.y+=static_cast<float>(m_MouseState.lY);
m_CurrentCoordinates.z+=static_cast<float>(m_MouseState.lZ);
}
}
D3DXVECTOR3 MouseManager::GetMousePosition()
{
return m_CurrentCoordinates;
}
D3DXVECTOR3 MouseManager::GetMouseMovement()
{
D3DXVECTOR3 distance;
distance.x=static_cast<float>(m_MouseState.lX);
distance.y=static_cast<float>(m_MouseState.lY);
distance.z=static_cast<float>(m_MouseState.lZ);
return distance;
}
bool MouseManager::MouseButtonDown(int button)
{
if(m_MouseState.rgbButtons[button] & 0x80)
{
return true;
}
return false;
} | C++ |
//=======================================================================================
// d3dApp.h by Frank Luna (C) 2008 All Rights Reserved.
//
// Simple Direct3D demo application class.
// Make sure you link: d3d10.lib d3dx10d.lib dxerr.lib dxguid.lib.
// Link d3dx10.lib for release mode builds instead of d3dx10d.lib.
//=======================================================================================
#ifndef D3DAPP_H
#define D3DAPP_H
#include <windows.h>
#include <d3d10.h>
#include <d3dx10.h>
#include "GameTimer.h"
#include <string>
#include "iCamera.h"
#include "MouseManager.h"
#include "shaderManager.h"
#include "sceneObjectManager.h"
#define ReleaseCOM(x) { if(x){ x->Release();x = 0; } }
class D3DApp
{
public:
D3DApp(HINSTANCE hInstance);
virtual ~D3DApp();
HINSTANCE getAppInst();
HWND getMainWnd();
int Run();
// Framework methods. Derived client class overrides these methods to
// implement specific application requirements.
virtual void initApp();
virtual void OnResize();// reset projection/etc
virtual void UpdateScene(float dt);
virtual void DrawScene();
virtual void DrawFPS();
virtual LRESULT msgProc(UINT msg, WPARAM wParam, LPARAM lParam);
protected:
void initMainWindow();
void initDirect3D();
HINSTANCE mhAppInst;
HWND mhMainWnd;
bool mAppPaused;
bool mMinimized;
bool mMaximized;
bool mResizing;
GameTimer mTimer;
ShaderManager * m_ShaderManager;
MouseManager * m_MouseManager;
SceneObjectManager * m_SceneObjectManager;
std::string mFrameStats;
ID3D10Device* md3dDevice;
IDXGISwapChain* mSwapChain;
ID3D10Texture2D* mDepthStencilBuffer;
ID3D10RenderTargetView* mRenderTargetView;
ID3D10DepthStencilView* mDepthStencilView;
ID3DX10Font* mFont;
std::string m_ShaderPath;
//Camera interface, derived class should initialize it with a proper camera object
ICamera * m_Camera;
// Derived class should set these in derived constructor to customize starting values.
std::string mMainWndCaption;
D3D10_DRIVER_TYPE md3dDriverType;
D3DXCOLOR mClearColor;
int mClientWidth;
int mClientHeight;
D3DXMATRIX m_View;
D3DXMATRIX m_Projection;
D3DXVECTOR3 m_EyePos;
private:
ID3D10DepthStencilState * mDepthStencilState; //to protect depth stencil state against font drawing
};
#endif // D3DAPP_H | C++ |
#include "sphere.h"
Sphere::Sphere(ID3D10Device* d, int size, float scale)
{
m_size=size;
m_scale=scale;
pd3dDevice = d;
m_SphereObject=new DrawableObject(pd3dDevice);
generate();
}
HRESULT Sphere::generate()
{
//Generate vertices
ofstream g_log("log.txt");
SimpleVertex*vertices=GenerateSphere(m_size, m_scale, g_log);
//Generate indices
int ic=(m_size-1)*(m_size-1)*2*3; //number of indices
DWORD * indices= (DWORD*)malloc(ic *sizeof(DWORD));
int j=0;
g_log<<"index buffer \n";
for(int i=0; i<ic; i+=6)
{
indices[i]=j;
indices[i+1]=j+m_size;
indices[i+2]=j+m_size+1;
indices[i+3]=j;
indices[i+4]=j+m_size+1;
indices[i+5]=j+1;
g_log<<indices[i]<<" ";
g_log<<indices[i+1]<<" ";
g_log<<indices[i+2]<<" \n";
g_log<<indices[i+3]<<" ";
g_log<<indices[i+4]<<" ";
g_log<<indices[i+5]<<" \n";
j++;
if((j+1)%(m_size)==0) j++;
}
m_SphereObject->CreateVertexBuffer(vertices,m_size*m_size);
m_SphereObject->CreateIndexBuffer(indices,ic);
free(indices);
free(vertices);
return S_OK;
}
void Sphere::render()
{
m_SphereObject->Draw();
}
Sphere::~Sphere()
{
if(m_SphereObject)
{
delete(m_SphereObject);
m_SphereObject=NULL;
}
}
DrawableObject * Sphere::GetSphere()
{
return m_SphereObject;
}
| C++ |
#ifndef _IDRAWABLE
#define _IDRAWABLE
class IDrawable
{
public:
virtual ~IDrawable(){};
virtual void Draw()=0;
};
#endif | C++ |
#include "tree.h"
Tree::Tree(ID3D10Device* d, int s)
{
m_size=s;
m_pd3dDevice = d;
D3DXCreateMatrixStack(0,&m_matrixStack);
}
///<Summary> generate tree branch structures form a L-system </Summary>
HRESULT Tree::generateLSys(LSystem * system, int level, float length )
{
string s=system->Expand(level);
char c;
D3DXMATRIX world;
D3DXMatrixIdentity(&world);
if(this->m_BranchList.size()>0) this->m_BranchList.clear();
if(this->m_LeafList.size()>0) this->m_LeafList.clear();
stack<branch*> branchStack;
branch * current = NULL;
for(unsigned int i=0; i<s.length(); i++)
{
c=s[i];
switch(c)
{
case 'F': addBranch(&world, length, ¤t);
break;
case '+': rotateY(DEFAULT_ANGLE,&world);
break;
case '-': rotateY(-DEFAULT_ANGLE,&world);
break;
case '<': rotateX(DEFAULT_ANGLE,&world);
break;
case '>': rotateX(-DEFAULT_ANGLE,&world);
break;
case '/': rotateZ(DEFAULT_ANGLE,&world);
break;
case '\\': rotateZ(-DEFAULT_ANGLE,&world);
break;
case '[': push(&world);
branchStack.push(current);
break;
case ']': pop(&world);
current = branchStack.top();
branchStack.pop();
break;
case '|': rotateY(3.14f,&world);
break;
default:
break;
}
}
this->calculateThickness(&m_BranchList);
return S_OK;
}
Tree::~Tree()
{
}
void Tree::rotateZ(float angle,D3DXMATRIX * w)
{
D3DXMATRIX mRotation;
D3DXMatrixRotationZ(&mRotation,angle);
D3DXMatrixMultiply(w, &mRotation, w);
}
void Tree::rotateX(float angle,D3DXMATRIX * w)
{
D3DXMATRIX mRotation;
D3DXMatrixRotationX(&mRotation,angle);
D3DXMatrixMultiply(w, &mRotation, w);
}
void Tree::rotateY(float angle,D3DXMATRIX * w)
{
D3DXMATRIX mRotation;
D3DXMatrixRotationY(&mRotation,angle);
D3DXMatrixMultiply(w, &mRotation, w);
}
void Tree::push(D3DXMATRIX * w)
{
D3DXMATRIX * tmp =(D3DXMATRIX*)malloc(sizeof(D3DXMATRIX)) ;
memcpy(tmp, w, sizeof(D3DXMATRIX));
m_matrixStack->Push();
m_matrixStack->LoadMatrix(tmp);
}
void Tree::pop(D3DXMATRIX * w)
{
D3DXMATRIX *tmp=m_matrixStack->GetTop();
memcpy(w, tmp, sizeof(D3DXMATRIX));
m_matrixStack->Pop();
}
void Tree::addBranch(D3DXMATRIX *w , float length, branch ** p)
{
D3DXVECTOR4 position = D3DXVECTOR4 (0.0f, 0.0f, 0.0f, 1.0f);
D3DXVECTOR4 direction = D3DXVECTOR4 (0.0f, 1.0f, 0.0f, 1.0f);
D3DXVec4Transform(&position, &position, w);
D3DXVec4Transform(&direction, &direction, w);
branch * b=new branch();
b->direction[0]=direction.x-position.x;
b->direction[1]=direction.y-position.y;
b->direction[2]=direction.z-position.z;
b->position[0]=position.x;
b->position[1]=position.y;
b->position[2]=position.z;
b->length=length;
b->level=0;
b->prev=*p;
if(*p!=NULL)
{
b->prevDirection[0]=(*p)->direction[0];
b->prevDirection[1]=(*p)->direction[1];
b->prevDirection[2]=(*p)->direction[2];
}
else
{
b->prevDirection[0]=0.0f;
b->prevDirection[1]=1.0f;
b->prevDirection[2]=0.0f;
}
this->m_BranchList.push_back(b);
*p=this->m_BranchList.back();
D3DXMATRIX mTranslation;
D3DXMatrixTranslation(&mTranslation,0,length, 0);
D3DXMatrixMultiply(w, &mTranslation, w);
}
void Tree::calculateThickness(std::vector<branch*> * b)
{
std::vector<branch*>::iterator i=b->begin();
for(i=b->begin(); i!=b->end(); i++)
{
bool end=true;
std::vector<branch*>::iterator j=b->begin();
for(j=b->begin(); j!=b->end(); j++)
{
if((*j)->prev==*i)
end=false;
}
if(end)
{
int l=1;
branch * current=*i;
current->level=l;
current->leafs=true;
this->m_LeafList.push_back(*current);
while(current->prev!=NULL)
{
current=current->prev;
l++;
if(current->level<l)
current->level=l;
else
break;
}
}
}
}
HRESULT Tree::generateLeafsCUDA(int n, float m_size)
{
m_leafCount=n;
//allocate memory for vertices and indices
DWORD * indices=(DWORD*) malloc(this->m_LeafList.size() * sizeof(DWORD) * m_leafCount * IPL);;
SimpleVertex * vertices=(SimpleVertex*) malloc(this->m_LeafList.size() * sizeof(SimpleVertex) * m_leafCount * VPL);
ofstream g_log("log2.txt");
branch * tempArray=new branch[this->m_LeafList.size()];
std::vector<branch>::iterator j=this->m_LeafList.begin();
int p=0;
for(j=this->m_LeafList.begin(); j!=this->m_LeafList.end(); j++)
{
tempArray[p]=*j;
p++;
}
generateLeafs(tempArray, this->m_LeafList.size(), n, m_size, vertices, indices, g_log);
m_Leafs=new DrawableObject(m_pd3dDevice);
//create buffers
m_Leafs->CreateVertexBuffer(vertices, this->m_LeafList.size() * m_leafCount * VPL);
m_Leafs->CreateIndexBuffer(indices, this->m_LeafList.size() * m_leafCount * IPL,D3D10_PRIMITIVE_TOPOLOGY_POINTLIST);
free(indices);
free(vertices);
return S_OK;
}
//Generate treee vertices and indices on CUDA
HRESULT Tree::generateCuda(int w, float r)
{
//set no. of m_walls and allocate memory
m_walls=w;
SimpleVertex *v=(SimpleVertex*)malloc( this->m_BranchList.size() * w * VPW *sizeof(SimpleVertex)) ;
DWORD *ind=(DWORD*)malloc( this->m_BranchList.size() * w * IPW *sizeof(DWORD)) ;
ofstream g_log("log.txt");
//call CUDA kernel to generate vertices
branch * tempArray=new branch[this->m_BranchList.size()];
std::vector<branch*>::iterator i=this->m_BranchList.begin();
int j=0;
for(i=this->m_BranchList.begin(); i!=this->m_BranchList.end(); i++)
{
tempArray[j]=**i;
j++;
}
generateTree(tempArray,this->m_BranchList.size(),w,r ,v,ind,g_log);
m_Branches=new DrawableObject(m_pd3dDevice);
//create buffers
m_Branches->CreateVertexBuffer(v,this->m_BranchList.size() * w * VPW);
m_Branches->CreateIndexBuffer(ind, this->m_BranchList.size() * w * IPW);
free(v);
free(ind);
return S_OK;
}
void Tree::renderBranches()
{
if(m_Branches)
m_Branches->Draw();
}
void Tree::renderLeafs()
{
if(m_Leafs)
m_Leafs->Draw();
}
DrawableObject * Tree::GetBranches()
{
if(m_Branches)
return m_Branches;
else
return NULL;
}
DrawableObject * Tree::GetLeafs()
{
if(m_Leafs)
return m_Leafs;
else
return NULL;
}
// | C++ |
#ifndef _TREE
#define _TREE
#include <d3d10.h>
#include <d3dx10.h>
#include <string>
#include "treeCuda.h"
#include "l_systems.h"
#include "tree_helpers.h"
#include "vertex.h"
#include <stack>
#include <vector>
#include "drawableObject.h"
const float DEFAULT_ANGLE=0.3f;
class Tree
{
private:
int m_size;
int m_leafCount; //number of leafs per branch
int m_walls;
ID3D10Device* m_pd3dDevice;
DrawableObject * m_Leafs;
DrawableObject * m_Branches;
LPD3DXMATRIXSTACK m_matrixStack;
///list of branch structures
std::vector<branch*> m_BranchList;
///list of branches with leafs
std::vector<branch> m_LeafList;
void calculateThickness(std::vector<branch*> * b);
void rotateZ(float angle,D3DXMATRIX * w);
void rotateX(float angle,D3DXMATRIX * w);
void rotateY(float angle,D3DXMATRIX * w);
void push(D3DXMATRIX * w);
void pop(D3DXMATRIX * w);
void addBranch(D3DXMATRIX*, float length, branch ** p);
public:
Tree(ID3D10Device* d, int s);
~Tree();
HRESULT generateLSys(LSystem * system, int level, float length );
HRESULT generateCuda(int w, float r);
HRESULT generateLeafsCUDA(int n, float size);
void renderBranches();
void renderLeafs();
DrawableObject * GetBranches();
DrawableObject * GetLeafs();
};
#endif | C++ |
//=======================================================================================
// GameTimer.cpp by Frank Luna (C) 2008 All Rights Reserved.
//=======================================================================================
#include "GameTimer.h"
#include <windows.h>
GameTimer::GameTimer()
: mSecondsPerCount(0.0), mDeltaTime(-1.0), mBaseTime(0),
mPausedTime(0), mPrevTime(0), mCurrTime(0), mStopped(false)
{
__int64 countsPerSec;
QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
mSecondsPerCount = 1.0 / (double)countsPerSec;
}
// Returns the total time elapsed since reset() was called, NOT counting any
// time when the clock is stopped.
float GameTimer::getGameTime()const
{
// If we are stopped, do not count the time that has passed since we stopped.
//
// ----*---------------*------------------------------*------> time
// mBaseTime mStopTime mCurrTime
if( mStopped )
{
return (float)((mStopTime - mBaseTime)*mSecondsPerCount);
}
// The distance mCurrTime - mBaseTime includes paused time,
// which we do not want to count. To correct this, we can subtract
// the paused time from mCurrTime:
//
// (mCurrTime - mPausedTime) - mBaseTime
//
// |<-------d------->|
// ----*---------------*-----------------*------------*------> time
// mBaseTime mStopTime startTime mCurrTime
else
{
return (float)(((mCurrTime-mPausedTime)-mBaseTime)*mSecondsPerCount);
}
}
float GameTimer::getDeltaTime()const
{
return (float)mDeltaTime;
}
void GameTimer::reset()
{
__int64 currTime;
QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
mBaseTime = currTime;
mPrevTime = currTime;
mStopTime = 0;
mStopped = false;
}
void GameTimer::start()
{
__int64 startTime;
QueryPerformanceCounter((LARGE_INTEGER*)&startTime);
// Accumulate the time elapsed between stop and start pairs.
//
// |<-------d------->|
// ----*---------------*-----------------*------------> time
// mBaseTime mStopTime startTime
if( mStopped )
{
mPausedTime += (startTime - mStopTime);
mPrevTime = startTime;
mStopTime = 0;
mStopped = false;
}
}
void GameTimer::stop()
{
if( !mStopped )
{
__int64 currTime;
QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
mStopTime = currTime;
mStopped = true;
}
}
void GameTimer::tick()
{
if( mStopped )
{
mDeltaTime = 0.0;
return;
}
__int64 currTime;
QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
mCurrTime = currTime;
// Time difference between this frame and the previous.
mDeltaTime = (mCurrTime - mPrevTime)*mSecondsPerCount;
// Prepare for next frame.
mPrevTime = mCurrTime;
// Force nonnegative. The DXSDK's CDXUTTimer mentions that if the
// processor goes into a power save mode or we get shuffled to another
// processor, then mDeltaTime can be negative.
if(mDeltaTime < 0.0)
{
mDeltaTime = 0.0;
}
}
| C++ |
#ifndef _TERRAIN
#define _TERRAIN
#include <d3d10.h>
#include <d3dx10.h>
#include "terrainCuda.h"
#include "drawableObject.h"
#define lerp(t, a, b) ( a + t * (b - a) )
class Terrain
{
private:
int m_size;
float m_scale;
ID3D10Device* pd3dDevice;
DrawableObject* m_TerrainObject;
float ** m_HeightMap;
public:
Terrain(ID3D10Device* d, int m_size, float scale);
~Terrain();
HRESULT generate();
void render();
DrawableObject * GetTerrain();
float GetHeight(float x, float y);
};
#endif | C++ |
#include "terrain.h"
Terrain::Terrain(ID3D10Device* d, int size, float scale)
{
m_size=size;
m_scale=scale;
pd3dDevice = d;
m_TerrainObject=new DrawableObject(pd3dDevice);
generate();
}
HRESULT Terrain::generate()
{
//Generate vertices
ofstream g_log("log.txt");
SimpleVertex*vertices=generateTerrain(m_size, m_scale, g_log);
//Generate indices
int ic=(m_size-1)*(m_size-1)*2*3; //number of indices
DWORD * indices= (DWORD*)malloc(ic *sizeof(DWORD));
int j=0;
g_log<<"index buffer \n";
for(int i=0; i<ic; i+=6)
{
indices[i]=j;
indices[i+1]=j+m_size;
indices[i+2]=j+m_size+1;
indices[i+3]=j;
indices[i+4]=j+m_size+1;
indices[i+5]=j+1;
g_log<<indices[i]<<" ";
g_log<<indices[i+1]<<" ";
g_log<<indices[i+2]<<" \n";
g_log<<indices[i+3]<<" ";
g_log<<indices[i+4]<<" ";
g_log<<indices[i+5]<<" \n";
j++;
if((j+1)%(m_size)==0) j++;
}
m_TerrainObject->CreateVertexBuffer(vertices,m_size*m_size);
m_TerrainObject->CreateIndexBuffer(indices,ic);
///generate height map
m_HeightMap = new float*[m_size];
for(int i=0;i<m_size; i++)
m_HeightMap[i]=new float[m_size];
for(int i=0; i<m_size; i++)
{
for(int j=0; j<m_size; j++)
{
m_HeightMap[i][j]=vertices[i*m_size+j].Pos.y;
}
}
free(indices);
free(vertices);
return S_OK;
}
void Terrain::render()
{
m_TerrainObject->Draw();
}
Terrain::~Terrain()
{
if(m_TerrainObject)
{
delete(m_TerrainObject);
m_TerrainObject=NULL;
}
if(m_HeightMap)
{
for(int i=0; i<m_size; i++)
delete(m_HeightMap[i]);
delete(m_HeightMap);
}
}
DrawableObject * Terrain::GetTerrain()
{
return m_TerrainObject;
}
float Terrain::GetHeight( float x, float z )
{
float result=0.0f;
if(!m_HeightMap)
return result;
int x0=static_cast<int>(x/m_scale);
int y0=static_cast<int>(z/m_scale);
int x1=x0+1;
int y1=y0+1;
if(x0<0||y0<0||x1>m_size-1||y1>m_size-1)
return result;
float dx=x/m_scale-x0;
float dy=z/m_scale-y0;
float r0=lerp(dy,m_HeightMap[y0][x0],m_HeightMap[y1][x0]);
float r1=lerp(dy,m_HeightMap[y0][x1],m_HeightMap[y1][x1]);
result=lerp(dx,r0,r1);
return result;
} | C++ |
//=======================================================================================
// GameTimer.h by Frank Luna (C) 2008 All Rights Reserved.
//=======================================================================================
#ifndef GAMETIMER_H
#define GAMETIMER_H
class GameTimer
{
public:
GameTimer();
float getGameTime()const; // in seconds
float getDeltaTime()const; // in seconds
void reset(); // Call before message loop.
void start(); // Call when unpaused.
void stop(); // Call when paused.
void tick(); // Call every frame.
private:
double mSecondsPerCount;
double mDeltaTime;
__int64 mBaseTime;
__int64 mPausedTime;
__int64 mStopTime;
__int64 mPrevTime;
__int64 mCurrTime;
bool mStopped;
};
#endif // GAMETIMER_H | C++ |
#include "sceneObjectManager.h"
SceneObjectManager::SceneObjectManager(ID3D10Device *device, ShaderManager *shaderManager)
{
m_d3dDevice=device;
m_ShaderManager=shaderManager;
;
}
SceneObjectManager::~SceneObjectManager()
{
if(m_d3dDevice)
{
m_d3dDevice->Release();
m_d3dDevice=NULL;
}
if(m_ShaderManager)
delete(m_ShaderManager);
std::map<std::string,std::vector<SceneObject*>>::iterator it;
for(it=m_ObjectMap.begin(); it!=m_ObjectMap.end(); it++)
{
std::vector<SceneObject*>::iterator jt;
std::vector<SceneObject*> tmp=it->second;
for(jt=tmp.begin(); jt!=tmp.end(); jt++)
tmp.erase(jt);
}
}
void SceneObjectManager::AddObject(DrawableObject * object, std::string technique, D3DXVECTOR3 position, D3DXQUATERNION rotation )
{
if(m_ShaderManager->getTechniqueByName(technique)==NULL)
return;
SceneObject * sceneObject=new SceneObject();
sceneObject->m_Object=object;
D3DXMATRIX translationMatrix;
D3DXMatrixTranslation(&translationMatrix,position.x,position.y,position.z);
sceneObject->m_TranslationMatrix=translationMatrix;
sceneObject->m_Rotation=rotation;
if(m_ObjectMap.find(technique)==m_ObjectMap.end())
{
std::vector<SceneObject*> newVector;
newVector.push_back(sceneObject);
m_ObjectMap[technique]=newVector;
}
else
{
std::vector<SceneObject*> oldVector=m_ObjectMap[technique];
oldVector.push_back(sceneObject);
m_ObjectMap[technique]=oldVector;
}
}
void SceneObjectManager::Draw()
{
D3D10_TECHNIQUE_DESC techDesc;
D3DXMATRIX worldMatrix;
std::map<std::string,std::vector<SceneObject*>>::iterator it;
for(it=m_ObjectMap.begin(); it!=m_ObjectMap.end(); it++)
{
//get technique
ID3D10EffectTechnique * technique=m_ShaderManager->getTechniqueByName(it->first);
technique->GetDesc(&techDesc);
//get list of objects associated with current technique
std::vector<SceneObject*> objectVector=it->second;
//draw all the objects
std::vector<SceneObject*>::iterator jt;
for(jt=objectVector.begin(); jt!=objectVector.end(); jt++)
{
D3DXMATRIX worldMatrix;
D3DXMATRIX rotationMatrix;
D3DXMatrixRotationQuaternion(&rotationMatrix,&(*jt)->m_Rotation);
D3DXMatrixMultiply(&worldMatrix, &rotationMatrix,&(*jt)->m_TranslationMatrix);
m_ShaderManager->setMatrixVariable("World", static_cast<float*>(worldMatrix) );
for( UINT p = 0; p < techDesc.Passes; ++p )
{
technique->GetPassByIndex(p)->Apply( 0 );
(*jt)->m_Object->Draw();
}
}
}
}
void SceneObjectManager::SetEyeParameters( ICamera * camera )
{
m_EyeDirection=camera->getEyeDirection();
m_EyePosition=camera->getEyePosition();
} | C++ |
#ifndef _CAMERA
#define _CAMERA
#include <d3d10.h>
#include <d3dx10.h>
#include "iCamera.h"
class Camera:public ICamera
{
private:
D3DXVECTOR3 m_ToEye;
D3DXVECTOR3 m_At;
D3DXVECTOR3 m_Up;
float m_Radius;
D3DXQUATERNION m_Rotation;
public:
Camera();
D3DXMATRIX getViewMatrix();
D3DXVECTOR3 getEyePosition();
void move(D3DXVECTOR3 v);
void RotateY(float angle);
void RotateX(float angle);
void Zoom(float step);
D3DXVECTOR3 GetAtPosition();
void SetAtPosition(D3DXVECTOR3 position);
};
#endif | C++ |
#pragma once
#include <d3d10.h>
#include <d3dx10.h>
class ICamera
{
public:
virtual D3DXMATRIX getViewMatrix()=0;
virtual D3DXVECTOR3 getEyePosition()=0;
virtual D3DXVECTOR3 getEyeDirection()=0;
virtual ~ICamera(){};
}; | C++ |
#include "RandomTexture.h"
RandomTexture::RandomTexture(ID3D10Device * device)
{
m_d3dDevice=device;
D3D10_TEXTURE3D_DESC desc;
desc.Width=64;
desc.Height=64;
desc.Depth=64;
desc.MipLevels=1;
desc.Format=DXGI_FORMAT_R32_FLOAT;
desc.Usage=D3D10_USAGE_DYNAMIC;
desc.BindFlags=D3D10_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags=D3D10_CPU_ACCESS_WRITE;
desc.MiscFlags=0;
m_d3dDevice->CreateTexture3D(&desc, NULL, &m_Texture);
D3D10_MAPPED_TEXTURE3D mappedTex;
m_Texture->Map(D3D10CalcSubresource(0,0,1),D3D10_MAP_WRITE_DISCARD, 0,&mappedTex);
float * randomData=(float*)mappedTex.pData;
for(int i=0; i<desc.Width; i++)
{
for(int j=0; j<desc.Height; j++)
{
for(int k=0; k<desc.Depth; k++)
{
randomData[i*desc.Width*desc.Depth+j*desc.Width+k]=(float)(rand()%100)/100;
}
}
}
m_Texture->Unmap((D3D10CalcSubresource(0,0,1)));
D3D10_SHADER_RESOURCE_VIEW_DESC srDesc;
srDesc.Format = desc.Format;
srDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE3D;
srDesc.Texture2D.MostDetailedMip = 0;
srDesc.Texture2D.MipLevels = 1;
m_d3dDevice->CreateShaderResourceView(m_Texture,&srDesc,&m_TextureView);
}
RandomTexture::~RandomTexture()
{
if(m_Texture)
{
m_Texture->Release();
m_Texture=NULL;
}
if(m_TextureView)
{
m_TextureView->Release();
m_TextureView=NULL;
}
}
ID3D10ShaderResourceView* RandomTexture::GetRandomTexture()
{
return m_TextureView;
} | C++ |
#ifndef _CUDATEST
#define _CUDATEST
#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>
#include <cutil.h>
#include <fstream>
#include "vertex.h"
#include "tree_helpers.h"
using namespace std;
const int VPW=2; /// vertices per wall
const int IPW=6;/// indices per wall
const int VPL=1;/// vertices per leaf
const int IPL=1;/// indices per leaf
int generateTree(branch * b, int s, int w, float r, SimpleVertex* vertices, DWORD * indices , ofstream &out);
int generateLeafs(branch * b, int s, int n, float size, SimpleVertex* vertices, DWORD * indices , ofstream &out);
#endif
| C++ |
#include "l_systems.h"
LSystem::LSystem()
{
start="0";
}
LSystem::LSystem(std::string s, std::map<char,string> m)
{
start=s;
Rules=m;
}
void LSystem::SetStart(string s)
{
start=s;
}
void LSystem::AddRule(char p, std::string s)
{
Rules[p]=s;
}
void LSystem::RemoveRule(char p)
{
map<char,string>::iterator it;
it=Rules.find(p);
if(it!=Rules.end())
Rules.erase(it);
}
string LSystem::Expand(int level)
{
string finalString=this->start;
for(int i=0; i<level; i++)
{
string tmp=finalString;
finalString.clear();
for(int j=0; j<(int)tmp.length(); j++)
{
char c=tmp[j];
if(Rules.find(c)!=Rules.end())
finalString+=Rules[c];
else
finalString+=tmp[j];
}
}
return finalString;
} | C++ |
#include "shader_manager.h"
ShaderManager::ShaderManager(ID3D10Device * device, std::string shaderFilePath)
{
m_pd3dDevice=device;
// Create the effect
DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
dwShaderFlags |= D3D10_SHADER_DEBUG;
#endif
HRESULT hr=D3DX10CreateEffectFromFile( shaderFilePath.c_str(), NULL, NULL, "fx_4_0", dwShaderFlags, 0,
m_pd3dDevice, NULL, NULL, &m_pd3dEffect, NULL, NULL );
if(FAILED(hr))
MessageBox(NULL, "Error opening shader file", "Error",0);
}
void ShaderManager::addScalarVariable( std::string name )
{
if(!m_pd3dEffect)
return;
if(m_ScalarVariables[name]!=NULL)
{
MessageBox(NULL, "Variable already exists",name.c_str(),0);
return;
}
ID3D10EffectScalarVariable* variable=m_pd3dEffect->GetVariableByName( name.c_str() )->AsScalar();
m_ScalarVariables[name]=variable;
}
ID3D10EffectScalarVariable * ShaderManager::getScalarVariableByName( std::string name )
{
if(m_ScalarVariables[name]==NULL)
{
MessageBox(NULL, "Variable doesn't exist",name.c_str(),0);
return NULL;
}
ID3D10EffectScalarVariable * variable = m_ScalarVariables[name];
return variable;
}
void ShaderManager::addVectorVariable( std::string name )
{
if(!m_pd3dEffect)
return;
if(m_VectorVariables[name]!=NULL)
{
MessageBox(NULL, "Variable already exists",name.c_str(),0);
return;
}
ID3D10EffectVectorVariable* variable=m_pd3dEffect->GetVariableByName( name.c_str() )->AsVector();
m_VectorVariables[name]=variable;
}
ID3D10EffectVectorVariable * ShaderManager::getVectorVariableByName( std::string name )
{
if(m_VectorVariables[name]==NULL)
{
MessageBox(NULL, "Variable doesn't exist",name.c_str(),0);
return NULL;
}
ID3D10EffectVectorVariable * variable = m_VectorVariables[name];
return variable;
}
void ShaderManager::addMatrixVariable( std::string name )
{
if(!m_pd3dEffect)
return;
if(m_MatrixVariables[name]!=NULL)
{
MessageBox(NULL, "Variable already exists",name.c_str(),0);
return;
}
ID3D10EffectMatrixVariable* variable=m_pd3dEffect->GetVariableByName( name.c_str() )->AsMatrix();
m_MatrixVariables[name]=variable;
}
ID3D10EffectMatrixVariable * ShaderManager::getMatrixVariableByName( std::string name )
{
if(m_MatrixVariables[name]==NULL)
{
MessageBox(NULL, "Variable doesn't exist",name.c_str(),0);
return NULL;
}
ID3D10EffectMatrixVariable * variable = m_MatrixVariables[name];
return variable;
}
void ShaderManager::addResourceVariable( std::string name )
{
if(!m_pd3dEffect)
return;
if(m_ResourceVariables[name]!=NULL)
{
MessageBox(NULL, "Variable already exists",name.c_str(),0);
return;
}
ID3D10EffectShaderResourceVariable* variable=m_pd3dEffect->GetVariableByName( name.c_str() )->AsShaderResource();
m_ResourceVariables[name]=variable;
}
ID3D10EffectShaderResourceVariable * ShaderManager::getResourceVariableByName( std::string name )
{
if(m_ResourceVariables[name]==NULL)
{
MessageBox(NULL, "Variable doesn't exist",name.c_str(),0);
return NULL;
}
ID3D10EffectShaderResourceVariable * variable = m_ResourceVariables[name];
return variable;
}
void ShaderManager::setScalarVariable( std::string name, float value )
{
ID3D10EffectScalarVariable* variable=m_ScalarVariables[name];
if(variable==NULL)
{
MessageBox(NULL,"Variable doesn't exist",name.c_str(),0);
return;
}
variable->SetFloat(value);
}
void ShaderManager::setVectorVariable( std::string name, float* value )
{
ID3D10EffectVectorVariable* variable=m_VectorVariables[name];
if(variable==NULL)
{
MessageBox(NULL,"Variable doesn't exist",name.c_str(),0);
return;
}
variable->SetFloatVector(value);
}
void ShaderManager::setMatrixVariable( std::string name, float* value )
{
ID3D10EffectMatrixVariable* variable=m_MatrixVariables[name];
if(variable==NULL)
{
MessageBox(NULL,"Variable doesn't exist",name.c_str(),0);
return;
}
variable->SetMatrix(value);
}
void ShaderManager::setResourceVariable(std::string name, ID3D10ShaderResourceView* value)
{
ID3D10EffectShaderResourceVariable* variable=m_ResourceVariables[name];
if(variable==NULL)
{
MessageBox(NULL,"Variable doesn't exist",name.c_str(),0);
return;
}
variable->SetResource(value);
}
void ShaderManager::addTechnique( std::string name )
{
ID3D10EffectTechnique* technique=m_pd3dEffect->GetTechniqueByName(name.c_str());
if(!technique)
{
MessageBox(NULL,"Error adding technique", "Error", 0);
return;
}
m_Techniques[name]=technique;
}
ID3D10EffectTechnique* ShaderManager::getTechniqueByName( std::string name )
{
ID3D10EffectTechnique* technique=m_Techniques[name];
if(!technique)
MessageBox(NULL,"The technique doesn't exist", "Error",0);
return technique;
} | C++ |
#pragma once
#include <d3d10.h>
#include <d3dx10.h>
#include "terrain.h"
#include "drawableObject.h"
//Single vertices for generating plant billboards by geometry shader
class TerrainPlants
{
private:
ID3D10Device * m_d3dDevice;
int m_size;
DrawableObject * m_DrawableObject;
public:
TerrainPlants(ID3D10Device * device, int size);
~TerrainPlants();
DrawableObject * GetDrawableObject();
void Generate(Terrain * terrain, D3DXVECTOR2 upperLeft, D3DXVECTOR2 lowerRight); //generate points
}; | C++ |
/*
* SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
* Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice including the dates of first publication and
* either this permission notice or a reference to
* http://oss.sgi.com/projects/FreeB/
* 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
* SILICON GRAPHICS, INC. 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.
*
* Except as contained in this notice, the name of Silicon Graphics, Inc.
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization from
* Silicon Graphics, Inc.
*
* OpenGL ES 1.0 CM port of GLU by Mike Gorchak <mike@malva.ua>
*/
#ifndef __glues_h__
#define __glues_h__
#if defined(__USE_SDL_GLES__)
#include <SDL/SDL_opengles.h>
#ifndef GLAPI
#define GLAPI GL_API
#endif
#elif defined (__QNXNTO__)
#include <GLES/gl.h>
#include <GLES/glext.h>
#elif defined(_WIN32) && (defined(_M_IX86) || defined(_M_X64))
/* mainly for PowerVR OpenGL ES 1.x win32 emulator */
#include <GLES\gl.h>
#include <GLES\glext.h>
#undef APIENTRY
#define APIENTRY
#if defined(GLUES_EXPORTS)
#define GLAPI __declspec(dllexport)
#else
#define GLAPI __declspec(dllimport)
#endif
#elif defined(ANDROID)
#include <GLES/gl.h>
#define APIENTRY
#define GLAPI
#else
#error "Platform is unsupported"
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif /* APIENTRYP */
#ifdef __cplusplus
extern "C" {
#endif
/*************************************************************/
/* Extensions */
#define GLU_EXT_object_space_tess 1
#define GLU_EXT_nurbs_tessellator 1
/* Boolean */
#define GLU_FALSE 0
#define GLU_TRUE 1
/* Version */
#define GLU_VERSION_1_1 1
#define GLU_VERSION_1_2 1
#define GLU_VERSION_1_3 1
/* StringName */
#define GLU_VERSION 100800
#define GLU_EXTENSIONS 100801
/* ErrorCode */
#define GLU_INVALID_ENUM 100900
#define GLU_INVALID_VALUE 100901
#define GLU_OUT_OF_MEMORY 100902
#define GLU_INCOMPATIBLE_GL_VERSION 100903
#define GLU_INVALID_OPERATION 100904
/* QuadricDrawStyle */
#define GLU_POINT 100010
#define GLU_LINE 100011
#define GLU_FILL 100012
#define GLU_SILHOUETTE 100013
/* QuadricCallback */
#define GLU_ERROR 100103
/* QuadricNormal */
#define GLU_SMOOTH 100000
#define GLU_FLAT 100001
#define GLU_NONE 100002
/* QuadricOrientation */
#define GLU_OUTSIDE 100020
#define GLU_INSIDE 100021
/*************************************************************/
#ifdef __cplusplus
class GLUquadric;
class GLUtesselator;
class GLUnurbs;
#else
typedef struct GLUquadric GLUquadric;
typedef struct GLUtesselator GLUtesselator;
typedef struct GLUnurbs GLUnurbs;
#endif
typedef GLUquadric GLUquadricObj;
typedef GLUtesselator GLUtesselatorObj;
typedef GLUtesselator GLUtriangulatorObj;
typedef GLUnurbs GLUnurbsObj;
/* Internal convenience typedefs */
typedef void (APIENTRYP _GLUfuncptr)();
GLAPI GLboolean APIENTRY gluCheckExtension(const GLubyte* extName, const GLubyte* extString);
GLAPI void APIENTRY gluCylinder(GLUquadric* quad, GLfloat base, GLfloat top, GLfloat height, GLint slices, GLint stacks);
GLAPI void APIENTRY gluDeleteQuadric(GLUquadric* quad);
GLAPI void APIENTRY gluDisk(GLUquadric* quad, GLfloat inner, GLfloat outer, GLint slices, GLint loops);
GLAPI const GLubyte* APIENTRY gluErrorString(GLenum error);
GLAPI const GLubyte * APIENTRY gluGetString(GLenum name);
GLAPI void APIENTRY gluLookAt(GLfloat eyeX, GLfloat eyeY, GLfloat eyeZ, GLfloat centerX, GLfloat centerY, GLfloat centerZ, GLfloat upX, GLfloat upY, GLfloat upZ);
GLAPI GLUquadric* APIENTRY gluNewQuadric(void);
GLAPI void APIENTRY gluOrtho2D(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top);
GLAPI void APIENTRY gluPartialDisk(GLUquadric* quad, GLfloat inner, GLfloat outer, GLint slices, GLint loops, GLfloat start, GLfloat sweep);
GLAPI void APIENTRY gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar);
GLAPI void APIENTRY gluPickMatrix(GLfloat x_, GLfloat y, GLfloat delX, GLfloat delY, GLint *viewport);
GLAPI GLint APIENTRY gluProject(GLfloat objX, GLfloat objY, GLfloat objZ, const GLfloat *model, const GLfloat *proj, const GLint *view, GLfloat* winX, GLfloat* winY, GLfloat* winZ);
GLAPI void APIENTRY gluQuadricCallback(GLUquadric* quad, GLenum which, _GLUfuncptr CallBackFunc);
GLAPI void APIENTRY gluQuadricDrawStyle(GLUquadric* quad, GLenum draw);
GLAPI void APIENTRY gluQuadricNormals(GLUquadric* quad, GLenum normal);
GLAPI void APIENTRY gluQuadricOrientation(GLUquadric* quad, GLenum orientation);
GLAPI void APIENTRY gluQuadricTexture(GLUquadric* quad, GLboolean texture);
GLAPI void APIENTRY gluSphere(GLUquadric* quad, GLfloat radius, GLint slices, GLint stacks);
GLAPI GLint APIENTRY gluUnProject(GLfloat winX, GLfloat winY, GLfloat winZ, const GLfloat *model, const GLfloat *proj, const GLint *view, GLfloat* objX, GLfloat* objY, GLfloat* objZ);
GLAPI GLint APIENTRY gluUnProject4(GLfloat winX, GLfloat winY, GLfloat winZ, GLfloat clipW, const GLfloat *model, const GLfloat *proj, const GLint *view, GLfloat nearVal, GLfloat farVal, GLfloat* objX, GLfloat* objY, GLfloat* objZ, GLfloat* objW);
GLAPI GLint APIENTRY gluScaleImage(GLenum format, GLsizei widthin,
GLsizei heightin, GLenum typein,
const void* datain, GLsizei widthout,
GLsizei heightout, GLenum typeout, void* dataout);
GLAPI GLint APIENTRY gluBuild2DMipmapLevels(GLenum target, GLint internalFormat,
GLsizei width, GLsizei height, GLenum format,
GLenum type, GLint userLevel, GLint baseLevel,
GLint maxLevel, const void *data);
GLAPI GLint APIENTRY gluBuild2DMipmaps(GLenum target, GLint internalFormat,
GLsizei width, GLsizei height, GLenum format,
GLenum type, const void* data);
#define GLU_TESS_MAX_COORD 1.0e37f
/* TessCallback */
#define GLU_TESS_BEGIN 100100
#define GLU_BEGIN 100100
#define GLU_TESS_VERTEX 100101
#define GLU_VERTEX 100101
#define GLU_TESS_END 100102
#define GLU_END 100102
#define GLU_TESS_ERROR 100103
#define GLU_TESS_EDGE_FLAG 100104
#define GLU_EDGE_FLAG 100104
#define GLU_TESS_COMBINE 100105
#define GLU_TESS_BEGIN_DATA 100106
#define GLU_TESS_VERTEX_DATA 100107
#define GLU_TESS_END_DATA 100108
#define GLU_TESS_ERROR_DATA 100109
#define GLU_TESS_EDGE_FLAG_DATA 100110
#define GLU_TESS_COMBINE_DATA 100111
/* TessContour */
#define GLU_CW 100120
#define GLU_CCW 100121
#define GLU_INTERIOR 100122
#define GLU_EXTERIOR 100123
#define GLU_UNKNOWN 100124
/* TessProperty */
#define GLU_TESS_WINDING_RULE 100140
#define GLU_TESS_BOUNDARY_ONLY 100141
#define GLU_TESS_TOLERANCE 100142
/* TessError */
#define GLU_TESS_ERROR1 100151
#define GLU_TESS_ERROR2 100152
#define GLU_TESS_ERROR3 100153
#define GLU_TESS_ERROR4 100154
#define GLU_TESS_ERROR5 100155
#define GLU_TESS_ERROR6 100156
#define GLU_TESS_ERROR7 100157
#define GLU_TESS_ERROR8 100158
#define GLU_TESS_MISSING_BEGIN_POLYGON 100151
#define GLU_TESS_MISSING_BEGIN_CONTOUR 100152
#define GLU_TESS_MISSING_END_POLYGON 100153
#define GLU_TESS_MISSING_END_CONTOUR 100154
#define GLU_TESS_COORD_TOO_LARGE 100155
#define GLU_TESS_NEED_COMBINE_CALLBACK 100156
/* TessWinding */
#define GLU_TESS_WINDING_ODD 100130
#define GLU_TESS_WINDING_NONZERO 100131
#define GLU_TESS_WINDING_POSITIVE 100132
#define GLU_TESS_WINDING_NEGATIVE 100133
#define GLU_TESS_WINDING_ABS_GEQ_TWO 100134
GLAPI void APIENTRY gluBeginPolygon(GLUtesselator* tess);
GLAPI void APIENTRY gluDeleteTess(GLUtesselator* tess);
GLAPI void APIENTRY gluEndPolygon(GLUtesselator* tess);
GLAPI void APIENTRY gluGetTessProperty(GLUtesselator* tess, GLenum which, GLfloat* data);
GLAPI GLUtesselator* APIENTRY gluNewTess(void);
GLAPI void APIENTRY gluNextContour(GLUtesselator* tess, GLenum type);
GLAPI void APIENTRY gluTessBeginContour(GLUtesselator* tess);
GLAPI void APIENTRY gluTessBeginPolygon(GLUtesselator* tess, GLvoid* data);
GLAPI void APIENTRY gluTessCallback(GLUtesselator* tess, GLenum which, _GLUfuncptr CallBackFunc);
GLAPI void APIENTRY gluTessEndContour(GLUtesselator* tess);
GLAPI void APIENTRY gluTessEndPolygon(GLUtesselator* tess);
GLAPI void APIENTRY gluTessNormal(GLUtesselator* tess, GLfloat valueX, GLfloat valueY, GLfloat valueZ);
GLAPI void APIENTRY gluTessProperty(GLUtesselator* tess, GLenum which, GLfloat data);
GLAPI void APIENTRY gluTessVertex(GLUtesselator* tess, GLfloat* location, GLvoid* data);
/* NurbsDisplay */
/* GLU_FILL */
#define GLU_OUTLINE_POLYGON 100240
#define GLU_OUTLINE_PATCH 100241
/* NurbsCallback */
#define GLU_NURBS_ERROR 100103
#define GLU_ERROR 100103
#define GLU_NURBS_BEGIN 100164
#define GLU_NURBS_BEGIN_EXT 100164
#define GLU_NURBS_VERTEX 100165
#define GLU_NURBS_VERTEX_EXT 100165
#define GLU_NURBS_NORMAL 100166
#define GLU_NURBS_NORMAL_EXT 100166
#define GLU_NURBS_COLOR 100167
#define GLU_NURBS_COLOR_EXT 100167
#define GLU_NURBS_TEXTURE_COORD 100168
#define GLU_NURBS_TEX_COORD_EXT 100168
#define GLU_NURBS_END 100169
#define GLU_NURBS_END_EXT 100169
#define GLU_NURBS_BEGIN_DATA 100170
#define GLU_NURBS_BEGIN_DATA_EXT 100170
#define GLU_NURBS_VERTEX_DATA 100171
#define GLU_NURBS_VERTEX_DATA_EXT 100171
#define GLU_NURBS_NORMAL_DATA 100172
#define GLU_NURBS_NORMAL_DATA_EXT 100172
#define GLU_NURBS_COLOR_DATA 100173
#define GLU_NURBS_COLOR_DATA_EXT 100173
#define GLU_NURBS_TEXTURE_COORD_DATA 100174
#define GLU_NURBS_TEX_COORD_DATA_EXT 100174
#define GLU_NURBS_END_DATA 100175
#define GLU_NURBS_END_DATA_EXT 100175
/* NurbsError */
#define GLU_NURBS_ERROR1 100251
#define GLU_NURBS_ERROR2 100252
#define GLU_NURBS_ERROR3 100253
#define GLU_NURBS_ERROR4 100254
#define GLU_NURBS_ERROR5 100255
#define GLU_NURBS_ERROR6 100256
#define GLU_NURBS_ERROR7 100257
#define GLU_NURBS_ERROR8 100258
#define GLU_NURBS_ERROR9 100259
#define GLU_NURBS_ERROR10 100260
#define GLU_NURBS_ERROR11 100261
#define GLU_NURBS_ERROR12 100262
#define GLU_NURBS_ERROR13 100263
#define GLU_NURBS_ERROR14 100264
#define GLU_NURBS_ERROR15 100265
#define GLU_NURBS_ERROR16 100266
#define GLU_NURBS_ERROR17 100267
#define GLU_NURBS_ERROR18 100268
#define GLU_NURBS_ERROR19 100269
#define GLU_NURBS_ERROR20 100270
#define GLU_NURBS_ERROR21 100271
#define GLU_NURBS_ERROR22 100272
#define GLU_NURBS_ERROR23 100273
#define GLU_NURBS_ERROR24 100274
#define GLU_NURBS_ERROR25 100275
#define GLU_NURBS_ERROR26 100276
#define GLU_NURBS_ERROR27 100277
#define GLU_NURBS_ERROR28 100278
#define GLU_NURBS_ERROR29 100279
#define GLU_NURBS_ERROR30 100280
#define GLU_NURBS_ERROR31 100281
#define GLU_NURBS_ERROR32 100282
#define GLU_NURBS_ERROR33 100283
#define GLU_NURBS_ERROR34 100284
#define GLU_NURBS_ERROR35 100285
#define GLU_NURBS_ERROR36 100286
#define GLU_NURBS_ERROR37 100287
/* NurbsProperty */
#define GLU_AUTO_LOAD_MATRIX 100200
#define GLU_CULLING 100201
#define GLU_SAMPLING_TOLERANCE 100203
#define GLU_DISPLAY_MODE 100204
#define GLU_PARAMETRIC_TOLERANCE 100202
#define GLU_SAMPLING_METHOD 100205
#define GLU_U_STEP 100206
#define GLU_V_STEP 100207
#define GLU_NURBS_MODE 100160
#define GLU_NURBS_MODE_EXT 100160
#define GLU_NURBS_TESSELLATOR 100161
#define GLU_NURBS_TESSELLATOR_EXT 100161
#define GLU_NURBS_RENDERER 100162
#define GLU_NURBS_RENDERER_EXT 100162
/* NurbsSampling */
#define GLU_OBJECT_PARAMETRIC_ERROR 100208
#define GLU_OBJECT_PARAMETRIC_ERROR_EXT 100208
#define GLU_OBJECT_PATH_LENGTH 100209
#define GLU_OBJECT_PATH_LENGTH_EXT 100209
#define GLU_PATH_LENGTH 100215
#define GLU_PARAMETRIC_ERROR 100216
#define GLU_DOMAIN_DISTANCE 100217
/* NurbsTrim */
#define GLU_MAP1_TRIM_2 100210
#define GLU_MAP1_TRIM_3 100211
GLAPI void APIENTRY gluBeginCurve(GLUnurbs* nurb);
GLAPI void APIENTRY gluBeginSurface(GLUnurbs* nurb);
GLAPI void APIENTRY gluBeginTrim(GLUnurbs* nurb);
GLAPI void APIENTRY gluDeleteNurbsRenderer(GLUnurbs* nurb);
GLAPI void APIENTRY gluEndCurve(GLUnurbs* nurb);
GLAPI void APIENTRY gluEndSurface(GLUnurbs* nurb);
GLAPI void APIENTRY gluEndTrim(GLUnurbs* nurb);
GLAPI void APIENTRY gluGetNurbsProperty(GLUnurbs* nurb, GLenum property, GLfloat* data);
GLAPI void APIENTRY gluLoadSamplingMatrices(GLUnurbs* nurb, const GLfloat* model, const GLfloat* perspective, const GLint* view);
GLAPI GLUnurbs* APIENTRY gluNewNurbsRenderer(void);
GLAPI void APIENTRY gluNurbsCallback(GLUnurbs* nurb, GLenum which, _GLUfuncptr CallBackFunc);
GLAPI void APIENTRY gluNurbsCallbackData(GLUnurbs* nurb, GLvoid* userData);
GLAPI void APIENTRY gluNurbsCallbackDataEXT(GLUnurbs* nurb, GLvoid* userData);
GLAPI void APIENTRY gluNurbsCurve(GLUnurbs* nurb, GLint knotCount, GLfloat* knots, GLint stride, GLfloat* control, GLint order, GLenum type);
GLAPI void APIENTRY gluNurbsProperty(GLUnurbs* nurb, GLenum property, GLfloat value);
GLAPI void APIENTRY gluNurbsSurface(GLUnurbs* nurb, GLint sKnotCount, GLfloat* sKnots, GLint tKnotCount, GLfloat* tKnots, GLint sStride, GLint tStride, GLfloat* control, GLint sOrder, GLint tOrder, GLenum type);
GLAPI void APIENTRY gluPwlCurve(GLUnurbs* nurb, GLint count, GLfloat* data, GLint stride, GLenum type);
/* OpenGL (and OpenGL ES 1.1 for OpenGL ES 1.0) emulation layer */
#define GLU_AUTO_NORMAL 0x0D80
#define GLU_MAP1_COLOR_4 0x0D90
#define GLU_MAP1_INDEX 0x0D91
#define GLU_MAP1_NORMAL 0x0D92
#define GLU_MAP1_TEXTURE_COORD_1 0x0D93
#define GLU_MAP1_TEXTURE_COORD_2 0x0D94
#define GLU_MAP1_TEXTURE_COORD_3 0x0D95
#define GLU_MAP1_TEXTURE_COORD_4 0x0D96
#define GLU_MAP1_VERTEX_3 0x0D97
#define GLU_MAP1_VERTEX_4 0x0D98
#define GLU_MAP2_COLOR_4 0x0DB0
#define GLU_MAP2_INDEX 0x0DB1
#define GLU_MAP2_NORMAL 0x0DB2
#define GLU_MAP2_TEXTURE_COORD_1 0x0DB3
#define GLU_MAP2_TEXTURE_COORD_2 0x0DB4
#define GLU_MAP2_TEXTURE_COORD_3 0x0DB5
#define GLU_MAP2_TEXTURE_COORD_4 0x0DB6
#define GLU_MAP2_VERTEX_3 0x0DB7
#define GLU_MAP2_VERTEX_4 0x0DB8
#ifndef GL_MODELVIEW_MATRIX
#define GL_MODELVIEW_MATRIX 0x0BA6
#endif /* GL_MODELVIEW_MATRIX */
#ifndef GL_PROJECTION_MATRIX
#define GL_PROJECTION_MATRIX 0x0BA7
#endif /* GL_PROJECTION_MATRIX */
#ifndef GL_VIEWPORT
#define GL_VIEWPORT 0x0BA2
#endif /* GL_VIEWPORT */
GLAPI void APIENTRY gluEnable(GLenum cap);
GLAPI void APIENTRY gluDisable(GLenum cap);
GLAPI void APIENTRY gluGetFloatv(GLenum pname, GLfloat* params);
GLAPI void APIENTRY gluGetIntegerv(GLenum pname, GLint* params);
GLAPI void APIENTRY gluViewport(GLint x_, GLint y, GLsizei width, GLsizei height);
#ifdef __cplusplus
}
#endif
#endif /* __glues_h__ */
| C++ |
/*
* SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
* Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice including the dates of first publication and
* either this permission notice or a reference to
* http://oss.sgi.com/projects/FreeB/
* 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
* SILICON GRAPHICS, INC. 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.
*
* Except as contained in this notice, the name of Silicon Graphics, Inc.
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization from
* Silicon Graphics, Inc.
*
* OpenGL ES CM 1.0 port of GLU by Mike Gorchak <mike@malva.ua>
*/
#ifndef __GLUES_QUAD_H__
#define __GLUES_QUAD_H__
#if defined(__USE_SDL_GLES__)
#include <SDL/SDL_opengles.h>
#ifndef GLAPI
#define GLAPI GL_API
#endif
#elif defined (__QNXNTO__)
#include <GLES/gl.h>
#elif defined(_WIN32) && (defined(_M_IX86) || defined(_M_X64))
/* mainly for PowerVR OpenGL ES 1.x win32 emulator */
#include <GLES\gl.h>
#undef APIENTRY
#define APIENTRY
#if defined(GLUES_EXPORTS)
#define GLAPI __declspec(dllexport)
#else
#define GLAPI __declspec(dllimport)
#endif
#elif defined(ANDROID)
#include <GLES/gl.h>
#define APIENTRY
#define GLAPI
#else
#error "Platform is unsupported"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* ErrorCode */
#define GLU_INVALID_ENUM 100900
#define GLU_INVALID_VALUE 100901
#define GLU_OUT_OF_MEMORY 100902
#define GLU_INCOMPATIBLE_GL_VERSION 100903
#define GLU_INVALID_OPERATION 100904
/* QuadricDrawStyle */
#define GLU_POINT 100010
#define GLU_LINE 100011
#define GLU_FILL 100012
#define GLU_SILHOUETTE 100013
/* QuadricCallback */
#define GLU_ERROR 100103
/* QuadricNormal */
#define GLU_SMOOTH 100000
#define GLU_FLAT 100001
#define GLU_NONE 100002
/* QuadricOrientation */
#define GLU_OUTSIDE 100020
#define GLU_INSIDE 100021
#ifdef __cplusplus
class GLUquadric;
#else
typedef struct GLUquadric GLUquadric;
#endif
typedef GLUquadric GLUquadricObj;
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif /* APIENTRYP */
/* Internal convenience typedefs */
typedef void (APIENTRYP _GLUfuncptr)();
GLAPI GLUquadric* APIENTRY gluNewQuadric(void);
GLAPI void APIENTRY gluDeleteQuadric(GLUquadric* state);
GLAPI void APIENTRY gluQuadricCallback(GLUquadric* qobj, GLenum which,
_GLUfuncptr fn);
GLAPI void APIENTRY gluQuadricNormals(GLUquadric* qobj, GLenum normals);
GLAPI void APIENTRY gluQuadricTexture(GLUquadric* qobj, GLboolean textureCoords);
GLAPI void APIENTRY gluQuadricOrientation(GLUquadric* qobj, GLenum orientation);
GLAPI void APIENTRY gluQuadricDrawStyle(GLUquadric* qobj, GLenum drawStyle);
GLAPI void APIENTRY gluCylinder(GLUquadric* qobj, GLfloat baseRadius,
GLfloat topRadius, GLfloat height,
GLint slices, GLint stacks);
GLAPI void APIENTRY gluDisk(GLUquadric* qobj, GLfloat innerRadius,
GLfloat outerRadius, GLint slices, GLint loops);
GLAPI void APIENTRY gluPartialDisk(GLUquadric* qobj, GLfloat innerRadius,
GLfloat outerRadius, GLint slices,
GLint loops, GLfloat startAngle,
GLfloat sweepAngle);
GLAPI void APIENTRY gluSphere(GLUquadric* qobj, GLfloat radius, GLint slices,
GLint stacks);
#ifdef __cplusplus
}
#endif
#endif /* __GLUES_QUAD_H__ */
| C++ |
/*
* SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
* Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice including the dates of first publication and
* either this permission notice or a reference to
* http://oss.sgi.com/projects/FreeB/
* 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
* SILICON GRAPHICS, INC. 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.
*
* Except as contained in this notice, the name of Silicon Graphics, Inc.
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization from
* Silicon Graphics, Inc.
*
* OpenGL ES 1.0 CM port of GLU by Mike Gorchak <mike@malva.ua>
*/
#ifndef __glues_h__
#define __glues_h__
#if defined(__USE_SDL_GLES__)
#include <SDL/SDL_opengles.h>
#ifndef GLAPI
#define GLAPI GL_API
#endif
#elif defined (__QNXNTO__)
#include <GLES/gl.h>
#include <GLES/glext.h>
#elif defined(_WIN32) && (defined(_M_IX86) || defined(_M_X64))
/* mainly for PowerVR OpenGL ES 1.x win32 emulator */
#include <GLES\gl.h>
#include <GLES\glext.h>
#undef APIENTRY
#define APIENTRY
#if defined(GLUES_EXPORTS)
#define GLAPI __declspec(dllexport)
#else
#define GLAPI __declspec(dllimport)
#endif
#elif defined(ANDROID)
#include <GLES/gl.h>
#define APIENTRY
#define GLAPI
#else
#error "Platform is unsupported"
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif /* APIENTRYP */
#ifdef __cplusplus
extern "C" {
#endif
/*************************************************************/
/* Extensions */
#define GLU_EXT_object_space_tess 1
#define GLU_EXT_nurbs_tessellator 1
/* Boolean */
#define GLU_FALSE 0
#define GLU_TRUE 1
/* Version */
#define GLU_VERSION_1_1 1
#define GLU_VERSION_1_2 1
#define GLU_VERSION_1_3 1
/* StringName */
#define GLU_VERSION 100800
#define GLU_EXTENSIONS 100801
/* ErrorCode */
#define GLU_INVALID_ENUM 100900
#define GLU_INVALID_VALUE 100901
#define GLU_OUT_OF_MEMORY 100902
#define GLU_INCOMPATIBLE_GL_VERSION 100903
#define GLU_INVALID_OPERATION 100904
/* QuadricDrawStyle */
#define GLU_POINT 100010
#define GLU_LINE 100011
#define GLU_FILL 100012
#define GLU_SILHOUETTE 100013
/* QuadricCallback */
#define GLU_ERROR 100103
/* QuadricNormal */
#define GLU_SMOOTH 100000
#define GLU_FLAT 100001
#define GLU_NONE 100002
/* QuadricOrientation */
#define GLU_OUTSIDE 100020
#define GLU_INSIDE 100021
/*************************************************************/
#ifdef __cplusplus
class GLUquadric;
class GLUtesselator;
class GLUnurbs;
#else
typedef struct GLUquadric GLUquadric;
typedef struct GLUtesselator GLUtesselator;
typedef struct GLUnurbs GLUnurbs;
#endif
typedef GLUquadric GLUquadricObj;
typedef GLUtesselator GLUtesselatorObj;
typedef GLUtesselator GLUtriangulatorObj;
typedef GLUnurbs GLUnurbsObj;
/* Internal convenience typedefs */
typedef void (APIENTRYP _GLUfuncptr)();
GLAPI GLboolean APIENTRY gluCheckExtension(const GLubyte* extName, const GLubyte* extString);
GLAPI void APIENTRY gluCylinder(GLUquadric* quad, GLfloat base, GLfloat top, GLfloat height, GLint slices, GLint stacks);
GLAPI void APIENTRY gluDeleteQuadric(GLUquadric* quad);
GLAPI void APIENTRY gluDisk(GLUquadric* quad, GLfloat inner, GLfloat outer, GLint slices, GLint loops);
GLAPI const GLubyte* APIENTRY gluErrorString(GLenum error);
GLAPI const GLubyte * APIENTRY gluGetString(GLenum name);
GLAPI void APIENTRY gluLookAt(GLfloat eyeX, GLfloat eyeY, GLfloat eyeZ, GLfloat centerX, GLfloat centerY, GLfloat centerZ, GLfloat upX, GLfloat upY, GLfloat upZ);
GLAPI GLUquadric* APIENTRY gluNewQuadric(void);
GLAPI void APIENTRY gluOrtho2D(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top);
GLAPI void APIENTRY gluPartialDisk(GLUquadric* quad, GLfloat inner, GLfloat outer, GLint slices, GLint loops, GLfloat start, GLfloat sweep);
GLAPI void APIENTRY gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar);
GLAPI void APIENTRY gluPickMatrix(GLfloat x_, GLfloat y, GLfloat delX, GLfloat delY, GLint *viewport);
GLAPI GLint APIENTRY gluProject(GLfloat objX, GLfloat objY, GLfloat objZ, const GLfloat *model, const GLfloat *proj, const GLint *view, GLfloat* winX, GLfloat* winY, GLfloat* winZ);
GLAPI void APIENTRY gluQuadricCallback(GLUquadric* quad, GLenum which, _GLUfuncptr CallBackFunc);
GLAPI void APIENTRY gluQuadricDrawStyle(GLUquadric* quad, GLenum draw);
GLAPI void APIENTRY gluQuadricNormals(GLUquadric* quad, GLenum normal);
GLAPI void APIENTRY gluQuadricOrientation(GLUquadric* quad, GLenum orientation);
GLAPI void APIENTRY gluQuadricTexture(GLUquadric* quad, GLboolean texture);
GLAPI void APIENTRY gluSphere(GLUquadric* quad, GLfloat radius, GLint slices, GLint stacks);
GLAPI GLint APIENTRY gluUnProject(GLfloat winX, GLfloat winY, GLfloat winZ, const GLfloat *model, const GLfloat *proj, const GLint *view, GLfloat* objX, GLfloat* objY, GLfloat* objZ);
GLAPI GLint APIENTRY gluUnProject4(GLfloat winX, GLfloat winY, GLfloat winZ, GLfloat clipW, const GLfloat *model, const GLfloat *proj, const GLint *view, GLfloat nearVal, GLfloat farVal, GLfloat* objX, GLfloat* objY, GLfloat* objZ, GLfloat* objW);
GLAPI GLint APIENTRY gluScaleImage(GLenum format, GLsizei widthin,
GLsizei heightin, GLenum typein,
const void* datain, GLsizei widthout,
GLsizei heightout, GLenum typeout, void* dataout);
GLAPI GLint APIENTRY gluBuild2DMipmapLevels(GLenum target, GLint internalFormat,
GLsizei width, GLsizei height, GLenum format,
GLenum type, GLint userLevel, GLint baseLevel,
GLint maxLevel, const void *data);
GLAPI GLint APIENTRY gluBuild2DMipmaps(GLenum target, GLint internalFormat,
GLsizei width, GLsizei height, GLenum format,
GLenum type, const void* data);
#define GLU_TESS_MAX_COORD 1.0e37f
/* TessCallback */
#define GLU_TESS_BEGIN 100100
#define GLU_BEGIN 100100
#define GLU_TESS_VERTEX 100101
#define GLU_VERTEX 100101
#define GLU_TESS_END 100102
#define GLU_END 100102
#define GLU_TESS_ERROR 100103
#define GLU_TESS_EDGE_FLAG 100104
#define GLU_EDGE_FLAG 100104
#define GLU_TESS_COMBINE 100105
#define GLU_TESS_BEGIN_DATA 100106
#define GLU_TESS_VERTEX_DATA 100107
#define GLU_TESS_END_DATA 100108
#define GLU_TESS_ERROR_DATA 100109
#define GLU_TESS_EDGE_FLAG_DATA 100110
#define GLU_TESS_COMBINE_DATA 100111
/* TessContour */
#define GLU_CW 100120
#define GLU_CCW 100121
#define GLU_INTERIOR 100122
#define GLU_EXTERIOR 100123
#define GLU_UNKNOWN 100124
/* TessProperty */
#define GLU_TESS_WINDING_RULE 100140
#define GLU_TESS_BOUNDARY_ONLY 100141
#define GLU_TESS_TOLERANCE 100142
/* TessError */
#define GLU_TESS_ERROR1 100151
#define GLU_TESS_ERROR2 100152
#define GLU_TESS_ERROR3 100153
#define GLU_TESS_ERROR4 100154
#define GLU_TESS_ERROR5 100155
#define GLU_TESS_ERROR6 100156
#define GLU_TESS_ERROR7 100157
#define GLU_TESS_ERROR8 100158
#define GLU_TESS_MISSING_BEGIN_POLYGON 100151
#define GLU_TESS_MISSING_BEGIN_CONTOUR 100152
#define GLU_TESS_MISSING_END_POLYGON 100153
#define GLU_TESS_MISSING_END_CONTOUR 100154
#define GLU_TESS_COORD_TOO_LARGE 100155
#define GLU_TESS_NEED_COMBINE_CALLBACK 100156
/* TessWinding */
#define GLU_TESS_WINDING_ODD 100130
#define GLU_TESS_WINDING_NONZERO 100131
#define GLU_TESS_WINDING_POSITIVE 100132
#define GLU_TESS_WINDING_NEGATIVE 100133
#define GLU_TESS_WINDING_ABS_GEQ_TWO 100134
GLAPI void APIENTRY gluBeginPolygon(GLUtesselator* tess);
GLAPI void APIENTRY gluDeleteTess(GLUtesselator* tess);
GLAPI void APIENTRY gluEndPolygon(GLUtesselator* tess);
GLAPI void APIENTRY gluGetTessProperty(GLUtesselator* tess, GLenum which, GLfloat* data);
GLAPI GLUtesselator* APIENTRY gluNewTess(void);
GLAPI void APIENTRY gluNextContour(GLUtesselator* tess, GLenum type);
GLAPI void APIENTRY gluTessBeginContour(GLUtesselator* tess);
GLAPI void APIENTRY gluTessBeginPolygon(GLUtesselator* tess, GLvoid* data);
GLAPI void APIENTRY gluTessCallback(GLUtesselator* tess, GLenum which, _GLUfuncptr CallBackFunc);
GLAPI void APIENTRY gluTessEndContour(GLUtesselator* tess);
GLAPI void APIENTRY gluTessEndPolygon(GLUtesselator* tess);
GLAPI void APIENTRY gluTessNormal(GLUtesselator* tess, GLfloat valueX, GLfloat valueY, GLfloat valueZ);
GLAPI void APIENTRY gluTessProperty(GLUtesselator* tess, GLenum which, GLfloat data);
GLAPI void APIENTRY gluTessVertex(GLUtesselator* tess, GLfloat* location, GLvoid* data);
/* NurbsDisplay */
/* GLU_FILL */
#define GLU_OUTLINE_POLYGON 100240
#define GLU_OUTLINE_PATCH 100241
/* NurbsCallback */
#define GLU_NURBS_ERROR 100103
#define GLU_ERROR 100103
#define GLU_NURBS_BEGIN 100164
#define GLU_NURBS_BEGIN_EXT 100164
#define GLU_NURBS_VERTEX 100165
#define GLU_NURBS_VERTEX_EXT 100165
#define GLU_NURBS_NORMAL 100166
#define GLU_NURBS_NORMAL_EXT 100166
#define GLU_NURBS_COLOR 100167
#define GLU_NURBS_COLOR_EXT 100167
#define GLU_NURBS_TEXTURE_COORD 100168
#define GLU_NURBS_TEX_COORD_EXT 100168
#define GLU_NURBS_END 100169
#define GLU_NURBS_END_EXT 100169
#define GLU_NURBS_BEGIN_DATA 100170
#define GLU_NURBS_BEGIN_DATA_EXT 100170
#define GLU_NURBS_VERTEX_DATA 100171
#define GLU_NURBS_VERTEX_DATA_EXT 100171
#define GLU_NURBS_NORMAL_DATA 100172
#define GLU_NURBS_NORMAL_DATA_EXT 100172
#define GLU_NURBS_COLOR_DATA 100173
#define GLU_NURBS_COLOR_DATA_EXT 100173
#define GLU_NURBS_TEXTURE_COORD_DATA 100174
#define GLU_NURBS_TEX_COORD_DATA_EXT 100174
#define GLU_NURBS_END_DATA 100175
#define GLU_NURBS_END_DATA_EXT 100175
/* NurbsError */
#define GLU_NURBS_ERROR1 100251
#define GLU_NURBS_ERROR2 100252
#define GLU_NURBS_ERROR3 100253
#define GLU_NURBS_ERROR4 100254
#define GLU_NURBS_ERROR5 100255
#define GLU_NURBS_ERROR6 100256
#define GLU_NURBS_ERROR7 100257
#define GLU_NURBS_ERROR8 100258
#define GLU_NURBS_ERROR9 100259
#define GLU_NURBS_ERROR10 100260
#define GLU_NURBS_ERROR11 100261
#define GLU_NURBS_ERROR12 100262
#define GLU_NURBS_ERROR13 100263
#define GLU_NURBS_ERROR14 100264
#define GLU_NURBS_ERROR15 100265
#define GLU_NURBS_ERROR16 100266
#define GLU_NURBS_ERROR17 100267
#define GLU_NURBS_ERROR18 100268
#define GLU_NURBS_ERROR19 100269
#define GLU_NURBS_ERROR20 100270
#define GLU_NURBS_ERROR21 100271
#define GLU_NURBS_ERROR22 100272
#define GLU_NURBS_ERROR23 100273
#define GLU_NURBS_ERROR24 100274
#define GLU_NURBS_ERROR25 100275
#define GLU_NURBS_ERROR26 100276
#define GLU_NURBS_ERROR27 100277
#define GLU_NURBS_ERROR28 100278
#define GLU_NURBS_ERROR29 100279
#define GLU_NURBS_ERROR30 100280
#define GLU_NURBS_ERROR31 100281
#define GLU_NURBS_ERROR32 100282
#define GLU_NURBS_ERROR33 100283
#define GLU_NURBS_ERROR34 100284
#define GLU_NURBS_ERROR35 100285
#define GLU_NURBS_ERROR36 100286
#define GLU_NURBS_ERROR37 100287
/* NurbsProperty */
#define GLU_AUTO_LOAD_MATRIX 100200
#define GLU_CULLING 100201
#define GLU_SAMPLING_TOLERANCE 100203
#define GLU_DISPLAY_MODE 100204
#define GLU_PARAMETRIC_TOLERANCE 100202
#define GLU_SAMPLING_METHOD 100205
#define GLU_U_STEP 100206
#define GLU_V_STEP 100207
#define GLU_NURBS_MODE 100160
#define GLU_NURBS_MODE_EXT 100160
#define GLU_NURBS_TESSELLATOR 100161
#define GLU_NURBS_TESSELLATOR_EXT 100161
#define GLU_NURBS_RENDERER 100162
#define GLU_NURBS_RENDERER_EXT 100162
/* NurbsSampling */
#define GLU_OBJECT_PARAMETRIC_ERROR 100208
#define GLU_OBJECT_PARAMETRIC_ERROR_EXT 100208
#define GLU_OBJECT_PATH_LENGTH 100209
#define GLU_OBJECT_PATH_LENGTH_EXT 100209
#define GLU_PATH_LENGTH 100215
#define GLU_PARAMETRIC_ERROR 100216
#define GLU_DOMAIN_DISTANCE 100217
/* NurbsTrim */
#define GLU_MAP1_TRIM_2 100210
#define GLU_MAP1_TRIM_3 100211
GLAPI void APIENTRY gluBeginCurve(GLUnurbs* nurb);
GLAPI void APIENTRY gluBeginSurface(GLUnurbs* nurb);
GLAPI void APIENTRY gluBeginTrim(GLUnurbs* nurb);
GLAPI void APIENTRY gluDeleteNurbsRenderer(GLUnurbs* nurb);
GLAPI void APIENTRY gluEndCurve(GLUnurbs* nurb);
GLAPI void APIENTRY gluEndSurface(GLUnurbs* nurb);
GLAPI void APIENTRY gluEndTrim(GLUnurbs* nurb);
GLAPI void APIENTRY gluGetNurbsProperty(GLUnurbs* nurb, GLenum property, GLfloat* data);
GLAPI void APIENTRY gluLoadSamplingMatrices(GLUnurbs* nurb, const GLfloat* model, const GLfloat* perspective, const GLint* view);
GLAPI GLUnurbs* APIENTRY gluNewNurbsRenderer(void);
GLAPI void APIENTRY gluNurbsCallback(GLUnurbs* nurb, GLenum which, _GLUfuncptr CallBackFunc);
GLAPI void APIENTRY gluNurbsCallbackData(GLUnurbs* nurb, GLvoid* userData);
GLAPI void APIENTRY gluNurbsCallbackDataEXT(GLUnurbs* nurb, GLvoid* userData);
GLAPI void APIENTRY gluNurbsCurve(GLUnurbs* nurb, GLint knotCount, GLfloat* knots, GLint stride, GLfloat* control, GLint order, GLenum type);
GLAPI void APIENTRY gluNurbsProperty(GLUnurbs* nurb, GLenum property, GLfloat value);
GLAPI void APIENTRY gluNurbsSurface(GLUnurbs* nurb, GLint sKnotCount, GLfloat* sKnots, GLint tKnotCount, GLfloat* tKnots, GLint sStride, GLint tStride, GLfloat* control, GLint sOrder, GLint tOrder, GLenum type);
GLAPI void APIENTRY gluPwlCurve(GLUnurbs* nurb, GLint count, GLfloat* data, GLint stride, GLenum type);
/* OpenGL (and OpenGL ES 1.1 for OpenGL ES 1.0) emulation layer */
#define GLU_AUTO_NORMAL 0x0D80
#define GLU_MAP1_COLOR_4 0x0D90
#define GLU_MAP1_INDEX 0x0D91
#define GLU_MAP1_NORMAL 0x0D92
#define GLU_MAP1_TEXTURE_COORD_1 0x0D93
#define GLU_MAP1_TEXTURE_COORD_2 0x0D94
#define GLU_MAP1_TEXTURE_COORD_3 0x0D95
#define GLU_MAP1_TEXTURE_COORD_4 0x0D96
#define GLU_MAP1_VERTEX_3 0x0D97
#define GLU_MAP1_VERTEX_4 0x0D98
#define GLU_MAP2_COLOR_4 0x0DB0
#define GLU_MAP2_INDEX 0x0DB1
#define GLU_MAP2_NORMAL 0x0DB2
#define GLU_MAP2_TEXTURE_COORD_1 0x0DB3
#define GLU_MAP2_TEXTURE_COORD_2 0x0DB4
#define GLU_MAP2_TEXTURE_COORD_3 0x0DB5
#define GLU_MAP2_TEXTURE_COORD_4 0x0DB6
#define GLU_MAP2_VERTEX_3 0x0DB7
#define GLU_MAP2_VERTEX_4 0x0DB8
#ifndef GL_MODELVIEW_MATRIX
#define GL_MODELVIEW_MATRIX 0x0BA6
#endif /* GL_MODELVIEW_MATRIX */
#ifndef GL_PROJECTION_MATRIX
#define GL_PROJECTION_MATRIX 0x0BA7
#endif /* GL_PROJECTION_MATRIX */
#ifndef GL_VIEWPORT
#define GL_VIEWPORT 0x0BA2
#endif /* GL_VIEWPORT */
GLAPI void APIENTRY gluEnable(GLenum cap);
GLAPI void APIENTRY gluDisable(GLenum cap);
GLAPI void APIENTRY gluGetFloatv(GLenum pname, GLfloat* params);
GLAPI void APIENTRY gluGetIntegerv(GLenum pname, GLint* params);
GLAPI void APIENTRY gluViewport(GLint x_, GLint y, GLsizei width, GLsizei height);
#ifdef __cplusplus
}
#endif
#endif /* __glues_h__ */
| C++ |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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 <jni.h>
#include "HelloBoost.h"
#include <boost/filesystem.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost::filesystem;
/* This is a trivial JNI example where we use a native method
* to return a new VM String. See the corresponding Java source
* file located at:
*
* apps/samples/hello-jni/project/src/com/example/HelloJni/HelloJni.java
*/
JNIEXPORT jstring JNICALL Java_com_theveganrobot_cmake_HelloBoost_boostMkDir
(JNIEnv * env, jobject)
{
boost::shared_ptr<int> ptri(new int(13));
path mypath("foopath");
if(!exists(mypath))
create_directory(mypath);
return env->NewStringUTF( "Hello Boost from JNI !");
}
| C++ |
/*
* Copyright (C) 2010 Ethan Rublee
*
* 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 <string>
#include <iostream>
#include <sstream>
#include <jni.h>
#include <math.h>
#include <stdexcept>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_theveganrobot_cmake_HelloWorld
* Method: stringFromJNI
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_theveganrobot_cmake_HelloWorld_stringFromJNI
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
std::string helloStringStream(){
//test string stream
std::stringstream ss;
ss << "JNI -- pi = " << M_PI << "\n";
try
{
throw std::runtime_error("Do exceptions work?");
}
catch(std::runtime_error e)
{
ss << "Exception caught: " << e.what() << "\nI guess they do ;)" << std::endl;
}
return ss.str();
}
JNIEXPORT jstring JNICALL Java_com_theveganrobot_cmake_HelloWorld_stringFromJNI
(JNIEnv *env, jobject obj)
{
return env->NewStringUTF(helloStringStream().c_str());
}
| C++ |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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 <jni.h>
#include "HelloEigen.h"
#include <iostream>
#include <sstream>
#include <Eigen/Dense>
#include <string>
using namespace Eigen;
std::string helloMatrix(){
std::stringstream ss;
ss << __PRETTY_FUNCTION__ << std::endl;
MatrixXd m(2,2);
m(0,0) = 3;
m(1,0) = 2.5;
m(0,1) = -1;
m(1,1) = m(1,0) + m(0,1);
ss << "Here is the matrix m:\n" << m << std::endl;
VectorXd v(2);
v(0) = 4;
v(1) = v(0) - 1;
ss << "Here is the vector v:\n" << v << std::endl;
return ss.str();
}
JNIEXPORT jstring JNICALL Java_com_theveganrobot_cmake_HelloEigen_helloMatrix
(JNIEnv * env, jobject)
{
return env->NewStringUTF( helloMatrix().c_str());
}
| C++ |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.
*/
// OpenGL ES 2.0 code
#include <jni.h>
#include <android/log.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LOG_TAG "libgl2jni"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
static void printGLString(const char *name, GLenum s) {
const char *v = (const char *) glGetString(s);
LOGI("GL %s = %s\n", name, v);
}
static void checkGlError(const char* op) {
for (GLint error = glGetError(); error; error
= glGetError()) {
LOGI("after %s() glError (0x%x)\n", op, error);
}
}
static const char gVertexShader[] =
"attribute vec4 vPosition;\n"
"void main() {\n"
" gl_Position = vPosition;\n"
"}\n";
static const char gFragmentShader[] =
"precision mediump float;\n"
"void main() {\n"
" gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
GLuint loadShader(GLenum shaderType, const char* pSource) {
GLuint shader = glCreateShader(shaderType);
if (shader) {
glShaderSource(shader, 1, &pSource, NULL);
glCompileShader(shader);
GLint compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint infoLen = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen) {
char* buf = (char*) malloc(infoLen);
if (buf) {
glGetShaderInfoLog(shader, infoLen, NULL, buf);
LOGE("Could not compile shader %d:\n%s\n",
shaderType, buf);
free(buf);
}
glDeleteShader(shader);
shader = 0;
}
}
}
return shader;
}
GLuint createProgram(const char* pVertexSource, const char* pFragmentSource) {
GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
if (!vertexShader) {
return 0;
}
GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
if (!pixelShader) {
return 0;
}
GLuint program = glCreateProgram();
if (program) {
glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
glLinkProgram(program);
GLint linkStatus = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus != GL_TRUE) {
GLint bufLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
if (bufLength) {
char* buf = (char*) malloc(bufLength);
if (buf) {
glGetProgramInfoLog(program, bufLength, NULL, buf);
LOGE("Could not link program:\n%s\n", buf);
free(buf);
}
}
glDeleteProgram(program);
program = 0;
}
}
return program;
}
GLuint gProgram;
GLuint gvPositionHandle;
bool setupGraphics(int w, int h) {
printGLString("Version", GL_VERSION);
printGLString("Vendor", GL_VENDOR);
printGLString("Renderer", GL_RENDERER);
printGLString("Extensions", GL_EXTENSIONS);
LOGI("setupGraphics(%d, %d)", w, h);
gProgram = createProgram(gVertexShader, gFragmentShader);
if (!gProgram) {
LOGE("Could not create program.");
return false;
}
gvPositionHandle = glGetAttribLocation(gProgram, "vPosition");
checkGlError("glGetAttribLocation");
LOGI("glGetAttribLocation(\"vPosition\") = %d\n",
gvPositionHandle);
glViewport(0, 0, w, h);
checkGlError("glViewport");
return true;
}
const GLfloat gTriangleVertices[] = { 0.0f, 0.5f, -0.5f, -0.5f,
0.5f, -0.5f };
void renderFrame() {
static float grey;
grey += 0.01f;
if (grey > 1.0f) {
grey = 0.0f;
}
glClearColor(grey, grey, grey, 1.0f);
checkGlError("glClearColor");
glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
checkGlError("glClear");
glUseProgram(gProgram);
checkGlError("glUseProgram");
glVertexAttribPointer(gvPositionHandle, 2, GL_FLOAT, GL_FALSE, 0, gTriangleVertices);
checkGlError("glVertexAttribPointer");
glEnableVertexAttribArray(gvPositionHandle);
checkGlError("glEnableVertexAttribArray");
glDrawArrays(GL_TRIANGLES, 0, 3);
checkGlError("glDrawArrays");
}
extern "C" {
JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_init(JNIEnv * env, jobject obj, jint width, jint height);
JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_step(JNIEnv * env, jobject obj);
};
JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_init(JNIEnv * env, jobject obj, jint width, jint height)
{
setupGraphics(width, height);
}
JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_step(JNIEnv * env, jobject obj)
{
renderFrame();
}
| C++ |
/*
* DFAFramework.cpp
*
* Created on: Jan 29, 2011
* Author: Fuyao Zhao, Mark Hahnenberg
*/
#include "DFAFramework.h"
using namespace llvm;
DFAFramework::~DFAFramework() {
}
DFAValue DFAFramework::transfer(BasicBlock *bb, DFAValue value) {
DFAValue tmp = value;
if (isFoward()) {
for (BasicBlock::InstListType::iterator it = bb->getInstList().begin(); it
!= bb->getInstList().end(); it++) {
in[it] = tmp;
tmp = transfer(it, tmp);
out[it] = tmp;
}
} else {
for (BasicBlock::InstListType::reverse_iterator it =
bb->getInstList().rbegin(); it != bb->getInstList().rend(); it++) {
Instruction *p = &*it; //a bit tricky here to do &(*it), * is a overridden operator for reverse_iterator
out[p] = tmp;
tmp = transfer(p, tmp);
in[p] = tmp;
}
}
return tmp;
}
DFAValue DFAFramework::meetAll(BasicBlock *BB) {
DFAValue val;
if (isFoward()) { //if the problem is a forward problem
val = in[BB];
for (pred_iterator PI = pred_begin(BB); PI != pred_end(BB); ++PI) {
BasicBlock *pred = *PI;
val = meet(val, out[pred]);
}
} else { //if the problem is backward problem
val = out[BB];
for (succ_iterator PI = succ_begin(BB); PI != succ_end(BB); ++PI) {
BasicBlock *succ = *PI;
val = meet(val, in[succ]);
}
}
return val;
}
map<Value *, DFAValue> & DFAFramework::solve(Function *fun) {
initialize(fun);
if (isFoward()) {
while (1) {
bool change = false;
for (Function::iterator B = fun->getBasicBlockList().begin(); B
!= fun->getBasicBlockList().end(); B++) { // use naive order now, todo use better order
in[B] = meetAll(B);
DFAValue res = transfer(B, in[B]);
if (res != out[B]) //check if anything change
change = true;
out[B] = res;
}
if (!change)
break;
}
return out;
} else {
while (1) {
bool change = false;
for (Function::iterator B = fun->getBasicBlockList().begin(); B
!= fun->getBasicBlockList().end(); B++) { // use naive order now, todo use better order
out[B] = meetAll(B);
DFAValue res = transfer(B, out[B]);
if (res != in[B]) //check if anything change
change = true;
in[B] = res;
}
if (!change)
break;
}
return in;
}
}
map<Value *, DFAValue> & DFAFramework::getIn() {
return in;
}
map<Value *, DFAValue> & DFAFramework::getOut() {
return out;
}
| C++ |
//2nd step: strong connected graph
#include "DSWP.h"
using namespace llvm;
using namespace std;
void DSWP::findSCC(Loop *L) {
used.clear();
for (Loop::block_iterator bi = L->getBlocks().begin(); bi != L->getBlocks().end(); bi++) {
BasicBlock *BB = *bi;
for (BasicBlock::iterator ui = BB->begin(); ui != BB->end(); ui++) {
Instruction *inst = &(*ui);
if (!used[inst]) {
dfs1(inst);
}
}
}
used.clear();
sccNum = 0;
for (int i = list.size() - 1; i >= 0; i --) {
Instruction *inst = list[i];
if (!used[inst]) {
dfs2(inst);
sccNum++;
}
}
}
void DSWP::dfs1(Instruction *I) {
used[I] = true;
for (vector<Edge>::iterator ei = pdg[I]->begin(); ei != pdg[I]->end(); ei++) {
Instruction *next = ei->v;
if (!used[next])
dfs1(next);
}
list.push_back(I);
}
void DSWP::dfs2(Instruction *I) {
used[I] = true;
for (vector<Edge>::iterator ei = rev[I]->begin(); ei != rev[I]->end(); ei++) {
Instruction *next = ei->v;
if (!used[next])
dfs2(next);
}
sccId[I] = sccNum;
}
void DSWP::buildDAG(Loop *L) {
for (int i = 0; i < sccNum; i++) {
dag[i] = new vector<int>();
}
map<int, map<int, bool> > added;
for (Loop::block_iterator bi = L->getBlocks().begin(); bi != L->getBlocks().end(); bi++) {
BasicBlock *BB = *bi;
for (BasicBlock::iterator ui = BB->begin(); ui != BB->end(); ui++) {
Instruction *I = &(*ui);
for (vector<Edge>::iterator ei = pdg[I]->begin(); ei != pdg[I]->end(); ei++) {
Instruction *next = ei->v;
int u = sccId[I];
int v = sccId[next];
//it is possible the edge has already been added
if (!added[u][v] && u != v) {
dag[u]->push_back(v);
added[u][v] = true;
}
}
}
}
//store InstInSCC, vector store all the inst for a scc
InstInSCC.clear();
for (int i = 0; i < sccNum; i++)
InstInSCC.push_back(vector<Instruction *>());
for (Loop::block_iterator bi = L->getBlocks().begin(); bi != L->getBlocks().end(); bi++) {
BasicBlock *BB = *bi;
for (BasicBlock::iterator ui = BB->begin(); ui != BB->end(); ui++) {
Instruction *I = &(*ui);
InstInSCC[sccId[I]].push_back(I);
}
}
}
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.