diff --git a/windows/templates/1-WinApp/WinApp_c.txt b/windows/templates/1-WinApp/WinApp_c.txt new file mode 100644 index 00000000..7ed1bb93 --- /dev/null +++ b/windows/templates/1-WinApp/WinApp_c.txt @@ -0,0 +1,66 @@ +#include + +/* This is where all the input to the window goes to */ +LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { + switch(Message) { + + /* Upon destruction, tell the main thread to stop */ + case WM_DESTROY: { + PostQuitMessage(0); + break; + } + + /* All other messages (a lot of them) are processed using default procedures */ + default: + return DefWindowProc(hwnd, Message, wParam, lParam); + } + return 0; +} + +/* The 'main' function of Win32 GUI programs: this is where execution starts */ +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { + WNDCLASSEX wc; /* A properties struct of our window */ + HWND hwnd; /* A 'HANDLE', hence the H, or a pointer to our window */ + MSG msg; /* A temporary location for all messages */ + + /* zero out the struct and set the stuff we want to modify */ + memset(&wc,0,sizeof(wc)); + wc.cbSize = sizeof(WNDCLASSEX); + wc.lpfnWndProc = WndProc; /* This is where we will send messages to */ + wc.hInstance = hInstance; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + + /* White, COLOR_WINDOW is just a #define for a system color, try Ctrl+Clicking it */ + wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); + wc.lpszClassName = "WindowClass"; + wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); /* Load a standard icon */ + wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); /* use the name "A" to use the project icon */ + + if(!RegisterClassEx(&wc)) { + MessageBox(NULL, "Window Registration Failed!","Error!",MB_ICONEXCLAMATION|MB_OK); + return 0; + } + + hwnd = CreateWindowEx(WS_EX_CLIENTEDGE,"WindowClass","Caption",WS_VISIBLE|WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, /* x */ + CW_USEDEFAULT, /* y */ + 640, /* width */ + 480, /* height */ + NULL,NULL,hInstance,NULL); + + if(hwnd == NULL) { + MessageBox(NULL, "Window Creation Failed!","Error!",MB_ICONEXCLAMATION|MB_OK); + return 0; + } + + /* + This is the heart of our program where all input is processed and + sent to WndProc. Note that GetMessage blocks code flow until it receives something, so + this loop will not produce unreasonably high CPU usage + */ + while(GetMessage(&msg, NULL, 0, 0) > 0) { /* If no error is received... */ + TranslateMessage(&msg); /* Translate key codes to chars if present */ + DispatchMessage(&msg); /* Send it to WndProc */ + } + return msg.wParam; +} diff --git a/windows/templates/1-WinApp/Windows.ico b/windows/templates/1-WinApp/Windows.ico new file mode 100644 index 00000000..b2682537 Binary files /dev/null and b/windows/templates/1-WinApp/Windows.ico differ diff --git a/windows/templates/1-WinApp/info.template b/windows/templates/1-WinApp/info.template new file mode 100644 index 00000000..69b8b277 --- /dev/null +++ b/windows/templates/1-WinApp/info.template @@ -0,0 +1,19 @@ +[Template] +ver=2 +Name=Windows Application +Name[zh_CN]=Windows程序 +Icon=Windows.ico +Description=A standard Windows application +Description[zh_CN]=基于Windows API开发的图形界面应用程序 +Category=Basic +Category[zh_CN]=基础 + +[Unit0] +CName=main.c +CppName=main.cpp +C=winapp_c.txt +Cpp=winapp_c.txt + +[Project] +UnitCount=1 +Type=0 diff --git a/windows/templates/2-ConsoleApp/ConsoleApp_c.txt b/windows/templates/2-ConsoleApp/ConsoleApp_c.txt new file mode 100644 index 00000000..e10d74fc --- /dev/null +++ b/windows/templates/2-ConsoleApp/ConsoleApp_c.txt @@ -0,0 +1,8 @@ +#include +#include + +/* run this program using the console pauser or add your own getch, system("pause") or input loop */ + +int main(int argc, char *argv[]) { + return 0; +} \ No newline at end of file diff --git a/windows/templates/2-ConsoleApp/ConsoleApp_cpp.txt b/windows/templates/2-ConsoleApp/ConsoleApp_cpp.txt new file mode 100644 index 00000000..5627b733 --- /dev/null +++ b/windows/templates/2-ConsoleApp/ConsoleApp_cpp.txt @@ -0,0 +1,7 @@ +#include + +/* run this program using the console pauser or add your own getch, system("pause") or input loop */ + +int main(int argc, char** argv) { + return 0; +} \ No newline at end of file diff --git a/windows/templates/2-ConsoleApp/ConsoleToo.ico b/windows/templates/2-ConsoleApp/ConsoleToo.ico new file mode 100644 index 00000000..4238e81f Binary files /dev/null and b/windows/templates/2-ConsoleApp/ConsoleToo.ico differ diff --git a/windows/templates/2-ConsoleApp/info.template b/windows/templates/2-ConsoleApp/info.template new file mode 100644 index 00000000..d36ab83b --- /dev/null +++ b/windows/templates/2-ConsoleApp/info.template @@ -0,0 +1,19 @@ +[Template] +ver=2 +Name=Console Application +Name[zh_CN]=控制台程序 +Icon=ConsoleToo.ico +Description=A console application (MS-DOS window) +Description[zh_CN]=控制台应用程序 +Category=Basic +Category[zh_CN]=基础 + +[Unit0] +CName=main.c +CppName=main.cpp +C=consoleapp_c.txt +Cpp=consoleapp_cpp.txt + +[Project] +UnitCount=1 +Type=1 diff --git a/windows/templates/3-StaticLib/StaticLib.ico b/windows/templates/3-StaticLib/StaticLib.ico new file mode 100644 index 00000000..10d38f5c Binary files /dev/null and b/windows/templates/3-StaticLib/StaticLib.ico differ diff --git a/windows/templates/3-StaticLib/info.template b/windows/templates/3-StaticLib/info.template new file mode 100644 index 00000000..1912820f --- /dev/null +++ b/windows/templates/3-StaticLib/info.template @@ -0,0 +1,17 @@ +[Template] +ver=2 +Name=Static Library +Name[zh_CN]=静态链接库 +Icon=StaticLib.ico +Description=A static library (.a) +Description[zh_CN]=静态链接库(.a) +Category=Basic +Category[zh_CN]=基础 + +[Unit0] +CName= +CppName= + +[Project] +UnitCount=1 +Type=2 diff --git a/windows/templates/4-DLL/DLL.ico b/windows/templates/4-DLL/DLL.ico new file mode 100644 index 00000000..11c8e046 Binary files /dev/null and b/windows/templates/4-DLL/DLL.ico differ diff --git a/windows/templates/4-DLL/Dll_c.txt b/windows/templates/4-DLL/Dll_c.txt new file mode 100644 index 00000000..10b41500 --- /dev/null +++ b/windows/templates/4-DLL/Dll_c.txt @@ -0,0 +1,34 @@ +/* Replace "dll.h" with the name of your header */ +#include "dll.h" +#include + +DLLIMPORT void HelloWorld() +{ + MessageBox(0,"Hello World from DLL!\n","Hi",MB_ICONINFORMATION); +} + +BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved) +{ + switch(fdwReason) + { + case DLL_PROCESS_ATTACH: + { + break; + } + case DLL_PROCESS_DETACH: + { + break; + } + case DLL_THREAD_ATTACH: + { + break; + } + case DLL_THREAD_DETACH: + { + break; + } + } + + /* Return TRUE on success, FALSE on failure */ + return TRUE; +} diff --git a/windows/templates/4-DLL/Dll_cpp.txt b/windows/templates/4-DLL/Dll_cpp.txt new file mode 100644 index 00000000..9ff2a678 --- /dev/null +++ b/windows/templates/4-DLL/Dll_cpp.txt @@ -0,0 +1,44 @@ +/* Replace "dll.h" with the name of your header */ +#include "dll.h" +#include + +DllClass::DllClass() +{ + +} + +DllClass::~DllClass() +{ + +} + +void DllClass::HelloWorld() +{ + MessageBox(0, "Hello World from DLL!\n","Hi",MB_ICONINFORMATION); +} + +BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved) +{ + switch(fdwReason) + { + case DLL_PROCESS_ATTACH: + { + break; + } + case DLL_PROCESS_DETACH: + { + break; + } + case DLL_THREAD_ATTACH: + { + break; + } + case DLL_THREAD_DETACH: + { + break; + } + } + + /* Return TRUE on success, FALSE on failure */ + return TRUE; +} diff --git a/windows/templates/4-DLL/Dll_h.txt b/windows/templates/4-DLL/Dll_h.txt new file mode 100644 index 00000000..394eb826 --- /dev/null +++ b/windows/templates/4-DLL/Dll_h.txt @@ -0,0 +1,12 @@ +#ifndef _DLL_H_ +#define _DLL_H_ + +#if BUILDING_DLL +#define DLLIMPORT __declspec(dllexport) +#else +#define DLLIMPORT __declspec(dllimport) +#endif + +DLLIMPORT void HelloWorld(); + +#endif diff --git a/windows/templates/4-DLL/Dll_hpp.txt b/windows/templates/4-DLL/Dll_hpp.txt new file mode 100644 index 00000000..e2f2084a --- /dev/null +++ b/windows/templates/4-DLL/Dll_hpp.txt @@ -0,0 +1,18 @@ +#ifndef _DLL_H_ +#define _DLL_H_ + +#if BUILDING_DLL +#define DLLIMPORT __declspec(dllexport) +#else +#define DLLIMPORT __declspec(dllimport) +#endif + +class DLLIMPORT DllClass +{ + public: + DllClass(); + virtual ~DllClass(); + void HelloWorld(); +}; + +#endif diff --git a/windows/templates/4-DLL/info.template b/windows/templates/4-DLL/info.template new file mode 100644 index 00000000..be9d32fa --- /dev/null +++ b/windows/templates/4-DLL/info.template @@ -0,0 +1,28 @@ +[Template] +ver=2 +Name=DLL +Name[zh_CN]=动态链接库 +Icon=DLL.ico +Description=A Dynamic Link Library (DLL) +Description[zh_CN]=动态链接库(DLL) +Category=Basic +Category[zh_CN]=基础 + +[Unit0] +CName=dllmain.c +CppName=dllmain.cpp +C=DLL_c.txt +Cpp=Dll_cpp.txt + +[Unit1] +CName=dll.h +CppName=dll.h +C=DLL_h.txt +Cpp=Dll_hpp.txt + +[Project] +UnitCount=2 +Type=3 + +Compiler=-DBUILDING_DLL=1 +CppCompiler=-DBUILDING_DLL=1 \ No newline at end of file diff --git a/windows/templates/FileEditor/Editor.ico b/windows/templates/FileEditor/Editor.ico new file mode 100644 index 00000000..f58b11a8 Binary files /dev/null and b/windows/templates/FileEditor/Editor.ico differ diff --git a/windows/templates/FileEditor/FileEditor_c.txt b/windows/templates/FileEditor/FileEditor_c.txt new file mode 100644 index 00000000..cf827919 --- /dev/null +++ b/windows/templates/FileEditor/FileEditor_c.txt @@ -0,0 +1,172 @@ +#include +#include "main.h" + +BOOL LoadFile(HWND hEdit, LPSTR pszFileName) { + HANDLE hFile; + BOOL bSuccess = FALSE; + + hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0); + if(hFile != INVALID_HANDLE_VALUE) { + DWORD dwFileSize; + dwFileSize = GetFileSize(hFile, NULL); + if(dwFileSize != 0xFFFFFFFF) { + LPSTR pszFileText; + pszFileText = (LPSTR)GlobalAlloc(GPTR, dwFileSize + 1); + if(pszFileText != NULL) { + DWORD dwRead; + if(ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL)) { + pszFileText[dwFileSize] = 0; // Null terminator + if(SetWindowText(hEdit, pszFileText)) + bSuccess = TRUE; // It worked! + } + GlobalFree(pszFileText); + } + } + CloseHandle(hFile); + } + return bSuccess; +} + +BOOL SaveFile(HWND hEdit, LPSTR pszFileName) { + HANDLE hFile; + BOOL bSuccess = FALSE; + + hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + if(hFile != INVALID_HANDLE_VALUE) { + DWORD dwTextLength; + dwTextLength = GetWindowTextLength(hEdit); + if(dwTextLength > 0) { + LPSTR pszText; + pszText = (LPSTR)GlobalAlloc(GPTR, dwTextLength + 1); + if(pszText != NULL) { + if(GetWindowText(hEdit, pszText, dwTextLength + 1)) { + DWORD dwWritten; + if(WriteFile(hFile, pszText, dwTextLength, &dwWritten, NULL)) + bSuccess = TRUE; + } + GlobalFree(pszText); + } + } + CloseHandle(hFile); + } + return bSuccess; +} + +BOOL DoFileOpenSave(HWND hwnd, BOOL bSave) { + OPENFILENAME ofn; + char szFileName[MAX_PATH]; + + ZeroMemory(&ofn, sizeof(ofn)); + szFileName[0] = 0; + + ofn.lStructSize = sizeof(ofn); + ofn.hwndOwner = hwnd; + ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0\0"; + ofn.lpstrFile = szFileName; + ofn.nMaxFile = MAX_PATH; + ofn.lpstrDefExt = "txt"; + + if(bSave) { + ofn.Flags = OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT; + if(GetSaveFileName(&ofn)) { + if(!SaveFile(GetDlgItem(hwnd, IDC_MAIN_TEXT), szFileName)) { + MessageBox(hwnd, "Save file failed.", "Error",MB_OK|MB_ICONEXCLAMATION); + return FALSE; + } + } + } else { + ofn.Flags = OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_HIDEREADONLY; + if(GetOpenFileName(&ofn)) { + if(!LoadFile(GetDlgItem(hwnd, IDC_MAIN_TEXT), szFileName)) { + MessageBox(hwnd, "Load of file failed.", "Error",MB_OK|MB_ICONEXCLAMATION); + return FALSE; + } + } + } + return TRUE; +} + +LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { + switch(Message) { + case WM_CREATE: + CreateWindow("EDIT", "",WS_CHILD|WS_VISIBLE|WS_HSCROLL|WS_VSCROLL|ES_MULTILINE|ES_WANTRETURN,CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,hwnd, (HMENU)IDC_MAIN_TEXT, GetModuleHandle(NULL), NULL); + SendDlgItemMessage(hwnd, IDC_MAIN_TEXT, WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT), MAKELPARAM(TRUE,0)); + break; + case WM_SIZE: + if(wParam != SIZE_MINIMIZED) + MoveWindow(GetDlgItem(hwnd, IDC_MAIN_TEXT), 0, 0, LOWORD(lParam),HIWORD(lParam), TRUE); + break; + case WM_SETFOCUS: + SetFocus(GetDlgItem(hwnd, IDC_MAIN_TEXT)); + break; + case WM_COMMAND: + switch(LOWORD(wParam)) { + case CM_FILE_OPEN: + DoFileOpenSave(hwnd, FALSE); + break; + case CM_FILE_SAVEAS: + DoFileOpenSave(hwnd, TRUE); + break; + case CM_FILE_EXIT: + PostMessage(hwnd, WM_CLOSE, 0, 0); + break; + case CM_ABOUT: + MessageBox (NULL, "File Editor for Windows!\nCreated using the Win32 API" , "About...", 0); + break; + } + break; + case WM_CLOSE: + DestroyWindow(hwnd); + break; + case WM_DESTROY: + PostQuitMessage(0); + break; + default: + return DefWindowProc(hwnd, Message, wParam, lParam); + } + return 0; +} + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow) { + WNDCLASSEX wc; + HWND hwnd; + MSG Msg; + + wc.cbSize = sizeof(WNDCLASSEX); + wc.style = 0; + wc.lpfnWndProc = WndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = hInstance; + wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); + wc.lpszMenuName = "MAINMENU"; + wc.lpszClassName = "WindowClass"; + wc.hIconSm = LoadIcon(hInstance,"A"); /* A is name used by project icons */ + + if(!RegisterClassEx(&wc)) { + MessageBox(0,"Window Registration Failed!","Error!",MB_ICONEXCLAMATION|MB_OK|MB_SYSTEMMODAL); + return 0; + } + + hwnd = CreateWindowEx(WS_EX_CLIENTEDGE,"WindowClass","File Editor Example Program",WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + CW_USEDEFAULT, + 320,240, + NULL, NULL, hInstance, NULL); + + if(hwnd == NULL) { + MessageBox(0, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION|MB_OK|MB_SYSTEMMODAL); + return 0; + } + + ShowWindow(hwnd,1); + UpdateWindow(hwnd); + + while(GetMessage(&Msg, NULL, 0, 0) > 0) { + TranslateMessage(&Msg); + DispatchMessage(&Msg); + } + return Msg.wParam; +} diff --git a/windows/templates/FileEditor/FileEditor_h.txt b/windows/templates/FileEditor/FileEditor_h.txt new file mode 100644 index 00000000..de62f0d0 --- /dev/null +++ b/windows/templates/FileEditor/FileEditor_h.txt @@ -0,0 +1,6 @@ +#define CM_FILE_SAVEAS 9072 +#define CM_FILE_EXIT 9071 +#define CM_FILE_OPEN 9070 +#define CM_ABOUT 9069 + +#define IDC_MAIN_TEXT 1001 diff --git a/windows/templates/FileEditor/FileEditor_rc.txt b/windows/templates/FileEditor/FileEditor_rc.txt new file mode 100644 index 00000000..98abdae6 --- /dev/null +++ b/windows/templates/FileEditor/FileEditor_rc.txt @@ -0,0 +1,18 @@ +#include "main.h" + +MAINMENU MENU +{ + POPUP "&File" + { + MENUITEM "&Open...", CM_FILE_OPEN + MENUITEM "Save &As...", CM_FILE_SAVEAS + MENUITEM SEPARATOR + MENUITEM "E&xit", CM_FILE_EXIT + } + + POPUP "&Help" + { + MENUITEM "&About", CM_ABOUT + } +} + diff --git a/windows/templates/FileEditor/info.template b/windows/templates/FileEditor/info.template new file mode 100644 index 00000000..e7d5a136 --- /dev/null +++ b/windows/templates/FileEditor/info.template @@ -0,0 +1,31 @@ +[Template] +ver=2 +Name=File Editor +Name[zh_CN]=文件编辑器 +Icon=Editor.ico +Description=A simple Win32 file editor +Description[zh_CN]=一个简单的Win32文件编辑器 +Category=Win32 + +[Unit0] +CName=main.c +CppName=main.cpp +C=FileEditor_c.txt +Cpp=FileEditor_c.txt + +[Unit1] +CName=main.h +CppName=main.h +C=FileEditor_h.txt +Cpp=FileEditor_h.txt + +[Unit2] +CName=resource.rc +CppName=resource.rc +C=FileEditor_rc.txt +Cpp=FileEditor_rc.txt + +[Project] +UnitCount=3 +Type=0 +Icon=Editor.ico diff --git a/windows/templates/GLFW/GLFW.ico b/windows/templates/GLFW/GLFW.ico new file mode 100644 index 00000000..2a515ce7 Binary files /dev/null and b/windows/templates/GLFW/GLFW.ico differ diff --git a/windows/templates/GLFW/GLFW_main.cpp.txt b/windows/templates/GLFW/GLFW_main.cpp.txt new file mode 100644 index 00000000..3d5cfdae --- /dev/null +++ b/windows/templates/GLFW/GLFW_main.cpp.txt @@ -0,0 +1,111 @@ +#include +// GLEW +#define GLEW_STATIC +#include +// GLFW +#include +// Other includes +#include "shader.h" + +// Function prototypes +void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); + +// Window dimensions +const GLuint WIDTH = 800, HEIGHT = 600; + +// The MAIN function, from here we start the application and run the game loop +int main() +{ + // Init GLFW + glfwInit(); + // Set all the required options for GLFW + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); + + // Create a GLFWwindow object that we can use for GLFW's functions + GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); + glfwMakeContextCurrent(window); + + // Set the required callback functions + glfwSetKeyCallback(window, key_callback); + + // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions + glewExperimental = GL_TRUE; + // Initialize GLEW to setup the OpenGL Function pointers + glewInit(); + + // Define the viewport dimensions + glViewport(0, 0, WIDTH, HEIGHT); + + + //ȡshaderļ룬shader.h + Shader ourShader("shader.vs", "shader.frag"); + + + // һά飬ÿһԣǰλԣɫ + GLfloat vertices[] = { + // Positions // Colors + 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Right + -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // Bottom Left + 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // Top + }; + GLuint VBO, VAO;//㻺壬ڹ + glGenVertexArrays(1, &VAO);//飬һһ޶ʶ + glGenBuffers(1, &VBO);//㻺壬һһ޶ʶ + + glBindVertexArray(VAO);//󶨶 + glBindBuffer(GL_ARRAY_BUFFER, VBO);//󶨶㻺 + //ָԴΪverticesĸԿιݣGL_STATIC_DRWAı + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); + + // ָԵĽʽδӶ㻺ȡӦĶԺӦɫԡ˵ɫ֪ȥĸԷɫ + //ÿһԣ2֣һλԣɫԣÿһλúɫ + + //ɫʹlayout(location = 0)positionԵλֵ(Location)˵һԷ + //λԵάȣͣ:Ƿ׼壬λԵֽڳȣڻеƫʼλ + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); + glEnableVertexAttribArray(0);//0ΪĬǽõ + + // һӦɫеlayout (location = 1) in vec3 color;˵ɫԵƫverticesһ + glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); + glEnableVertexAttribArray(1);//1. + + //(Vertex Array Object, VAO)ĺôǣöָʱֻҪĴִһΣ֮ٻʱֻҪӦVAOˡѭеİٽ + glBindVertexArray(0); // VAO + // Game loop + while (!glfwWindowShouldClose(window)) + { + // ¼ӦĻصĵkey_callback + glfwPollEvents(); + + // Render + // Clear the colorbuffer + glClearColor(0.2f, 0.3f, 0.3f, 1.0f);//Ⱦɫ̨ + glClear(GL_COLOR_BUFFER_BIT);//ǰ̨ + + // Draw the triangle + ourShader.Use();//ɫ + glBindVertexArray(VAO);//ÿѭã󶨺VAO + glDrawArrays(GL_TRIANGLES, 0, 3); + glBindVertexArray(0);// + + // Swap the screen buffers + glfwSwapBuffers(window); + } + // Properly de-allocate all resources once they've outlived their purpose + glDeleteVertexArrays(1, &VAO); + glDeleteBuffers(1, &VBO); + // Terminate GLFW, clearing any resources allocated by GLFW. + glfwTerminate(); + return 0; +} + + +// Is called whenever a key is pressed/released via GLFW +void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) +{ + if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) + glfwSetWindowShouldClose(window, GL_TRUE); +} diff --git a/windows/templates/GLFW/GLFW_shader.frag.txt b/windows/templates/GLFW/GLFW_shader.frag.txt new file mode 100644 index 00000000..00bbbd11 --- /dev/null +++ b/windows/templates/GLFW/GLFW_shader.frag.txt @@ -0,0 +1,8 @@ +#version 330 core +in vec3 ourColor; +out vec4 color; + +void main() +{ + color = vec4(ourColor, 1.0f); +} diff --git a/windows/templates/GLFW/GLFW_shader.h.txt b/windows/templates/GLFW/GLFW_shader.h.txt new file mode 100644 index 00000000..01387630 --- /dev/null +++ b/windows/templates/GLFW/GLFW_shader.h.txt @@ -0,0 +1,98 @@ +#ifndef SHADER_H +#define SHADER_H + +#include +#include +#include +#include + +#include + +class Shader +{ +public: + GLuint Program; + // Constructor generates the shader on the fly + Shader(const GLchar* vertexPath, const GLchar* fragmentPath) + { + // 1. Retrieve the vertex/fragment source code from filePath + std::string vertexCode; + std::string fragmentCode; + std::ifstream vShaderFile; + std::ifstream fShaderFile; + // ensures ifstream objects can throw exceptions: + vShaderFile.exceptions(std::ifstream::badbit); + fShaderFile.exceptions(std::ifstream::badbit); + try + { + // Open files + vShaderFile.open(vertexPath); + fShaderFile.open(fragmentPath); + std::stringstream vShaderStream, fShaderStream; + // Read file's buffer contents into streams + vShaderStream << vShaderFile.rdbuf(); + fShaderStream << fShaderFile.rdbuf(); + // close file handlers + vShaderFile.close(); + fShaderFile.close(); + // Convert stream into string + vertexCode = vShaderStream.str(); + fragmentCode = fShaderStream.str(); + } + catch (std::ifstream::failure e) + { + std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl; + } + const GLchar* vShaderCode = vertexCode.c_str(); + const GLchar * fShaderCode = fragmentCode.c_str(); + // 2. Compile shaders + GLuint vertex, fragment; + GLint success; + GLchar infoLog[512]; + // Vertex Shader + vertex = glCreateShader(GL_VERTEX_SHADER);//ɫ + glShaderSource(vertex, 1, &vShaderCode, NULL);//ָԴ + glCompileShader(vertex);//ɫ + // Print compile errors if any + glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);//鿴Ƿɹ + if (!success) + { + glGetShaderInfoLog(vertex, 512, NULL, infoLog); + std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; + } + // Fragment Shader + fragment = glCreateShader(GL_FRAGMENT_SHADER);//Ƭɫ + glShaderSource(fragment, 1, &fShaderCode, NULL); + glCompileShader(fragment); + // Print compile errors if any + glGetShaderiv(fragment, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(fragment, 512, NULL, infoLog); + std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; + } + // Shader Program + this->Program = glCreateProgram();//ɫ + glAttachShader(this->Program, vertex);//ɫ + glAttachShader(this->Program, fragment);//Ƭɫ + glLinkProgram(this->Program);//ӱ + // Print linking errors if any + glGetProgramiv(this->Program, GL_LINK_STATUS, &success); + if (!success) + { + glGetProgramInfoLog(this->Program, 512, NULL, infoLog); + std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; + } + // Delete the shaders as they're linked into our program now and no longer necessery + glDeleteShader(vertex); + glDeleteShader(fragment); + + } + // Uses the current shader + void Use() + { + glUseProgram(this->Program); + } +}; + +#endif diff --git a/windows/templates/GLFW/GLFW_shader.vs.txt b/windows/templates/GLFW/GLFW_shader.vs.txt new file mode 100644 index 00000000..b2141e1b --- /dev/null +++ b/windows/templates/GLFW/GLFW_shader.vs.txt @@ -0,0 +1,11 @@ +#version 330 core +layout (location = 0) in vec3 position;//in locationĶйء +layout (location = 1) in vec3 color; + +out vec3 ourColor;//out 3άΪƬɫ룬 + +void main() +{ + gl_Position = vec4(position, 1.0f); + ourColor = color; +} diff --git a/windows/templates/GLFW/info.template b/windows/templates/GLFW/info.template new file mode 100644 index 00000000..e577055e --- /dev/null +++ b/windows/templates/GLFW/info.template @@ -0,0 +1,39 @@ +[Template] +ver=2 +Name=GLFW +Description=A simple GLFW program +Description[zh_CN]=一个简单的GLFW程序 +Icon=GLFW.ico +Category=3D +Category[zh_CN]=3D + +[Unit0] +CppName=main.cpp +Cpp=GLFW_main.cpp.txt + +[Unit1] +CppName=shader.h +Cpp=GLFW_shader.h.txt + +[Unit2] +CppName=shader.frag +Cpp=GLFW_shader.frag.txt + +[Unit3] +CppName=shader.vs +Cpp=GLFW_shader.vs.txt + +[Project] +UnitCount=4 +Type=1 +IsCpp=1 +Compiler= +CppCompiler= +Linker=-lglfw3 -lglew32 -lopengl32 -lwinmm -lgdi32_@@__@@_ +CompilerSettings=0000000000110000000001000 +CompilerSet=1 +UseUTF8=0 +StaticLink=1 +AddCharset=1 +IncludeVersionInfo=0 +SupportXPThemes=0 diff --git a/windows/templates/GLUT/CL_GLUT.ico b/windows/templates/GLUT/CL_GLUT.ico new file mode 100644 index 00000000..2a515ce7 Binary files /dev/null and b/windows/templates/GLUT/CL_GLUT.ico differ diff --git a/windows/templates/GLUT/CL_GLUT_glmatrix.c.txt b/windows/templates/GLUT/CL_GLUT_glmatrix.c.txt new file mode 100644 index 00000000..b3dad22d --- /dev/null +++ b/windows/templates/GLUT/CL_GLUT_glmatrix.c.txt @@ -0,0 +1,219 @@ +#include +#define _USE_MATH_DEFINES +#include +#include "glmatrix.h" + +#ifndef M_PI +#define M_PI 3.141592653589793 +#endif + +#define MMODE_IDX(x) ((x) - GL_MODELVIEW) +#define MAT_STACK_SIZE 32 +#define MAT_IDENT {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1} + +static int mm_idx = 0; +static float mat_stack[3][MAT_STACK_SIZE][16] = {{MAT_IDENT}, {MAT_IDENT}, {MAT_IDENT}}; +static int stack_top[3]; + +void gl_matrix_mode(int mm) +{ + mm_idx = MMODE_IDX(mm); +} + +void gl_push_matrix(void) +{ + int top = stack_top[mm_idx]; + + memcpy(mat_stack[mm_idx][top + 1], mat_stack[mm_idx][top], 16 * sizeof(float)); + stack_top[mm_idx]++; +} + +void gl_pop_matrix(void) +{ + stack_top[mm_idx]--; +} + +void gl_load_identity(void) +{ + static const float idmat[] = MAT_IDENT; + int top = stack_top[mm_idx]; + float *mat = mat_stack[mm_idx][top]; + + memcpy(mat, idmat, sizeof idmat); +} + +void gl_load_matrixf(const float *m) +{ + int top = stack_top[mm_idx]; + float *mat = mat_stack[mm_idx][top]; + + memcpy(mat, m, 16 * sizeof *mat); +} + +#define M4(i, j) ((i << 2) + j) + +void gl_mult_matrixf(const float *m2) +{ + int i, j; + int top = stack_top[mm_idx]; + float *m1 = mat_stack[mm_idx][top]; + float res[16]; + + for(i=0; i<4; i++) { + for(j=0; j<4; j++) { + res[M4(i,j)] = m1[M4(i,0)] * m2[M4(0,j)] + + m1[M4(i,1)] * m2[M4(1,j)] + + m1[M4(i,2)] * m2[M4(2,j)] + + m1[M4(i,3)] * m2[M4(3,j)]; + } + } + + memcpy(m1, res, sizeof res); +} + +void gl_translatef(float x, float y, float z) +{ + float mat[] = MAT_IDENT; + + mat[12] = x; + mat[13] = y; + mat[14] = z; + + gl_mult_matrixf(mat); +} + +void gl_rotatef(float angle, float x, float y, float z) +{ + float mat[] = MAT_IDENT; + + float angle_rad = (float)M_PI * angle / 180.f; + float sina = (float)sin(angle_rad); + float cosa = (float)cos(angle_rad); + float one_minus_cosa = 1.f - cosa; + float nxsq = x * x; + float nysq = y * y; + float nzsq = z * z; + + mat[0] = nxsq + (1.f - nxsq) * cosa; + mat[4] = x * y * one_minus_cosa - z * sina; + mat[8] = x * z * one_minus_cosa + y * sina; + mat[1] = x * y * one_minus_cosa + z * sina; + mat[5] = nysq + (1.f - nysq) * cosa; + mat[9] = y * z * one_minus_cosa - x * sina; + mat[2] = x * z * one_minus_cosa - y * sina; + mat[6] = y * z * one_minus_cosa + x * sina; + mat[10] = nzsq + (1.f - nzsq) * cosa; + + gl_mult_matrixf(mat); +} + +void gl_scalef(float x, float y, float z) +{ + float mat[] = MAT_IDENT; + + mat[0] = x; + mat[5] = y; + mat[10] = z; + + gl_mult_matrixf(mat); +} + +void gl_ortho(float left, float right, float bottom, float top, float znear, float zfar) +{ + float mat[] = MAT_IDENT; + + float dx = right - left; + float dy = top - bottom; + float dz = zfar - znear; + + float tx = -(right + left) / dx; + float ty = -(top + bottom) / dy; + float tz = -(zfar + znear) / dz; + + float sx = 2.f / dx; + float sy = 2.f / dy; + float sz = -2.f / dz; + + mat[0] = sx; + mat[5] = sy; + mat[10] = sz; + mat[12] = tx; + mat[13] = ty; + mat[14] = tz; + + gl_mult_matrixf(mat); +} + +void gl_frustum(float left, float right, float bottom, float top, float znear, float zfar) +{ + float mat[] = MAT_IDENT; + + float dx = right - left; + float dy = top - bottom; + float dz = zfar - znear; + + float a = (right + left) / dx; + float b = (top + bottom) / dy; + float c = -(zfar + znear) / dz; + float d = -2.f * zfar * znear / dz; + + mat[0] = 2.f * znear / dx; + mat[5] = 2.f * znear / dy; + mat[8] = a; + mat[9] = b; + mat[10] = c; + mat[11] = -1.f; + mat[14] = d; + mat[15] = 0; + + gl_mult_matrixf(mat); +} + +void glu_perspective(float vfov, float aspect, float znear, float zfar) +{ + float vfov_rad = (float)M_PI * vfov / 180.f; + float x = znear * (float)tan(vfov_rad / 2.f); + gl_frustum(-aspect * x, aspect * x, -x, x, znear, zfar); +} + +/* return the matrix (16 elements, 4x4 matrix, row-major order */ +float* get_matrix(int mm) +{ + int idx = MMODE_IDX(mm); + int top = stack_top[idx]; + return mat_stack[idx][top]; +} + + +#define M3(i, j) ((i * 3) + j) +static float inv_transpose_result[9]; + +/* return the inverse transpose of the left-upper 3x3 of a matrix + The returned pointer is only valid until the next time this function is + called, so make a deep copy when you want to keep it around. + */ +float* get_inv_transpose_3x3(int mm) +{ + int idx = MMODE_IDX(mm); + int top = stack_top[idx]; + float *m1 = mat_stack[idx][top]; + + + float determinant = +m1[M4(0,0)]*(m1[M4(1,1)]*m1[M4(2,2)]-m1[M4(2,1)]*m1[M4(1,2)]) + -m1[M4(0,1)]*(m1[M4(1,0)]*m1[M4(2,2)]-m1[M4(1,2)]*m1[M4(2,0)]) + +m1[M4(0,2)]*(m1[M4(1,0)]*m1[M4(2,1)]-m1[M4(1,1)]*m1[M4(2,0)]); + + float invdet = 1/determinant; + + inv_transpose_result[M3(0,0)] = (m1[M4(1,1)]*m1[M4(2,2)]-m1[M4(2,1)]*m1[M4(1,2)])*invdet; + inv_transpose_result[M3(1,0)] = -(m1[M4(0,1)]*m1[M4(2,2)]-m1[M4(0,2)]*m1[M4(2,1)])*invdet; + inv_transpose_result[M3(2,0)] = (m1[M4(0,1)]*m1[M4(1,2)]-m1[M4(0,2)]*m1[M4(1,1)])*invdet; + inv_transpose_result[M3(0,1)] = -(m1[M4(1,0)]*m1[M4(2,2)]-m1[M4(1,2)]*m1[M4(2,0)])*invdet; + inv_transpose_result[M3(1,1)] = (m1[M4(0,0)]*m1[M4(2,2)]-m1[M4(0,2)]*m1[M4(2,0)])*invdet; + inv_transpose_result[M3(2,1)] = -(m1[M4(0,0)]*m1[M4(1,2)]-m1[M4(1,0)]*m1[M4(0,2)])*invdet; + inv_transpose_result[M3(0,2)] = (m1[M4(1,0)]*m1[M4(2,1)]-m1[M4(2,0)]*m1[M4(1,1)])*invdet; + inv_transpose_result[M3(1,2)] = -(m1[M4(0,0)]*m1[M4(2,1)]-m1[M4(2,0)]*m1[M4(0,1)])*invdet; + inv_transpose_result[M3(2,2)] = (m1[M4(0,0)]*m1[M4(1,1)]-m1[M4(1,0)]*m1[M4(0,1)])*invdet; + + return inv_transpose_result; +} diff --git a/windows/templates/GLUT/CL_GLUT_glmatrix.h.txt b/windows/templates/GLUT/CL_GLUT_glmatrix.h.txt new file mode 100644 index 00000000..7cf2c68a --- /dev/null +++ b/windows/templates/GLUT/CL_GLUT_glmatrix.h.txt @@ -0,0 +1,31 @@ +#ifndef GLMATRIX_H_ +#define GLMATRIX_H_ + +#ifndef GL_MODELVIEW +#define GL_MODELVIEW 0x1700 +#endif +#ifndef GL_PROJECTION +#define GL_PROJECTION 0x1701 +#endif +#ifndef GL_TEXTURE +#define GL_TEXTURE 0x1702 +#endif + +void gl_matrix_mode(int mmode); +void gl_push_matrix(void); +void gl_pop_matrix(void); +void gl_load_identity(void); +void gl_load_matrixf(const float *mat); +void gl_mult_matrixf(const float *mat); +void gl_translatef(float x, float y, float z); +void gl_rotatef(float angle, float x, float y, float z); +void gl_scalef(float x, float y, float z); +void gl_ortho(float left, float right, float bottom, float top, float znear, float zfar); +void gl_frustum(float left, float right, float bottom, float top, float znear, float zfar); +void glu_perspective(float vfov, float aspect, float znear, float zfar); + +/* getters */ +float* get_matrix(int mm); +float* get_inv_transpose_3x3(int mm); + +#endif /* GLMATRIX_H_ */ diff --git a/windows/templates/GLUT/CL_GLUT_shapes.c.txt b/windows/templates/GLUT/CL_GLUT_shapes.c.txt new file mode 100644 index 00000000..09fb5efa --- /dev/null +++ b/windows/templates/GLUT/CL_GLUT_shapes.c.txt @@ -0,0 +1,946 @@ +/*! \file shapes.c + \ingroup demos + + This program is a test harness for the various shapes + in OpenGLUT. It may also be useful to see which + parameters control what behavior in the OpenGLUT + objects. + + Spinning wireframe and solid-shaded shapes are + displayed. Some parameters can be adjusted. + + Keys: + - Esc   Quit + - q Q   Quit + - i I   Show info + - p P   Toggle perspective or orthographic projection + - r R   Toggle fixed or animated rotation around model X-axis + - s S   Toggle toggle fixed function or shader render path + - n N   Toggle visualization of object's normal vectors + - = +   Increase \a slices + - - _   Decreate \a slices + - , <   Decreate \a stacks + - . >   Increase \a stacks + - 9 (   Decreate \a depth (Sierpinski Sponge) + - 0 )   Increase \a depth (Sierpinski Sponge) + - up    Increase "outer radius" + - down  Decrease "outer radius" + - left  Decrease "inner radius" + - right Increase "inner radius" + - PgUp  Next shape-drawing function + - PgDn  Prev shape-drawing function + + \author Written by Nigel Stewart November 2003 + + \author Portions Copyright (C) 2004, the OpenGLUT project contributors.
+ OpenGLUT branched from freeglut in February, 2004. + + \image html openglut_shapes.png OpenGLUT Geometric Shapes Demonstration + \include demos/shapes/shapes.c +*/ + +#include + +#include +#include +#include +#include + +#include "glmatrix.h" + +#ifdef _MSC_VER +/* DUMP MEMORY LEAKS */ +#include +#endif + +/* report GL errors, if any, to stderr */ +void checkError(const char *functionName) +{ + GLenum error; + while (( error = glGetError() ) != GL_NO_ERROR) { + fprintf (stderr, "GL error 0x%X detected in %s\n", error, functionName); + } +} + +/* + * OpenGL 2+ shader mode needs some function and macro definitions, + * avoiding a dependency on additional libraries like GLEW or the + * GL/glext.h header + */ +#ifndef GL_FRAGMENT_SHADER +#define GL_FRAGMENT_SHADER 0x8B30 +#endif + +#ifndef GL_VERTEX_SHADER +#define GL_VERTEX_SHADER 0x8B31 +#endif + +#ifndef GL_COMPILE_STATUS +#define GL_COMPILE_STATUS 0x8B81 +#endif + +#ifndef GL_LINK_STATUS +#define GL_LINK_STATUS 0x8B82 +#endif + +#ifndef GL_INFO_LOG_LENGTH +#define GL_INFO_LOG_LENGTH 0x8B84 +#endif + +typedef ptrdiff_t ourGLsizeiptr; +typedef char ourGLchar; + +#ifndef APIENTRY +#define APIENTRY +#endif + +#ifndef GL_VERSION_2_0 +typedef GLuint (APIENTRY *PFNGLCREATESHADERPROC) (GLenum type); +typedef void (APIENTRY *PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const ourGLchar **string, const GLint *length); +typedef void (APIENTRY *PFNGLCOMPILESHADERPROC) (GLuint shader); +typedef GLuint (APIENTRY *PFNGLCREATEPROGRAMPROC) (void); +typedef void (APIENTRY *PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRY *PFNGLLINKPROGRAMPROC) (GLuint program); +typedef void (APIENTRY *PFNGLUSEPROGRAMPROC) (GLuint program); +typedef void (APIENTRY *PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); +typedef void (APIENTRY *PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, ourGLchar *infoLog); +typedef void (APIENTRY *PFNGLGETPROGRAMIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRY *PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, ourGLchar *infoLog); +typedef GLint (APIENTRY *PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const ourGLchar *name); +typedef GLint (APIENTRY *PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const ourGLchar *name); +typedef void (APIENTRY *PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRY *PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#endif + +PFNGLCREATESHADERPROC gl_CreateShader; +PFNGLSHADERSOURCEPROC gl_ShaderSource; +PFNGLCOMPILESHADERPROC gl_CompileShader; +PFNGLCREATEPROGRAMPROC gl_CreateProgram; +PFNGLATTACHSHADERPROC gl_AttachShader; +PFNGLLINKPROGRAMPROC gl_LinkProgram; +PFNGLUSEPROGRAMPROC gl_UseProgram; +PFNGLGETSHADERIVPROC gl_GetShaderiv; +PFNGLGETSHADERINFOLOGPROC gl_GetShaderInfoLog; +PFNGLGETPROGRAMIVPROC gl_GetProgramiv; +PFNGLGETPROGRAMINFOLOGPROC gl_GetProgramInfoLog; +PFNGLGETATTRIBLOCATIONPROC gl_GetAttribLocation; +PFNGLGETUNIFORMLOCATIONPROC gl_GetUniformLocation; +PFNGLUNIFORMMATRIX4FVPROC gl_UniformMatrix4fv; +PFNGLUNIFORMMATRIX3FVPROC gl_UniformMatrix3fv; + +void initExtensionEntries(void) +{ + gl_CreateShader = (PFNGLCREATESHADERPROC) glutGetProcAddress ("glCreateShader"); + gl_ShaderSource = (PFNGLSHADERSOURCEPROC) glutGetProcAddress ("glShaderSource"); + gl_CompileShader = (PFNGLCOMPILESHADERPROC) glutGetProcAddress ("glCompileShader"); + gl_CreateProgram = (PFNGLCREATEPROGRAMPROC) glutGetProcAddress ("glCreateProgram"); + gl_AttachShader = (PFNGLATTACHSHADERPROC) glutGetProcAddress ("glAttachShader"); + gl_LinkProgram = (PFNGLLINKPROGRAMPROC) glutGetProcAddress ("glLinkProgram"); + gl_UseProgram = (PFNGLUSEPROGRAMPROC) glutGetProcAddress ("glUseProgram"); + gl_GetShaderiv = (PFNGLGETSHADERIVPROC) glutGetProcAddress ("glGetShaderiv"); + gl_GetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) glutGetProcAddress ("glGetShaderInfoLog"); + gl_GetProgramiv = (PFNGLGETPROGRAMIVPROC) glutGetProcAddress ("glGetProgramiv"); + gl_GetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC) glutGetProcAddress ("glGetProgramInfoLog"); + gl_GetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC) glutGetProcAddress ("glGetAttribLocation"); + gl_GetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) glutGetProcAddress ("glGetUniformLocation"); + gl_UniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC) glutGetProcAddress ("glUniformMatrix4fv"); + gl_UniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC) glutGetProcAddress ("glUniformMatrix3fv"); + if (!gl_CreateShader || !gl_ShaderSource || !gl_CompileShader || !gl_CreateProgram || !gl_AttachShader || !gl_LinkProgram || !gl_UseProgram || !gl_GetShaderiv || !gl_GetShaderInfoLog || !gl_GetProgramiv || !gl_GetProgramInfoLog || !gl_GetAttribLocation || !gl_GetUniformLocation || !gl_UniformMatrix4fv || !gl_UniformMatrix3fv) + { + fprintf (stderr, "glCreateShader, glShaderSource, glCompileShader, glCreateProgram, glAttachShader, glLinkProgram, glUseProgram, glGetShaderiv, glGetShaderInfoLog, glGetProgramiv, glGetProgramInfoLog, glGetAttribLocation, glGetUniformLocation, glUniformMatrix4fv or gl_UniformMatrix3fv not found"); + exit(1); + } +} + +const ourGLchar *vertexShaderSource[] = { + "/**", + " * From the OpenGL Programming wikibook: http://en.wikibooks.org/wiki/GLSL_Programming/GLUT/Smooth_Specular_Highlights", + " * This file is in the public domain.", + " * Contributors: Sylvain Beucler", + " */", + "attribute vec3 fg_coord;", + "attribute vec3 fg_normal;", + "varying vec4 position; /* position of the vertex (and fragment) in world space */", + "varying vec3 varyingNormalDirection; /* surface normal vector in world space */", + "uniform mat4 m, p; /* don't need v, as always identity in our demo */", + "uniform mat3 m_3x3_inv_transp;", + " ", + "void main()", + "{", + " vec4 fg_coord4 = vec4(fg_coord, 1.0);", + " position = m * fg_coord4;", + " varyingNormalDirection = normalize(m_3x3_inv_transp * fg_normal);", + " ", + " mat4 mvp = p*m; /* normally p*v*m */", + " gl_Position = mvp * fg_coord4;", + "}" +}; + +const ourGLchar *fragmentShaderSource[] = { + "/**", + " * From the OpenGL Programming wikibook: http://en.wikibooks.org/wiki/GLSL_Programming/GLUT/Smooth_Specular_Highlights", + " * This file is in the public domain.", + " * Contributors: Martin Kraus, Sylvain Beucler", + " */", + "varying vec4 position; /* position of the vertex (and fragment) in world space */", + "varying vec3 varyingNormalDirection; /* surface normal vector in world space */", + "/* uniform mat4 v_inv; // in this demo, the view matrix is always an identity matrix */", + " ", + "struct lightSource", + "{", + " vec4 position;", + " vec4 diffuse;", + " vec4 specular;", + " float constantAttenuation, linearAttenuation, quadraticAttenuation;", + " float spotCutoff, spotExponent;", + " vec3 spotDirection;", + "};", + "lightSource light0 = lightSource(", + " vec4(2.0, 5.0, 5.0, 0.0),", + " vec4(1.0, 1.0, 1.0, 1.0),", + " vec4(1.0, 1.0, 1.0, 1.0),", + " 0.0, 1.0, 0.0,", + " 180.0, 0.0,", + " vec3(0.0, 0.0, 0.0)", + ");", + "vec4 scene_ambient = vec4(0.2, 0.2, 0.2, 1.0);", + " ", + "struct material", + "{", + " vec4 ambient;", + " vec4 diffuse;", + " vec4 specular;", + " float shininess;", + "};", + "material frontMaterial = material(", + " vec4(1.0, 0.0, 0.0, 1.0),", + " vec4(1.0, 0.0, 0.0, 1.0),", + " vec4(1.0, 1.0, 1.0, 1.0),", + " 100.0", + ");", + " ", + "void main()", + "{", + " vec3 normalDirection = normalize(varyingNormalDirection);", + " /* vec3 viewDirection = normalize(vec3(v_inv * vec4(0.0, 0.0, 0.0, 1.0) - position)); */", + " vec3 viewDirection = normalize(vec3(vec4(0.0, 0.0, 0.0, 1.0) - position)); /* in this demo, the view matrix is always an identity matrix */", + " vec3 lightDirection;", + " float attenuation;", + " ", + " if (0.0 == light0.position.w) /* directional light? */", + " {", + " attenuation = 1.0; /* no attenuation */", + " lightDirection = normalize(vec3(light0.position));", + " } ", + " else /* point light or spotlight (or other kind of light) */", + " {", + " vec3 positionToLightSource = vec3(light0.position - position);", + " float distance = length(positionToLightSource);", + " lightDirection = normalize(positionToLightSource);", + " attenuation = 1.0 / (light0.constantAttenuation", + " + light0.linearAttenuation * distance", + " + light0.quadraticAttenuation * distance * distance);", + " ", + " if (light0.spotCutoff <= 90.0) /* spotlight? */", + " {", + " float clampedCosine = max(0.0, dot(-lightDirection, light0.spotDirection));", + " if (clampedCosine < cos(radians(light0.spotCutoff))) /* outside of spotlight cone? */", + " {", + " attenuation = 0.0;", + " }", + " else", + " {", + " attenuation = attenuation * pow(clampedCosine, light0.spotExponent); ", + " }", + " }", + " }", + " ", + " vec3 ambientLighting = vec3(scene_ambient) * vec3(frontMaterial.ambient);", + " ", + " vec3 diffuseReflection = attenuation ", + " * vec3(light0.diffuse) * vec3(frontMaterial.diffuse)", + " * max(0.0, dot(normalDirection, lightDirection));", + " ", + " vec3 specularReflection;", + " if (dot(normalDirection, lightDirection) < 0.0) /* light source on the wrong side? */", + " {", + " specularReflection = vec3(0.0, 0.0, 0.0); /* no specular reflection */", + " }", + " else /* light source on the right side */", + " {", + " specularReflection = attenuation * vec3(light0.specular) * vec3(frontMaterial.specular) ", + " * pow(max(0.0, dot(reflect(-lightDirection, normalDirection), viewDirection)), frontMaterial.shininess);", + " }", + " ", + " gl_FragColor = vec4(ambientLighting + diffuseReflection + specularReflection, 1.0);", + "}" +}; + +GLint getAttribOrUniformLocation(const char* name, GLuint program, GLboolean isAttrib) +{ + if (isAttrib) + { + GLint attrib = gl_GetAttribLocation(program, name); + if (attrib == -1) + { + fprintf(stderr, "Warning: Could not bind attrib %s\n", name); + } + + checkError ("getAttribOrUniformLocation"); + return attrib; + } + else + { + GLint uniform = gl_GetUniformLocation(program, name); + if (uniform == -1) + { + fprintf(stderr, "Warning: Could not bind uniform %s\n", name); + } + + checkError ("getAttribOrUniformLocation"); + return uniform; + } +} + +GLuint program; +GLint attribute_fg_coord = -1, attribute_fg_normal = -1; +GLint uniform_m = -1, uniform_p = -1, uniform_m_3x3_inv_transp = -1; +GLint shaderReady = 0; /* Set to 1 when all initialization went well, to -1 when shader somehow unusable. */ + + + +void compileAndCheck(GLuint shader) +{ + GLint status; + gl_CompileShader (shader); + gl_GetShaderiv (shader, GL_COMPILE_STATUS, &status); + if (status == GL_FALSE) { + GLint infoLogLength; + ourGLchar *infoLog; + gl_GetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLength); + infoLog = (ourGLchar*) malloc (infoLogLength); + gl_GetShaderInfoLog (shader, infoLogLength, NULL, infoLog); + fprintf (stderr, "compile log: %s\n", infoLog); + free (infoLog); + } + checkError ("compileAndCheck"); +} + +GLuint compileShaderSource(GLenum type, GLsizei count, const ourGLchar **string) +{ + GLuint shader = gl_CreateShader (type); + gl_ShaderSource (shader, count, string, NULL); + + checkError ("compileShaderSource"); + + compileAndCheck (shader); + return shader; +} + +void linkAndCheck(GLuint program) +{ + GLint status; + gl_LinkProgram (program); + gl_GetProgramiv (program, GL_LINK_STATUS, &status); + if (status == GL_FALSE) { + GLint infoLogLength; + ourGLchar *infoLog; + gl_GetProgramiv (program, GL_INFO_LOG_LENGTH, &infoLogLength); + infoLog = (ourGLchar*) malloc (infoLogLength); + gl_GetProgramInfoLog (program, infoLogLength, NULL, infoLog); + fprintf (stderr, "link log: %s\n", infoLog); + free (infoLog); + } + checkError ("linkAndCheck"); +} + +void createProgram(GLuint vertexShader, GLuint fragmentShader) +{ + program = gl_CreateProgram (); + if (vertexShader != 0) { + gl_AttachShader (program, vertexShader); + } + if (fragmentShader != 0) { + gl_AttachShader (program, fragmentShader); + } + + checkError ("createProgram"); + + linkAndCheck (program); +} + +void initShader(void) +{ + const GLsizei vertexShaderLines = sizeof(vertexShaderSource) / sizeof(ourGLchar*); + GLuint vertexShader = + compileShaderSource (GL_VERTEX_SHADER, vertexShaderLines, vertexShaderSource); + + const GLsizei fragmentShaderLines = sizeof(fragmentShaderSource) / sizeof(ourGLchar*); + GLuint fragmentShader = + compileShaderSource (GL_FRAGMENT_SHADER, fragmentShaderLines, fragmentShaderSource); + + checkError ("initShader - 1"); + + createProgram (vertexShader, fragmentShader); + + gl_UseProgram (program); + + attribute_fg_coord = getAttribOrUniformLocation("fg_coord" , program, GL_TRUE); + attribute_fg_normal = getAttribOrUniformLocation("fg_normal" , program, GL_TRUE); + uniform_m = getAttribOrUniformLocation("m" , program, GL_FALSE); + uniform_p = getAttribOrUniformLocation("p" , program, GL_FALSE); + uniform_m_3x3_inv_transp= getAttribOrUniformLocation("m_3x3_inv_transp" , program, GL_FALSE); + + gl_UseProgram (0); + + if (attribute_fg_coord==-1 || attribute_fg_normal==-1 || + uniform_m==-1 || uniform_p==-1 || uniform_m_3x3_inv_transp==-1) + shaderReady = -1; + else + shaderReady = 1; + + checkError ("initShader - 2"); +} + +/* + * This macro is only intended to be used on arrays, of course. + */ +#define NUMBEROF(x) ((sizeof(x))/(sizeof(x[0]))) + +/* + * These global variables control which object is drawn, + * and how it is drawn. No object uses all of these + * variables. + */ +static int function_index; +static int slices = 16; +static int stacks = 16; +static double irad = .25; +static double orad = 1.0; /* doubles as size for objects other than Torus */ +static int depth = 4; +static double offset[ 3 ] = { 0, 0, 0 }; +static GLboolean show_info = GL_TRUE; +static float ar; +static GLboolean persProject = GL_TRUE; +static GLboolean animateXRot = GL_FALSE; +static GLboolean useShader = GL_FALSE; +static GLboolean visNormals = GL_FALSE; +static GLboolean flat; + +/* + * Enum to tell drawSizeInfo what to draw for each object + */ +#define GEO_NO_SIZE 0 +#define GEO_SIZE 1 +#define GEO_SCALE 2 +#define GEO_INNER_OUTER_RAD 4 +#define GEO_RAD 8 +#define GEO_BASE_HEIGHT 16 +#define GEO_RAD_HEIGHT 32 + +/* + * These one-liners draw particular objects, fetching appropriate + * information from the above globals. They are just thin wrappers + * for the FreeGLUT objects. + */ +static void drawSolidTetrahedron(void) { glutSolidTetrahedron (); } +static void drawWireTetrahedron(void) { glutWireTetrahedron (); } +static void drawSolidCube(void) { glutSolidCube(orad); } /* orad doubles as size input */ +static void drawWireCube(void) { glutWireCube(orad); } /* orad doubles as size input */ +static void drawSolidOctahedron(void) { glutSolidOctahedron (); } +static void drawWireOctahedron(void) { glutWireOctahedron (); } +static void drawSolidDodecahedron(void) { glutSolidDodecahedron (); } +static void drawWireDodecahedron(void) { glutWireDodecahedron (); } +static void drawSolidRhombicDodecahedron(void) { glutSolidRhombicDodecahedron (); } +static void drawWireRhombicDodecahedron(void) { glutWireRhombicDodecahedron (); } +static void drawSolidIcosahedron(void) { glutSolidIcosahedron (); } +static void drawWireIcosahedron(void) { glutWireIcosahedron (); } +static void drawSolidSierpinskiSponge(void) { glutSolidSierpinskiSponge (depth, offset, orad);} /* orad doubles as size input */ +static void drawWireSierpinskiSponge(void) { glutWireSierpinskiSponge (depth, offset, orad); } /* orad doubles as size input */ +static void drawSolidTorus(void) { glutSolidTorus(irad,orad,slices,stacks); } +static void drawWireTorus(void) { glutWireTorus (irad,orad,slices,stacks); } +static void drawSolidSphere(void) { glutSolidSphere(orad,slices,stacks); } /* orad doubles as size input */ +static void drawWireSphere(void) { glutWireSphere(orad,slices,stacks); } /* orad doubles as size input */ +static void drawSolidCone(void) { glutSolidCone(irad,orad,slices,stacks); } /* irad doubles as base input, and orad as height input */ +static void drawWireCone(void) { glutWireCone(irad,orad,slices,stacks); } /* irad doubles as base input, and orad as height input */ +static void drawSolidCylinder(void) { glutSolidCylinder(irad,orad,slices,stacks); } /* irad doubles as radius input, and orad as height input */ +static void drawWireCylinder(void) { glutWireCylinder(irad,orad,slices,stacks); } /* irad doubles as radius input, and orad as height input */ +/* per Glut manpage, it should be noted that the teapot is rendered + * with clockwise winding for front facing polygons... + * Same for the teacup and teaspoon + */ +static void drawSolidTeapot(void) +{ glFrontFace(GL_CW); glutSolidTeapot(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawWireTeapot(void) +{ glFrontFace(GL_CW); glutWireTeapot(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawSolidTeacup(void) +{ glFrontFace(GL_CW); glutSolidTeacup(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawWireTeacup(void) +{ glFrontFace(GL_CW); glutWireTeacup(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawSolidTeaspoon(void) +{ glFrontFace(GL_CW); glutSolidTeaspoon(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawWireTeaspoon(void) +{ glFrontFace(GL_CW); glutWireTeaspoon(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} + +#define RADIUSFAC 0.70710678118654752440084436210485f + +static void drawSolidCuboctahedron(void) +{ + GLfloat radius = RADIUSFAC*(GLfloat)orad; /* orad doubles as size */ + glBegin( GL_TRIANGLES ); + glNormal3d( 0.577350269189, 0.577350269189, 0.577350269189); glVertex3d( radius, radius, 0.0 ); glVertex3d( 0.0, radius, radius ); glVertex3d( radius, 0.0, radius ); + glNormal3d( 0.577350269189, 0.577350269189,-0.577350269189); glVertex3d( radius, radius, 0.0 ); glVertex3d( radius, 0.0,-radius ); glVertex3d( 0.0, radius,-radius ); + glNormal3d( 0.577350269189,-0.577350269189, 0.577350269189); glVertex3d( radius,-radius, 0.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( 0.0,-radius, radius ); + glNormal3d( 0.577350269189,-0.577350269189,-0.577350269189); glVertex3d( radius,-radius, 0.0 ); glVertex3d( 0.0,-radius,-radius ); glVertex3d( radius, 0.0,-radius ); + glNormal3d(-0.577350269189, 0.577350269189, 0.577350269189); glVertex3d(-radius, radius, 0.0 ); glVertex3d(-radius, 0.0, radius ); glVertex3d( 0.0, radius, radius ); + glNormal3d(-0.577350269189, 0.577350269189,-0.577350269189); glVertex3d(-radius, radius, 0.0 ); glVertex3d( 0.0, radius,-radius ); glVertex3d(-radius, 0.0,-radius ); + glNormal3d(-0.577350269189,-0.577350269189, 0.577350269189); glVertex3d(-radius,-radius, 0.0 ); glVertex3d( 0.0,-radius, radius ); glVertex3d(-radius, 0.0, radius ); + glNormal3d(-0.577350269189,-0.577350269189,-0.577350269189); glVertex3d(-radius,-radius, 0.0 ); glVertex3d(-radius, 0.0,-radius ); glVertex3d( 0.0,-radius,-radius ); + glEnd(); + + glBegin( GL_QUADS ); + glNormal3d( 1.0, 0.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( radius, 0.0,-radius ); + glNormal3d(-1.0, 0.0, 0.0 ); glVertex3d(-radius, radius, 0.0 ); glVertex3d(-radius, 0.0,-radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d(-radius, 0.0, radius ); + glNormal3d( 0.0, 1.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( 0.0, radius,-radius ); glVertex3d(-radius, radius, 0.0 ); glVertex3d( 0.0, radius, radius ); + glNormal3d( 0.0,-1.0, 0.0 ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( 0.0,-radius, radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d( 0.0,-radius,-radius ); + glNormal3d( 0.0, 0.0, 1.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( 0.0, radius, radius ); glVertex3d(-radius, 0.0, radius ); glVertex3d( 0.0,-radius, radius ); + glNormal3d( 0.0, 0.0,-1.0 ); glVertex3d( radius, 0.0,-radius ); glVertex3d( 0.0,-radius,-radius ); glVertex3d(-radius, 0.0,-radius ); glVertex3d( 0.0, radius,-radius ); + glEnd(); +} + +static void drawWireCuboctahedron(void) +{ + GLfloat radius = RADIUSFAC*(GLfloat)orad; /* orad doubles as size */ + glBegin( GL_LINE_LOOP ); + glNormal3d( 1.0, 0.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( radius, 0.0,-radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d(-1.0, 0.0, 0.0 ); glVertex3d(-radius, radius, 0.0 ); glVertex3d(-radius, 0.0,-radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d(-radius, 0.0, radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d( 0.0, 1.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( 0.0, radius,-radius ); glVertex3d(-radius, radius, 0.0 ); glVertex3d( 0.0, radius, radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d( 0.0,-1.0, 0.0 ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( 0.0,-radius, radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d( 0.0,-radius,-radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d( 0.0, 0.0, 1.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( 0.0, radius, radius ); glVertex3d(-radius, 0.0, radius ); glVertex3d( 0.0,-radius, radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d( 0.0, 0.0,-1.0 ); glVertex3d( radius, 0.0,-radius ); glVertex3d( 0.0,-radius,-radius ); glVertex3d(-radius, 0.0,-radius ); glVertex3d( 0.0, radius,-radius ); + glEnd(); +} + +#undef RADIUSFAC + +/* + * This structure defines an entry in our function-table. + */ +typedef struct +{ + const char * const name; + void (*solid) (void); + void (*wire) (void); + int drawSizeInfoFlag; +} entry; + +#define ENTRY(e,f) {#e, drawSolid##e, drawWire##e,f} +static const entry table [] = +{ + ENTRY (Tetrahedron,GEO_NO_SIZE), + ENTRY (Cube,GEO_SIZE), + ENTRY (Octahedron,GEO_NO_SIZE), + ENTRY (Dodecahedron,GEO_NO_SIZE), + ENTRY (RhombicDodecahedron,GEO_NO_SIZE), + ENTRY (Icosahedron,GEO_NO_SIZE), + ENTRY (SierpinskiSponge,GEO_SCALE), + ENTRY (Teapot,GEO_SIZE), + ENTRY (Teacup,GEO_SIZE), + ENTRY (Teaspoon,GEO_SIZE), + ENTRY (Torus,GEO_INNER_OUTER_RAD), + ENTRY (Sphere,GEO_RAD), + ENTRY (Cone,GEO_BASE_HEIGHT), + ENTRY (Cylinder,GEO_RAD_HEIGHT), + ENTRY (Cuboctahedron,GEO_SIZE) /* This one doesn't work when in shader mode and is then skipped */ +}; +#undef ENTRY + +/*! + Does printf()-like work using freeglut + glutBitmapString(). Uses a fixed font. Prints + at the indicated row/column position. + + Limitation: Cannot address pixels. + Limitation: Renders in screen coords, not model coords. +*/ +static void shapesPrintf (int row, int col, const char *fmt, ...) +{ + static char buf[256]; + int viewport[4]; + void *font = GLUT_BITMAP_9_BY_15; + va_list args; + + va_start(args, fmt); +#if defined(WIN32) && !defined(__CYGWIN__) + (void) _vsnprintf (buf, sizeof(buf), fmt, args); +#else + (void) vsnprintf (buf, sizeof(buf), fmt, args); +#endif + va_end(args); + + glGetIntegerv(GL_VIEWPORT,viewport); + + glPushMatrix(); + glLoadIdentity(); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + + glOrtho(0,viewport[2],0,viewport[3],-1,1); + + glRasterPos2i + ( + glutBitmapWidth(font, ' ') * col, + - glutBitmapHeight(font) * row + viewport[3] + ); + glutBitmapString (font, (unsigned char*)buf); + + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); +} + +/* Print info about the about the current shape and render state on the screen */ +static void DrawSizeInfo(int *row) +{ + switch (table [function_index].drawSizeInfoFlag) + { + case GEO_NO_SIZE: + break; + case GEO_SIZE: + shapesPrintf ((*row)++, 1, "Size Up Down : %f", orad); + break; + case GEO_SCALE: + shapesPrintf ((*row)++, 1, "Scale Up Down : %f", orad); + break; + case GEO_INNER_OUTER_RAD: + shapesPrintf ((*row)++, 1, "Inner radius Left Right: %f", irad); + shapesPrintf ((*row)++, 1, "Outer radius Up Down : %f", orad); + break; + case GEO_RAD: + shapesPrintf ((*row)++, 1, "Radius Up Down : %f", orad); + break; + case GEO_BASE_HEIGHT: + shapesPrintf ((*row)++, 1, "Base Left Right: %f", irad); + shapesPrintf ((*row)++, 1, "Height Up Down : %f", orad); + break; + case GEO_RAD_HEIGHT: + shapesPrintf ((*row)++, 1, "Radius Left Right: %f", irad); + shapesPrintf ((*row)++, 1, "Height Up Down : %f", orad); + break; + } +} + +static void drawInfo() +{ + int row = 1; + shapesPrintf (row++, 1, "Shape PgUp PgDn: %s", table [function_index].name); + shapesPrintf (row++, 1, "Slices +-: %d Stacks <>: %d", slices, stacks); + shapesPrintf (row++, 1, "nSides +-: %d nRings <>: %d", slices, stacks); + shapesPrintf (row++, 1, "Depth (): %d", depth); + DrawSizeInfo(&row); + if (persProject) + shapesPrintf (row++, 1, "Perspective projection (p)"); + else + shapesPrintf (row++, 1, "Orthographic projection (p)"); + if (useShader) { + shapesPrintf (row++, 1, "Using shader (s)"); + } else { + shapesPrintf (row++, 1, "Using fixed function pipeline (s)"); + if (flat) + shapesPrintf (row++, 1, "Flat shading (f)"); + else + shapesPrintf (row++, 1, "Smooth shading (f)"); + } + if (animateXRot) + shapesPrintf (row++, 1, "2D rotation (r)"); + else + shapesPrintf (row++, 1, "1D rotation (r)"); + shapesPrintf (row++, 1, "visualizing normals: %i (n)",visNormals); +} + +/* GLUT callback Handlers */ +static void +resize(int width, int height) +{ + ar = (float) width / (float) height; + + glViewport(0, 0, width, height); +} + +static void display(void) +{ + const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0; + const double a = t*89.0; + const double b = (animateXRot?t:1)*67.0; + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glutSetOption(GLUT_GEOMETRY_VISUALIZE_NORMALS,visNormals); /* Normals visualized or not? */ + + glShadeModel(flat ? GL_FLAT : GL_SMOOTH); /* flat or gouraud shading */ + + if (useShader && !shaderReady) + initShader(); + + if (useShader && shaderReady) + { + /* setup use of shader (and vertex buffer by FreeGLUT) */ + gl_UseProgram (program); + glutSetVertexAttribCoord3(attribute_fg_coord); + glutSetVertexAttribNormal(attribute_fg_normal); + /* There is also a glutSetVertexAttribTexCoord2, which is used only when drawing the teapot, teacup or teaspoon */ + + gl_matrix_mode(GL_PROJECTION); + gl_load_identity(); + if (persProject) + gl_frustum(-ar, ar, -1.f, 1.f, 2.f, 100.f); + else + gl_ortho(-ar*3, ar*3, -3.f, 3.f, 2.f, 100.f); + gl_UniformMatrix4fv (uniform_p, 1, GL_FALSE, get_matrix(GL_PROJECTION)); + + + gl_matrix_mode(GL_MODELVIEW); + gl_load_identity(); + + gl_push_matrix(); + /* Not in reverse order like normal OpenGL, our util library multiplies the matrices in the order they are specified in */ + gl_rotatef((float)a,0,0,1); + gl_rotatef((float)b,1,0,0); + gl_translatef(0,1.2f,-6); + gl_UniformMatrix4fv (uniform_m , 1, GL_FALSE, get_matrix(GL_MODELVIEW)); + gl_UniformMatrix3fv (uniform_m_3x3_inv_transp, 1, GL_FALSE, get_inv_transpose_3x3(GL_MODELVIEW)); + table [function_index].solid (); + gl_pop_matrix(); + + gl_push_matrix(); + gl_rotatef((float)a,0,0,1); + gl_rotatef((float)b,1,0,0); + gl_translatef(0,-1.2f,-6); + gl_UniformMatrix4fv (uniform_m , 1, GL_FALSE, get_matrix(GL_MODELVIEW)); + gl_UniformMatrix3fv (uniform_m_3x3_inv_transp, 1, GL_FALSE, get_inv_transpose_3x3(GL_MODELVIEW)); + table [function_index].wire (); + gl_pop_matrix(); + + gl_UseProgram (0); + glutSetVertexAttribCoord3(-1); + glutSetVertexAttribNormal(-1); + + checkError ("display"); + } + else + { + /* fixed function pipeline */ + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + if (persProject) + glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0); + else + glOrtho(-ar*3, ar*3, -3.0, 3.0, 2.0, 100.0); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glEnable(GL_LIGHTING); + + glColor3d(1,0,0); + + glPushMatrix(); + glTranslated(0,1.2,-6); + glRotated(b,1,0,0); + glRotated(a,0,0,1); + table [function_index].solid (); + glPopMatrix(); + + glPushMatrix(); + glTranslated(0,-1.2,-6); + glRotated(b,1,0,0); + glRotated(a,0,0,1); + table [function_index].wire (); + glPopMatrix(); + + glDisable(GL_LIGHTING); + glColor3d(0.1,0.1,0.4); + } + + if( show_info ) + /* print info to screen */ + drawInfo(); + else + /* print to command line instead */ + printf ( "Shape %d slides %d stacks %d\n", function_index, slices, stacks ) ; + + glutSwapBuffers(); +} + + +static void +key(unsigned char key, int x, int y) +{ + switch (key) + { + case 27 : + case 'Q': + case 'q': glutLeaveMainLoop () ; break; + + case 'I': + case 'i': show_info=!show_info; break; + + case '=': + case '+': slices++; break; + + case '-': + case '_': if( slices > -1 ) slices--; break; + + case ',': + case '<': if( stacks > -1 ) stacks--; break; + + case '.': + case '>': stacks++; break; + + case '9': + case '(': if( depth > -1 ) depth--; break; + + case '0': + case ')': ++depth; break; + + case 'P': + case 'p': persProject=!persProject; break; + + case 'R': + case 'r': animateXRot=!animateXRot; break; + + case 'S': + case 's': + useShader=!useShader; + /* Cuboctahedron can't be shown when in shader mode, move to next */ + if (useShader && NUMBEROF (table)-1 == ( unsigned )function_index) + function_index = 0; + break; + + case 'F': + case 'f': + flat ^= 1; + break; + + case 'N': + case 'n': visNormals=!visNormals; break; + + default: + break; + } + + glutPostRedisplay(); +} + +static void special (int key, int x, int y) +{ + switch (key) + { + case GLUT_KEY_PAGE_UP: ++function_index; break; + case GLUT_KEY_PAGE_DOWN: --function_index; break; + case GLUT_KEY_UP: orad *= 2; break; + case GLUT_KEY_DOWN: orad /= 2; break; + + case GLUT_KEY_RIGHT: irad *= 2; break; + case GLUT_KEY_LEFT: irad /= 2; break; + + default: + break; + } + + if (0 > function_index) + function_index = NUMBEROF (table) - 1; + + if (NUMBEROF (table) <= ( unsigned )function_index) + function_index = 0; + + /* Cuboctahedron can't be shown when in shader mode, skip it */ + if (useShader && NUMBEROF (table)-1 == ( unsigned )function_index) + { + if (key==GLUT_KEY_PAGE_UP) + function_index = 0; + else + function_index -= 1; + } +} + + +static void +idle(void) +{ + glutPostRedisplay(); +} + +const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f }; +const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; +const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; +const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f }; + +const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f }; +const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f }; +const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; +const GLfloat high_shininess[] = { 100.0f }; + +/* Program entry point */ + +int +main(int argc, char *argv[]) +{ + glutInitWindowSize(800,600); + glutInitWindowPosition(40,40); + glutInit(&argc, argv); + glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE); + + glutCreateWindow("FreeGLUT Shapes"); + + glutReshapeFunc(resize); + glutDisplayFunc(display); + glutKeyboardFunc(key); + glutSpecialFunc(special); + glutIdleFunc(idle); + + glutSetOption ( GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION ) ; + + glClearColor(1,1,1,1); + glEnable(GL_CULL_FACE); + glCullFace(GL_BACK); + + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LESS); + + glEnable(GL_LIGHT0); + glEnable(GL_NORMALIZE); + glEnable(GL_COLOR_MATERIAL); + + glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); + glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); + glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); + glLightfv(GL_LIGHT0, GL_POSITION, light_position); + + glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); + glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); + glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); + glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess); + + initExtensionEntries(); + + glutMainLoop(); + +#ifdef _MSC_VER + /* DUMP MEMORY LEAK INFORMATION */ + _CrtDumpMemoryLeaks () ; +#endif + + return EXIT_SUCCESS; +} diff --git a/windows/templates/GLUT/info.template b/windows/templates/GLUT/info.template new file mode 100644 index 00000000..6faecdd2 --- /dev/null +++ b/windows/templates/GLUT/info.template @@ -0,0 +1,28 @@ +[Template] +ver=2 +Name=GLUT +Icon=CL_GLUT.ico +Description=A simple GLUT program +Description[zh_CN]=一个简单的GLUT程序 +Category=3D +Category[zh_CN]=3D + +[Unit0] +CName=main.c +C=CL_GLUT_shapes.c.txt + +[Unit1] +CName=glmatrix.h +C=CL_GLUT_glmatrix.h.txt + +[Unit2] +CName=glmatrix.c +C=CL_GLUT_glmatrix.c.txt + +[Project] +UnitCount=3 +Type=0 +IsCpp=0 +linker=-lm -lfreeglut.dll -lopengl32 -lwinmm -lgdi32 + + diff --git a/windows/templates/Graphics/CL_Graphics.ico b/windows/templates/Graphics/CL_Graphics.ico new file mode 100644 index 00000000..3749cee3 Binary files /dev/null and b/windows/templates/Graphics/CL_Graphics.ico differ diff --git a/windows/templates/Graphics/CL_Graphics_cpp.txt b/windows/templates/Graphics/CL_Graphics_cpp.txt new file mode 100644 index 00000000..c4952ed3 --- /dev/null +++ b/windows/templates/Graphics/CL_Graphics_cpp.txt @@ -0,0 +1,32 @@ +#include +#include + +void paintstar(double x, double y, double r, double a) +{ + int pt[10]; + for (int n = 0; n < 5; ++n) + { + pt[n*2] = (int)( -cos( PI * 4 / 5 * n + a ) * r + x ); + pt[n*2+1] = (int)( sin( PI * 4 / 5 * n + a) * r + y ); + } + fillpoly(5, pt); +} + +int main() +{ + initgraph( 640, 480 ); + setcolor( RGB(0xff, 0xff, 0xff) ); + setfillcolor( RGB(0, 0, 0xff) ); + setrendermode(RENDER_MANUAL); + + double r = 0; + for ( ; is_run(); delay_fps(60) ) + { + r += 0.02; + if (r > PI * 2) r -= PI * 2; + + cleardevice(); + paintstar(300, 200, 100, r); + } + return 0; +} \ No newline at end of file diff --git a/windows/templates/Graphics/info.template b/windows/templates/Graphics/info.template new file mode 100644 index 00000000..c3fe249f --- /dev/null +++ b/windows/templates/Graphics/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=Graphics.h +Icon=CL_Graphics.ico +Description=A simple program use Easy Graphics Engine +Description[zh_CN]=使用EGE库的简单绘图程序 +Category=Multimedia +Category[zh_CN]=多媒体 + +[Unit0] +CppName=main.cpp +Cpp=CL_Graphics_cpp.txt + +[Project] +UnitCount=1 +Type=0 +IsCpp=1 +linker=-lgraphics -luuid -lmsimg32 -lgdi32 -limm32 -lole32 -loleaut32 -lwinmm -lgdiplus_@@__@@_ + + diff --git a/windows/templates/Hello/Communication.ico b/windows/templates/Hello/Communication.ico new file mode 100644 index 00000000..1d232575 Binary files /dev/null and b/windows/templates/Hello/Communication.ico differ diff --git a/windows/templates/Hello/Hello_c.txt b/windows/templates/Hello/Hello_c.txt new file mode 100644 index 00000000..015f3f20 --- /dev/null +++ b/windows/templates/Hello/Hello_c.txt @@ -0,0 +1,6 @@ +#include + +int main(int argc, char** argv) { + printf("Hello world!\n"); + return 0; +} \ No newline at end of file diff --git a/windows/templates/Hello/Hello_cpp.txt b/windows/templates/Hello/Hello_cpp.txt new file mode 100644 index 00000000..59205e45 --- /dev/null +++ b/windows/templates/Hello/Hello_cpp.txt @@ -0,0 +1,5 @@ +#include + +int main(int argc, char** argv) { + std::cout << "Hello world!\n"; +} \ No newline at end of file diff --git a/windows/templates/Hello/info.template b/windows/templates/Hello/info.template new file mode 100644 index 00000000..522f468e --- /dev/null +++ b/windows/templates/Hello/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=Hello World +Name[zh_CN]=世界,你好! +Icon=Communication.ico +Description=A classic Hello World program +Description[zh_CN]=一个经典的“世界,你好!”程序 +Category=Console +Category[zh_CN]=控制台 + +[Unit0] +CName=main.c +CppName=main.cpp +C=Hello_c.txt +Cpp=Hello_cpp.txt + +[Project] +UnitCount=1 +Type=1 +Icon=Communication.ico diff --git a/windows/templates/HelloInput/ConsoleToo.ico b/windows/templates/HelloInput/ConsoleToo.ico new file mode 100644 index 00000000..4238e81f Binary files /dev/null and b/windows/templates/HelloInput/ConsoleToo.ico differ diff --git a/windows/templates/HelloInput/HelloInput_c.txt b/windows/templates/HelloInput/HelloInput_c.txt new file mode 100644 index 00000000..6e385c03 --- /dev/null +++ b/windows/templates/HelloInput/HelloInput_c.txt @@ -0,0 +1,27 @@ +#include + +void Foo() { + printf("Hello World!\n"); +} + +int main(int argc, char** argv) { + char input = 0; + + printf("Hello! This is a console application.\n"); + printf("Press q to quit, press a to execute foo.\n"); + while(1) { + if(scanf("%c",&input) == 1) { + if(input == 'a') { + Foo(); + } else if(input == 'q') { + break; + } else if(input != '\n') { + printf("Unknown command '%c'! Ignoring...\n",input); + } + } else { + printf("Invalid input! Ignoring...\n"); + } + } + + return 0; +} diff --git a/windows/templates/HelloInput/HelloInput_cpp.txt b/windows/templates/HelloInput/HelloInput_cpp.txt new file mode 100644 index 00000000..0cb67617 --- /dev/null +++ b/windows/templates/HelloInput/HelloInput_cpp.txt @@ -0,0 +1,27 @@ +#include +using std::cin; +using std::cout; +using std::endl; + +void Foo() { + cout << "Hello World!" << endl; +} + +int main(int argc, char** argv) { + char input = 0; + + cout << "Hello! This is a console application." << endl; + cout << "Press q to quit, press a to execute foo." << endl; + while(1) { + cin >> input; + if(input == 'a') { + Foo(); + } else if(input == 'q') { + break; + } else if(input != '\n') { + cout << "Unknown command '" << input << "'! Ignoring...\n"; + } + } + + return 0; +} diff --git a/windows/templates/HelloInput/info.template b/windows/templates/HelloInput/info.template new file mode 100644 index 00000000..1874052f --- /dev/null +++ b/windows/templates/HelloInput/info.template @@ -0,0 +1,19 @@ +[Template] +ver=2 +Name=Input Loop +Name[zh_CN]=输入循环 +Icon=ConsoleToo.ico +Description=A console with an input loop +Description[zh_CN]=一个带输入循环的控制台程序 +Category=Console +Category[zh_CN]=控制台 + +[Unit0] +CName=main.c +CppName=main.cpp +C=HelloInput_c.txt +Cpp=HelloInput_cpp.txt + +[Project] +UnitCount=1 +Type=1 diff --git a/windows/templates/Jackpot/Games.ico b/windows/templates/Jackpot/Games.ico new file mode 100644 index 00000000..1acc99db Binary files /dev/null and b/windows/templates/Jackpot/Games.ico differ diff --git a/windows/templates/Jackpot/Jackpot_cpp.txt b/windows/templates/Jackpot/Jackpot_cpp.txt new file mode 100644 index 00000000..af939395 --- /dev/null +++ b/windows/templates/Jackpot/Jackpot_cpp.txt @@ -0,0 +1,88 @@ +#include +#include +#include + +using namespace std; + +void Start(); +void GetResults(); + +int i, j, life, maxrand; +char c; + +void Start() { + i = 0; + j = 0; + life = 0; + maxrand = 6; + + cout << "Select difficulty mode:\n"; // the user has to select a difficutly level + cout << "1 : Easy (0-15)\n"; + cout << "2 : Medium (0-30)\n"; + cout << "3 : Difficult (0-50)\n"; + cout << "or type another key to quit\n"; + c = 30; + + cin >> c; // read the user's choice + cout << "\n"; + + switch (c) { + case '1': + maxrand = 15; // the random number will be between 0 and maxrand + break; + case '2': + maxrand = 30; + break; + case '3': + maxrand = 50; + break; + default: + exit(0); + break; + } + + life = 5; // number of lifes of the player + srand((unsigned)time(NULL)); // init Rand() function + j = rand() % maxrand; // j get a random value between 0 and maxrand + + GetResults(); +} + +void GetResults() { + if (life <= 0) { // if player has no more life then he loses + cout << "You lose !\n\n"; + Start(); + } + + cout << "Type a number: \n"; + cin >> i; + + if((i>maxrand) || (i<0)) { // if the user number isn't correct, restart + cout << "Error: number not between 0 and \n" << maxrand; + GetResults(); + } + + if(i == j) { + cout << "YOU WIN!\n\n"; // the user found the secret number + Start(); + } else if(i>j) { + cout << "Too BIG\n"; + life = life - 1; + cout << "Lives remaining: " << life << "\n\n"; + GetResults(); + } else if(i +#include + +#include "main.h" + +LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam); +LRESULT CALLBACK MDIChildWndProc(HWND hwnd, UINT Message, WPARAM wParam,LPARAM lParam); + +char g_szAppName[] = "MyMDIWindow"; +char g_szChild[] = "MyMDIChild"; +HINSTANCE g_hInst; +HWND g_hMDIClient, g_hStatusBar, g_hToolBar; +HWND g_hMainWindow; + +BOOL LoadFile(HWND hEdit, LPSTR pszFileName) { + HANDLE hFile; + BOOL bSuccess = FALSE; + + hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + if(hFile != INVALID_HANDLE_VALUE) { + DWORD dwFileSize; + dwFileSize = GetFileSize(hFile, NULL); + if(dwFileSize != 0xFFFFFFFF) { + LPSTR pszFileText; + pszFileText = (LPSTR)(GlobalAlloc(GPTR, dwFileSize + 1)); + if(pszFileText != NULL) { + DWORD dwRead; + if(ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL)) { + pszFileText[dwFileSize] = 0; // Null terminator + if(SetWindowText(hEdit, pszFileText)) + bSuccess = TRUE; // It worked! + } + GlobalFree(pszFileText); + } + } + CloseHandle(hFile); + } + return bSuccess; +} + +BOOL SaveFile(HWND hEdit, LPSTR pszFileName) { + HANDLE hFile; + BOOL bSuccess = FALSE; + + hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, NULL, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + if(hFile != INVALID_HANDLE_VALUE) { + DWORD dwTextLength; + dwTextLength = GetWindowTextLength(hEdit); + if(dwTextLength > 0) {// No need to bother if there's no text. + LPSTR pszText; + pszText = (LPSTR)(GlobalAlloc(GPTR, dwTextLength + 1)); + if(pszText != NULL) { + if(GetWindowText(hEdit, pszText, dwTextLength + 1)) { + DWORD dwWritten; + if(WriteFile(hFile, pszText, dwTextLength, &dwWritten, NULL)) + bSuccess = TRUE; + } + GlobalFree(pszText); + } + } + CloseHandle(hFile); + } + return bSuccess; +} + +BOOL GetFileName(HWND hwnd, LPSTR pszFileName, BOOL bSave) { + OPENFILENAME ofn; + + ZeroMemory(&ofn, sizeof(ofn)); + pszFileName[0] = 0; + + ofn.lStructSize = sizeof(ofn); + ofn.hwndOwner = hwnd; + ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0\0"; + ofn.lpstrFile = pszFileName; + ofn.nMaxFile = MAX_PATH; + ofn.lpstrDefExt = "txt"; + + if(bSave) { + ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | + OFN_OVERWRITEPROMPT; + if(!GetSaveFileName(&ofn)) + return FALSE; + } else { + ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; + if(!GetOpenFileName(&ofn)) + return FALSE; + } + return TRUE; +} + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpszCmdParam, int nCmdShow) { + MSG Msg; + WNDCLASSEX WndClassEx; + + g_hInst = hInstance; + + WndClassEx.cbSize = sizeof(WNDCLASSEX); + WndClassEx.style = CS_HREDRAW | CS_VREDRAW; + WndClassEx.lpfnWndProc = WndProc; + WndClassEx.cbClsExtra = 0; + WndClassEx.cbWndExtra = 0; + WndClassEx.hInstance = hInstance; + WndClassEx.hIcon = LoadIcon(NULL, IDI_APPLICATION); + WndClassEx.hCursor = LoadCursor(NULL, IDC_ARROW); + WndClassEx.hbrBackground = (HBRUSH)(COLOR_3DSHADOW+1); + WndClassEx.lpszMenuName = "MAIN"; + WndClassEx.lpszClassName = g_szAppName; + WndClassEx.hIconSm = LoadIcon(NULL, IDI_APPLICATION); + + if(!RegisterClassEx(&WndClassEx)) { + MessageBox(0, "Could Not Register Window", "Oh Oh...",MB_ICONEXCLAMATION | MB_OK); + return -1; + } + + WndClassEx.lpfnWndProc = MDIChildWndProc; + WndClassEx.lpszMenuName = NULL; + WndClassEx.lpszClassName = g_szChild; + WndClassEx.hbrBackground = (HBRUSH)(COLOR_3DFACE+1); + + if(!RegisterClassEx(&WndClassEx)) { + MessageBox(0, "Could Not Register Child Window", "Oh Oh...", + MB_ICONEXCLAMATION | MB_OK); + return -1; + } + + g_hMainWindow = CreateWindowEx(WS_EX_APPWINDOW,g_szAppName,"MDI File Editor",WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + 0, 0, hInstance, NULL); + + if (g_hMainWindow == NULL){ + MessageBox(0, "No Window", "Oh Oh...", MB_ICONEXCLAMATION | MB_OK); + return -1; + } + + ShowWindow(g_hMainWindow, nCmdShow); + UpdateWindow(g_hMainWindow); + + while(GetMessage(&Msg, NULL, 0, 0)) { + if (!TranslateMDISysAccel(g_hMDIClient, &Msg)) { + TranslateMessage(&Msg); + DispatchMessage(&Msg); + } + } + return Msg.wParam; +} + +LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { + switch(Message) { + case WM_CREATE: { + CLIENTCREATESTRUCT ccs; + int iStatusWidths[] = {200, 300, -1}; + TBADDBITMAP tbab; + TBBUTTON tbb[9]; + + // Find window menu where children will be listed + ccs.hWindowMenu = GetSubMenu(GetMenu(hwnd), 2); + ccs.idFirstChild = ID_MDI_FIRSTCHILD; + g_hMDIClient = CreateWindowEx(WS_EX_CLIENTEDGE, "mdiclient", NULL, + WS_CHILD | WS_CLIPCHILDREN | WS_VSCROLL | WS_HSCROLL, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + hwnd, (HMENU)ID_MDI_CLIENT, g_hInst, (LPVOID)&ccs); + ShowWindow(g_hMDIClient, SW_SHOW); + + g_hStatusBar = CreateWindowEx(0, STATUSCLASSNAME, NULL, + WS_CHILD | WS_VISIBLE | SBARS_SIZEGRIP, 0, 0, 0, 0, + hwnd, (HMENU)ID_STATUSBAR, g_hInst, NULL); + SendMessage(g_hStatusBar, SB_SETPARTS, 3, (LPARAM)iStatusWidths); + SendMessage(g_hStatusBar, SB_SETTEXT, 2, (LPARAM)"Toolbar & Statusbar Example"); + + g_hToolBar = CreateWindowEx(0, TOOLBARCLASSNAME, NULL, + WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, + hwnd, (HMENU)ID_TOOLBAR, g_hInst, NULL); + + // Send the TB_BUTTONSTRUCTSIZE message, which is required for + // backward compatibility. + SendMessage(g_hToolBar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0); + + tbab.hInst = HINST_COMMCTRL; + tbab.nID = IDB_STD_SMALL_COLOR; + SendMessage(g_hToolBar, TB_ADDBITMAP, 0, (LPARAM)&tbab); + + ZeroMemory(tbb, sizeof(tbb)); + + tbb[0].iBitmap = STD_FILENEW; + tbb[0].fsState = TBSTATE_ENABLED; + tbb[0].fsStyle = TBSTYLE_BUTTON; + tbb[0].idCommand = CM_FILE_NEW; + + tbb[1].iBitmap = STD_FILEOPEN; + tbb[1].fsState = TBSTATE_ENABLED; + tbb[1].fsStyle = TBSTYLE_BUTTON; + tbb[1].idCommand = CM_FILE_OPEN; + + tbb[2].iBitmap = STD_FILESAVE; + tbb[2].fsStyle = TBSTYLE_BUTTON; + tbb[2].idCommand = CM_FILE_SAVE; + + tbb[3].fsStyle = TBSTYLE_SEP; + + tbb[4].iBitmap = STD_CUT; + tbb[4].fsStyle = TBSTYLE_BUTTON; + tbb[4].idCommand = CM_EDIT_CUT; + + tbb[5].iBitmap = STD_COPY; + tbb[5].fsStyle = TBSTYLE_BUTTON; + tbb[5].idCommand = CM_EDIT_COPY; + + tbb[6].iBitmap = STD_PASTE; + tbb[6].fsStyle = TBSTYLE_BUTTON; + tbb[6].idCommand = CM_EDIT_PASTE; + + tbb[7].fsStyle = TBSTYLE_SEP; + + tbb[8].iBitmap = STD_UNDO; + tbb[8].fsStyle = TBSTYLE_BUTTON; + tbb[8].idCommand = CM_EDIT_UNDO; + + SendMessage(g_hToolBar, TB_ADDBUTTONS, 9, (LPARAM)&tbb); + return 0; + } + case WM_COMMAND: { + switch(LOWORD(wParam)) { + case CM_FILE_EXIT: + PostMessage(hwnd, WM_CLOSE, 0, 0); + break; + case CM_FILE_NEW: { + MDICREATESTRUCT mcs; + HWND hChild; + + mcs.szTitle = "[Untitled]"; + mcs.szClass = g_szChild; + mcs.hOwner = g_hInst; + mcs.x = mcs.cx = CW_USEDEFAULT; + mcs.y = mcs.cy = CW_USEDEFAULT; + mcs.style = MDIS_ALLCHILDSTYLES; + + hChild = (HWND)SendMessage(g_hMDIClient, WM_MDICREATE,0, (LPARAM)&mcs); + if(!hChild) { + MessageBox(hwnd, "MDI Child creation failed.", "Oh Oh...",MB_ICONEXCLAMATION | MB_OK); + } + break; + } + case CM_FILE_OPEN: { + MDICREATESTRUCT mcs; + HWND hChild; + char szFileName[MAX_PATH]; + + if(!GetFileName(hwnd, szFileName, FALSE)) + break; + + mcs.szTitle = szFileName; + mcs.szClass = g_szChild; + mcs.hOwner = g_hInst; + mcs.x = mcs.cx = CW_USEDEFAULT; + mcs.y = mcs.cy = CW_USEDEFAULT; + mcs.style = MDIS_ALLCHILDSTYLES; + + hChild = (HWND)SendMessage(g_hMDIClient, WM_MDICREATE, 0, (LPARAM)&mcs); + + if(!hChild) { + MessageBox(hwnd, "MDI Child creation failed.", "Oh Oh...", + MB_ICONEXCLAMATION | MB_OK); + } + break; + } + case CM_WINDOW_TILEHORZ: + PostMessage(g_hMDIClient, WM_MDITILE, MDITILE_HORIZONTAL, 0); + break; + case CM_WINDOW_TILEVERT: + PostMessage(g_hMDIClient, WM_MDITILE, MDITILE_VERTICAL, 0); + break; + case CM_WINDOW_CASCADE: + PostMessage(g_hMDIClient, WM_MDICASCADE, 0, 0); + break; + case CM_WINDOW_ARRANGE: + PostMessage(g_hMDIClient, WM_MDIICONARRANGE, 0, 0); + break; + default: { + if(LOWORD(wParam) >= ID_MDI_FIRSTCHILD){ + DefFrameProc(hwnd, g_hMDIClient, Message, wParam, lParam); + } else { + HWND hChild; + hChild = (HWND)SendMessage(g_hMDIClient, WM_MDIGETACTIVE,0,0); + if(hChild){ + SendMessage(hChild, WM_COMMAND, wParam, lParam); + } + } + } + } + break; + } + case WM_SIZE: { + RECT rectClient, rectStatus, rectTool; + UINT uToolHeight, uStatusHeight, uClientAlreaHeight; + + SendMessage(g_hToolBar, TB_AUTOSIZE, 0, 0); + SendMessage(g_hStatusBar, WM_SIZE, 0, 0); + + GetClientRect(hwnd, &rectClient); + GetWindowRect(g_hStatusBar, &rectStatus); + GetWindowRect(g_hToolBar, &rectTool); + + uToolHeight = rectTool.bottom - rectTool.top; + uStatusHeight = rectStatus.bottom - rectStatus.top; + uClientAlreaHeight = rectClient.bottom; + + MoveWindow(g_hMDIClient, 0, uToolHeight, rectClient.right, uClientAlreaHeight - uStatusHeight - uToolHeight, TRUE); + break; + } + case WM_CLOSE: + DestroyWindow(hwnd); + break; + case WM_DESTROY: + PostQuitMessage(0); + break; + default: + return DefFrameProc(hwnd, g_hMDIClient, Message, wParam, lParam); + } + return 0; +} + +LRESULT CALLBACK MDIChildWndProc(HWND hwnd, UINT Message, WPARAM wParam,LPARAM lParam) { + switch(Message) { + case WM_CREATE: { + char szFileName[MAX_PATH]; + HWND hEdit; + + hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL | ES_MULTILINE | ES_WANTRETURN, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + hwnd, (HMENU)IDC_CHILD_EDIT, g_hInst, NULL); + + SendMessage(hEdit, WM_SETFONT, + (WPARAM)GetStockObject(DEFAULT_GUI_FONT), MAKELPARAM(TRUE, 0)); + + GetWindowText(hwnd, szFileName, MAX_PATH); + if(*szFileName != '[') { + if(!LoadFile(hEdit, szFileName)) { + MessageBox(hwnd, "Couldn't Load File.", "Error.",MB_OK | MB_ICONEXCLAMATION); + return -1; //cancel window creation + } + } + break; + } + case WM_SIZE: + if(wParam != SIZE_MINIMIZED) + MoveWindow(GetDlgItem(hwnd, IDC_CHILD_EDIT), 0, 0, LOWORD(lParam),HIWORD(lParam), TRUE); + break; + case WM_MDIACTIVATE: { + HMENU hMenu, hFileMenu; + BOOL EnableFlag; + char szFileName[MAX_PATH]; + + hMenu = GetMenu(g_hMainWindow); + if(hwnd == (HWND)lParam){ //being activated + EnableFlag = TRUE; + } else{ + EnableFlag = FALSE; //being de-activated + } + EnableMenuItem(hMenu, 1, MF_BYPOSITION | (EnableFlag ? MF_ENABLED : MF_GRAYED)); + EnableMenuItem(hMenu, 2, MF_BYPOSITION | (EnableFlag ? MF_ENABLED : MF_GRAYED)); + + hFileMenu = GetSubMenu(hMenu, 0); + EnableMenuItem(hFileMenu, CM_FILE_SAVE, MF_BYCOMMAND | (EnableFlag ? MF_ENABLED : MF_GRAYED)); + EnableMenuItem(hFileMenu, CM_FILE_SAVEAS, MF_BYCOMMAND | (EnableFlag ? MF_ENABLED : MF_GRAYED)); + + DrawMenuBar(g_hMainWindow); + + SendMessage(g_hToolBar, TB_ENABLEBUTTON, CM_FILE_SAVE, MAKELONG(EnableFlag, 0)); + SendMessage(g_hToolBar, TB_ENABLEBUTTON, CM_EDIT_UNDO, MAKELONG(EnableFlag, 0)); + SendMessage(g_hToolBar, TB_ENABLEBUTTON, CM_EDIT_CUT, MAKELONG(EnableFlag, 0)); + SendMessage(g_hToolBar, TB_ENABLEBUTTON, CM_EDIT_COPY, MAKELONG(EnableFlag, 0)); + SendMessage(g_hToolBar, TB_ENABLEBUTTON, CM_EDIT_PASTE, MAKELONG(EnableFlag, 0)); + + GetWindowText(hwnd, szFileName, MAX_PATH); + SendMessage(g_hStatusBar, SB_SETTEXT, 0, (LPARAM)(EnableFlag ? szFileName : "")); + break; + } + case WM_SETFOCUS: + SetFocus(GetDlgItem(hwnd, IDC_CHILD_EDIT)); + break; + case WM_COMMAND: { + switch(LOWORD(wParam)) { + case CM_FILE_SAVE: { + char szFileName[MAX_PATH]; + + GetWindowText(hwnd, szFileName, MAX_PATH); + if(*szFileName != '[') { + if(!SaveFile(GetDlgItem(hwnd, IDC_CHILD_EDIT), szFileName)) { + MessageBox(hwnd, "Couldn't Save File.", "Error.",MB_OK | MB_ICONEXCLAMATION); + return 0; + } + } else { + PostMessage(hwnd, WM_COMMAND,MAKEWPARAM(CM_FILE_SAVEAS, 0), 0); + } + return 0; + } + case CM_FILE_SAVEAS: { + char szFileName[MAX_PATH]; + + if(GetFileName(hwnd, szFileName, TRUE)) { + if(!SaveFile(GetDlgItem(hwnd, IDC_CHILD_EDIT), szFileName)) { + MessageBox(hwnd, "Couldn't Save File.", "Error.",MB_OK | MB_ICONEXCLAMATION); + return 0; + } else { + SetWindowText(hwnd, szFileName); + } + } + return 0; + } + case CM_EDIT_UNDO: + SendDlgItemMessage(hwnd, IDC_CHILD_EDIT, EM_UNDO, 0, 0); + break; + case CM_EDIT_CUT: + SendDlgItemMessage(hwnd, IDC_CHILD_EDIT, WM_CUT, 0, 0); + break; + case CM_EDIT_COPY: + SendDlgItemMessage(hwnd, IDC_CHILD_EDIT, WM_COPY, 0, 0); + break; + case CM_EDIT_PASTE: + SendDlgItemMessage(hwnd, IDC_CHILD_EDIT, WM_PASTE, 0, 0); + break; + } + return 0; + } + } + return DefMDIChildProc(hwnd, Message, wParam, lParam); +} diff --git a/windows/templates/MDIEditor/MDIEditor_h.txt b/windows/templates/MDIEditor/MDIEditor_h.txt new file mode 100644 index 00000000..e033af66 --- /dev/null +++ b/windows/templates/MDIEditor/MDIEditor_h.txt @@ -0,0 +1,24 @@ +#define CM_WINDOW_TILEVERT 9080 +#define CM_WINDOW_TILEHORZ 9082 +#define CM_WINDOW_ARRANGE 9081 +#define CM_WINDOW_TILE 9080 +#define CM_WINDOW_CASCADE 9076 +#define CM_EDIT_PASTE 9079 +#define CM_EDIT_COPY 9078 +#define CM_EDIT_CUT 9077 +#define CM_EDIT_REDO 9076 +#define CM_EDIT_UNDO 9075 +#define CM_FILE_SAVEAS 9074 +#define CM_FILE_SAVE 9073 +#define CM_FILE_OPEN 9072 +#define CM_HELP_ABOUT 9072 +#define CM_FILE_EXIT 9071 +#define CM_FILE_NEW 9070 + +#define ID_STATUSBAR 4997 +#define ID_TOOLBAR 4998 + +#define ID_MDI_CLIENT 4999 +#define ID_MDI_FIRSTCHILD 50000 + +#define IDC_CHILD_EDIT 2000 diff --git a/windows/templates/MDIEditor/MDIEditor_rc.txt b/windows/templates/MDIEditor/MDIEditor_rc.txt new file mode 100644 index 00000000..8428b5d3 --- /dev/null +++ b/windows/templates/MDIEditor/MDIEditor_rc.txt @@ -0,0 +1,31 @@ +#include "main.h" + +MAIN MENU +{ + POPUP "&File" + { + MENUITEM "&New", CM_FILE_NEW + MENUITEM "&Open...", CM_FILE_OPEN + MENUITEM "&Save", CM_FILE_SAVE, GRAYED + MENUITEM "Save &As...", CM_FILE_SAVEAS, GRAYED + MENUITEM SEPARATOR + MENUITEM "E&xit", CM_FILE_EXIT + } + + POPUP "&Edit", GRAYED + { + MENUITEM "&Undo\tCtrl+Z", CM_EDIT_UNDO + MENUITEM SEPARATOR + MENUITEM "Cu&t\tCtrl+X", CM_EDIT_CUT + MENUITEM "&Copy\tCtrl+C", CM_EDIT_COPY + MENUITEM "&Paste\tCtrl+V", CM_EDIT_PASTE + } + + POPUP "&Window", GRAYED + { + MENUITEM "&Cascade", CM_WINDOW_CASCADE + MENUITEM "Tile &Horizontal", CM_WINDOW_TILEHORZ + MENUITEM "Tile &Vertical", CM_WINDOW_TILEVERT + MENUITEM "Arrange &Icons", CM_WINDOW_ARRANGE + } +} diff --git a/windows/templates/MDIEditor/Windows.ico b/windows/templates/MDIEditor/Windows.ico new file mode 100644 index 00000000..b2682537 Binary files /dev/null and b/windows/templates/MDIEditor/Windows.ico differ diff --git a/windows/templates/MDIEditor/info.template b/windows/templates/MDIEditor/info.template new file mode 100644 index 00000000..605ace77 --- /dev/null +++ b/windows/templates/MDIEditor/info.template @@ -0,0 +1,30 @@ +[Template] +ver=2 +Name=MDI Editor +Name[zh_CN]=MDI编辑器 +Icon=Windows.ico +Description=A Win32 MDI file editor +Description[zh_CN]=一个Win32多文档界面(MDI)文件编辑器 +Category=Win32 + +[Unit0] +CName=main.c +CppName=main.cpp +C=MDIEditor_c.txt +Cpp=MDIEditor_c.txt + +[Unit1] +CName=main.h +CppName=main.h +C=MDIEditor_h.txt +Cpp=MDIEditor_h.txt + +[Unit2] +CName=resource.rc +CppName=resource.rc +C=MDIEditor_rc.txt +Cpp=MDIEditor_rc.txt + +[Project] +UnitCount=3 +Type=0 diff --git a/windows/templates/OpenGL/OpenGL.txt b/windows/templates/OpenGL/OpenGL.txt new file mode 100644 index 00000000..58c1f1de --- /dev/null +++ b/windows/templates/OpenGL/OpenGL.txt @@ -0,0 +1,190 @@ +/************************** + * Includes + * + **************************/ + +#include +#include + + +/************************** + * Function Declarations + * + **************************/ + +LRESULT CALLBACK WndProc (HWND hWnd, UINT message, +WPARAM wParam, LPARAM lParam); +void EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC); +void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC); + + +/************************** + * WinMain + * + **************************/ + +int WINAPI WinMain (HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPSTR lpCmdLine, + int iCmdShow) +{ + WNDCLASS wc; + HWND hWnd; + HDC hDC; + HGLRC hRC; + MSG msg; + BOOL bQuit = FALSE; + float theta = 0.0f; + + /* register window class */ + wc.style = CS_OWNDC; + wc.lpfnWndProc = WndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = hInstance; + wc.hIcon = LoadIcon (NULL, IDI_APPLICATION); + wc.hCursor = LoadCursor (NULL, IDC_ARROW); + wc.hbrBackground = (HBRUSH) GetStockObject (BLACK_BRUSH); + wc.lpszMenuName = NULL; + wc.lpszClassName = "GLSample"; + RegisterClass (&wc); + + /* create main window */ + hWnd = CreateWindow ( + "GLSample", "OpenGL Sample", + WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE, + 0, 0, 256, 256, + NULL, NULL, hInstance, NULL); + + /* enable OpenGL for the window */ + EnableOpenGL (hWnd, &hDC, &hRC); + + /* program main loop */ + while (!bQuit) + { + /* check for messages */ + if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) + { + /* handle or dispatch messages */ + if (msg.message == WM_QUIT) + { + bQuit = TRUE; + } + else + { + TranslateMessage (&msg); + DispatchMessage (&msg); + } + } + else + { + /* OpenGL animation code goes here */ + + glClearColor (0.0f, 0.0f, 0.0f, 0.0f); + glClear (GL_COLOR_BUFFER_BIT); + + glPushMatrix (); + glRotatef (theta, 0.0f, 0.0f, 1.0f); + glBegin (GL_TRIANGLES); + glColor3f (1.0f, 0.0f, 0.0f); glVertex2f (0.0f, 1.0f); + glColor3f (0.0f, 1.0f, 0.0f); glVertex2f (0.87f, -0.5f); + glColor3f (0.0f, 0.0f, 1.0f); glVertex2f (-0.87f, -0.5f); + glEnd (); + glPopMatrix (); + + SwapBuffers (hDC); + + theta += 1.0f; + Sleep (1); + } + } + + /* shutdown OpenGL */ + DisableOpenGL (hWnd, hDC, hRC); + + /* destroy the window explicitly */ + DestroyWindow (hWnd); + + return msg.wParam; +} + + +/******************** + * Window Procedure + * + ********************/ + +LRESULT CALLBACK WndProc (HWND hWnd, UINT message, + WPARAM wParam, LPARAM lParam) +{ + + switch (message) + { + case WM_CREATE: + return 0; + case WM_CLOSE: + PostQuitMessage (0); + return 0; + + case WM_DESTROY: + return 0; + + case WM_KEYDOWN: + switch (wParam) + { + case VK_ESCAPE: + PostQuitMessage(0); + return 0; + } + return 0; + + default: + return DefWindowProc (hWnd, message, wParam, lParam); + } +} + + +/******************* + * Enable OpenGL + * + *******************/ + +void EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC) +{ + PIXELFORMATDESCRIPTOR pfd; + int iFormat; + + /* get the device context (DC) */ + *hDC = GetDC (hWnd); + + /* set the pixel format for the DC */ + ZeroMemory (&pfd, sizeof (pfd)); + pfd.nSize = sizeof (pfd); + pfd.nVersion = 1; + pfd.dwFlags = PFD_DRAW_TO_WINDOW | + PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; + pfd.iPixelType = PFD_TYPE_RGBA; + pfd.cColorBits = 24; + pfd.cDepthBits = 16; + pfd.iLayerType = PFD_MAIN_PLANE; + iFormat = ChoosePixelFormat (*hDC, &pfd); + SetPixelFormat (*hDC, iFormat, &pfd); + + /* create and enable the render context (RC) */ + *hRC = wglCreateContext( *hDC ); + wglMakeCurrent( *hDC, *hRC ); + +} + + +/****************** + * Disable OpenGL + * + ******************/ + +void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC) +{ + wglMakeCurrent (NULL, NULL); + wglDeleteContext (hRC); + ReleaseDC (hWnd, hDC); +} diff --git a/windows/templates/OpenGL/Pizza.ico b/windows/templates/OpenGL/Pizza.ico new file mode 100644 index 00000000..a098ba12 Binary files /dev/null and b/windows/templates/OpenGL/Pizza.ico differ diff --git a/windows/templates/OpenGL/info.template b/windows/templates/OpenGL/info.template new file mode 100644 index 00000000..3e2f82ee --- /dev/null +++ b/windows/templates/OpenGL/info.template @@ -0,0 +1,19 @@ +[Template] +ver=2 +Name=OpenGL +Icon=Pizza.ico +Description=A basic OpenGL program +Description[zh_CN]=一个基本的OpenGL程序 +Category=3D +Category[zh_CN]=3D + +[Unit0] +CName=main.c +CppName=main.cpp +C=OpenGL.txt +Cpp=OpenGL.txt + +[Project] +UnitCount=1 +Type=0 +Linker=-lopengl32 diff --git a/windows/templates/OpenMP/File Management.ico b/windows/templates/OpenMP/File Management.ico new file mode 100644 index 00000000..09099e21 Binary files /dev/null and b/windows/templates/OpenMP/File Management.ico differ diff --git a/windows/templates/OpenMP/OpenMP_c.txt b/windows/templates/OpenMP/OpenMP_c.txt new file mode 100644 index 00000000..17d77efd --- /dev/null +++ b/windows/templates/OpenMP/OpenMP_c.txt @@ -0,0 +1,17 @@ +#include +#include + +int main() { + + int i; + + #pragma omp parallel num_threads(2) + printf("Hi, I'm thread number %d!\n",omp_get_thread_num()); + + #pragma omp parallel for num_threads(2) + for(i = 0;i < 20;i++) { + printf("\nThread number %d, executing iteration %d...",omp_get_thread_num(),i); + } + + return 0; +} diff --git a/windows/templates/OpenMP/OpenMP_cpp.txt b/windows/templates/OpenMP/OpenMP_cpp.txt new file mode 100644 index 00000000..44eff209 --- /dev/null +++ b/windows/templates/OpenMP/OpenMP_cpp.txt @@ -0,0 +1,26 @@ +#include +#include + +// not using iostream here due to output ordering issues + +// iostream tends to output each part between <<'s separately to the console, +// which can lead to random output if multiple threads are doing the same +// thing. + +// printf will generally output the whole result string in one go, so results +// of separate printf calls, even from different threads, will remain intact + +// Another fix, other than using printf, would be to give each thread its own +// place to store output temporarily (a stringstream), and then output the whole +// result in one go. + +int main() { + + #pragma omp parallel num_threads(2) + printf("Hi, I'm thread number %d!\n",omp_get_thread_num()); + + #pragma omp parallel for num_threads(2) + for(int i = 0;i < 20;i++) { + printf("\nThread number %d, executing iteration %d...",omp_get_thread_num(),i); + } +} \ No newline at end of file diff --git a/windows/templates/OpenMP/info.template b/windows/templates/OpenMP/info.template new file mode 100644 index 00000000..590417cf --- /dev/null +++ b/windows/templates/OpenMP/info.template @@ -0,0 +1,21 @@ +[Template] +ver=2 +Name=OpenMP +Icon=File Management.ico +Description=A OpenMP multithreading example +Description[zh_CN]=一个OpenMP多线程示例 +Category=Console +Category[zh_CN]=控制台 + +[Unit0] +CName=main.c +CppName=main.cpp +C=OpenMP_c.txt +Cpp=OpenMP_cpp.txt + +[Project] +UnitCount=1 +Type=1 +Compiler=-fopenmp +CppCompiler=-fopenmp +Linker=-lgomp diff --git a/windows/templates/Single Dialog Application/Single Dialog Application.ico b/windows/templates/Single Dialog Application/Single Dialog Application.ico new file mode 100644 index 00000000..94551655 Binary files /dev/null and b/windows/templates/Single Dialog Application/Single Dialog Application.ico differ diff --git a/windows/templates/Single Dialog Application/Single Dialog Application.project.ico b/windows/templates/Single Dialog Application/Single Dialog Application.project.ico new file mode 100644 index 00000000..94551655 Binary files /dev/null and b/windows/templates/Single Dialog Application/Single Dialog Application.project.ico differ diff --git a/windows/templates/Single Dialog Application/Single_Dialog_Application_main.c.txt b/windows/templates/Single Dialog Application/Single_Dialog_Application_main.c.txt new file mode 100644 index 00000000..303c4562 --- /dev/null +++ b/windows/templates/Single Dialog Application/Single_Dialog_Application_main.c.txt @@ -0,0 +1,42 @@ +#include +#include "resource.h" + +HINSTANCE hInst; + +LRESULT MainDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam); + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { + MSG msg; + HWND hMainDlg = NULL; + + hInst = hInstance; + hMainDlg = CreateDialog(hInstance, (LPCTSTR)IDD_MAIN_DIALOG, 0,(DLGPROC)MainDlgProc); + ShowWindow(hMainDlg, nCmdShow); + while (GetMessage(&msg, NULL, 0, 0)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + return 0; +} + +LRESULT MainDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { + switch (message) { + case WM_INITDIALOG : + return TRUE ; + case WM_COMMAND : + switch (LOWORD (wParam)) { + case IDOK : + case IDCANCEL : + DestroyWindow(hDlg); + return TRUE ; + } + break ; + case WM_CLOSE: + DestroyWindow(hDlg); + return TRUE; + case WM_DESTROY: + PostQuitMessage(0); + return TRUE; + }; + return FALSE;//FALSEȱʡԻDefDlgProc(),ʾûдϢ +} diff --git a/windows/templates/Single Dialog Application/Single_Dialog_Application_resource.h.txt b/windows/templates/Single Dialog Application/Single_Dialog_Application_resource.h.txt new file mode 100644 index 00000000..099111ef --- /dev/null +++ b/windows/templates/Single Dialog Application/Single_Dialog_Application_resource.h.txt @@ -0,0 +1,5 @@ +#ifndef IDC_STATIC +#define IDC_STATIC (-1) +#endif + +#define IDD_MAIN_DIALOG 101 \ No newline at end of file diff --git a/windows/templates/Single Dialog Application/Single_Dialog_Application_resource.rc.txt b/windows/templates/Single Dialog Application/Single_Dialog_Application_resource.rc.txt new file mode 100644 index 00000000..c36ab46b --- /dev/null +++ b/windows/templates/Single Dialog Application/Single_Dialog_Application_resource.rc.txt @@ -0,0 +1,24 @@ +// Generated by ResEdit 1.6.5 +// Copyright (C) 2006-2015 +// http://www.resedit.net + +#include +#include +#include +#include "resource.h" + + + + +// +// Dialog resources +// +LANGUAGE 0, SUBLANG_NEUTRAL +IDD_MAIN_DIALOG DIALOG 0, 0, 186, 95 +STYLE DS_3DLOOK | DS_CENTER | DS_MODALFRAME | DS_SHELLFONT | WS_CAPTION | WS_VISIBLE | WS_POPUP | WS_SYSMENU +CAPTION "Dialog" +FONT 8, "Ms Shell Dlg" +{ + PUSHBUTTON "Cancel", IDCANCEL, 129, 24, 50, 14, 0, WS_EX_LEFT + DEFPUSHBUTTON "OK", IDOK, 129, 7, 50, 14, 0, WS_EX_LEFT +} diff --git a/windows/templates/Single Dialog Application/info.template b/windows/templates/Single Dialog Application/info.template new file mode 100644 index 00000000..8e7ac030 --- /dev/null +++ b/windows/templates/Single Dialog Application/info.template @@ -0,0 +1,33 @@ +[Template] +ver=2 +Name=Single Dialog Application +Name[zh_CN]=单对话框程序 +Icon=Single Dialog Application.ico +Description=An Appliction use a dialog as the main UI +Description[zh_CN]=使用一个对话框作为主用户界面简单程序 +Category=Win32 + +[Unit0] +CName=main.c +C=Single_Dialog_Application_main.c.txt + +[Unit1] +CName=resource.rc +C=Single_Dialog_Application_resource.rc.txt + +[Unit2] +CName=resource.h +C=Single_Dialog_Application_resource.h.txt + +[Project] +UnitCount=3 +Type=0 +IsCpp=0 +Compiler= +CppCompiler= +Linker= +CompilerSettings=0000000000000000000000000 +CompilerSet=0 +IncludeVersionInfo=0 +SupportXPThemes=0 +Icon=Single Dialog Application.project.ico diff --git a/windows/templates/StdThread/Software.ico b/windows/templates/StdThread/Software.ico new file mode 100644 index 00000000..283fe4e0 Binary files /dev/null and b/windows/templates/StdThread/Software.ico differ diff --git a/windows/templates/StdThread/StdThread_c.txt b/windows/templates/StdThread/StdThread_c.txt new file mode 100644 index 00000000..2e5ed0fd --- /dev/null +++ b/windows/templates/StdThread/StdThread_c.txt @@ -0,0 +1,2 @@ +// Please note that MinGW32 compilers currently do not support . Use MinGW64 builds like TDM-GCC instead. +// C does not support this magic ;) \ No newline at end of file diff --git a/windows/templates/StdThread/StdThread_cpp.txt b/windows/templates/StdThread/StdThread_cpp.txt new file mode 100644 index 00000000..6138bd5a --- /dev/null +++ b/windows/templates/StdThread/StdThread_cpp.txt @@ -0,0 +1,43 @@ +// Please note that MinGW32 compilers currently do not support . Use MinGW64 builds like TDM-GCC instead. + +#include +using std::thread; +#include +using std::vector; +#include + +struct ThreadItem { + char* result; // could've used stringstream too, but don't like their syntax + thread worker; +}; + +void* ThreadFunction(char** result) { + *result = new char[256]; + snprintf(*result,256,"Hello World from thread ID %d", + std::this_thread::get_id()); +} + +int main() { + // Get the amount of "processing units" + int n = std::thread::hardware_concurrency(); + + // Create array of threads + vector threadlist; + threadlist.resize(n); + + // Spawn a thread for each core + for(int i = 0;i < n;i++) { + threadlist[i].worker = thread(ThreadFunction,&threadlist[i].result); // pass rand() as data argument + } + + // Wait for them all to finish + for(int i = 0;i < n;i++) { + threadlist[i].worker.join(); + } + + // Present their calculation results + printf("Results:\n"); + for(int i = 0;i < n;i++) { + printf("%s\n",threadlist[i].result); + } +} \ No newline at end of file diff --git a/windows/templates/StdThread/info.template b/windows/templates/StdThread/info.template new file mode 100644 index 00000000..050e0a80 --- /dev/null +++ b/windows/templates/StdThread/info.template @@ -0,0 +1,21 @@ +[Template] +ver=2 +Name=std::thread +Icon=Software.ico +Description=A C++ multithreading example +Description[zh_CN]=一个C++多线程示例 +Category=Console +Category[zh_CN]=控制台 + +[Unit0] +CName=main.c +CppName=main.cpp +C=StdThread_c.txt +Cpp=StdThread_cpp.txt + +[Project] +UnitCount=1 +Type=1 +Compiler= +CppCompiler=-std=gnu++11 +Linker= diff --git a/windows/templates/Turtle/CL_Turtle.ico b/windows/templates/Turtle/CL_Turtle.ico new file mode 100644 index 00000000..b6d93825 Binary files /dev/null and b/windows/templates/Turtle/CL_Turtle.ico differ diff --git a/windows/templates/Turtle/CL_Turtle_cpp.txt b/windows/templates/Turtle/CL_Turtle_cpp.txt new file mode 100644 index 00000000..68a520a9 --- /dev/null +++ b/windows/templates/Turtle/CL_Turtle_cpp.txt @@ -0,0 +1,27 @@ +#include + +int main() { + int n; + initWorld(800,600); + +// Press F2 toggle display of grids +// Press F3 toggle display of the turtle +// Press F5 capture screen + + setSpeed(500); +// setRewind(true); +// setImmediate(true); + setPenSize(1); + + n=50; + for (int i=0;i + +static char g_szClassName[] = "MyWindowClass"; +static HINSTANCE g_hInst = NULL; + +const UINT idTimer1 = 1; +UINT nTimerDelay = 10; + +HBITMAP hbmBall, hbmMask; +BITMAP bm; + +int ballX, ballY; +int deltaX, deltaY; + +int deltaValue = 4; + +void EraseBall(HDC hdc) +{ + RECT rc; + rc.left = ballX; + rc.top = ballY; + rc.right = ballX + bm.bmWidth; + rc.bottom = ballY + bm.bmHeight; + FillRect(hdc, &rc, (HBRUSH)(COLOR_BTNFACE+1)); +} + +void DrawBall(HDC hdc) +{ + HDC hdcMemory; + hdcMemory = CreateCompatibleDC(hdc); + + SelectObject(hdcMemory, hbmMask); + BitBlt(hdc, ballX, ballY, bm.bmWidth, bm.bmHeight, hdcMemory, 0, 0, SRCAND); + + SelectObject(hdcMemory, hbmBall); + BitBlt(hdc, ballX, ballY, bm.bmWidth, bm.bmHeight, hdcMemory, 0, 0, SRCPAINT); + + DeleteDC(hdcMemory); +} + +void UpdateBall(HWND hwnd) +{ + RECT rc; + GetClientRect(hwnd, &rc); + + ballX += deltaX; + ballY += deltaY; + + if(ballX < 0){ + ballX = 0; + deltaX = deltaValue; + } + else if(ballX + bm.bmWidth > rc.right){ + ballX = rc.right - bm.bmWidth; + deltaX = -deltaValue; + } + if(ballY < 0){ + ballY = 0; + deltaY = deltaValue; + } + else if(ballY + bm.bmHeight > rc.bottom){ + ballY = rc.bottom - bm.bmHeight; + deltaY = -deltaValue; + } +} + +LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) +{ + switch(Message) + { + case WM_CREATE: + hbmBall = LoadBitmap(g_hInst, "BALLBMP"); + hbmMask = LoadBitmap(g_hInst, "MASKBMP"); + if(!hbmBall || !hbmMask){ + MessageBox(hwnd, "Load of resources failed.", "Error", + MB_OK | MB_ICONEXCLAMATION); + return -1; + } + + GetObject(hbmBall, sizeof(bm), &bm); + SetTimer(hwnd, idTimer1, nTimerDelay, NULL); + + ballX = 0; + ballY = 0; + deltaX = deltaValue; + deltaY = deltaValue; + + break; + case WM_TIMER: + if(hbmBall && hbmMask) + { + HDC hdcWindow; + hdcWindow = GetDC(hwnd); + + EraseBall(hdcWindow); + UpdateBall(hwnd); + DrawBall(hdcWindow); + + ReleaseDC(hwnd, hdcWindow); + } + break; + case WM_PAINT: + if(hbmBall && hbmMask) + { + PAINTSTRUCT ps; + HDC hdcWindow; + hdcWindow = BeginPaint(hwnd, &ps); + + DrawBall(hdcWindow); + + EndPaint(hwnd, &ps); + } + break; + case WM_CLOSE: + DestroyWindow(hwnd); + break; + case WM_DESTROY: + KillTimer(hwnd, idTimer1); + + DeleteObject(hbmBall); + DeleteObject(hbmMask); + PostQuitMessage(0); + break; + default: + return DefWindowProc(hwnd, Message, wParam, lParam); + } + return 0; +} + + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, + LPSTR lpCmdLine, int nCmdShow) +{ + WNDCLASSEX WndClass; + HWND hwnd; + MSG Msg; + + g_hInst = hInstance; + + WndClass.cbSize = sizeof(WNDCLASSEX); + WndClass.style = 0; + WndClass.lpfnWndProc = WndProc; + WndClass.cbClsExtra = 0; + WndClass.cbWndExtra = 0; + WndClass.hInstance = g_hInst; + WndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); + WndClass.hCursor = LoadCursor(NULL, IDC_ARROW); + WndClass.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1); + WndClass.lpszMenuName = NULL; + WndClass.lpszClassName = g_szClassName; + WndClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); + + if(!RegisterClassEx(&WndClass)) + { + MessageBox(0, "Window Registration Failed!", "Error!", + MB_ICONEXCLAMATION | MB_OK | MB_SYSTEMMODAL); + return 0; + } + + hwnd = CreateWindowEx( + WS_EX_CLIENTEDGE, + g_szClassName, + "A Bitmap Program", + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, 320, 240, + NULL, NULL, g_hInst, NULL); + + if(hwnd == NULL) + { + MessageBox(0, "Window Creation Failed!", "Error!", + MB_ICONEXCLAMATION | MB_OK | MB_SYSTEMMODAL); + return 0; + } + + ShowWindow(hwnd, nCmdShow); + UpdateWindow(hwnd); + + while(GetMessage(&Msg, NULL, 0, 0)) + { + TranslateMessage(&Msg); + DispatchMessage(&Msg); + } + return Msg.wParam; +} + diff --git a/windows/templates/WinAnim/WinAnim_rc.txt b/windows/templates/WinAnim/WinAnim_rc.txt new file mode 100644 index 00000000..82988149 --- /dev/null +++ b/windows/templates/WinAnim/WinAnim_rc.txt @@ -0,0 +1,2 @@ +BALLBMP BITMAP "ball.bmp" // can be found in the Templates folder, please copy to the project folder +MASKBMP BITMAP "ballmask.bmp" // as above \ No newline at end of file diff --git a/windows/templates/WinAnim/Windows.ico b/windows/templates/WinAnim/Windows.ico new file mode 100644 index 00000000..b2682537 Binary files /dev/null and b/windows/templates/WinAnim/Windows.ico differ diff --git a/windows/templates/WinAnim/info.template b/windows/templates/WinAnim/info.template new file mode 100644 index 00000000..a3ef1cf7 --- /dev/null +++ b/windows/templates/WinAnim/info.template @@ -0,0 +1,24 @@ +[Template] +ver=2 +Name=Animation Example +Name[zh_CN]=动画示例 +Icon=Windows.ico +Description=A Win32 painting example +Description[zh_CN]=一个Win32绘图示例 +Category=Win32 + +[Unit0] +CName=main.c +CppName=main.cpp +C=WinAnim_c.txt +Cpp=WinAnim_c.txt + +[Unit1] +CName=resource.rc +CppName=resource.rc +C=WinAnim_rc.txt +Cpp=WinAnim_rc.txt + +[Project] +UnitCount=2 +Type=0 diff --git a/windows/templates/epitrochoid/epitrochoid.ico b/windows/templates/epitrochoid/epitrochoid.ico new file mode 100644 index 00000000..34a221ab Binary files /dev/null and b/windows/templates/epitrochoid/epitrochoid.ico differ diff --git a/windows/templates/epitrochoid/epitrochoid_c.txt b/windows/templates/epitrochoid/epitrochoid_c.txt new file mode 100644 index 00000000..6566b3ad --- /dev/null +++ b/windows/templates/epitrochoid/epitrochoid_c.txt @@ -0,0 +1,125 @@ +#include +#include +#include + +#define RAYGUI_IMPLEMENTATION +#include + +void updateRadius(int baseL, int outerL, int pointL, int *pBaseR, int *pOuterR, int *pPointR) { + int totalL=baseL+outerL; + if (pointL>outerL) + totalL+=pointL; + else + totalL+=outerL; + int totalR = 420; + int remainder = totalR % totalL; + if (remainder!=0) { + if (remainder < totalL / 2) { + totalR -= remainder; + } else { + totalR += ( totalL - remainder); + } + } + *pBaseR = (totalR) / totalL * baseL; + *pOuterR = (totalR) / totalL * outerL; + *pPointR = (totalR) / totalL * pointL; +} + + +int main() { + int baseL=2; + int outerL=13; + int pointL=3; + int baseR,outerR,pointR; + int cx=450,cy=450; + int speed = 1; + Color trackColor = BLUE; + updateRadius(baseL, outerL, pointL, &baseR, &outerR, & pointR); + InitWindow(1300,900,"Epitrochoid"); + SetTraceLogLevel(LOG_WARNING); + SetTargetFPS(60); + GuiSetStyle(DEFAULT,TEXT_SIZE,20); + + Image trackImage=GenImageColor(900,900,WHITE); + //border + ImageFillRectangleEx(&trackImage,0,0,900,900,LIGHTGRAY); + ImageFillRectangleEx(&trackImage,5,5,890,890,WHITE); + + Image circlesImage = GenImageColor(900,900,BLANK); + float r=0; + int lastx,lasty; + lasty=cy; + lastx=cx+(baseR+outerR-pointR); + int frameCount = 0; + while(!WindowShouldClose()) { + //GUI + int newOuterL = GuiSliderBar((Rectangle){ 70, 20, 200, 30 },"Outer",TextFormat("%i", (int)outerL), outerL, 1, 50); + int newBaseL = GuiSliderBar((Rectangle){ 70, 60, 200, 30 },"Base",TextFormat("%i", (int)baseL), baseL, 1, 50); + int newPointL = GuiSliderBar((Rectangle){ 70, 100, 200, 30 },"Point",TextFormat("%i", (int)pointL), pointL, 1, 50); + speed = GuiSliderBar((Rectangle){ 70, 150, 200, 30 },"Speed",TextFormat("%i", (int)speed), speed, 1, 50); + GuiLabel((Rectangle){ 20, 220, 80, 30 },TextFormat("Color: 0x%X%X%X ",(int)(trackColor.r), (int)(trackColor.g),(int)(trackColor.b))); + trackColor= GuiColorPicker((Rectangle){ 50, 250, 196, 192 }, NULL, trackColor); + int doClear = GuiButton((Rectangle){ 120, 700, 80, 30 },"Clear"); + if (newOuterL!=outerL || newBaseL!=baseL || newPointL!=pointL) { + if (newOuterL!=outerL) + pointL=newOuterL; + else + pointL=newPointL; + outerL=newOuterL; + baseL=newBaseL; + updateRadius(baseL, outerL, pointL, &baseR, &outerR, & pointR); + lasty=cy; + lastx=cx+(baseR+outerR-pointR); + r=0; + ImageClearBackground(&trackImage,WHITE); + ImageFillRectangleEx(&trackImage,0,0,900,900,LIGHTGRAY); + ImageFillRectangleEx(&trackImage,5,5,890,890,WHITE); + } else if (doClear) { + ImageClearBackground(&trackImage,WHITE); + ImageFillRectangleEx(&trackImage,0,0,900,900,LIGHTGRAY); + ImageFillRectangleEx(&trackImage,5,5,890,890,WHITE); + } + //update datas + r+=0.01; + float outerCX=cx+ (baseR+outerR)*cos(r); + float outerCY=cy+ (baseR+outerR)*sin(r); + float theta = r * (baseL+outerL) / outerL; + int x=round(outerCX - pointR * cos(theta)); + int y=round(outerCY - pointR * sin(theta)); + + //update image (in CPU) + //ImageClearBackground(&trackImage,WHITE); + ImageDrawLineEx(&trackImage,lastx,lasty,x,y,3,trackColor); + + frameCount++; + if (frameCount>=speed) { + ImageClearBackground(&circlesImage,BLANK); + //base circle + ImageDrawCircleEx(&circlesImage,cx,cy,baseR,1,LIGHTRED); + ImageDrawCircleEx(&circlesImage,outerCX,outerCY,outerR,1,LIGHTSLATEGRAY); + ImageDrawLineEx(&circlesImage,cx,cy,outerCX,outerCY,1,LIGHTRED); + ImageDrawLineEx(&circlesImage,x,y,outerCX,outerCY,1,LIGHTSLATEGRAY); + ImageDrawPointEx(&circlesImage,x,y,7,RED); + + //Drawing in GPU + Texture trackTexture = LoadTextureFromImage(trackImage); + Texture circlesTexture = LoadTextureFromImage(circlesImage); + BeginDrawing(); + ClearBackground(WHITE); + DrawTexture(trackTexture,300,0,WHITE); + DrawTexture(circlesTexture,300,0,WHITE); + EndDrawing(); + UnloadTexture(circlesTexture); + UnloadTexture(trackTexture); + frameCount=0; + } + + lastx=x; + lasty=y; + } + + //Clean up + UnloadImage(circlesImage); + UnloadImage(trackImage); + CloseWindow(); +} diff --git a/windows/templates/epitrochoid/info.template b/windows/templates/epitrochoid/info.template new file mode 100644 index 00000000..43a2b337 --- /dev/null +++ b/windows/templates/epitrochoid/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=Epitrochoid +Name[zh_CN]=外旋轮线 +Icon=Epitrochoid.ico +Description=A simple epitrochoid drawing app +Description[zh_CN]=外旋轮线绘制程序 +Category=Game +Category[zh_CN]=游戏 + +[Unit0] +CName=main.c +C=epitrochoid_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lrdrawing -lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 diff --git a/windows/templates/hypotrochoid/hypotrochoid.ico b/windows/templates/hypotrochoid/hypotrochoid.ico new file mode 100644 index 00000000..bff8482f Binary files /dev/null and b/windows/templates/hypotrochoid/hypotrochoid.ico differ diff --git a/windows/templates/hypotrochoid/hypotrochoid_c.txt b/windows/templates/hypotrochoid/hypotrochoid_c.txt new file mode 100644 index 00000000..e962516d --- /dev/null +++ b/windows/templates/hypotrochoid/hypotrochoid_c.txt @@ -0,0 +1,140 @@ +#include +#include +#include + +#define RAYGUI_IMPLEMENTATION +#include + +void updateRadius(int baseL, int innerL,int pointL, int *pBaseR, int *pInnerR, int *pPointR) { + int totalL=baseL; + if (innerL>baseL) { + if (innerL>pointL) + totalL = (2*innerL-baseL); + else { + totalL = (innerL+pointL-baseL); + } + } else { + if (pointL>innerL) + totalL = baseL-innerL+pointL; + } + int totalR = 420; + int remainder = totalR % totalL; + if (remainder!=0) { + if (remainder < totalL / 2) { + totalR -= remainder; + } else { + totalR += ( totalL - remainder); + } + } + *pBaseR = totalR / totalL * baseL; + *pInnerR = totalR / totalL * innerL; + *pPointR = totalR / totalL * pointL; +} + + +int main() { + int baseL=6; + int innerL=3; + int pointL=6; + int baseR,innerR,pointR; + int cx=450,cy=450; + int speed = 1; + Color trackColor = BLUE; + updateRadius(baseL, innerL, pointL, &baseR, &innerR, &pointR); + InitWindow(1300,900,"Hypotrochoid"); + SetTraceLogLevel(LOG_WARNING); + SetTargetFPS(60); + GuiSetStyle(DEFAULT,TEXT_SIZE,20); + + Image trackImage=GenImageColor(900,900,WHITE); + //border + ImageFillRectangleEx(&trackImage,0,0,900,900,LIGHTGRAY); + ImageFillRectangleEx(&trackImage,5,5,890,890,WHITE); + + Image circlesImage = GenImageColor(900,900,BLANK); + float r=0; + int lastx,lasty; + bool skip=true; + lasty=cy; + lastx=cx+baseR; + int frameCount = 0; + while(!WindowShouldClose()) { + //GUI + int newInnerL = GuiSliderBar((Rectangle){ 70, 20, 200, 30 },"Inner",TextFormat("%i", (int)innerL), innerL, 1, 50); + int newBaseL = GuiSliderBar((Rectangle){ 70, 60, 200, 30 },"Base",TextFormat("%i", (int)baseL), baseL, 1, 50); + int newPointL = GuiSliderBar((Rectangle){ 70, 100, 200, 30 },"Point",TextFormat("%i", (int)pointL), pointL, 1, 50); + speed = GuiSliderBar((Rectangle){ 70, 150, 200, 30 },"Speed",TextFormat("%i", (int)speed), speed, 1, 50); + GuiLabel((Rectangle){ 20, 220, 80, 30 },TextFormat("Color: 0x%X%X%X ",(int)(trackColor.r), (int)(trackColor.g),(int)(trackColor.b))); + trackColor= GuiColorPicker((Rectangle){ 50, 250, 196, 192 }, NULL, trackColor); + int doClear = GuiButton((Rectangle){ 120, 700, 80, 30 },"Clear"); + if (newInnerL!=innerL || newBaseL!=baseL || newPointL!=pointL) { + if (newInnerL!=innerL) + pointL=newInnerL; + else + pointL=newPointL; + innerL=newInnerL; + baseL=newBaseL; + updateRadius(baseL, innerL, pointL, &baseR, &innerR, &pointR); + r=0; + skip=true; + ImageClearBackground(&trackImage,WHITE); + ImageFillRectangleEx(&trackImage,0,0,900,900,LIGHTGRAY); + ImageFillRectangleEx(&trackImage,5,5,890,890,WHITE); + } else if (doClear) { + ImageClearBackground(&trackImage,WHITE); + ImageFillRectangleEx(&trackImage,0,0,900,900,LIGHTGRAY); + ImageFillRectangleEx(&trackImage,5,5,890,890,WHITE); + } + //update datas + float innerCX=cx+ (baseR-innerR)*cos(r); + float innerCY=cy+ (baseR-innerR)*sin(r); + int x,y; + float theta; + if (innerL=speed) { + ImageClearBackground(&circlesImage,BLANK); + //base circle + ImageDrawCircleEx(&circlesImage,cx,cy,baseR,1,LIGHTRED); + ImageDrawCircleEx(&circlesImage,innerCX,innerCY,innerR,1,LIGHTGRAY); + ImageDrawLineEx(&circlesImage,innerCX,innerCY,cx,cy,1,LIGHTRED); + ImageDrawLineEx(&circlesImage,innerCX,innerCY,x,y,1,LIGHTGRAY); + ImageDrawPointEx(&circlesImage,x,y,7,RED); + + //Drawing in GPU + Texture trackTexture = LoadTextureFromImage(trackImage); + Texture circlesTexture = LoadTextureFromImage(circlesImage); + BeginDrawing(); + ClearBackground(WHITE); + DrawTexture(trackTexture,300,0,WHITE); + DrawTexture(circlesTexture,300,0,WHITE); + EndDrawing(); + UnloadTexture(circlesTexture); + UnloadTexture(trackTexture); + frameCount=0; + } + lastx=x; + lasty=y; + skip=false; + r+=0.01; + } + + //Clean up + UnloadImage(circlesImage); + UnloadImage(trackImage); + CloseWindow(); +} diff --git a/windows/templates/hypotrochoid/info.template b/windows/templates/hypotrochoid/info.template new file mode 100644 index 00000000..5fb9227e --- /dev/null +++ b/windows/templates/hypotrochoid/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=Hypotrochoid +Name[zh_CN]=内旋轮线 +Icon=hypotrochoid.ico +Description=A simple hypotrochoid drawing app +Description[zh_CN]=内旋轮线绘制程序 +Category=Game +Category[zh_CN]=游戏 + +[Unit0] +CName=main.c +C=hypotrochoid_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lrdrawing -lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 diff --git a/windows/templates/mysql/info.template b/windows/templates/mysql/info.template new file mode 100644 index 00000000..535c213c --- /dev/null +++ b/windows/templates/mysql/info.template @@ -0,0 +1,19 @@ +[Template] +ver=2 +Name=MySQL(MyriaDB) +Icon=mysql.ico +Description=A Sqlite3 API Example +Description[zh_CN]=MySQL数据库示例程序 +Category=Database +Category[zh_CN]=数据库 + +[Unit0] +CName=main.c +C=mysql_c.txt + +[Project] +UnitCount=1 +Type=1 +Compiler= +CppCompiler= +Linker=-lmysqlclient -lws2_32 -ladvapi32 -lkernel32 -lshlwapi -lcrypt32 -lz -lsecur32 diff --git a/windows/templates/mysql/mysql.ico b/windows/templates/mysql/mysql.ico new file mode 100644 index 00000000..b78e8166 Binary files /dev/null and b/windows/templates/mysql/mysql.ico differ diff --git a/windows/templates/mysql/mysql_c.txt b/windows/templates/mysql/mysql_c.txt new file mode 100644 index 00000000..80b3384b --- /dev/null +++ b/windows/templates/mysql/mysql_c.txt @@ -0,0 +1,103 @@ +/* + A demo for mysql client, from https://zetcode.com/db/mysqlc/ +*/ +#include +#include +#include + +void finish_with_error(MYSQL *con) +{ + fprintf(stderr, "%s\n", mysql_error(con)); + mysql_close(con); + exit(1); +} + +int main(int argc, char **argv) +{ + MYSQL *con = mysql_init(NULL); + + if (con == NULL) + { + fprintf(stderr, "%s\n", mysql_error(con)); + exit(1); + } + + if (mysql_real_connect(con, "localhost", "root", "", + "testdb", 0, NULL, 0) == NULL) + { + finish_with_error(con); + } + + //Create table + if (mysql_query(con, "DROP TABLE IF EXISTS cars")) { + finish_with_error(con); + } + + if (mysql_query(con, "CREATE TABLE cars(id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), price INT)")) { + finish_with_error(con); + } + + // insert datas + if (mysql_query(con, "INSERT INTO cars VALUES(1,'Audi',52642)")) { + finish_with_error(con); + } + + if (mysql_query(con, "INSERT INTO cars VALUES(2,'Mercedes',57127)")) { + finish_with_error(con); + } + + if (mysql_query(con, "INSERT INTO cars VALUES(3,'Skoda',9000)")) { + finish_with_error(con); + } + + if (mysql_query(con, "INSERT INTO cars VALUES(4,'Volvo',29000)")) { + finish_with_error(con); + } + + if (mysql_query(con, "INSERT INTO cars VALUES(5,'Bentley',350000)")) { + finish_with_error(con); + } + + if (mysql_query(con, "INSERT INTO cars VALUES(6,'Citroen',21000)")) { + finish_with_error(con); + } + + if (mysql_query(con, "INSERT INTO cars VALUES(7,'Hummer',41400)")) { + finish_with_error(con); + } + + if (mysql_query(con, "INSERT INTO cars VALUES(8,'Volkswagen',21600)")) { + finish_with_error(con); + } + + //query datas + if (mysql_query(con, "SELECT * FROM cars")) + { + finish_with_error(con); + } + + MYSQL_RES *result = mysql_store_result(con); + + if (result == NULL) + { + finish_with_error(con); + } + + int num_fields = mysql_num_fields(result); + + MYSQL_ROW row; + + while ((row = mysql_fetch_row(result))) + { + for(int i = 0; i < num_fields; i++) + { + printf("%s ", row[i] ? row[i] : "NULL"); + } + + printf("\n"); + } + + mysql_free_result(result); + mysql_close(con); + exit(0); +} \ No newline at end of file diff --git a/windows/templates/raygui/info.template b/windows/templates/raygui/info.template new file mode 100644 index 00000000..86a7cd62 --- /dev/null +++ b/windows/templates/raygui/info.template @@ -0,0 +1,21 @@ +[Template] +ver=2 +Name=raygui +Name[zh_CN]=raygui +Icon=raygui.ico +Description=raygui demo +Description[zh_CN]=Raygui演示 +Category=Multimedia +Category[zh_CN]=多媒体 + +[Unit0] +CName=main.c +C=raygui_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 + diff --git a/windows/templates/raygui/raygui.ico b/windows/templates/raygui/raygui.ico new file mode 100644 index 00000000..b8668114 Binary files /dev/null and b/windows/templates/raygui/raygui.ico differ diff --git a/windows/templates/raygui/raygui_c.txt b/windows/templates/raygui/raygui_c.txt new file mode 100644 index 00000000..5e0a84db --- /dev/null +++ b/windows/templates/raygui/raygui_c.txt @@ -0,0 +1,251 @@ +/******************************************************************************************* +* +* raygui - controls test suite +* +* TEST CONTROLS: +* - GuiDropdownBox() +* - GuiCheckBox() +* - GuiSpinner() +* - GuiValueBox() +* - GuiTextBox() +* - GuiButton() +* - GuiComboBox() +* - GuiListView() +* - GuiToggleGroup() +* - GuiTextBoxMulti() +* - GuiColorPicker() +* - GuiSlider() +* - GuiSliderBar() +* - GuiProgressBar() +* - GuiColorBarAlpha() +* - GuiScrollPanel() +* +* +* DEPENDENCIES: +* raylib 4.0 - Windowing/input management and drawing. +* raygui 3.2 - Immediate-mode GUI controls. +* +* COMPILATION (Windows - MinGW): +* gcc -o $(NAME_PART).exe $(FILE_NAME) -I../../src -lraylib -lopengl32 -lgdi32 -std=c99 +* +* LICENSE: zlib/libpng +* +* Copyright (c) 2016-2022 Ramon Santamaria (@raysan5) +* +**********************************************************************************************/ + +#include + +#define RAYGUI_IMPLEMENTATION +//#define RAYGUI_CUSTOM_ICONS // It requires providing gui_icons.h in the same directory +//#include "gui_icons.h" // External icons data provided, it can be generated with rGuiIcons tool +#include + +#include // Required for: strcpy() + +//------------------------------------------------------------------------------------ +// Program main entry point +//------------------------------------------------------------------------------------ +int main() +{ + // Initialization + //--------------------------------------------------------------------------------------- + const int screenWidth = 690; + const int screenHeight = 560; + + InitWindow(screenWidth, screenHeight, "raygui - controls test suite"); + SetExitKey(0); + + // GUI controls initialization + //---------------------------------------------------------------------------------- + //GuiSetStyle(DEFAULT,TEXT_SIZE,16); + int dropdownBox000Active = 0; + bool dropDown000EditMode = false; + + int dropdownBox001Active = 0; + bool dropDown001EditMode = false; + + int spinner001Value = 0; + bool spinnerEditMode = false; + + int valueBox002Value = 0; + bool valueBoxEditMode = false; + + char textBoxText[64] = "Text box"; + bool textBoxEditMode = false; + + int listViewScrollIndex = 0; + int listViewActive = -1; + + int listViewExScrollIndex = 0; + int listViewExActive = 2; + int listViewExFocus = -1; + const char *listViewExList[8] = { "This", "is", "a", "list view", "with", "disable", "elements", "amazing!" }; + + char multiTextBoxText[256] = "Multi text box"; + bool multiTextBoxEditMode = false; + Color colorPickerValue = RED; + + int sliderValue = 50; + int sliderBarValue = 60; + float progressValue = 0.4f; + + bool forceSquaredChecked = false; + + float alphaValue = 0.5f; + + int comboBoxActive = 1; + + int toggleGroupActive = 0; + + Vector2 viewScroll = { 0, 0 }; + //---------------------------------------------------------------------------------- + + // Custom GUI font loading + //Font font = LoadFontEx("fonts/rainyhearts16.ttf", 12, 0, 0); + //GuiSetFont(font); + + bool exitWindow = false; + bool showMessageBox = false; + + char textInput[256] = { 0 }; + bool showTextInputBox = false; + + char textInputFileName[256] = { 0 }; + + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!exitWindow) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + exitWindow = WindowShouldClose(); + + if (IsKeyPressed(KEY_ESCAPE)) showMessageBox = !showMessageBox; + + if (IsKeyDown(KEY_LEFT_CONTROL) && IsKeyPressed(KEY_S)) showTextInputBox = true; + +// incompatible with raylib 4.0 +// if (IsFileDropped()) +// { +// int dropFileCount = 0; +// char **droppedFiles = LoadDroppedFiles(&dropFileCount); +// +// if ((dropFileCount > 0) && IsFileExtension(droppedFiles[0], ".rgs")) GuiLoadStyle(droppedFiles[0]); +// +// UnloadDroppedFiles(); // Clear internal buffers +// } + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(GetColor(GuiGetStyle(DEFAULT, BACKGROUND_COLOR))); + + // raygui: controls drawing + //---------------------------------------------------------------------------------- + if (dropDown000EditMode || dropDown001EditMode) GuiLock(); + else if (!dropDown000EditMode && !dropDown001EditMode) GuiUnlock(); + //GuiDisable(); + + // First GUI column + //GuiSetStyle(CHECKBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); + forceSquaredChecked = GuiCheckBox((Rectangle){ 25, 108, 15, 15 }, "FORCE CHECK!", forceSquaredChecked); + + GuiSetStyle(TEXTBOX, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); + //GuiSetStyle(VALUEBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); + if (GuiSpinner((Rectangle){ 25, 135, 125, 30 }, NULL, &spinner001Value, 0, 100, spinnerEditMode)) spinnerEditMode = !spinnerEditMode; + if (GuiValueBox((Rectangle){ 25, 175, 125, 30 }, NULL, &valueBox002Value, 0, 100, valueBoxEditMode)) valueBoxEditMode = !valueBoxEditMode; + GuiSetStyle(TEXTBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); + if (GuiTextBox((Rectangle){ 25, 215, 125, 30 }, textBoxText, 64, textBoxEditMode)) textBoxEditMode = !textBoxEditMode; + + GuiSetStyle(BUTTON, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); + + if (GuiButton((Rectangle){ 25, 255, 125, 30 }, GuiIconText(ICON_FILE_SAVE, "Save File"))) showTextInputBox = true; + + GuiGroupBox((Rectangle){ 25, 310, 125, 150 }, "STATES"); + //GuiLock(); + GuiSetState(STATE_NORMAL); if (GuiButton((Rectangle){ 30, 320, 115, 30 }, "NORMAL")) { } + GuiSetState(STATE_FOCUSED); if (GuiButton((Rectangle){ 30, 355, 115, 30 }, "FOCUSED")) { } + GuiSetState(STATE_PRESSED); if (GuiButton((Rectangle){ 30, 390, 115, 30 }, "#15#PRESSED")) { } + GuiSetState(STATE_DISABLED); if (GuiButton((Rectangle){ 30, 425, 115, 30 }, "DISABLED")) { } + GuiSetState(STATE_NORMAL); + //GuiUnlock(); + + comboBoxActive = GuiComboBox((Rectangle){ 25, 470, 125, 30 }, "ONE;TWO;THREE;FOUR", comboBoxActive); + + // NOTE: GuiDropdownBox must draw after any other control that can be covered on unfolding + GuiSetStyle(DROPDOWNBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); + if (GuiDropdownBox((Rectangle){ 25, 65, 125, 30 }, "#01#ONE;#02#TWO;#03#THREE;#04#FOUR", &dropdownBox001Active, dropDown001EditMode)) dropDown001EditMode = !dropDown001EditMode; + + GuiSetStyle(DROPDOWNBOX, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); + if (GuiDropdownBox((Rectangle){ 25, 25, 125, 30 }, "ONE;TWO;THREE", &dropdownBox000Active, dropDown000EditMode)) dropDown000EditMode = !dropDown000EditMode; + + // Second GUI column + listViewActive = GuiListView((Rectangle){ 165, 25, 140, 140 }, "Charmander;Bulbasaur;#18#Squirtel;Pikachu;Eevee;Pidgey", &listViewScrollIndex, listViewActive); + listViewExActive = GuiListViewEx((Rectangle){ 165, 180, 140, 200 }, listViewExList, 8, &listViewExFocus, &listViewExScrollIndex, listViewExActive); + + toggleGroupActive = GuiToggleGroup((Rectangle){ 165, 400, 140, 25 }, "#1#ONE\n#3#TWO\n#8#THREE\n#23#", toggleGroupActive); + + // Third GUI column + if (GuiTextBoxMulti((Rectangle){ 320, 25, 225, 140 }, multiTextBoxText, 256, multiTextBoxEditMode)) multiTextBoxEditMode = !multiTextBoxEditMode; + colorPickerValue = GuiColorPicker((Rectangle){ 320, 185, 196, 192 }, NULL, colorPickerValue); + + sliderValue = GuiSlider((Rectangle){ 355, 400, 165, 20 }, "TEST", TextFormat("%2.2f", (float)sliderValue), sliderValue, -50, 100); + sliderBarValue = GuiSliderBar((Rectangle){ 320, 430, 200, 20 }, NULL, TextFormat("%i", (int)sliderBarValue), sliderBarValue, 0, 100); + progressValue = GuiProgressBar((Rectangle){ 320, 460, 200, 20 }, NULL, NULL, progressValue, 0, 1); + + // NOTE: View rectangle could be used to perform some scissor test + Rectangle view = GuiScrollPanel((Rectangle){ 560, 25, 100, 160 }, NULL, (Rectangle){ 560, 25, 200, 400 }, &viewScroll); + + GuiPanel((Rectangle){ 560, 25 + 180, 100, 160 }, "Panel Info"); + + GuiGrid((Rectangle) { 560, 25 + 180 + 180, 100, 120 }, NULL, 20, 2); + + GuiStatusBar((Rectangle){ 0, (float)GetScreenHeight() - 20, (float)GetScreenWidth(), 20 }, "This is a status bar"); + + alphaValue = GuiColorBarAlpha((Rectangle){ 320, 490, 200, 30 }, NULL, alphaValue); + + if (showMessageBox) + { + DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), Fade(RAYWHITE, 0.8f)); + int result = GuiMessageBox((Rectangle){ (float)GetScreenWidth()/2 - 125, (float)GetScreenHeight()/2 - 50, 250, 100 }, GuiIconText(ICON_EXIT, "Close Window"), "Do you really want to exit?", "Yes;No"); + + if ((result == 0) || (result == 2)) showMessageBox = false; + else if (result == 1) exitWindow = true; + } + + if (showTextInputBox) + { + DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), Fade(RAYWHITE, 0.8f)); + int result = GuiTextInputBox((Rectangle){ (float)GetScreenWidth()/2 - 120, (float)GetScreenHeight()/2 - 60, 240, 140 }, "Save", GuiIconText(ICON_FILE_SAVE, "Save file as..."), "Ok;Cancel", textInput, 255, NULL); + + if (result == 1) + { + // TODO: Validate textInput value and save + + strcpy(textInputFileName, textInput); + } + + if ((result == 0) || (result == 1) || (result == 2)) + { + showTextInputBox = false; + strcpy(textInput, "\0"); + } + } + //---------------------------------------------------------------------------------- + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} diff --git a/windows/templates/raylib-3d/info.template b/windows/templates/raylib-3d/info.template new file mode 100644 index 00000000..745ffcda --- /dev/null +++ b/windows/templates/raylib-3d/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=raylib 3D +Name[zh_CN]=raylib 3D +Icon=raylib.ico +Description=A simple 3D program using raylib ( https://raylib.com ) +Description[zh_CN]=简单的raylib 3D程序 ( https://raylib.com ) +Category=3D +Category[zh_CN]=3D + +[Unit0] +CName=main.c +C=raylib_3d_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 diff --git a/windows/templates/raylib-3d/raylib.ico b/windows/templates/raylib-3d/raylib.ico new file mode 100644 index 00000000..14db8eab Binary files /dev/null and b/windows/templates/raylib-3d/raylib.ico differ diff --git a/windows/templates/raylib-3d/raylib_3d_c.txt b/windows/templates/raylib-3d/raylib_3d_c.txt new file mode 100644 index 00000000..27d12023 --- /dev/null +++ b/windows/templates/raylib-3d/raylib_3d_c.txt @@ -0,0 +1,113 @@ +/******************************************************************************************* +* +* raylib [models] example - Waving cubes +* +* This example has been created using raylib 2.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Example contributed by Codecat (@codecat) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2019 Codecat (@codecat) and Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include + +#include + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [models] example - waving cubes"); + + // Initialize the camera + Camera3D camera = { 0 }; + camera.position = (Vector3){ 30.0f, 20.0f, 30.0f }; + camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; + camera.fovy = 70.0f; + camera.projection = CAMERA_PERSPECTIVE; + + // Specify the amount of blocks in each direction + const int numBlocks = 15; + + SetTargetFPS(60); + SetTraceLogLevel(LOG_WARNING); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + double time = GetTime(); + + // Calculate time scale for cube position and size + float scale = (2.0f + (float)sin(time))*0.7f; + + // Move camera around the scene + double cameraTime = time*0.3; + camera.position.x = (float)cos(cameraTime)*40.0f; + camera.position.z = (float)sin(cameraTime)*40.0f; + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawGrid(10, 5.0f); + + for (int x = 0; x < numBlocks; x++) + { + for (int y = 0; y < numBlocks; y++) + { + for (int z = 0; z < numBlocks; z++) + { + // Scale of the blocks depends on x/y/z positions + float blockScale = (x + y + z)/30.0f; + + // Scatter makes the waving effect by adding blockScale over time + float scatter = sinf(blockScale*20.0f + (float)(time*4.0f)); + + // Calculate the cube position + Vector3 cubePos = { + (float)(x - numBlocks/2)*(scale*3.0f) + scatter, + (float)(y - numBlocks/2)*(scale*2.0f) + scatter, + (float)(z - numBlocks/2)*(scale*3.0f) + scatter + }; + + // Pick a color with a hue depending on cube position for the rainbow color effect + Color cubeColor = ColorFromHSV((float)(((x + y + z)*18)%360), 0.75f, 0.9f); + + // Calculate cube size + float cubeSize = (2.4f - scale)*blockScale; + + // And finally, draw the cube! + DrawCube(cubePos, cubeSize, cubeSize, cubeSize, cubeColor); + } + } + } + + EndMode3D(); + + DrawFPS(10, 10); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/windows/templates/raylib-arkanoid/info.template b/windows/templates/raylib-arkanoid/info.template new file mode 100644 index 00000000..79c94263 --- /dev/null +++ b/windows/templates/raylib-arkanoid/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=arkanoid +Name[zh_CN]=打砖块 +Icon=raylib_arkanoid.ico +Description=arkanoid game using raylib ( https://raylib.com ) +Description[zh_CN]=经典的打砖块游戏(基于raylib) ( https://raylib.com ) +Category=Game +Category[zh_CN]=游戏 + +[Unit0] +CName=main.c +C=raylib_arkanoid_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 diff --git a/windows/templates/raylib-arkanoid/raylib_arkanoid.ico b/windows/templates/raylib-arkanoid/raylib_arkanoid.ico new file mode 100644 index 00000000..be05b231 Binary files /dev/null and b/windows/templates/raylib-arkanoid/raylib_arkanoid.ico differ diff --git a/windows/templates/raylib-arkanoid/raylib_arkanoid.png b/windows/templates/raylib-arkanoid/raylib_arkanoid.png new file mode 100644 index 00000000..99718cdc Binary files /dev/null and b/windows/templates/raylib-arkanoid/raylib_arkanoid.png differ diff --git a/windows/templates/raylib-arkanoid/raylib_arkanoid_c.txt b/windows/templates/raylib-arkanoid/raylib_arkanoid_c.txt new file mode 100644 index 00000000..ae906423 --- /dev/null +++ b/windows/templates/raylib-arkanoid/raylib_arkanoid_c.txt @@ -0,0 +1,324 @@ +/******************************************************************************************* +* +* raylib - classic game: arkanoid +* +* Sample game developed by Marc Palau and Ramon Santamaria +* +* This game has been created using raylib v1.3 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2015 Ramon Santamaria (@raysan5) +* +* Icon from https://www.flaticon.com/free-icon/arkanoid_2927802 +********************************************************************************************/ + +#include + +#include +#include +#include +#include + +#if defined(PLATFORM_WEB) +#include +#endif + +//---------------------------------------------------------------------------------- +// Some Defines +//---------------------------------------------------------------------------------- +#define PLAYER_MAX_LIFE 5 +#define LINES_OF_BRICKS 5 +#define BRICKS_PER_LINE 20 + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- +typedef enum GameScreen { LOGO, TITLE, GAMEPLAY, ENDING } GameScreen; + +typedef struct Player { + Vector2 position; + Vector2 size; + int life; +} Player; + +typedef struct Ball { + Vector2 position; + Vector2 speed; + int radius; + bool active; +} Ball; + +typedef struct Brick { + Vector2 position; + bool active; +} Brick; + +//------------------------------------------------------------------------------------ +// Global Variables Declaration +//------------------------------------------------------------------------------------ +static const int screenWidth = 800; +static const int screenHeight = 450; + +static bool gameOver = false; +static bool pause = false; + +static Player player = { 0 }; +static Ball ball = { 0 }; +static Brick brick[LINES_OF_BRICKS][BRICKS_PER_LINE] = { 0 }; +static Vector2 brickSize = { 0 }; + +//------------------------------------------------------------------------------------ +// Module Functions Declaration (local) +//------------------------------------------------------------------------------------ +static void InitGame(void); // Initialize game +static void UpdateGame(void); // Update game (one frame) +static void DrawGame(void); // Draw game (one frame) +static void UnloadGame(void); // Unload game +static void UpdateDrawFrame(void); // Update and Draw (one frame) + +//------------------------------------------------------------------------------------ +// Program main entry point +//------------------------------------------------------------------------------------ +int main(void) +{ + // Initialization (Note windowTitle is unused on Android) + //--------------------------------------------------------- + InitWindow(screenWidth, screenHeight, "classic game: arkanoid"); + + InitGame(); + +#if defined(PLATFORM_WEB) + emscripten_set_main_loop(UpdateDrawFrame, 60, 1); +#else + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update and Draw + //---------------------------------------------------------------------------------- + UpdateDrawFrame(); + //---------------------------------------------------------------------------------- + } +#endif + // De-Initialization + //-------------------------------------------------------------------------------------- + UnloadGame(); // Unload loaded data (textures, sounds, models...) + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} + +//------------------------------------------------------------------------------------ +// Module Functions Definitions (local) +//------------------------------------------------------------------------------------ + +// Initialize game variables +void InitGame(void) +{ + brickSize = (Vector2){ GetScreenWidth()/BRICKS_PER_LINE, 40 }; + + // Initialize player + player.position = (Vector2){ screenWidth/2, screenHeight*7/8 }; + player.size = (Vector2){ screenWidth/10, 20 }; + player.life = PLAYER_MAX_LIFE; + + // Initialize ball + ball.position = (Vector2){ screenWidth/2, screenHeight*7/8 - 30 }; + ball.speed = (Vector2){ 0, 0 }; + ball.radius = 7; + ball.active = false; + + // Initialize bricks + int initialDownPosition = 50; + + for (int i = 0; i < LINES_OF_BRICKS; i++) + { + for (int j = 0; j < BRICKS_PER_LINE; j++) + { + brick[i][j].position = (Vector2){ j*brickSize.x + brickSize.x/2, i*brickSize.y + initialDownPosition }; + brick[i][j].active = true; + } + } +} + +// Update game (one frame) +void UpdateGame(void) +{ + if (!gameOver) + { + if (IsKeyPressed('P')) pause = !pause; + + if (!pause) + { + // Player movement logic + if (IsKeyDown(KEY_LEFT)) player.position.x -= 5; + if ((player.position.x - player.size.x/2) <= 0) player.position.x = player.size.x/2; + if (IsKeyDown(KEY_RIGHT)) player.position.x += 5; + if ((player.position.x + player.size.x/2) >= screenWidth) player.position.x = screenWidth - player.size.x/2; + + // Ball launching logic + if (!ball.active) + { + if (IsKeyPressed(KEY_SPACE)) + { + ball.active = true; + ball.speed = (Vector2){ 0, -5 }; + } + } + + // Ball movement logic + if (ball.active) + { + ball.position.x += ball.speed.x; + ball.position.y += ball.speed.y; + } + else + { + ball.position = (Vector2){ player.position.x, screenHeight*7/8 - 30 }; + } + + // Collision logic: ball vs walls + if (((ball.position.x + ball.radius) >= screenWidth) || ((ball.position.x - ball.radius) <= 0)) ball.speed.x *= -1; + if ((ball.position.y - ball.radius) <= 0) ball.speed.y *= -1; + if ((ball.position.y + ball.radius) >= screenHeight) + { + ball.speed = (Vector2){ 0, 0 }; + ball.active = false; + + player.life--; + } + + // Collision logic: ball vs player + if (CheckCollisionCircleRec(ball.position, ball.radius, + (Rectangle){ player.position.x - player.size.x/2, player.position.y - player.size.y/2, player.size.x, player.size.y})) + { + if (ball.speed.y > 0) + { + ball.speed.y *= -1; + ball.speed.x = (ball.position.x - player.position.x)/(player.size.x/2)*5; + } + } + + // Collision logic: ball vs bricks + for (int i = 0; i < LINES_OF_BRICKS; i++) + { + for (int j = 0; j < BRICKS_PER_LINE; j++) + { + if (brick[i][j].active) + { + // Hit below + if (((ball.position.y - ball.radius) <= (brick[i][j].position.y + brickSize.y/2)) && + ((ball.position.y - ball.radius) > (brick[i][j].position.y + brickSize.y/2 + ball.speed.y)) && + ((fabs(ball.position.x - brick[i][j].position.x)) < (brickSize.x/2 + ball.radius*2/3)) && (ball.speed.y < 0)) + { + brick[i][j].active = false; + ball.speed.y *= -1; + } + // Hit above + else if (((ball.position.y + ball.radius) >= (brick[i][j].position.y - brickSize.y/2)) && + ((ball.position.y + ball.radius) < (brick[i][j].position.y - brickSize.y/2 + ball.speed.y)) && + ((fabs(ball.position.x - brick[i][j].position.x)) < (brickSize.x/2 + ball.radius*2/3)) && (ball.speed.y > 0)) + { + brick[i][j].active = false; + ball.speed.y *= -1; + } + // Hit left + else if (((ball.position.x + ball.radius) >= (brick[i][j].position.x - brickSize.x/2)) && + ((ball.position.x + ball.radius) < (brick[i][j].position.x - brickSize.x/2 + ball.speed.x)) && + ((fabs(ball.position.y - brick[i][j].position.y)) < (brickSize.y/2 + ball.radius*2/3)) && (ball.speed.x > 0)) + { + brick[i][j].active = false; + ball.speed.x *= -1; + } + // Hit right + else if (((ball.position.x - ball.radius) <= (brick[i][j].position.x + brickSize.x/2)) && + ((ball.position.x - ball.radius) > (brick[i][j].position.x + brickSize.x/2 + ball.speed.x)) && + ((fabs(ball.position.y - brick[i][j].position.y)) < (brickSize.y/2 + ball.radius*2/3)) && (ball.speed.x < 0)) + { + brick[i][j].active = false; + ball.speed.x *= -1; + } + } + } + } + + // Game over logic + if (player.life <= 0) gameOver = true; + else + { + gameOver = true; + + for (int i = 0; i < LINES_OF_BRICKS; i++) + { + for (int j = 0; j < BRICKS_PER_LINE; j++) + { + if (brick[i][j].active) gameOver = false; + } + } + } + } + } + else + { + if (IsKeyPressed(KEY_ENTER)) + { + InitGame(); + gameOver = false; + } + } +} + +// Draw game (one frame) +void DrawGame(void) +{ + BeginDrawing(); + + ClearBackground(RAYWHITE); + + if (!gameOver) + { + // Draw player bar + DrawRectangle(player.position.x - player.size.x/2, player.position.y - player.size.y/2, player.size.x, player.size.y, BLACK); + + // Draw player lives + for (int i = 0; i < player.life; i++) DrawRectangle(20 + 40*i, screenHeight - 30, 35, 10, LIGHTGRAY); + + // Draw ball + DrawCircleV(ball.position, ball.radius, MAROON); + + // Draw bricks + for (int i = 0; i < LINES_OF_BRICKS; i++) + { + for (int j = 0; j < BRICKS_PER_LINE; j++) + { + if (brick[i][j].active) + { + if ((i + j) % 2 == 0) DrawRectangle(brick[i][j].position.x - brickSize.x/2, brick[i][j].position.y - brickSize.y/2, brickSize.x, brickSize.y, GRAY); + else DrawRectangle(brick[i][j].position.x - brickSize.x/2, brick[i][j].position.y - brickSize.y/2, brickSize.x, brickSize.y, DARKGRAY); + } + } + } + + if (pause) DrawText("GAME PAUSED", screenWidth/2 - MeasureText("GAME PAUSED", 40)/2, screenHeight/2 - 40, 40, GRAY); + } + else DrawText("PRESS [ENTER] TO PLAY AGAIN", GetScreenWidth()/2 - MeasureText("PRESS [ENTER] TO PLAY AGAIN", 20)/2, GetScreenHeight()/2 - 50, 20, GRAY); + + EndDrawing(); +} + +// Unload game variables +void UnloadGame(void) +{ + // TODO: Unload all dynamic loaded data (textures, sounds, models...) +} + +// Update and Draw (one frame) +void UpdateDrawFrame(void) +{ + UpdateGame(); + DrawGame(); +} \ No newline at end of file diff --git a/windows/templates/raylib-shader/info.template b/windows/templates/raylib-shader/info.template new file mode 100644 index 00000000..3d0dfad9 --- /dev/null +++ b/windows/templates/raylib-shader/info.template @@ -0,0 +1,28 @@ +[Template] +ver=2 +Name=raylib 3D Shader +Name[zh_CN]=raylib 3D 着色器 +Icon=raylib.ico +Description=A 3D Shader program using raylib ( https://raylib.com ) +Description[zh_CN]=带着色器的raylib 3D程序 ( https://raylib.com ) +Category=3D +Category[zh_CN]=3D + +[Unit0] +CPPName=main.c +C=raylib_3d_shader_c.txt + +[Unit1] +Source=raylib_base.vs +Target=vertices_shader.vs + +[Unit2] +Source=raylib_base.fs +Target=fragment_shader.fs + +[Project] +UnitCount=3 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 diff --git a/windows/templates/raylib-shader/raylib.ico b/windows/templates/raylib-shader/raylib.ico new file mode 100644 index 00000000..14db8eab Binary files /dev/null and b/windows/templates/raylib-shader/raylib.ico differ diff --git a/windows/templates/raylib-shader/raylib_3d_shader_c.txt b/windows/templates/raylib-shader/raylib_3d_shader_c.txt new file mode 100644 index 00000000..9292ddcf --- /dev/null +++ b/windows/templates/raylib-shader/raylib_3d_shader_c.txt @@ -0,0 +1,68 @@ +#include +#include + +int main(void) +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) + InitWindow(screenWidth, screenHeight, "raylib shader"); + + // Define the camera to look into our 3d world + Camera camera = { 0 }; + camera.position = (Vector3){ 2.0f, 4.0f, 6.0f }; // Camera position + camera.target = (Vector3){ 0.0f, 0.5f, 0.0f }; // Camera looking at point + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) + camera.fovy = 45.0f; // Camera field-of-view Y + camera.projection = CAMERA_PERSPECTIVE; // Camera mode type + + // Load plane model from a generated mesh + Model model = LoadModelFromMesh(GenMeshCube(10.0f, 10.0f, 3.3)); + + Shader shader = LoadShader("vertices_shader.vs","fragment_shader.fs"); + + // Assign out lighting shader to model + model.materials[0].shader = shader; + + SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTraceLogLevel(LOG_WARNING); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + UpdateCamera(&camera); // Update camera + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawModel(model, Vector3Zero(), 1.0f, WHITE); + + DrawGrid(10, 1.0f); + + EndMode3D(); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + UnloadModel(model); // Unload the model + UnloadShader(shader); // Unload shader + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/windows/templates/raylib-shader/raylib_base.fs b/windows/templates/raylib-shader/raylib_base.fs new file mode 100644 index 00000000..6b500622 --- /dev/null +++ b/windows/templates/raylib-shader/raylib_base.fs @@ -0,0 +1,25 @@ +#version 330 + +// Input vertex attributes (from vertex shader) +in vec2 fragTexCoord; +in vec4 fragColor; + +// Input uniform values +uniform sampler2D texture0; +uniform vec4 colDiffuse; + +// Output fragment color +out vec4 finalColor; + +// NOTE: Add here your custom variables + +void main() +{ + // Texel color fetching from texture sampler + vec4 texelColor = texture(texture0, fragTexCoord); + + // NOTE: Implement here your fragment shader code + + finalColor = texelColor*colDiffuse; +} + diff --git a/windows/templates/raylib-shader/raylib_base.vs b/windows/templates/raylib-shader/raylib_base.vs new file mode 100644 index 00000000..8cc2abb2 --- /dev/null +++ b/windows/templates/raylib-shader/raylib_base.vs @@ -0,0 +1,26 @@ +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; +in vec2 vertexTexCoord; +in vec3 vertexNormal; +in vec4 vertexColor; + +// Input uniform values +uniform mat4 mvp; + +// Output vertex attributes (to fragment shader) +out vec2 fragTexCoord; +out vec4 fragColor; + +// NOTE: Add here your custom variables + +void main() +{ + // Send vertex attributes to fragment shader + fragTexCoord = vertexTexCoord; + fragColor = vertexColor; + + // Calculate final vertex position + gl_Position = mvp*vec4(vertexPosition, 1.0); +} \ No newline at end of file diff --git a/windows/templates/raylib-snake/info.template b/windows/templates/raylib-snake/info.template new file mode 100644 index 00000000..ccc5af02 --- /dev/null +++ b/windows/templates/raylib-snake/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=snake +Name[zh_CN]=吞食蛇 +Icon=raylib-snake.ico +Description=snake game using raylib ( https://raylib.com ) +Description[zh_CN]=经典的吞食蛇游戏(基于raylib) ( https://raylib.com ) +Category=Game +Category[zh_CN]=游戏 + +[Unit0] +CName=main.c +C=raylib_snake_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 diff --git a/windows/templates/raylib-snake/raylib-snake.ico b/windows/templates/raylib-snake/raylib-snake.ico new file mode 100644 index 00000000..9e8ce4af Binary files /dev/null and b/windows/templates/raylib-snake/raylib-snake.ico differ diff --git a/windows/templates/raylib-snake/raylib_snake_c.txt b/windows/templates/raylib-snake/raylib_snake_c.txt new file mode 100644 index 00000000..62eace4d --- /dev/null +++ b/windows/templates/raylib-snake/raylib_snake_c.txt @@ -0,0 +1,286 @@ +/******************************************************************************************* +* +* raylib - classic game: snake +* +* Sample game developed by Ian Eito, Albert Martos and Ramon Santamaria +* +* This game has been created using raylib v1.3 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2015 Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +#if defined(PLATFORM_WEB) + #include +#endif + +//---------------------------------------------------------------------------------- +// Some Defines +//---------------------------------------------------------------------------------- +#define SNAKE_LENGTH 256 +#define SQUARE_SIZE 31 + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- +typedef struct Snake { + Vector2 position; + Vector2 size; + Vector2 speed; + Color color; +} Snake; + +typedef struct Food { + Vector2 position; + Vector2 size; + bool active; + Color color; +} Food; + +//------------------------------------------------------------------------------------ +// Global Variables Declaration +//------------------------------------------------------------------------------------ +static const int screenWidth = 800; +static const int screenHeight = 450; + +static int framesCounter = 0; +static bool gameOver = false; +static bool pause = false; + +static Food fruit = { 0 }; +static Snake snake[SNAKE_LENGTH] = { 0 }; +static Vector2 snakePosition[SNAKE_LENGTH] = { 0 }; +static bool allowMove = false; +static Vector2 offset = { 0 }; +static int counterTail = 0; + +//------------------------------------------------------------------------------------ +// Module Functions Declaration (local) +//------------------------------------------------------------------------------------ +static void InitGame(void); // Initialize game +static void UpdateGame(void); // Update game (one frame) +static void DrawGame(void); // Draw game (one frame) +static void UnloadGame(void); // Unload game +static void UpdateDrawFrame(void); // Update and Draw (one frame) + +//------------------------------------------------------------------------------------ +// Program main entry point +//------------------------------------------------------------------------------------ +int main(void) +{ + // Initialization (Note windowTitle is unused on Android) + //--------------------------------------------------------- + InitWindow(screenWidth, screenHeight, "classic game: snake"); + + InitGame(); + +#if defined(PLATFORM_WEB) + emscripten_set_main_loop(UpdateDrawFrame, 60, 1); +#else + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update and Draw + //---------------------------------------------------------------------------------- + UpdateDrawFrame(); + //---------------------------------------------------------------------------------- + } +#endif + // De-Initialization + //-------------------------------------------------------------------------------------- + UnloadGame(); // Unload loaded data (textures, sounds, models...) + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} + +//------------------------------------------------------------------------------------ +// Module Functions Definitions (local) +//------------------------------------------------------------------------------------ + +// Initialize game variables +void InitGame(void) +{ + framesCounter = 0; + gameOver = false; + pause = false; + + counterTail = 1; + allowMove = false; + + offset.x = screenWidth%SQUARE_SIZE; + offset.y = screenHeight%SQUARE_SIZE; + + for (int i = 0; i < SNAKE_LENGTH; i++) + { + snake[i].position = (Vector2){ offset.x/2, offset.y/2 }; + snake[i].size = (Vector2){ SQUARE_SIZE, SQUARE_SIZE }; + snake[i].speed = (Vector2){ SQUARE_SIZE, 0 }; + + if (i == 0) snake[i].color = DARKBLUE; + else snake[i].color = BLUE; + } + + for (int i = 0; i < SNAKE_LENGTH; i++) + { + snakePosition[i] = (Vector2){ 0.0f, 0.0f }; + } + + fruit.size = (Vector2){ SQUARE_SIZE, SQUARE_SIZE }; + fruit.color = SKYBLUE; + fruit.active = false; +} + +// Update game (one frame) +void UpdateGame(void) +{ + if (!gameOver) + { + if (IsKeyPressed('P')) pause = !pause; + + if (!pause) + { + // Player control + if (IsKeyPressed(KEY_RIGHT) && (snake[0].speed.x == 0) && allowMove) + { + snake[0].speed = (Vector2){ SQUARE_SIZE, 0 }; + allowMove = false; + } + if (IsKeyPressed(KEY_LEFT) && (snake[0].speed.x == 0) && allowMove) + { + snake[0].speed = (Vector2){ -SQUARE_SIZE, 0 }; + allowMove = false; + } + if (IsKeyPressed(KEY_UP) && (snake[0].speed.y == 0) && allowMove) + { + snake[0].speed = (Vector2){ 0, -SQUARE_SIZE }; + allowMove = false; + } + if (IsKeyPressed(KEY_DOWN) && (snake[0].speed.y == 0) && allowMove) + { + snake[0].speed = (Vector2){ 0, SQUARE_SIZE }; + allowMove = false; + } + + // Snake movement + for (int i = 0; i < counterTail; i++) snakePosition[i] = snake[i].position; + + if ((framesCounter%5) == 0) + { + for (int i = 0; i < counterTail; i++) + { + if (i == 0) + { + snake[0].position.x += snake[0].speed.x; + snake[0].position.y += snake[0].speed.y; + allowMove = true; + } + else snake[i].position = snakePosition[i-1]; + } + } + + // Wall behaviour + if (((snake[0].position.x) > (screenWidth - offset.x)) || + ((snake[0].position.y) > (screenHeight - offset.y)) || + (snake[0].position.x < 0) || (snake[0].position.y < 0)) + { + gameOver = true; + } + + // Collision with yourself + for (int i = 1; i < counterTail; i++) + { + if ((snake[0].position.x == snake[i].position.x) && (snake[0].position.y == snake[i].position.y)) gameOver = true; + } + + // Fruit position calculation + if (!fruit.active) + { + fruit.active = true; + fruit.position = (Vector2){ GetRandomValue(0, (screenWidth/SQUARE_SIZE) - 1)*SQUARE_SIZE + offset.x/2, GetRandomValue(0, (screenHeight/SQUARE_SIZE) - 1)*SQUARE_SIZE + offset.y/2 }; + + for (int i = 0; i < counterTail; i++) + { + while ((fruit.position.x == snake[i].position.x) && (fruit.position.y == snake[i].position.y)) + { + fruit.position = (Vector2){ GetRandomValue(0, (screenWidth/SQUARE_SIZE) - 1)*SQUARE_SIZE + offset.x/2, GetRandomValue(0, (screenHeight/SQUARE_SIZE) - 1)*SQUARE_SIZE + offset.y/2 }; + i = 0; + } + } + } + + // Collision + if ((snake[0].position.x < (fruit.position.x + fruit.size.x) && (snake[0].position.x + snake[0].size.x) > fruit.position.x) && + (snake[0].position.y < (fruit.position.y + fruit.size.y) && (snake[0].position.y + snake[0].size.y) > fruit.position.y)) + { + snake[counterTail].position = snakePosition[counterTail - 1]; + counterTail += 1; + fruit.active = false; + } + + framesCounter++; + } + } + else + { + if (IsKeyPressed(KEY_ENTER)) + { + InitGame(); + gameOver = false; + } + } +} + +// Draw game (one frame) +void DrawGame(void) +{ + BeginDrawing(); + + ClearBackground(RAYWHITE); + + if (!gameOver) + { + // Draw grid lines + for (int i = 0; i < screenWidth/SQUARE_SIZE + 1; i++) + { + DrawLineV((Vector2){SQUARE_SIZE*i + offset.x/2, offset.y/2}, (Vector2){SQUARE_SIZE*i + offset.x/2, screenHeight - offset.y/2}, LIGHTGRAY); + } + + for (int i = 0; i < screenHeight/SQUARE_SIZE + 1; i++) + { + DrawLineV((Vector2){offset.x/2, SQUARE_SIZE*i + offset.y/2}, (Vector2){screenWidth - offset.x/2, SQUARE_SIZE*i + offset.y/2}, LIGHTGRAY); + } + + // Draw snake + for (int i = 0; i < counterTail; i++) DrawRectangleV(snake[i].position, snake[i].size, snake[i].color); + + // Draw fruit to pick + DrawRectangleV(fruit.position, fruit.size, fruit.color); + + if (pause) DrawText("GAME PAUSED", screenWidth/2 - MeasureText("GAME PAUSED", 40)/2, screenHeight/2 - 40, 40, GRAY); + } + else DrawText("PRESS [ENTER] TO PLAY AGAIN", GetScreenWidth()/2 - MeasureText("PRESS [ENTER] TO PLAY AGAIN", 20)/2, GetScreenHeight()/2 - 50, 20, GRAY); + + EndDrawing(); +} + +// Unload game variables +void UnloadGame(void) +{ + // TODO: Unload all dynamic loaded data (textures, sounds, models...) +} + +// Update and Draw (one frame) +void UpdateDrawFrame(void) +{ + UpdateGame(); + DrawGame(); +} \ No newline at end of file diff --git a/windows/templates/raylib-tetris/info.template b/windows/templates/raylib-tetris/info.template new file mode 100644 index 00000000..6b2253e8 --- /dev/null +++ b/windows/templates/raylib-tetris/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=Tetris +Name[zh_CN]=俄罗斯方块 +Icon=raylib-tetris.ico +Description=Tetris game using raylib ( https://raylib.com ) +Description[zh_CN]=经典的俄罗斯方块游戏(基于raylib) ( https://raylib.com ) +Category=Game +Category[zh_CN]=游戏 + +[Unit0] +CName=main.c +C=raylib_tetris_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 diff --git a/windows/templates/raylib-tetris/raylib-tetris.ico b/windows/templates/raylib-tetris/raylib-tetris.ico new file mode 100644 index 00000000..f026b750 Binary files /dev/null and b/windows/templates/raylib-tetris/raylib-tetris.ico differ diff --git a/windows/templates/raylib-tetris/raylib_tetris_c.txt b/windows/templates/raylib-tetris/raylib_tetris_c.txt new file mode 100644 index 00000000..08f37557 --- /dev/null +++ b/windows/templates/raylib-tetris/raylib_tetris_c.txt @@ -0,0 +1,791 @@ +/******************************************************************************************* +* +* raylib - classic game: tetris +* +* Sample game developed by Marc Palau and Ramon Santamaria +* +* This game has been created using raylib v1.3 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2015 Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +#include +#include +#include +#include + +#if defined(PLATFORM_WEB) + #include +#endif + +//---------------------------------------------------------------------------------- +// Some Defines +//---------------------------------------------------------------------------------- +#define SQUARE_SIZE 20 + +#define GRID_HORIZONTAL_SIZE 12 +#define GRID_VERTICAL_SIZE 20 + +#define LATERAL_SPEED 10 +#define TURNING_SPEED 12 +#define FAST_FALL_AWAIT_COUNTER 30 + +#define FADING_TIME 33 + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- +typedef enum GridSquare { EMPTY, MOVING, FULL, BLOCK, FADING } GridSquare; + +//------------------------------------------------------------------------------------ +// Global Variables Declaration +//------------------------------------------------------------------------------------ +static const int screenWidth = 800; +static const int screenHeight = 450; + +static bool gameOver = false; +static bool pause = false; + +// Matrices +static GridSquare grid [GRID_HORIZONTAL_SIZE][GRID_VERTICAL_SIZE]; +static GridSquare piece [4][4]; +static GridSquare incomingPiece [4][4]; + +// Theese variables keep track of the active piece position +static int piecePositionX = 0; +static int piecePositionY = 0; + +// Game parameters +static Color fadingColor; +//static int fallingSpeed; // In frames + +static bool beginPlay = true; // This var is only true at the begining of the game, used for the first matrix creations +static bool pieceActive = false; +static bool detection = false; +static bool lineToDelete = false; + +// Statistics +static int level = 1; +static int lines = 0; + +// Counters +static int gravityMovementCounter = 0; +static int lateralMovementCounter = 0; +static int turnMovementCounter = 0; +static int fastFallMovementCounter = 0; + +static int fadeLineCounter = 0; + +// Based on level +static int gravitySpeed = 30; + +//------------------------------------------------------------------------------------ +// Module Functions Declaration (local) +//------------------------------------------------------------------------------------ +static void InitGame(void); // Initialize game +static void UpdateGame(void); // Update game (one frame) +static void DrawGame(void); // Draw game (one frame) +static void UnloadGame(void); // Unload game +static void UpdateDrawFrame(void); // Update and Draw (one frame) + +// Additional module functions +static bool Createpiece(); +static void GetRandompiece(); +static void ResolveFallingMovement(bool *detection, bool *pieceActive); +static bool ResolveLateralMovement(); +static bool ResolveTurnMovement(); +static void CheckDetection(bool *detection); +static void CheckCompletion(bool *lineToDelete); +static void DeleteCompleteLines(); + +//------------------------------------------------------------------------------------ +// Program main entry point +//------------------------------------------------------------------------------------ +int main(void) +{ + // Initialization (Note windowTitle is unused on Android) + //--------------------------------------------------------- + InitWindow(screenWidth, screenHeight, "classic game: tetris"); + + InitGame(); + +#if defined(PLATFORM_WEB) + emscripten_set_main_loop(UpdateDrawFrame, 60, 1); +#else + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update and Draw + //---------------------------------------------------------------------------------- + UpdateDrawFrame(); + //---------------------------------------------------------------------------------- + } +#endif + // De-Initialization + //-------------------------------------------------------------------------------------- + UnloadGame(); // Unload loaded data (textures, sounds, models...) + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} + +//-------------------------------------------------------------------------------------- +// Game Module Functions Definition +//-------------------------------------------------------------------------------------- + +// Initialize game variables +void InitGame(void) +{ + // Initialize game statistics + level = 1; + lines = 0; + + fadingColor = GRAY; + + piecePositionX = 0; + piecePositionY = 0; + + pause = false; + + beginPlay = true; + pieceActive = false; + detection = false; + lineToDelete = false; + + // Counters + gravityMovementCounter = 0; + lateralMovementCounter = 0; + turnMovementCounter = 0; + fastFallMovementCounter = 0; + + fadeLineCounter = 0; + gravitySpeed = 30; + + // Initialize grid matrices + for (int i = 0; i < GRID_HORIZONTAL_SIZE; i++) + { + for (int j = 0; j < GRID_VERTICAL_SIZE; j++) + { + if ((j == GRID_VERTICAL_SIZE - 1) || (i == 0) || (i == GRID_HORIZONTAL_SIZE - 1)) grid[i][j] = BLOCK; + else grid[i][j] = EMPTY; + } + } + + // Initialize incoming piece matrices + for (int i = 0; i < 4; i++) + { + for (int j = 0; j< 4; j++) + { + incomingPiece[i][j] = EMPTY; + } + } +} + +// Update game (one frame) +void UpdateGame(void) +{ + if (!gameOver) + { + if (IsKeyPressed('P')) pause = !pause; + + if (!pause) + { + if (!lineToDelete) + { + if (!pieceActive) + { + // Get another piece + pieceActive = Createpiece(); + + // We leave a little time before starting the fast falling down + fastFallMovementCounter = 0; + } + else // Piece falling + { + // Counters update + fastFallMovementCounter++; + gravityMovementCounter++; + lateralMovementCounter++; + turnMovementCounter++; + + // We make sure to move if we've pressed the key this frame + if (IsKeyPressed(KEY_LEFT) || IsKeyPressed(KEY_RIGHT)) lateralMovementCounter = LATERAL_SPEED; + if (IsKeyPressed(KEY_UP)) turnMovementCounter = TURNING_SPEED; + + // Fall down + if (IsKeyDown(KEY_DOWN) && (fastFallMovementCounter >= FAST_FALL_AWAIT_COUNTER)) + { + // We make sure the piece is going to fall this frame + gravityMovementCounter += gravitySpeed; + } + + if (gravityMovementCounter >= gravitySpeed) + { + // Basic falling movement + CheckDetection(&detection); + + // Check if the piece has collided with another piece or with the boundings + ResolveFallingMovement(&detection, &pieceActive); + + // Check if we fullfilled a line and if so, erase the line and pull down the the lines above + CheckCompletion(&lineToDelete); + + gravityMovementCounter = 0; + } + + // Move laterally at player's will + if (lateralMovementCounter >= LATERAL_SPEED) + { + // Update the lateral movement and if success, reset the lateral counter + if (!ResolveLateralMovement()) lateralMovementCounter = 0; + } + + // Turn the piece at player's will + if (turnMovementCounter >= TURNING_SPEED) + { + // Update the turning movement and reset the turning counter + if (ResolveTurnMovement()) turnMovementCounter = 0; + } + } + + // Game over logic + for (int j = 0; j < 2; j++) + { + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) + { + if (grid[i][j] == FULL) + { + gameOver = true; + } + } + } + } + else + { + // Animation when deleting lines + fadeLineCounter++; + + if (fadeLineCounter%8 < 4) fadingColor = MAROON; + else fadingColor = GRAY; + + if (fadeLineCounter >= FADING_TIME) + { + DeleteCompleteLines(); + fadeLineCounter = 0; + lineToDelete = false; + + lines++; + } + } + } + } + else + { + if (IsKeyPressed(KEY_ENTER)) + { + InitGame(); + gameOver = false; + } + } +} + +// Draw game (one frame) +void DrawGame(void) +{ + BeginDrawing(); + + ClearBackground(RAYWHITE); + + if (!gameOver) + { + // Draw gameplay area + Vector2 offset; + offset.x = screenWidth/2 - (GRID_HORIZONTAL_SIZE*SQUARE_SIZE/2) - 50; + offset.y = screenHeight/2 - ((GRID_VERTICAL_SIZE - 1)*SQUARE_SIZE/2) + SQUARE_SIZE*2; + + offset.y -= 50; // NOTE: Harcoded position! + + int controller = offset.x; + + for (int j = 0; j < GRID_VERTICAL_SIZE; j++) + { + for (int i = 0; i < GRID_HORIZONTAL_SIZE; i++) + { + // Draw each square of the grid + if (grid[i][j] == EMPTY) + { + DrawLine(offset.x, offset.y, offset.x + SQUARE_SIZE, offset.y, LIGHTGRAY ); + DrawLine(offset.x, offset.y, offset.x, offset.y + SQUARE_SIZE, LIGHTGRAY ); + DrawLine(offset.x + SQUARE_SIZE, offset.y, offset.x + SQUARE_SIZE, offset.y + SQUARE_SIZE, LIGHTGRAY ); + DrawLine(offset.x, offset.y + SQUARE_SIZE, offset.x + SQUARE_SIZE, offset.y + SQUARE_SIZE, LIGHTGRAY ); + offset.x += SQUARE_SIZE; + } + else if (grid[i][j] == FULL) + { + DrawRectangle(offset.x, offset.y, SQUARE_SIZE, SQUARE_SIZE, GRAY); + offset.x += SQUARE_SIZE; + } + else if (grid[i][j] == MOVING) + { + DrawRectangle(offset.x, offset.y, SQUARE_SIZE, SQUARE_SIZE, DARKGRAY); + offset.x += SQUARE_SIZE; + } + else if (grid[i][j] == BLOCK) + { + DrawRectangle(offset.x, offset.y, SQUARE_SIZE, SQUARE_SIZE, LIGHTGRAY); + offset.x += SQUARE_SIZE; + } + else if (grid[i][j] == FADING) + { + DrawRectangle(offset.x, offset.y, SQUARE_SIZE, SQUARE_SIZE, fadingColor); + offset.x += SQUARE_SIZE; + } + } + + offset.x = controller; + offset.y += SQUARE_SIZE; + } + + // Draw incoming piece (hardcoded) + offset.x = 500; + offset.y = 45; + + int controler = offset.x; + + for (int j = 0; j < 4; j++) + { + for (int i = 0; i < 4; i++) + { + if (incomingPiece[i][j] == EMPTY) + { + DrawLine(offset.x, offset.y, offset.x + SQUARE_SIZE, offset.y, LIGHTGRAY ); + DrawLine(offset.x, offset.y, offset.x, offset.y + SQUARE_SIZE, LIGHTGRAY ); + DrawLine(offset.x + SQUARE_SIZE, offset.y, offset.x + SQUARE_SIZE, offset.y + SQUARE_SIZE, LIGHTGRAY ); + DrawLine(offset.x, offset.y + SQUARE_SIZE, offset.x + SQUARE_SIZE, offset.y + SQUARE_SIZE, LIGHTGRAY ); + offset.x += SQUARE_SIZE; + } + else if (incomingPiece[i][j] == MOVING) + { + DrawRectangle(offset.x, offset.y, SQUARE_SIZE, SQUARE_SIZE, GRAY); + offset.x += SQUARE_SIZE; + } + } + + offset.x = controler; + offset.y += SQUARE_SIZE; + } + + DrawText("INCOMING:", offset.x, offset.y - 100, 10, GRAY); + DrawText(TextFormat("LINES: %04i", lines), offset.x, offset.y + 20, 10, GRAY); + + if (pause) DrawText("GAME PAUSED", screenWidth/2 - MeasureText("GAME PAUSED", 40)/2, screenHeight/2 - 40, 40, GRAY); + } + else DrawText("PRESS [ENTER] TO PLAY AGAIN", GetScreenWidth()/2 - MeasureText("PRESS [ENTER] TO PLAY AGAIN", 20)/2, GetScreenHeight()/2 - 50, 20, GRAY); + + EndDrawing(); +} + +// Unload game variables +void UnloadGame(void) +{ + // TODO: Unload all dynamic loaded data (textures, sounds, models...) +} + +// Update and Draw (one frame) +void UpdateDrawFrame(void) +{ + UpdateGame(); + DrawGame(); +} + +//-------------------------------------------------------------------------------------- +// Additional module functions +//-------------------------------------------------------------------------------------- +static bool Createpiece() +{ + piecePositionX = (int)((GRID_HORIZONTAL_SIZE - 4)/2); + piecePositionY = 0; + + // If the game is starting and you are going to create the first piece, we create an extra one + if (beginPlay) + { + GetRandompiece(); + beginPlay = false; + } + + // We assign the incoming piece to the actual piece + for (int i = 0; i < 4; i++) + { + for (int j = 0; j< 4; j++) + { + piece[i][j] = incomingPiece[i][j]; + } + } + + // We assign a random piece to the incoming one + GetRandompiece(); + + // Assign the piece to the grid + for (int i = piecePositionX; i < piecePositionX + 4; i++) + { + for (int j = 0; j < 4; j++) + { + if (piece[i - (int)piecePositionX][j] == MOVING) grid[i][j] = MOVING; + } + } + + return true; +} + +static void GetRandompiece() +{ + int random = GetRandomValue(0, 6); + + for (int i = 0; i < 4; i++) + { + for (int j = 0; j < 4; j++) + { + incomingPiece[i][j] = EMPTY; + } + } + + switch (random) + { + case 0: { incomingPiece[1][1] = MOVING; incomingPiece[2][1] = MOVING; incomingPiece[1][2] = MOVING; incomingPiece[2][2] = MOVING; } break; //Cube + case 1: { incomingPiece[1][0] = MOVING; incomingPiece[1][1] = MOVING; incomingPiece[1][2] = MOVING; incomingPiece[2][2] = MOVING; } break; //L + case 2: { incomingPiece[1][2] = MOVING; incomingPiece[2][0] = MOVING; incomingPiece[2][1] = MOVING; incomingPiece[2][2] = MOVING; } break; //L inversa + case 3: { incomingPiece[0][1] = MOVING; incomingPiece[1][1] = MOVING; incomingPiece[2][1] = MOVING; incomingPiece[3][1] = MOVING; } break; //Recta + case 4: { incomingPiece[1][0] = MOVING; incomingPiece[1][1] = MOVING; incomingPiece[1][2] = MOVING; incomingPiece[2][1] = MOVING; } break; //Creu tallada + case 5: { incomingPiece[1][1] = MOVING; incomingPiece[2][1] = MOVING; incomingPiece[2][2] = MOVING; incomingPiece[3][2] = MOVING; } break; //S + case 6: { incomingPiece[1][2] = MOVING; incomingPiece[2][2] = MOVING; incomingPiece[2][1] = MOVING; incomingPiece[3][1] = MOVING; } break; //S inversa + } +} + +static void ResolveFallingMovement(bool *detection, bool *pieceActive) +{ + // If we finished moving this piece, we stop it + if (*detection) + { + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) + { + if (grid[i][j] == MOVING) + { + grid[i][j] = FULL; + *detection = false; + *pieceActive = false; + } + } + } + } + else // We move down the piece + { + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) + { + if (grid[i][j] == MOVING) + { + grid[i][j+1] = MOVING; + grid[i][j] = EMPTY; + } + } + } + + piecePositionY++; + } +} + +static bool ResolveLateralMovement() +{ + bool collision = false; + + // Piece movement + if (IsKeyDown(KEY_LEFT)) // Move left + { + // Check if is possible to move to left + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) + { + if (grid[i][j] == MOVING) + { + // Check if we are touching the left wall or we have a full square at the left + if ((i-1 == 0) || (grid[i-1][j] == FULL)) collision = true; + } + } + } + + // If able, move left + if (!collision) + { + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) // We check the matrix from left to right + { + // Move everything to the left + if (grid[i][j] == MOVING) + { + grid[i-1][j] = MOVING; + grid[i][j] = EMPTY; + } + } + } + + piecePositionX--; + } + } + else if (IsKeyDown(KEY_RIGHT)) // Move right + { + // Check if is possible to move to right + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) + { + if (grid[i][j] == MOVING) + { + // Check if we are touching the right wall or we have a full square at the right + if ((i+1 == GRID_HORIZONTAL_SIZE - 1) || (grid[i+1][j] == FULL)) + { + collision = true; + + } + } + } + } + + // If able move right + if (!collision) + { + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + for (int i = GRID_HORIZONTAL_SIZE - 1; i >= 1; i--) // We check the matrix from right to left + { + // Move everything to the right + if (grid[i][j] == MOVING) + { + grid[i+1][j] = MOVING; + grid[i][j] = EMPTY; + } + } + } + + piecePositionX++; + } + } + + return collision; +} + +static bool ResolveTurnMovement() +{ + // Input for turning the piece + if (IsKeyDown(KEY_UP)) + { + GridSquare aux; + bool checker = false; + + // Check all turning possibilities + if ((grid[piecePositionX + 3][piecePositionY] == MOVING) && + (grid[piecePositionX][piecePositionY] != EMPTY) && + (grid[piecePositionX][piecePositionY] != MOVING)) checker = true; + + if ((grid[piecePositionX + 3][piecePositionY + 3] == MOVING) && + (grid[piecePositionX + 3][piecePositionY] != EMPTY) && + (grid[piecePositionX + 3][piecePositionY] != MOVING)) checker = true; + + if ((grid[piecePositionX][piecePositionY + 3] == MOVING) && + (grid[piecePositionX + 3][piecePositionY + 3] != EMPTY) && + (grid[piecePositionX + 3][piecePositionY + 3] != MOVING)) checker = true; + + if ((grid[piecePositionX][piecePositionY] == MOVING) && + (grid[piecePositionX][piecePositionY + 3] != EMPTY) && + (grid[piecePositionX][piecePositionY + 3] != MOVING)) checker = true; + + if ((grid[piecePositionX + 1][piecePositionY] == MOVING) && + (grid[piecePositionX][piecePositionY + 2] != EMPTY) && + (grid[piecePositionX][piecePositionY + 2] != MOVING)) checker = true; + + if ((grid[piecePositionX + 3][piecePositionY + 1] == MOVING) && + (grid[piecePositionX + 1][piecePositionY] != EMPTY) && + (grid[piecePositionX + 1][piecePositionY] != MOVING)) checker = true; + + if ((grid[piecePositionX + 2][piecePositionY + 3] == MOVING) && + (grid[piecePositionX + 3][piecePositionY + 1] != EMPTY) && + (grid[piecePositionX + 3][piecePositionY + 1] != MOVING)) checker = true; + + if ((grid[piecePositionX][piecePositionY + 2] == MOVING) && + (grid[piecePositionX + 2][piecePositionY + 3] != EMPTY) && + (grid[piecePositionX + 2][piecePositionY + 3] != MOVING)) checker = true; + + if ((grid[piecePositionX + 2][piecePositionY] == MOVING) && + (grid[piecePositionX][piecePositionY + 1] != EMPTY) && + (grid[piecePositionX][piecePositionY + 1] != MOVING)) checker = true; + + if ((grid[piecePositionX + 3][piecePositionY + 2] == MOVING) && + (grid[piecePositionX + 2][piecePositionY] != EMPTY) && + (grid[piecePositionX + 2][piecePositionY] != MOVING)) checker = true; + + if ((grid[piecePositionX + 1][piecePositionY + 3] == MOVING) && + (grid[piecePositionX + 3][piecePositionY + 2] != EMPTY) && + (grid[piecePositionX + 3][piecePositionY + 2] != MOVING)) checker = true; + + if ((grid[piecePositionX][piecePositionY + 1] == MOVING) && + (grid[piecePositionX + 1][piecePositionY + 3] != EMPTY) && + (grid[piecePositionX + 1][piecePositionY + 3] != MOVING)) checker = true; + + if ((grid[piecePositionX + 1][piecePositionY + 1] == MOVING) && + (grid[piecePositionX + 1][piecePositionY + 2] != EMPTY) && + (grid[piecePositionX + 1][piecePositionY + 2] != MOVING)) checker = true; + + if ((grid[piecePositionX + 2][piecePositionY + 1] == MOVING) && + (grid[piecePositionX + 1][piecePositionY + 1] != EMPTY) && + (grid[piecePositionX + 1][piecePositionY + 1] != MOVING)) checker = true; + + if ((grid[piecePositionX + 2][piecePositionY + 2] == MOVING) && + (grid[piecePositionX + 2][piecePositionY + 1] != EMPTY) && + (grid[piecePositionX + 2][piecePositionY + 1] != MOVING)) checker = true; + + if ((grid[piecePositionX + 1][piecePositionY + 2] == MOVING) && + (grid[piecePositionX + 2][piecePositionY + 2] != EMPTY) && + (grid[piecePositionX + 2][piecePositionY + 2] != MOVING)) checker = true; + + if (!checker) + { + aux = piece[0][0]; + piece[0][0] = piece[3][0]; + piece[3][0] = piece[3][3]; + piece[3][3] = piece[0][3]; + piece[0][3] = aux; + + aux = piece[1][0]; + piece[1][0] = piece[3][1]; + piece[3][1] = piece[2][3]; + piece[2][3] = piece[0][2]; + piece[0][2] = aux; + + aux = piece[2][0]; + piece[2][0] = piece[3][2]; + piece[3][2] = piece[1][3]; + piece[1][3] = piece[0][1]; + piece[0][1] = aux; + + aux = piece[1][1]; + piece[1][1] = piece[2][1]; + piece[2][1] = piece[2][2]; + piece[2][2] = piece[1][2]; + piece[1][2] = aux; + } + + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) + { + if (grid[i][j] == MOVING) + { + grid[i][j] = EMPTY; + } + } + } + + for (int i = piecePositionX; i < piecePositionX + 4; i++) + { + for (int j = piecePositionY; j < piecePositionY + 4; j++) + { + if (piece[i - piecePositionX][j - piecePositionY] == MOVING) + { + grid[i][j] = MOVING; + } + } + } + + return true; + } + + return false; +} + +static void CheckDetection(bool *detection) +{ + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) + { + if ((grid[i][j] == MOVING) && ((grid[i][j+1] == FULL) || (grid[i][j+1] == BLOCK))) *detection = true; + } + } +} + +static void CheckCompletion(bool *lineToDelete) +{ + int calculator = 0; + + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + calculator = 0; + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) + { + // Count each square of the line + if (grid[i][j] == FULL) + { + calculator++; + } + + // Check if we completed the whole line + if (calculator == GRID_HORIZONTAL_SIZE - 2) + { + *lineToDelete = true; + calculator = 0; + // points++; + + // Mark the completed line + for (int z = 1; z < GRID_HORIZONTAL_SIZE - 1; z++) + { + grid[z][j] = FADING; + } + } + } + } +} + +static void DeleteCompleteLines() +{ + // Erase the completed line + for (int j = GRID_VERTICAL_SIZE - 2; j >= 0; j--) + { + while (grid[1][j] == FADING) + { + for (int i = 1; i < GRID_HORIZONTAL_SIZE - 1; i++) + { + grid[i][j] = EMPTY; + } + + for (int j2 = j-1; j2 >= 0; j2--) + { + for (int i2 = 1; i2 < GRID_HORIZONTAL_SIZE - 1; i2++) + { + if (grid[i2][j2] == FULL) + { + grid[i2][j2+1] = FULL; + grid[i2][j2] = EMPTY; + } + else if (grid[i2][j2] == FADING) + { + grid[i2][j2+1] = FADING; + grid[i2][j2] = EMPTY; + } + } + } + } + } +} \ No newline at end of file diff --git a/windows/templates/raylib/info.template b/windows/templates/raylib/info.template new file mode 100644 index 00000000..a196778a --- /dev/null +++ b/windows/templates/raylib/info.template @@ -0,0 +1,29 @@ +[Template] +ver=2 +Name=raylib +Name[zh_CN]=raylib +Icon=raylib-game.ico +Description=A simple interactive animation using raylib ( https://raylib.com ) +Description[zh_CN]=简单的raylib交互动画 ( https://raylib.com ) +Category=Multimedia +Category[zh_CN]=多媒体 + +[Unit0] +CName=main.c +C=raylib_c.txt + +[Unit1] +Source=raylib_boom.wav +Target=boom.wav + +[Unit2] +Source=raylib_explosion.png +Target=explosion.png + +[Project] +UnitCount=3 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 + diff --git a/windows/templates/raylib/raylib-game.ico b/windows/templates/raylib/raylib-game.ico new file mode 100644 index 00000000..ad116984 Binary files /dev/null and b/windows/templates/raylib/raylib-game.ico differ diff --git a/windows/templates/raylib/raylib_boom.wav b/windows/templates/raylib/raylib_boom.wav new file mode 100644 index 00000000..fd18137d Binary files /dev/null and b/windows/templates/raylib/raylib_boom.wav differ diff --git a/windows/templates/raylib/raylib_c.txt b/windows/templates/raylib/raylib_c.txt new file mode 100644 index 00000000..1da79751 --- /dev/null +++ b/windows/templates/raylib/raylib_c.txt @@ -0,0 +1,124 @@ +/******************************************************************************************* +* +* raylib [textures] example - sprite explosion +* +* This example has been created using raylib 2.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2019 Anata and Ramon Santamaria (@raysan5) +* Copyright (c) 2022 Roy Qu (royqh1979@gmail.com) +* +********************************************************************************************/ + +#include + +#define NUM_FRAMES_PER_LINE 5 +#define NUM_LINES 5 + +int main(void) +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [textures] example - sprite explosion"); + + InitAudioDevice(); + + // Load explosion sound + Sound fxBoom = LoadSound("boom.wav"); + + // Load explosion texture + Texture2D explosion = LoadTexture("explosion.png"); + + // Init variables for animation + float frameWidth = (float)(explosion.width/NUM_FRAMES_PER_LINE); // Sprite one frame rectangle width + float frameHeight = (float)(explosion.height/NUM_LINES); // Sprite one frame rectangle height + int currentFrame = 0; + int currentLine = 0; + + Rectangle frameRec = { 0, 0, frameWidth, frameHeight }; + Vector2 position = { 0.0f, 0.0f }; + + bool active = false; + int framesCounter = 0; + + SetTargetFPS(120); + SetTraceLogLevel(LOG_WARNING); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + + // Check for mouse button pressed and activate explosion (if not active) + if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT) ) + { + position = GetMousePosition(); + active = true; + + position.x -= frameWidth/2.0f; + position.y -= frameHeight/2.0f; + + PlaySound(fxBoom); + } + + // Compute explosion animation frames + if (active) + { + framesCounter++; + + if (framesCounter > 2) + { + currentFrame++; + + if (currentFrame >= NUM_FRAMES_PER_LINE) + { + currentFrame = 0; + currentLine++; + + if (currentLine >= NUM_LINES) + { + currentLine = 0; + active = false; + } + } + + framesCounter = 0; + } + } + + frameRec.x = frameWidth*currentFrame; + frameRec.y = frameHeight*currentLine; + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + // Draw explosion required frame rectangle + if (active) DrawTextureRec(explosion, frameRec, position, WHITE); + + DrawText("Click to explode!", 440, 400, 40, DARKGRAY); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + UnloadTexture(explosion); // Unload texture + UnloadSound(fxBoom); // Unload sound + + CloseAudioDevice(); + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/windows/templates/raylib/raylib_explosion.png b/windows/templates/raylib/raylib_explosion.png new file mode 100644 index 00000000..6df1cf36 Binary files /dev/null and b/windows/templates/raylib/raylib_explosion.png differ diff --git a/windows/templates/rdrawing-colors/info.template b/windows/templates/rdrawing-colors/info.template new file mode 100644 index 00000000..24e69956 --- /dev/null +++ b/windows/templates/rdrawing-colors/info.template @@ -0,0 +1,21 @@ +[Template] +ver=2 +Name=Colors +Name[zh_CN]=色彩常量 +Icon=rdrawing_colors.ico +Description=Demo for raylib & rdrawing color constants, and raygui scroll panel +Description[zh_CN]=演示raylib/rdrawing色彩常量和raygui滚动面板使用的示例程序 +Category=Multimedia +Category[zh_CN]=多媒体 + +[Unit0] +CName=main.c +C=rdrawing_colors_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lrdrawing -lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 + diff --git a/windows/templates/rdrawing-colors/rdrawing_colors.ico b/windows/templates/rdrawing-colors/rdrawing_colors.ico new file mode 100644 index 00000000..000c4907 Binary files /dev/null and b/windows/templates/rdrawing-colors/rdrawing_colors.ico differ diff --git a/windows/templates/rdrawing-colors/rdrawing_colors_c.txt b/windows/templates/rdrawing-colors/rdrawing_colors_c.txt new file mode 100644 index 00000000..0d9a36ca --- /dev/null +++ b/windows/templates/rdrawing-colors/rdrawing_colors_c.txt @@ -0,0 +1,350 @@ +#include +#include +#include + +#define RAYGUI_IMPLEMENTATION +#include + +//color classification from https://www.dofactory.com/css/color-names + +enum ColorPage{ + Red, + Pink, + Orange, + Yellow, + Green, + Blue, + Brown, + Purple, + Light, + Gray +} ; + +void drawRedColors(Image *pImg,Font font); +void drawPinkColors(Image *pImg,Font font); +void drawOrangeColors(Image *pImg,Font font); +void drawYellowColors(Image *pImg,Font font); +void drawGreenColors(Image *pImg,Font font); +void drawBlueColors(Image *pImg,Font font); +void drawBrownColors(Image *pImg,Font font); +void drawPurpleColors(Image *pImg,Font font); +void drawLightColors(Image *pImg,Font font); +void drawGrayColors(Image *pImg,Font font); + +int main() { + int currentPage=Red; + InitWindow(1000,900,"Rdrawing Predefined Colors"); + SetTraceLogLevel(LOG_WARNING); + SetTargetFPS(60); + bool fontChanged=false; + Font font; + if (FileExists("C:\\windows\\fonts\\cour.ttf")) { + font=LoadFont("C:\\windows\\fonts\\cour.ttf"); + fontChanged=true; + } else { + font=GetFontDefault(); + } + GuiSetStyle(DEFAULT,TEXT_SIZE,20); + GuiSetStyle(LISTVIEW,SCROLLBAR_WIDTH,20); + + Image img=GenImageColor(830,890,WHITE); + Rectangle panelRec = {165,5,830,890}; + Rectangle panelContentRec = {0,0,800,1190}; + Vector2 panelScroll = {1,1}; + while(!WindowShouldClose()) { + Texture texture; + BeginDrawing(); + if (GuiToggle((Rectangle){ 10, 10, 140, 30 },"Red",currentPage==Red)) { + currentPage=Red; + } + if (GuiToggle((Rectangle){ 10, 50, 140, 30 },"Pink",currentPage==Pink)) { + currentPage=Pink; + } + if (GuiToggle((Rectangle){ 10, 90, 140, 30 },"Orange",currentPage==Orange)) { + currentPage=Orange; + } + if (GuiToggle((Rectangle){ 10, 130, 140, 30 },"Yellow",currentPage==Yellow)) { + currentPage=Yellow; + } + if (GuiToggle((Rectangle){ 10, 170, 140, 30 },"Green",currentPage==Green)) { + panelContentRec = (Rectangle){0,0, + 830- 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - GuiGetStyle(LISTVIEW, SCROLLBAR_WIDTH), + 1170}; + if (currentPage!=Green) { + panelScroll=(Vector2){1,1}; + } + currentPage=Green; + } + if (GuiToggle((Rectangle){ 10, 210, 140, 30 },"Blue",currentPage==Blue)) { + panelContentRec = (Rectangle){0,0, + 830- 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - GuiGetStyle(LISTVIEW, SCROLLBAR_WIDTH), + 1220}; + if (currentPage!=Blue) { + panelScroll=(Vector2){1,1}; + } + currentPage=Blue; + } + if (GuiToggle((Rectangle){ 10, 250, 140, 30 },"Brown",currentPage==Brown)) { + currentPage=Brown; + } + if (GuiToggle((Rectangle){ 10, 290, 140, 30 },"Purple",currentPage==Purple)) { + currentPage=Purple; + } + if (GuiToggle((Rectangle){ 10, 330, 140, 30 },"Light",currentPage==Light)) { + currentPage=Light; + } + if (GuiToggle((Rectangle){ 10, 370, 140, 30 },"Gray",currentPage==Gray)) { + currentPage=Gray; + } + ImageClearBackground(&img,WHITE); + switch(currentPage) { + case Red: + drawRedColors(&img,font); + texture = LoadTextureFromImage(img); + break; + case Pink: + drawPinkColors(&img,font); + texture = LoadTextureFromImage(img); + break; + case Orange: + drawOrangeColors(&img,font); + texture = LoadTextureFromImage(img); + break; + case Yellow: + drawYellowColors(&img,font); + texture = LoadTextureFromImage(img); + break; + case Green: { + Rectangle view = GuiScrollPanel(panelRec,NULL,panelContentRec,&panelScroll); + Image tmpImage = GenImageColor(830,1170,WHITE); + Image tmpImage2 = GenImageColor(view.width,view.height,WHITE); + drawGreenColors(&tmpImage,font); + ImageDraw(&tmpImage2,tmpImage, + (Rectangle){view.x-panelRec.x-panelScroll.x,view.y-panelRec.y-panelScroll.y,view.width,view.height}, + (Rectangle){0,0,view.width,view.height},WHITE); + texture = LoadTextureFromImage(tmpImage2); + UnloadImage(tmpImage2); + UnloadImage(tmpImage); + } + break; + case Blue: { + Rectangle view = GuiScrollPanel(panelRec,NULL,panelContentRec,&panelScroll); + Image tmpImage = GenImageColor(830,1220,WHITE); + Image tmpImage2 = GenImageColor(view.width,view.height,WHITE); + drawBlueColors(&tmpImage,font); + ImageDraw(&tmpImage2,tmpImage, + (Rectangle){view.x-panelRec.x-panelScroll.x,view.y-panelRec.y-panelScroll.y,view.width,view.height}, + (Rectangle){0,0,view.width,view.height},WHITE); + texture = LoadTextureFromImage(tmpImage2); + UnloadImage(tmpImage2); + UnloadImage(tmpImage); + } + break; + case Brown: + drawBrownColors(&img,font); + texture = LoadTextureFromImage(img); + break; + case Purple: + drawPurpleColors(&img,font); + texture = LoadTextureFromImage(img); + break; + case Light: + drawLightColors(&img,font); + texture = LoadTextureFromImage(img); + break; + case Gray: + drawGrayColors(&img,font); + texture = LoadTextureFromImage(img); + break; + } + ClearBackground(LIGHTGRAY); + DrawTexture(texture,165,5,WHITE); + EndDrawing(); + UnloadTexture(texture); + } + + if (fontChanged) { + UnloadFont(font); + } + //Clean up + UnloadImage(img); + CloseWindow(); +} + +void drawColor(Image* pImg, Font font, int x, int y, Color color, const char* colorName) { + char buffer[255]; + ImageFillRectangleEx(pImg,x,y,200,40,color); + ImageDrawRectangleEx(pImg,x,y,200,40,2,BLACK); + ImageDrawTextEx(pImg,font,colorName,(Vector2){x+230,y+10},20,1,BLACK); + sprintf(buffer,"0x%02X%02X%02X",color.r,color.g,color.b); + ImageDrawTextEx(pImg,font,buffer,(Vector2){x+600,y+10},20,1,BLACK); +} + +void drawRedColors(Image *pImg,Font font) { + drawColor(pImg,font,50,20,LIGHTSALMON,"LIGHTSALMON"); + drawColor(pImg,font,50,70,DARKSALMON,"DARKSALMON"); + drawColor(pImg,font,50,120,SALMON,"SALMON"); + drawColor(pImg,font,50,170,LIGHTCORAL,"LIGHTCORAL"); + drawColor(pImg,font,50,220,INDIANRED,"INDIANRED"); + drawColor(pImg,font,50,270,RED,"RED"); + drawColor(pImg,font,50,320,CRIMSON,"CRIMSON"); + drawColor(pImg,font,50,370,MAROON,"MAROON"); + drawColor(pImg,font,50,420,FIREBRICK,"FIREBRICK"); + drawColor(pImg,font,50,470,DARKRED,"DARKRED"); +} + +void drawPinkColors(Image *pImg,Font font) { + drawColor(pImg,font,50,20,PINK,"PINK"); + drawColor(pImg,font,50,70,LIGHTPINK,"LIGHTPINK"); + drawColor(pImg,font,50,120,HOTPINK,"HOTPINK"); + drawColor(pImg,font,50,170,DEEPPINK,"DEEPPINK"); + drawColor(pImg,font,50,220,PALEVIOLETRED,"PALEVIOLETRED"); + drawColor(pImg,font,50,270,MEDIUMVIOLETRED,"MEDIUMVIOLETRED"); +} + +void drawOrangeColors(Image *pImg,Font font) { + drawColor(pImg,font,50,20,GOLD,"GOLD"); + drawColor(pImg,font,50,70,ORANGE,"ORANGE"); + drawColor(pImg,font,50,120,DARKORANGE,"DARKORANGE"); + drawColor(pImg,font,50,170,LIGHTSALMON,"LIGHTSALMON"); + drawColor(pImg,font,50,220,CORAL,"CORAL"); + drawColor(pImg,font,50,270,TOMATO,"TOMATO"); + drawColor(pImg,font,50,320,ORANGERED,"ORANGERED"); +} + +void drawYellowColors(Image* pImg, Font font) { + drawColor(pImg,font,50,20,LIGHTYELLOW,"LIGHTYELLOW"); + drawColor(pImg,font,50,70,LEMONCHIFFON,"LEMONCHIFFON"); + drawColor(pImg,font,50,120,LIGHTGOLDENRODYELLOW,"LIGHTGOLDENRODYELLOW"); + drawColor(pImg,font,50,170,YELLOW,"YELLOW"); + drawColor(pImg,font,50,220,PAPAYAWHIP,"PAPAYAWHIP"); + drawColor(pImg,font,50,270,MOCCASIN,"MOCCASIN"); + drawColor(pImg,font,50,320,PEACHPUFF,"PEACHPUFF"); + drawColor(pImg,font,50,370,PALEGOLDENROD,"PALEGOLDENROD"); + drawColor(pImg,font,50,420,KHAKI,"KHAKI"); + drawColor(pImg,font,50,470,DARKKHAKI,"DARKKHAKI"); +} + +void drawGreenColors(Image* pImg, Font font) { + drawColor(pImg,font,50,20,GREENYELLOW,"GREENYELLOW"); + drawColor(pImg,font,50,70,CHARTREUSE,"CHARTREUSE"); + drawColor(pImg,font,50,120,LAWNGREEN,"LAWNGREEN"); + drawColor(pImg,font,50,170,LIME,"LIME"); + drawColor(pImg,font,50,220,PALEGREEN,"PALEGREEN"); + drawColor(pImg,font,50,270,LIGHTGREEN,"LIGHTGREEN"); + drawColor(pImg,font,50,320,SPRINGGREEN,"SPRINGGREEN"); + drawColor(pImg,font,50,370,MEDIUMSPRINGGREEN,"MEDIUMSPRINGGREEN"); + drawColor(pImg,font,50,420,LIMEGREEN,"LIMEGREEN"); + drawColor(pImg,font,50,470,MEDIUMSEAGREEN,"MEDIUMSEAGREEN"); + drawColor(pImg,font,50,520,SEAGREEN,"SEAGREEN"); + drawColor(pImg,font,50,570,FORESTGREEN,"FORESTGREEN"); + drawColor(pImg,font,50,620,GREEN,"GREEN"); + drawColor(pImg,font,50,670,DARKGREEN,"DARKGREEN"); + drawColor(pImg,font,50,720,YELLOWGREEN,"YELLOWGREEN"); + drawColor(pImg,font,50,770,OLIVEDRAB,"OLIVEDRAB"); + drawColor(pImg,font,50,820,OLIVE,"OLIVE"); + drawColor(pImg,font,50,870,DARKOLIVEGREEN,"DARKOLIVEGREEN"); + drawColor(pImg,font,50,920,MEDIUMAQUAMARINE,"MEDIUMAQUAMARINE"); + drawColor(pImg,font,50,970,DARKSEAGREEN,"DARKSEAGREEN"); + drawColor(pImg,font,50,1020,LIGHTSEAGREEN,"LIGHTSEAGREEN"); + drawColor(pImg,font,50,1070,DARKCYAN,"DARKCYAN"); + drawColor(pImg,font,50,1120,TEAL,"TEAL"); +} + +void drawBlueColors(Image* pImg, Font font) { + drawColor(pImg,font,50,20,LIGHTCYAN,"LIGHTCYAN"); + drawColor(pImg,font,50,70,CYAN,"AQUA / CYAN"); + drawColor(pImg,font,50,120,AQUAMARINE,"AQUAMARINE"); + drawColor(pImg,font,50,170,PALETURQUOISE,"PALETURQUOISE"); + drawColor(pImg,font,50,220,TURQUOISE,"TURQUOISE"); + drawColor(pImg,font,50,270,MEDIUMTURQUOISE,"MEDIUMTURQUOISE"); + drawColor(pImg,font,50,320,DARKTURQUOISE,"DARKTURQUOISE"); + drawColor(pImg,font,50,370,CADETBLUE,"CADETBLUE"); + drawColor(pImg,font,50,420,STEELBLUE,"STEELBLUE"); + drawColor(pImg,font,50,470,LIGHTSTEELBLUE,"LIGHTSTEELBLUE"); + drawColor(pImg,font,50,520,POWDERBLUE,"POWDERBLUE"); + drawColor(pImg,font,50,570,LIGHTBLUE,"LIGHTBLUE"); + drawColor(pImg,font,50,620,SKYBLUE,"SKYBLUE"); + drawColor(pImg,font,50,670,LIGHTSKYBLUE,"LIGHTSKYBLUE"); + drawColor(pImg,font,50,720,DEEPSKYBLUE,"BEEPSKYBLUE"); + drawColor(pImg,font,50,770,DODGERBLUE,"DODGERBLUE"); + drawColor(pImg,font,50,820,CORNFLOWERBLUE,"CORNFLOWERBLUE"); + drawColor(pImg,font,50,870,MEDIUMSLATEBLUE,"MEDIUMSLATEBLUE"); + drawColor(pImg,font,50,920,ROYALBLUE,"ROYALBLUE"); + drawColor(pImg,font,50,970,BLUE,"BLUE"); + drawColor(pImg,font,50,1020,MEDIUMBLUE,"MEDIUMBLUE"); + drawColor(pImg,font,50,1070,DARKBLUE,"DARKBLUE"); + drawColor(pImg,font,50,1120,NAVY,"NAVY"); + drawColor(pImg,font,50,1170,MIDNIGHTBLUE,"MIDNIGHTBLUE"); +} + +void drawBrownColors(Image *pImg,Font font) { + drawColor(pImg,font,50,20,CORNSILK,"CORNSILK"); + drawColor(pImg,font,50,70,BLANCHEDALMOND,"BLANCHEDALMOND"); + drawColor(pImg,font,50,120,BISQUE,"BISQUE"); + drawColor(pImg,font,50,170,NAVAJOWHITE,"NAVAJOWHITE"); + drawColor(pImg,font,50,220,WHEAT,"WHEAT"); + drawColor(pImg,font,50,270,BURLYWOOD,"BURLYWOOD"); + drawColor(pImg,font,50,320,TAN,"TAN"); + drawColor(pImg,font,50,370,GOLDENROD,"GOLDENROD"); + drawColor(pImg,font,50,420,DARKGOLDENROD,"DARKGOLDENROD"); + drawColor(pImg,font,50,470,ROSYBROWN,"ROSYBROWN"); + drawColor(pImg,font,50,520,SANDYBROWN,"SANDYBROWN"); + drawColor(pImg,font,50,570,BEIGE,"BEIGE"); + drawColor(pImg,font,50,620,PERU,"PERU"); + drawColor(pImg,font,50,670,CHOCOLATE,"CHOCOLATE"); + drawColor(pImg,font,50,720,SIENNA,"SIENNA"); + drawColor(pImg,font,50,770,SADDLEBROWN,"SADDLEBROWN"); + drawColor(pImg,font,50,820,BROWN,"BROWN"); +} + +void drawPurpleColors(Image *pImg,Font font) { + drawColor(pImg,font,50,20,LAVENDER,"LAVENDER"); + drawColor(pImg,font,50,70,THISTLE,"THISTLE"); + drawColor(pImg,font,50,120,PLUM,"PLUM"); + drawColor(pImg,font,50,170,VIOLET,"VIOLET"); + drawColor(pImg,font,50,220,ORCHID,"ORCHID"); + drawColor(pImg,font,50,270,FUCHSIA,"FUCHSIA / MAGENTA"); + drawColor(pImg,font,50,320,MEDIUMORCHID,"MEDIUMORCHID"); + drawColor(pImg,font,50,370,BLUEVIOLET,"BLUEVIOLET"); + drawColor(pImg,font,50,420,DARKVIOLET,"DARKVIOLET"); + drawColor(pImg,font,50,470,DARKORCHID,"DARKORCHID"); + drawColor(pImg,font,50,520,DARKMAGENTA,"DARKMAGENTA"); + drawColor(pImg,font,50,570,PURPLE,"PURPLE"); + drawColor(pImg,font,50,620,INDIGO,"INDIGO"); + drawColor(pImg,font,50,670,MEDIUMSLATEBLUE,"MEDIUMSLATEBLUE"); + drawColor(pImg,font,50,720,SLATEBLUE,"SLATEBLUE"); + drawColor(pImg,font,50,770,DARKSLATEBLUE,"DARKSLATEBLUE"); +} + +void drawLightColors(Image *pImg,Font font) { + drawColor(pImg,font,50,20,WHITE,"WHITE"); + drawColor(pImg,font,50,70,SNOW,"SNOW"); + drawColor(pImg,font,50,120,FLORALWHITE,"FLORALWHITE"); + drawColor(pImg,font,50,170,IVORY,"IVORY"); + drawColor(pImg,font,50,220,HONEYDEW,"HONEYDEW"); + drawColor(pImg,font,50,270,MINTCREAM,"MINTCREAM"); + drawColor(pImg,font,50,320,AZURE,"AZURE"); + drawColor(pImg,font,50,370,ALICEBLUE,"ALICEBLUE"); + drawColor(pImg,font,50,420,GHOSTWHITE,"GHOSTWHITE"); + drawColor(pImg,font,50,470,WHITESMOKE,"WHITESMOKE"); + drawColor(pImg,font,50,520,SEASHELL,"SEASHELL"); + drawColor(pImg,font,50,570,OLDLACE,"OLDLACE"); + drawColor(pImg,font,50,620,ANTIQUEWHITE,"ANTIQUEWHITE"); + drawColor(pImg,font,50,670,LINEN,"LINEN"); + drawColor(pImg,font,50,720,LAVENDERBLUSH,"LAVENDERBLUSH"); + drawColor(pImg,font,50,770,MISTYROSE,"MISTYROSE"); +} + +void drawGrayColors(Image *pImg,Font font) { + drawColor(pImg,font,50,20,GAINSBORO,"GAINSBORO"); + drawColor(pImg,font,50,70,LIGHTGRAY,"LIGHTGRAY"); + drawColor(pImg,font,50,120,SILVER,"SILVER"); + drawColor(pImg,font,50,170,DARKGRAY,"DARKGRAY"); + drawColor(pImg,font,50,220,GRAY,"GRAY"); + drawColor(pImg,font,50,270,DIMGRAY,"DIMGRAY"); + drawColor(pImg,font,50,320,LIGHTSLATEGRAY,"LIGHTSLATEGRAY"); + drawColor(pImg,font,50,370,SLATEGRAY,"SLATEGRAY"); + drawColor(pImg,font,50,420,DARKSLATEGRAY,"DARKSLATEGRAY"); + drawColor(pImg,font,50,470,BLACK,"BLACK"); +} \ No newline at end of file diff --git a/windows/templates/rdrawing-doraemon/info.template b/windows/templates/rdrawing-doraemon/info.template new file mode 100644 index 00000000..6d9ca521 --- /dev/null +++ b/windows/templates/rdrawing-doraemon/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=Doraemon +Name[zh_CN]=哆啦A梦 +Icon=rdrawing-doraemon.ico +Description=A simple doraemon app using rdrawing (https://github.com/royqh1979/raylib-drawing) +Description[zh_CN]=使用rdrawing制作的哆啦A梦 (https://github.com/royqh1979/raylib-drawing) +Category=Game +Category[zh_CN]=游戏 + +[Unit0] +CName=main.c +C=rdrawing_doraemon_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lrdrawing -lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 diff --git a/windows/templates/rdrawing-doraemon/rdrawing-doraemon.ico b/windows/templates/rdrawing-doraemon/rdrawing-doraemon.ico new file mode 100644 index 00000000..e55edf0a Binary files /dev/null and b/windows/templates/rdrawing-doraemon/rdrawing-doraemon.ico differ diff --git a/windows/templates/rdrawing-doraemon/rdrawing_doraemon_c.txt b/windows/templates/rdrawing-doraemon/rdrawing_doraemon_c.txt new file mode 100644 index 00000000..d5e0e985 --- /dev/null +++ b/windows/templates/rdrawing-doraemon/rdrawing_doraemon_c.txt @@ -0,0 +1,246 @@ +#include +#include +#include + +#define SHRINK_FRAMES 2 + +Image genBodyImage(); +Image genShrinkImage0(); +Image genShrinkImage1(); +Image genShrinkImage2(); +Image genShrinkImage3(); +Image genShrinkImage4(); + +int main() { + InitWindow(800,600,"Doraemon"); + SetTraceLogLevel(LOG_WARNING); + SetTargetFPS(30); + + SetRandomSeed(time(NULL)); + + Image img=genBodyImage(); + Image shrinkImages[9]; + shrinkImages[0]=genShrinkImage0(); + shrinkImages[1]=genShrinkImage1(); + shrinkImages[2]=genShrinkImage2(); + shrinkImages[3]=genShrinkImage3(); + shrinkImages[4]=genShrinkImage4(); + shrinkImages[5]=genShrinkImage3(); + shrinkImages[6]=genShrinkImage2(); + shrinkImages[7]=genShrinkImage1(); + shrinkImages[8]=genShrinkImage0(); + + Texture texture = LoadTextureFromImage(img); + Texture shrinkTexture; + int stage = -1; + int repeats = 0; + + while(!WindowShouldClose()) { + if (stage==-1) { + int r = GetRandomValue(1,30); + if (r==1) { + stage=0; + repeats=0; + } + } + int idx=0; + if (stage>=0) { + idx=stage / SHRINK_FRAMES; + if (idx<9) { + shrinkTexture=LoadTextureFromImage(shrinkImages[idx]); + } else { + idx=0; + stage=0; + repeats++; + if (repeats>=3) + stage=-1; + } + } + if (stage>=0) { + stage++; + } + + BeginDrawing(); + ClearBackground(WHITE); + DrawTexture(texture,0,0,WHITE); + DrawTexture(shrinkTexture,0,0,WHITE); + EndDrawing(); + UnloadTexture(shrinkTexture); + } + + //Clean up + UnloadTexture(texture); + UnloadImage(img); + for (int i=0;i<9;i++) { + UnloadImage(shrinkImages[i]); + } + CloseWindow(); +} + +Image genBodyImage(){ + Image img=GenImageColor(800,600,WHITE); + // 画头 + Color fillColor = (Color){7,190,234,255}; + Color color=BLACK; + ImageFillRoundRectEx(&img,265, 94, 270, 260, 124, 124,fillColor); + ImageDrawRoundRectEx(&img,265, 94, 270, 260, 124, 124,1,color); + + fillColor = WHITE; // 脸 + ImageFillEllipseEx(&img, 400, 256, 115, 95, fillColor); + + ImageFillRoundRectEx(&img,337, 131, 63, 74, 28, 28, fillColor); // 右眼 + ImageDrawRoundRectEx(&img,337, 131, 63, 74, 28, 28,1, color); + ImageFillRoundRectEx(&img,400, 131, 63, 74, 28, 28, fillColor); // 左眼 + ImageDrawRoundRectEx(&img,400, 131, 63, 74, 28, 28,1, color); + + fillColor = BLACK; + ImageFillCircleEx(&img,384,184,6, fillColor); // 右眼球 + ImageFillCircleEx(&img,416,184,6, fillColor); // 左眼球 + + fillColor = (Color){201, 62, 0, 255}; // 鼻子 + ImageFillCircleEx(&img, 400, 208, 15, fillColor); + + ImageDrawLineEx(&img,400,223,400,296,1,color); // 人中 + ImageDrawArcEx(&img,400, 192, 108, 108, PI * 5 / 4, PI * 7 / 4,1,color); // 嘴 + + ImageDrawLineEx(&img,358, 227, 310, 209,1,color); // 胡子 + ImageDrawLineEx(&img,442, 227, 490, 209,1,color); + ImageDrawLineEx(&img,359, 235, 308, 235,1,color); + ImageDrawLineEx(&img,441, 235, 492, 235,1,color); + ImageDrawLineEx(&img,358, 243, 310, 261,1,color); + ImageDrawLineEx(&img,442, 243, 490, 261,1,color); + + // 画身体 + ImageDrawLineEx(&img, 319, 332, 262, 372,1,color); // 手臂(上) + ImageDrawLineEx(&img, 481, 332, 538, 372,1,color); + ImageDrawLineEx(&img, 304, 396, 284, 410,1,color); // 手臂(下) + ImageDrawLineEx(&img, 496, 396, 516, 410,1,color); + + ImageDrawLineEx(&img, 304, 385, 304, 478,1,color); // 腿外侧 + ImageDrawLineEx(&img, 496, 385, 496, 478,1,color); + ImageDrawArcEx(&img, 400, 479, 15,11,0,PI,1,color); // 腿内侧 + + fillColor=WHITE; // 手 + ImageFillCircleEx(&img, 260,399,27, fillColor); + ImageDrawCircleEx(&img, 260,399,27, 1, color); + ImageFillCircleEx(&img, 540,399,27, fillColor); + ImageDrawCircleEx(&img, 540,399,27, 1, color); + ImageFillRoundRectEx(&img,288,478,110,27,12,12,fillColor); // 脚 + ImageDrawRoundRectEx(&img,288,478,110,27,12,12,1,color); + ImageFillRoundRectEx(&img,402,478,110,27,12,12,fillColor); + ImageDrawRoundRectEx(&img,402,478,110,27,12,12,1,color); + + fillColor=(Color){7,190,234,255}; // 身体填充蓝色 + ImageFloodFill(&img,400,400,BLACK,fillColor); + + fillColor=WHITE; // 肚皮 + ImageFillCircleEx(&img,400,381,75,fillColor); + ImageFillRectangleEx(&img,340,304,120,20,fillColor); // 用白色矩形擦掉多余的肚皮 + + ImageDrawSectorEx(&img,400,381,58, 58,PI,2*PI,1,color); // 口袋 + + // 画铃铛 + fillColor=(Color){169, 38, 0,255}; // 绳子 + ImageFillRoundRectEx(&img,300,323,200,19,12,12,fillColor); + + fillColor=(Color){245, 237, 38,255}; // 铃铛外形 + ImageFillCircleEx(&img,400,349,19,fillColor); + + fillColor=BLACK; // 铃铛上的洞 + ImageFillEllipseEx(&img,400,354,4,4,fillColor); + ImageDrawLineEx(&img,400,357,400,368,3,color); + + ImageDrawLineEx(&img,384,340,416,340,1,color); // 铃铛上的纹路 + ImageDrawLineEx(&img,384,344,418,344,1,color); + return img; +} + +Image genShrinkImage0() { + Image img = GenImageColor(800,600, BLANK); + Color fillColor=WHITE; + Color color=BLACK; + ImageFillRoundRectEx(&img,337, 131, 63, 74, 28, 28, fillColor); // 右眼 + ImageFillRoundRectEx(&img,400, 131, 63, 74, 28, 28, fillColor); // 左眼 + ImageDrawRoundRectEx(&img,337, 131, 63, 74, 28, 28,1, color); + ImageDrawRoundRectEx(&img,400, 131, 63, 74, 28, 28,1, color); + + fillColor = BLACK; + ImageFillCircleEx(&img,384,184,6, fillColor); // 右眼球 + ImageFillCircleEx(&img,416,184,6, fillColor); // 左眼球 + fillColor = (Color){201, 62, 0, 255}; // 鼻子 + ImageFillCircleEx(&img, 400, 208, 15, fillColor); + return img; +} + +Image genShrinkImage1() { + Image img = GenImageColor(800,600, BLANK); + Color fillColor=WHITE; + Color color=BLACK; + ImageFillRoundRectEx(&img,337, 131, 63, 74, 28, 28, fillColor); // 右眼 + ImageFillRoundRectEx(&img,400, 131, 63, 74, 28, 28, fillColor); // 左眼 + ImageDrawRoundRectEx(&img,337, 150, 63, 37, 28, 28, 1, color); + ImageDrawRoundRectEx(&img,400, 150, 63, 37, 28, 28, 1, color); + + ImageFillRectangleEx(&img,337,168,63,19,fillColor); + ImageFillRectangleEx(&img,400,168,63,19,fillColor); + + ImageDrawRoundRectEx(&img,337, 131, 63, 74, 28, 28,1, color); + ImageDrawRoundRectEx(&img,400, 131, 63, 74, 28, 28,1, color); + + fillColor = BLACK; + ImageFillCircleEx(&img,384,184,6, fillColor); // 右眼球 + ImageFillCircleEx(&img,416,184,6, fillColor); // 左眼球 + fillColor = (Color){201, 62, 0, 255}; // 鼻子 + ImageFillCircleEx(&img, 400, 208, 15, fillColor); + return img; +} + +Image genShrinkImage2() { + Image img=GenImageColor(800,600,BLANK); + Color fillColor=WHITE; + Color color=BLACK; + ImageFillRoundRectEx(&img,337, 131, 63, 74, 28, 28, fillColor); // 右眼 + ImageFillRoundRectEx(&img,400, 131, 63, 74, 28, 28, fillColor); // 左眼 + + ImageDrawLineEx(&img,337,168,399,168,1,color); + ImageDrawLineEx(&img,400,168,462,168,1,color); + + ImageDrawRoundRectEx(&img,337, 131, 63, 74, 28, 28,1, color); + ImageDrawRoundRectEx(&img,400, 131, 63, 74, 28, 28,1, color); + fillColor = (Color){201, 62, 0, 255}; // 鼻子 + ImageFillCircleEx(&img, 400, 208, 15, fillColor); + return img; +} + +Image genShrinkImage3(){ + Image img=GenImageColor(800,600,BLANK); + Color fillColor=WHITE; + Color color=BLACK; + ImageFillRoundRectEx(&img,337, 131, 63, 74, 28, 28, fillColor); // 右眼 + ImageFillRoundRectEx(&img,400, 131, 63, 74, 28, 28, fillColor); // 左眼 + ImageDrawRoundRectEx(&img,337, 150, 63, 37, 28, 28, 1, color); + ImageDrawRoundRectEx(&img,400, 150, 63, 37, 28, 28, 1, color); + + ImageFillRectangleEx(&img,337,150,63,19,fillColor); + ImageFillRectangleEx(&img,400,150,63,19,fillColor); + + ImageDrawRoundRectEx(&img,337, 131, 63, 74, 28, 28,1, color); + ImageDrawRoundRectEx(&img,400, 131, 63, 74, 28, 28,1, color); + fillColor = (Color){201, 62, 0, 255}; // 鼻子 + ImageFillCircleEx(&img, 400, 208, 15, fillColor); + return img; +} + +Image genShrinkImage4() { + Image img=GenImageColor(800,600,BLANK); + Color fillColor=WHITE; + Color color=BLACK; + ImageFillRoundRectEx(&img,337, 131, 63, 74, 28, 28, fillColor); // 右眼 + ImageFillRoundRectEx(&img,400, 131, 63, 74, 28, 28, fillColor); // 左眼 + + ImageDrawRoundRectEx(&img,337, 131, 63, 74, 28, 28,1, color); + ImageDrawRoundRectEx(&img,400, 131, 63, 74, 28, 28,1, color); + fillColor = (Color){201, 62, 0, 255}; // 鼻子 + ImageFillCircleEx(&img, 400, 208, 15, fillColor); + return img; +} diff --git a/windows/templates/rdrawing/info.template b/windows/templates/rdrawing/info.template new file mode 100644 index 00000000..6b0a2a04 --- /dev/null +++ b/windows/templates/rdrawing/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=rdrawing +Name[zh_CN]=rdrawing +Icon=rdrawing.ico +Description=A simple 2d drawing app using raylib and rdrawing +Description[zh_CN]=基于raylib和rdrawing的2维绘图程序 (https://github.com/royqh1979/raylib-drawing) +Category=Multimedia +Category[zh_CN]=多媒体 + +[Unit0] +CName=main.c +C=rdrawing_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lrdrawing -lraylib -lopengl32 -lgdi32 -lwinmm +ExecEncoding=UTF-8 diff --git a/windows/templates/rdrawing/rdrawing.ico b/windows/templates/rdrawing/rdrawing.ico new file mode 100644 index 00000000..054968fd Binary files /dev/null and b/windows/templates/rdrawing/rdrawing.ico differ diff --git a/windows/templates/rdrawing/rdrawing_c.txt b/windows/templates/rdrawing/rdrawing_c.txt new file mode 100644 index 00000000..d5f89184 --- /dev/null +++ b/windows/templates/rdrawing/rdrawing_c.txt @@ -0,0 +1,48 @@ +#include +#include +#include + + +void paintstar(Image* pImage, double x, double y, double r, double a) +{ + int vx[5]; + int vy[5]; + for (int i = 0; i < 5; ++i) + { + vx[i] = (int)( -cos( PI * 4 / 5 * i + a ) * r + x ); + vy[i] = (int)( sin( PI * 4 / 5 * i + a) * r + y ); + } + ImageFillPolygonEx(pImage,vx,vy,5,LIGHTRED); + ImageDrawPolygonEx(pImage,vx,vy,5,2,DARKBROWN); +} + +int main() { + InitWindow(640,480,"rdrawing"); + SetTraceLogLevel(LOG_WARNING); + SetTargetFPS(60); + + Image img=GenImageColor(640,480,BLANK); + + double r = 0; + while(!WindowShouldClose()) { + //update datas + r += 0.02; + if (r > PI * 2) r -= PI * 2; + + //update image (in CPU) + ImageClearBackground(&img,BLANK); + paintstar(&img,320,240,200,r); + + //Drawing in GPU + Texture texture = LoadTextureFromImage(img); + BeginDrawing(); + ClearBackground(WHITE); + DrawTexture(texture,0,0,WHITE); + EndDrawing(); + UnloadTexture(texture); + } + + //Clean up + UnloadImage(img); + CloseWindow(); +} \ No newline at end of file diff --git a/windows/templates/sqlite/info.template b/windows/templates/sqlite/info.template new file mode 100644 index 00000000..10b0ded4 --- /dev/null +++ b/windows/templates/sqlite/info.template @@ -0,0 +1,19 @@ +[Template] +ver=2 +Name=Sqlite3 +Icon=sqlite.ico +Description=A Sqlite3 API Example +Description[zh_CN]=Sqlite3 示例程序 +Category=Database +Category[zh_CN]=数据库 + +[Unit0] +CName=main.c +C=sqlite_c.txt + +[Project] +UnitCount=1 +Type=1 +Compiler= +CppCompiler= +Linker=-lsqlite3 diff --git a/windows/templates/sqlite/sqlite.ico b/windows/templates/sqlite/sqlite.ico new file mode 100644 index 00000000..2d8f08a1 Binary files /dev/null and b/windows/templates/sqlite/sqlite.ico differ diff --git a/windows/templates/sqlite/sqlite_c.txt b/windows/templates/sqlite/sqlite_c.txt new file mode 100644 index 00000000..9e16ea19 --- /dev/null +++ b/windows/templates/sqlite/sqlite_c.txt @@ -0,0 +1,106 @@ +/* +An API demo of sqlite3 +author: Ady Liu +email: imxylz@gmail.com +web: http://www.blogjava.net/xylz/archive/2012/09/25/388519.html +*/ +#include +#include +#include + +int print_record(void *,int,char **,char **); + +int main(void){ + const char *sql_drop_table="drop table if exists t"; + const char *sql_create_table="create table t(id int primary key,msg varchar(128))"; + char *errmsg = 0; + int ret = 0; + int i = 0; + sqlite3_stmt *stmt; + char ca[255]; + + char **dbresult; + int j,nrow,ncolumn,index; + + sqlite3 *db = 0; + ret = sqlite3_open("./sqlite3-demo.db",&db); + if(ret != SQLITE_OK){ + fprintf(stderr,"Cannot open db: %s\n",sqlite3_errmsg(db)); + return 1; + } + printf("Open database\n"); + + ret = sqlite3_exec(db,sql_drop_table,NULL,NULL,&errmsg); + if(ret != SQLITE_OK){ + fprintf(stderr,"drop table fail: %s\n",errmsg); + } + ret &= sqlite3_exec(db,sql_create_table,NULL,NULL,&errmsg); + if(ret != SQLITE_OK){ + fprintf(stderr,"create table fail: %s\n",errmsg); + } + + ret = sqlite3_exec(db,"insert into t(id,msg) values(1,'Ady Liu')",NULL,NULL,&errmsg); + printf("Insert a record %s\n",ret == SQLITE_OK ? "OK":"FAIL"); + ret = sqlite3_exec(db,"insert into t(id,msg) values(2,'IMXYLZ')",NULL,NULL,&errmsg); + printf("Insert a record %s\n",ret == SQLITE_OK ? "OK":"FAIL"); + ret = sqlite3_exec(db,"delete from t where id < 3",NULL,NULL,&errmsg); + printf("Delete records: %s\n",ret == SQLITE_OK ? "OK":"FAIL"); + + + //prepare statement + sqlite3_prepare_v2(db,"insert into t(id,msg) values(?,?)",-1,&stmt,0); + for(i=10;i<20;i++){ + sprintf(ca,"HELLO#%i",i); + sqlite3_bind_int(stmt,1,i); + sqlite3_bind_text(stmt,2,ca,strlen(ca),SQLITE_STATIC); + sqlite3_step(stmt); + sqlite3_reset(stmt); + } + sqlite3_finalize(stmt); + + //select data + ret = sqlite3_exec(db,"select * from t",print_record,NULL,&errmsg); + if(ret != SQLITE_OK){ + fprintf(stderr,"query SQL error: %s\n",errmsg); + } + + sqlite3_exec(db,"update t set msg='MESSAGE#10' where id=10",NULL,NULL,&errmsg); + //select table + ret = sqlite3_get_table(db,"select * from t",&dbresult,&nrow,&ncolumn,&errmsg); + if(ret == SQLITE_OK){ + printf("query %i records.\n",nrow); + index=ncolumn; + for(i=0;i +#include +#include +#include +#define PORT 8888 +#define SERVER_IP "127.0.0.1" +#define BUFFER_SIZE 4196 + +const char* kExitFlag = "exit"; + +int main() { + // 初始化socket dll。 + WORD winsock_version = MAKEWORD(2,2); + WSADATA wsa_data; + if (WSAStartup(winsock_version, &wsa_data) != 0) { + printf("Failed to init socket!\n"); + return 1; + } + + SOCKET client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (client_socket == INVALID_SOCKET) { + printf("Failed to create server socket!\n"); + return 2; + } + + struct sockaddr_in server_addr; + server_addr.sin_family = AF_INET; + server_addr.sin_port = htons(PORT); + server_addr.sin_addr.S_un.S_addr = inet_addr(SERVER_IP); + if (connect(client_socket, (LPSOCKADDR)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) { + printf("Failed to connect server: %ld !\n", GetLastError()); + return 3; + } + + char recv_data[BUFFER_SIZE+1]; + + while (true) { + char data[BUFFER_SIZE+1]; + printf("Input data: "); + scanf("%s",data); + if (send(client_socket, data, strlen(data), 0) < 0) { + printf("Failed to send data!\n"); + break; + } + + int ret = recv(client_socket, recv_data, BUFFER_SIZE, 0); + if (ret < 0) { + printf("Failed to receive data!\n"); + break; + } + recv_data[ret]=0; // correctly ends received string + + printf("Receive data from server: \"%s\"\n",recv_data); + + if (strcmp(data,kExitFlag)==0) { + printf("Exit!\n"); + break; + } + } + + closesocket(client_socket); + WSACleanup(); + + return 0; +} \ No newline at end of file diff --git a/windows/templates/tcpserver/info.template b/windows/templates/tcpserver/info.template new file mode 100644 index 00000000..6b27f49f --- /dev/null +++ b/windows/templates/tcpserver/info.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=TCP Server +Name[zh_CN]=TCP服务器 +Icon=tcpserver.ico +Description=A winsock2 tcp server demo +Description[zh_CN]=基于Winsock2的TCP服务器程序示例 +Category=Network +Category[zh_CN]=网络 + +[Unit0] +CName=main.c +C=tcpserver_c.txt + +[Project] +UnitCount=1 +Type=1 +Compiler= +CppCompiler= +Linker=-lws2_32 diff --git a/windows/templates/tcpserver/tcpserver.ico b/windows/templates/tcpserver/tcpserver.ico new file mode 100644 index 00000000..b21a8bbe Binary files /dev/null and b/windows/templates/tcpserver/tcpserver.ico differ diff --git a/windows/templates/tcpserver/tcpserver_c.txt b/windows/templates/tcpserver/tcpserver_c.txt new file mode 100644 index 00000000..521cd7cc --- /dev/null +++ b/windows/templates/tcpserver/tcpserver_c.txt @@ -0,0 +1,77 @@ +#include +#include +#include +#include + +#define PORT 8888 +#define BUFFER_SIZE 4196 + +const char* kExitFlag = "exit"; + +int main() { + WORD winsock_version = MAKEWORD(2,2); + WSADATA wsa_data; + if (WSAStartup(winsock_version, &wsa_data) != 0) { + printf("Failed to init socket dll!\n"); + return 1; + } + + SOCKET server_socket= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (server_socket == INVALID_SOCKET) { + printf("Failed to create server socket!\n"); + return 2; + } + + struct sockaddr_in server_addr; + server_addr.sin_family = AF_INET; + server_addr.sin_port = htons(PORT); + server_addr.sin_addr.S_un.S_addr = INADDR_ANY; + + if (bind(server_socket, (LPSOCKADDR)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) { + printf("Failed to bind port!\n"); + return 3; + } + + if (listen(server_socket, 10)) { + printf("Failed to listen!\n"); + return 4; + } + + struct sockaddr_in client_addr; + int client_addr_len = sizeof(client_addr); + printf("Wait for connecting...\n"); + + SOCKET client_socket = accept(server_socket, (SOCKADDR*)&client_addr, &client_addr_len); + if (client_socket == INVALID_SOCKET) { + printf("Failed to accept!\n"); + return 5; + } + + printf("Succeed to receive a connection: %s\n" , inet_ntoa(client_addr.sin_addr)); + + char recv_buf[BUFFER_SIZE+1]; + while (true) { + int ret = recv(client_socket, recv_buf, BUFFER_SIZE, 0); + if (ret < 0) { + printf("Failed to receive data!\n"); + break; + } + recv_buf[ret]=0; // correctly ends received string + + printf("Receive from Client: \"%s\" \n", recv_buf); + if (strcmp(kExitFlag,recv_buf)==0) { + printf("Exit!\n"); + break; + } + + const char* send_data = "Hello, Tcp Client!"; + send(client_socket, send_data, strlen(send_data), 0); + } + + closesocket(client_socket); + closesocket(server_socket); + + WSACleanup(); + + return 0; +} \ No newline at end of file diff --git a/windows/templates/tinyfiledialogs/tinyfiledialogs.ico b/windows/templates/tinyfiledialogs/tinyfiledialogs.ico new file mode 100644 index 00000000..94551655 Binary files /dev/null and b/windows/templates/tinyfiledialogs/tinyfiledialogs.ico differ diff --git a/windows/templates/tinyfiledialogs/tinyfiledialogs.template b/windows/templates/tinyfiledialogs/tinyfiledialogs.template new file mode 100644 index 00000000..d2ac3db4 --- /dev/null +++ b/windows/templates/tinyfiledialogs/tinyfiledialogs.template @@ -0,0 +1,19 @@ +[Template] +ver=2 +Name=TinyFileDialogs +Name[zh_CN]=TinyFileDialogs +Icon=tinyfiledialogs.ico +Description=Demo app for tinyfiledialogs +Description[zh_CN]=tinyfiledialogs示例程序 +Category=UI +Category[zh_CN]=UI + +[Unit0] +CName=main.c +C=tinyfiledialogs_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-ltinyfiledialogs -lcomdlg32 -lole32 diff --git a/windows/templates/tinyfiledialogs/tinyfiledialogs_c.txt b/windows/templates/tinyfiledialogs/tinyfiledialogs_c.txt new file mode 100644 index 00000000..6e35afdf --- /dev/null +++ b/windows/templates/tinyfiledialogs/tinyfiledialogs_c.txt @@ -0,0 +1,235 @@ +/*_________ + / \ hello.c v3.8.8 [Apr 22, 2021] zlib licence + |tiny file| Hello World file created [November 9, 2014] + | dialogs | Copyright (c) 2014 - 2021 Guillaume Vareille http://ysengrin.com + \____ ___/ http://tinyfiledialogs.sourceforge.net + \| git clone http://git.code.sf.net/p/tinyfiledialogs/code tinyfd + ____________________________________________ + | | + | email: tinyfiledialogs at ysengrin.com | + |____________________________________________| + _________________________________________________________________________________ + | | + | the windows only wchar_t UTF-16 prototypes are at the bottom of the header file | + |_________________________________________________________________________________| + _________________________________________________________ + | | + | on windows: - since v3.6 char is UTF-8 by default | + | - if you want MBCS set tinyfd_winUtf8 to 0 | + | - functions like fopen expect MBCS | + |_________________________________________________________| + + If you like tinyfiledialogs, please upvote my stackoverflow answer + https://stackoverflow.com/a/47651444 + + - License - + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + */ + + +/* + - Here is the Hello World: + if a console is missing, it will use graphic dialogs + if a graphical display is absent, it will use console dialogs + (on windows the input box may take some time to open the first time) + */ + + +#include +#include +#include + +#ifdef _MSC_VER +#pragma warning(disable:4996) /* silences warnings about strcpy strcat fopen*/ +#endif + +int main( int argc , char * argv[] ) +{ + int lIntValue; + char const * lPassword; + char const * lTheSaveFileName; + char const * lTheOpenFileName; + char const * lTheSelectFolderName; + char const * lTheHexColor; + char const * lWillBeGraphicMode; + unsigned char lRgbColor[3]; + FILE * lIn; + char lBuffer[1024]; + char const * lFilterPatterns[2] = { "*.txt", "*.text" }; + + (void)argv; /*to silence stupid visual studio warning*/ + + tinyfd_verbose = argc - 1; /* default is 0 */ + tinyfd_silent = 1; /* default is 1 */ + + tinyfd_forceConsole = 0; /* default is 0 */ + tinyfd_assumeGraphicDisplay = 0; /* default is 0 */ + + /*tinyfd_beep();*/ + + lWillBeGraphicMode = tinyfd_inputBox("tinyfd_query", NULL, NULL); + + strcpy(lBuffer, "tinyfiledialogs\nv"); + strcat(lBuffer, tinyfd_version); + if (lWillBeGraphicMode) + { + strcat(lBuffer, "\ngraphic mode: "); + } + else + { + strcat(lBuffer, "\nconsole mode: "); + } + strcat(lBuffer, tinyfd_response); + tinyfd_messageBox("hello", lBuffer, "ok", "info", 0); + + tinyfd_notifyPopup("the title", "the message\n\tfrom outer-space", "info"); + + if ( lWillBeGraphicMode && ! tinyfd_forceConsole ) + { + lIntValue = tinyfd_messageBox("Hello World", "graphic dialogs [Yes] / console mode [No]", "yesno", "question", 1); + tinyfd_forceConsole = ! lIntValue; + } + + lPassword = tinyfd_inputBox( + "a text input box", "your content will be save and loaded", ""); + + if (!lPassword) return 1; + + tinyfd_messageBox("your content as read", lPassword, "ok", "info", 1); + + lTheSaveFileName = tinyfd_saveFileDialog( + "let us save this content", + "passwordFile.txt", + 2, + lFilterPatterns, + NULL); + + if (! lTheSaveFileName) + { + tinyfd_messageBox( + "Error", + "Save file name is NULL", + "ok", + "error", + 1); + return 1 ; + } + +#ifdef _WIN32 + if (tinyfd_winUtf8) + lIn = _wfopen(tinyfd_utf8to16(lTheSaveFileName), L"w"); /* the UTF-8 filename is converted to UTF-16 to open the file*/ + else +#endif + lIn = fopen(lTheSaveFileName, "w"); + + if (!lIn) + { + tinyfd_messageBox( + "Error", + "Can not open this file in write mode", + "ok", + "error", + 1); + return 1 ; + } + fputs(lPassword, lIn); + fclose(lIn); + + lTheOpenFileName = tinyfd_openFileDialog( + "let us read the content back", + "", + 2, + lFilterPatterns, + NULL, + 0); + + if (! lTheOpenFileName) + { + tinyfd_messageBox( + "Error", + "Open file name is NULL", + "ok", + "error", + 0); + return 1 ; + } + +#ifdef _WIN32 + if (tinyfd_winUtf8) + lIn = _wfopen(tinyfd_utf8to16(lTheOpenFileName), L"r"); /* the UTF-8 filename is converted to UTF-16 */ + else +#endif + lIn = fopen(lTheOpenFileName, "r"); + + if (!lIn) + { + tinyfd_messageBox( + "Error", + "Can not open this file in read mode", + "ok", + "error", + 1); + return(1); + } + + lBuffer[0] = '\0'; + fgets(lBuffer, sizeof(lBuffer), lIn); + fclose(lIn); + + tinyfd_messageBox("yourcontent as it was saved", lBuffer, "ok", "info", 1); + + lTheSelectFolderName = tinyfd_selectFolderDialog( + "let us just select a directory", NULL); + + if (!lTheSelectFolderName) + { + tinyfd_messageBox( + "Error", + "Select folder name is NULL", + "ok", + "error", + 1); + return 1; + } + + tinyfd_messageBox("The selected folder is", lTheSelectFolderName, "ok", "info", 1); + + lTheHexColor = tinyfd_colorChooser( + "choose a nice color", + "#FF0077", + lRgbColor, + lRgbColor); + + if (!lTheHexColor) + { + tinyfd_messageBox( + "Error", + "hexcolor is NULL", + "ok", + "error", + 1); + return 1; + } + + tinyfd_messageBox("The selected hexcolor is", lTheHexColor, "ok", "info", 1); + + tinyfd_messageBox("your read content was", lPassword, "ok", "info", 1); + + tinyfd_beep(); + + return 0; +}