This document provides an overview of CUDA C/C++ basics for processing data in parallel on GPUs. It discusses:
- The CUDA architecture which exposes GPU parallelism for general-purpose computing while retaining performance.
- The CUDA programming model which uses a grid of thread blocks, with each block containing a group of threads that execute concurrently.
- Key CUDA C/C++ concepts like declaring device functions, launching kernels, managing host and device memory, and using thread and block indexes to parallelize work across threads and blocks.
- A simple example of vector addition to demonstrate parallel execution using threads and blocks, with indexing to map threads/blocks to problem elements.
2011.02.18 marco parenzan - modelli di programmazione per le gpuMarco Parenzan
This document discusses programming languages and compilers for GPUs. It begins by noting that Nvidia/CUDA is not the only option for GPU computing and that other platforms like Intel and AMD exist. It then explains why GPU computing is useful due to GPUs' parallel processing capabilities. The document outlines some popular GPU products and programming models like CUDA, OpenCL, and DirectCompute. It provides kernel code examples for tasks like matrix multiplication in languages like C for CUDA and OpenCL. Finally, it discusses related topics like GPU programming libraries, host languages, and metaprogramming.
This document provides an overview and reference for QE, a 3D game engine. It describes the development environment including DirectX, OpenGL and Visual Studio. It outlines the engine's directory structure and key files. It also summarizes input handling, adding functions and classes to the engine loop, and deriving from the qeUpdateBase class. The document provides examples of initializing input, remapping keys, and reading the keyboard buffer. It references important QE API functions.
This document discusses teaching game development using mini-games to teach programming and design concepts. It provides an overview of setting up the development environment and tools, basic game programming concepts like cameras and matrices, and approaches for simple games like Pong to teach core mechanics.
The document contains questions and explanations about C programming keywords and concepts like pointers, arrays, structures, unions, and bit manipulation. It provides definitions and examples for keywords like #define, #include, #pragma, #asm, #ifdef, and #endif. It also gives solutions to questions about pointers, counting bits to access specific bits or bytes of memory at a particular address, and explaining differences between array parameters and pointers in function definitions in C.
Computer Project For Class XII Topic - The Snake Game Pritam Samanta
This was a group project but it was completely made by me. The program is fully working. There are no bugs. This will not work in OLD C++ COMPILERS namely turbo-c++,etc., but it will work in latest ANSI COMPLIERS namely Dev-c++, Code-blocks, ellipse, etc. If any one has any suggestion for correction or improvement please contact: [email protected]. Every suggestions are valuable. Feel free to share this with your friends to share the happiness.
I am Bernard. I am a C Assignment Expert at programminghomeworkhelp.com. I hold a Ph.D. in Programming from, University of Leeds, UK. I have been helping students with their homework for the past 9 years. I solve assignments related to C Programming.
Visit programminghomeworkhelp.com or email [email protected]. You can also call on +1 678 648 4277 for any assistance with C Programming Assignments.
This document provides a tutorial on Verilog HDL (Hardware Description Language). It discusses that HDLs like Verilog and VHDL are used to describe hardware using code. Verilog allows designers to describe designs at different levels of abstraction. Digital systems are highly complex, and Verilog provides a software platform for designers to express their designs with behavioral constructs. A Verilog program can be converted to a description used to manufacture chips like VLSI. The document then covers various Verilog topics like modules, ports, data types, always blocks, structural modeling, dataflow modeling, and behavioral modeling.
Verilog HDL is a hardware description language used to design and document electronic systems. Verilog HDL allows designers to design at various levels of abstraction. It is the most widely used HDL with a user community of more than 50,000 active designers.
A brief history
Verilog HDL originated at Automated Integrated Design Systems (later renamed as Gateway Design Automation) in 1985. The company was privately held at that time by Dr. Prabhu Goel, the inventor of the PODEM test generation algorithm. Verilog HDL was designed by Phil Moorby, who was later to become the Chief Designer for Verilog-XL and the first Corporate Fellow at Cadence Design Systems. Gateway Design Automation grew rapidly with the success of Verilog-XL and was finally acquired by Cadence Design Systems, San Jose, CA in 1989.
Verilog was invented as simulation language. Use of Verilog for synthesis was a complete afterthought. Rumors abound that there were merger discussions between Gateway and Synopsys in the early days, where neither gave the other much chance of success..
In the late 1980's it seemed evident that designers were going to be moving away from proprietary languages like n dot, HiLo and Verilog towards the US Depatment of Defense standard H.D.L., known as the VHSIC Hardware Description Language. VHSIC it self stands for "Very High Speen Intergrated Circuit" BTW).
Perhaps due to such market pressure, Cadence Design Systems decided to open the Verilog language to the public in 1990, and thus OVI (Open Verilog International) was born. Until that time, Verilog HDL was a proprietary language, being the property of Cadence Design Systems. When OVI was formed in 1991, a number of small companies began working on Verilog simulators, including Chronologic Simulation, Frontline Design Automation, and others. The first of these came to market in 1992, and now there are mature Verilog simulators available from many sources.
As a result, the Verilog market has grown substantially. The market for Verilog related tools in 1994 was well over $75,000,000, making it the most commercially significant hardware description language on the market.
An IEEE working group was established in 1993 under the Design Automation Sub-Committee to produce the IEEE Verilog standard 1364. Verilog became IEEE Standard 1364 in 1995.
As an international standard, the Verilog market continued to grow. In 1998 the market for Verilog simulators alone was well over $150,000,000; continuing its dominance.
The IEEE working group released a revised standard in March of 2002, known as IEEE 1364-2001. Significant publication errors marred this release, and a revised version was released in 2003, known as IEEE 1364-2001 Revision C.
This document provides instructions for building a simple toy UNIX-like operating system from scratch. It covers setting up the development environment with tools like GCC, NASM and an emulator. It then explains how to write a bootloader and kernel code in C and Assembly. Key concepts covered include the Global Descriptor Table (GDT) for memory segmentation and privilege levels, the Interrupt Descriptor Table (IDT) for registering interrupt handlers, and writing a basic text mode monitor for output. The document is intended as a tutorial for learning operating system development fundamentals.
The document discusses 5 object-oriented programming techniques:
1) Avoid calling virtual functions from constructors due to polymorphism issues.
2) Preserve method properties like signatures when overriding to adhere to principles like Liskov substitution.
3) Be aware of initialization order problems between classes and languages.
4) Avoid switch/if-else chains checking types and instead use polymorphism with virtual functions.
5) Be cautious of name hiding between scopes as it reduces readability and can cause defects.
Highlighted notes of:
Introduction to CUDA C: NVIDIA
Author: Blaise Barney
From: GPU Clusters, Lawrence Livermore National Laboratory
https://computing.llnl.gov/tutorials/linux_clusters/gpu/NVIDIA.Introduction_to_CUDA_C.1.pdf
Blaise Barney is a research scientist at Lawrence Livermore National Laboratory.
The document discusses getting started with computer graphics and OpenGL. It covers setting up an OpenGL environment, drawing basic graphics primitives like points and lines, and creating more complex shapes. Some key topics include using callback functions for event-driven graphics, establishing a window and coordinate system, drawing dots, lines, and polygons, and parameterizing shapes. Functions like glBegin, glEnd, and glVertex are introduced for drawing graphics.
This document provides an overview of the C programming language under Linux, covering preprocessing, compiling, assembling, linking, libraries, and related tools. It discusses:
1. The four main steps of preprocessing, compiling, assembling, and linking using GNU tools like cpp, cc1, as, and collect2.
2. How to display symbol tables using nm and strip symbols from executables.
3. Creating static libraries with ar and ranlib and linking them, as well as creating shared libraries with gcc and soname.
4. The roles of environment variables like LIBRARY_PATH and LD_LIBRARY_PATH in locating libraries.
C is a procedural programming language commonly used for system and application development. It uses functions and globally visible variables. Functions are declared before use. The main() function is the program entry point. Programs are compiled and linked separately. The C preprocessor handles includes and macros. Functions are defined with declarations and definitions. Control structures like if/else and loops are similar to other languages. Standard input/output functions handle file and terminal I/O. Formatted printing and scanning uses format specifiers. Type conversions must be explicitly cast.
The document discusses the Rust programming language, highlighting its features like concurrency, safety, and package management. It covers Rust's syntax including expressions, attributes, pattern matching and generics. The document also discusses how Rust handles concurrency through tasks and channels to enable safe parallelism and communication between threads.
The document discusses deep learning applications design, development and deployment in IoT edge. It describes using a Power9 system to train artificial neural network models using the MNIST dataset. It also covers building inference engines for Android phones and deploying visual recognition models to IBM Watson Studio.
BeagleBone Black: Platform Bring-Up with Upstream ComponentsGlobalLogic Ukraine
This document is intended to give the user overall instructions on how to obtain, build and flash upstream software to the BeagleBone Black board, with detailed explanation of all related features and components.
Please find the additional details in this deck: https://www.slideshare.net/GlobalLogicUkraine/beaglebone-black-with-upstream-software
The respective workshop was held by Victoriia Taraniuk (Associate Manager, Quality Assurance, Consultant, GlobalLogic) at GlobalLogic Mykolaiv Embedded TechTalk #1 on May 25, 2018.
The document discusses the Go programming language, including its history as a project at Google from 2007-2009, its goals of making programming fun again while having a safe static type system. It provides an overview of Go's syntax features like variables, functions, flow control statements, types, methods and interfaces, concurrency using goroutines and channels.
The document provides an overview of the GIFT-VT tools framework. It describes the different levels and types of tools, the classes and inheritance used to implement tools, modules and services, how tools are executed by the server by loading the shared library and calling functions, and examples of tool configuration files and Makefiles.
The document discusses different approaches to implementing GPU-like programming on CPUs using C++AMP. It covers using setjmp/longjmp to implement coroutines for "fake threading", using ucontext for coroutine context switching, and how to pass lambda functions and non-integer arguments to makecontext. Implementing barriers on CPUs requires synchronizing threads with an atomic counter instead of GPU shared memory. Overall, the document shows it is possible to run GPU-like programming models on CPUs by simulating the GPU programming model using language features for coroutines and threading.
Please write it in C, not python
/*------------------------------------------------------------------
File: plotFunctions.c
Author: Gilbert Arbez, Fall 2016
Description: Allows the user to plot a number of functions for
different ranges.
---------------------------------------------------------------------*/
#include <stdio.h>
#include <gng1106plplot.h> // provides definitions for using PLplot library
#include <math.h>
#include <float.h>
// Some definitions
#define NUM_POINTS 500 // Number of points used for plotting
#define X_IX 0 // Row index for storing x values
#define FX_IX 1 // Row index for storing f(x) values
#define TRUE 1
#define FALSE 0
// Structure for user input
typedef struct
{
int fNumber; // function number
double x0; // first value of x to plot
double xf; // final value of x to plot
} F_SELECT;
// function prototypes
void selectFunction(F_SELECT *);
void computeDataPoints(F_SELECT *fsPtr, int n, double [][n]);
double calcFx(double, int);
void plot(int n, double [][n]);
double getMinDouble(double [], int);
double getMaxDouble(double [], int);
/*---------------------------------------------------------------------
Function: main
Description: This function computes a set of points for plotting. The
function calcFx is called to computes the value of f(x) .
Modify calcFx to compute the values of f(x) desired.
In this template, the sin function is used.
------------------------------------------------------------------------*/
void main(void)
{
// Variable declarations
F_SELECT fselect;
double points[2][NUM_POINTS]; // row 0 contains values of x
// Get user input
selectFunction(&fselect);
// Compute the data points and save in array
computeDataPoints(&fselect, NUM_POINTS, points);
// Call plot function to plot
plot(NUM_POINTS, points);
}
/*-----------------------------------------------------------------------
Function: selectFunction
Parameters:
sfPtr - Pointer to F_SELECT structure variable to store input data.
Description: Prompts the user to get x0 and xf (range of x for plotting)
and to select a function to plot.
------------------------------------------------------------------------*/
void selectFunction(F_SELECT *sfPtr)
{
// Variable Declarations
int flag;
// Display function menu
printf("1) f(x) = sqrt(|x-1|) + 1n");
printf("2) f(x) = exp(-x)n");
printf("3) f(x) = sqrt(x^2+1) - xn");
printf("4) f(x) = [exp(-x) - 1)]/xn");
printf("5) f(x) = sin(x)+0.1*cos(10.0*x)n");
// Select a function
// Select a range of x for plotting
}
/*-----------------------------------------------------------------------
Function: computeDataPoints
Parameters:
fsPtr - Pointer to F_SELECT structure variable with input data.
n - number of points in the 2D array (i.e. number of columns)
points - 2D array that contains the data points - row X_IX with x values
and row FX_IX with the f(x) values.
Description: Calculates NUM_POINTS points of the function f(x) (selected by the
the user and computed with calcFx), and stored in the
2D array points. points[X.
This document provides information about a project to solve the eight queens puzzle using backtracking algorithms. It includes an introduction describing the puzzle, intended audience, and project scope. It also includes sections on the project overview describing the algorithm and operating environment, as well as modules, source code, and conclusions.
This document provides an introduction to game programming using C++ and the Simple DirectMedia Layer (SDL) library. It outlines the basic structure and modules of video games, including the fundamental game loop of input, update, and output. It then explains how to set up an SDL project in Xcode, implement the basic game loop, and use SDL functions to initialize graphics, handle input events, and display output. The goal is to familiarize students with building the core framework of a video game using industry standard tools and techniques.
The document describes a laboratory manual for Programming Laboratory - III. It contains 18 assignments divided into three groups - A, B, and C. The assignments include developing applications using a BeagleBone Black board to simulate operations like a lift and traffic lights, implementing a calculator using concurrent Lisp, applying software engineering methodologies to assignments, designing mathematical models, analyzing requirements and creating UML diagrams. It provides the setup instructions, relevant theory, and procedures to complete the assignments.
Here is The code in C language:
/*------------------------------------------------------------------
File: plotFunctions.c
Author: Gilbert Arbez, Fall 2016
Description: Allows the user to plot a number of functions for
different ranges.
---------------------------------------------------------------------*/
#include <stdio.h>
#include <gng1106plplot.h> // provides definitions for using PLplot library
#include <math.h>
#include <float.h>
// Some definitions
#define NUM_POINTS 500 // Number of points used for plotting
#define X_IX 0 // Row index for storing x values
#define FX_IX 1 // Row index for storing f(x) values
#define TRUE 1
#define FALSE 0
// Structure for user input
typedef struct
{
int fNumber; // function number
double x0; // first value of x to plot
double xf; // final value of x to plot
} F_SELECT;
// function prototypes
void selectFunction(F_SELECT *);
void computeDataPoints(F_SELECT *fsPtr, int n, double [][n]);
double calcFx(double, int);
void plot(int n, double [][n]);
double getMinDouble(double [], int);
double getMaxDouble(double [], int);
/*---------------------------------------------------------------------
Function: main
Description: This function computes a set of points for plotting. The
function calcFx is called to computes the value of f(x) .
Modify calcFx to compute the values of f(x) desired.
In this template, the sin function is used.
------------------------------------------------------------------------*/
void main(void)
{
// Variable declarations
F_SELECT fselect;
double points[2][NUM_POINTS]; // row 0 contains values of x
// Get user input
selectFunction(&fselect);
// Compute the data points and save in array
computeDataPoints(&fselect, NUM_POINTS, points);
// Call plot function to plot
plot(NUM_POINTS, points);
}
/*-----------------------------------------------------------------------
Function: selectFunction
Parameters:
sfPtr - Pointer to F_SELECT structure variable to store input data.
Description: Prompts the user to get x0 and xf (range of x for plotting)
and to select a function to plot.
------------------------------------------------------------------------*/
void selectFunction(F_SELECT *sfPtr)
{
// Variable Declarations
int flag;
// Display function menu
printf("1) f(x) = sqrt(|x-1|) + 1n");
printf("2) f(x) = exp(-x)n");
printf("3) f(x) = sqrt(x^2+1) - xn");
printf("4) f(x) = [exp(-x) - 1)]/xn");
printf("5) f(x) = sin(x)+0.1*cos(10.0*x)n");
// Select a function
// Select a range of x for plotting
}
/*-----------------------------------------------------------------------
Function: computeDataPoints
Parameters:
fsPtr - Pointer to F_SELECT structure variable with input data.
n - number of points in the 2D array (i.e. number of columns)
points - 2D array that contains the data points - row X_IX with x values
and row FX_IX with the f(x) values.
Description: Calculates NUM_POINTS points of the function f(x) (selected by the
the user and computed with calcFx), and stored in the
2D array points. points[X_.
Verilog HDL is a hardware description language used to design and document electronic systems. Verilog HDL allows designers to design at various levels of abstraction. It is the most widely used HDL with a user community of more than 50,000 active designers.
A brief history
Verilog HDL originated at Automated Integrated Design Systems (later renamed as Gateway Design Automation) in 1985. The company was privately held at that time by Dr. Prabhu Goel, the inventor of the PODEM test generation algorithm. Verilog HDL was designed by Phil Moorby, who was later to become the Chief Designer for Verilog-XL and the first Corporate Fellow at Cadence Design Systems. Gateway Design Automation grew rapidly with the success of Verilog-XL and was finally acquired by Cadence Design Systems, San Jose, CA in 1989.
Verilog was invented as simulation language. Use of Verilog for synthesis was a complete afterthought. Rumors abound that there were merger discussions between Gateway and Synopsys in the early days, where neither gave the other much chance of success..
In the late 1980's it seemed evident that designers were going to be moving away from proprietary languages like n dot, HiLo and Verilog towards the US Depatment of Defense standard H.D.L., known as the VHSIC Hardware Description Language. VHSIC it self stands for "Very High Speen Intergrated Circuit" BTW).
Perhaps due to such market pressure, Cadence Design Systems decided to open the Verilog language to the public in 1990, and thus OVI (Open Verilog International) was born. Until that time, Verilog HDL was a proprietary language, being the property of Cadence Design Systems. When OVI was formed in 1991, a number of small companies began working on Verilog simulators, including Chronologic Simulation, Frontline Design Automation, and others. The first of these came to market in 1992, and now there are mature Verilog simulators available from many sources.
As a result, the Verilog market has grown substantially. The market for Verilog related tools in 1994 was well over $75,000,000, making it the most commercially significant hardware description language on the market.
An IEEE working group was established in 1993 under the Design Automation Sub-Committee to produce the IEEE Verilog standard 1364. Verilog became IEEE Standard 1364 in 1995.
As an international standard, the Verilog market continued to grow. In 1998 the market for Verilog simulators alone was well over $150,000,000; continuing its dominance.
The IEEE working group released a revised standard in March of 2002, known as IEEE 1364-2001. Significant publication errors marred this release, and a revised version was released in 2003, known as IEEE 1364-2001 Revision C.
This document provides instructions for building a simple toy UNIX-like operating system from scratch. It covers setting up the development environment with tools like GCC, NASM and an emulator. It then explains how to write a bootloader and kernel code in C and Assembly. Key concepts covered include the Global Descriptor Table (GDT) for memory segmentation and privilege levels, the Interrupt Descriptor Table (IDT) for registering interrupt handlers, and writing a basic text mode monitor for output. The document is intended as a tutorial for learning operating system development fundamentals.
The document discusses 5 object-oriented programming techniques:
1) Avoid calling virtual functions from constructors due to polymorphism issues.
2) Preserve method properties like signatures when overriding to adhere to principles like Liskov substitution.
3) Be aware of initialization order problems between classes and languages.
4) Avoid switch/if-else chains checking types and instead use polymorphism with virtual functions.
5) Be cautious of name hiding between scopes as it reduces readability and can cause defects.
Highlighted notes of:
Introduction to CUDA C: NVIDIA
Author: Blaise Barney
From: GPU Clusters, Lawrence Livermore National Laboratory
https://computing.llnl.gov/tutorials/linux_clusters/gpu/NVIDIA.Introduction_to_CUDA_C.1.pdf
Blaise Barney is a research scientist at Lawrence Livermore National Laboratory.
The document discusses getting started with computer graphics and OpenGL. It covers setting up an OpenGL environment, drawing basic graphics primitives like points and lines, and creating more complex shapes. Some key topics include using callback functions for event-driven graphics, establishing a window and coordinate system, drawing dots, lines, and polygons, and parameterizing shapes. Functions like glBegin, glEnd, and glVertex are introduced for drawing graphics.
This document provides an overview of the C programming language under Linux, covering preprocessing, compiling, assembling, linking, libraries, and related tools. It discusses:
1. The four main steps of preprocessing, compiling, assembling, and linking using GNU tools like cpp, cc1, as, and collect2.
2. How to display symbol tables using nm and strip symbols from executables.
3. Creating static libraries with ar and ranlib and linking them, as well as creating shared libraries with gcc and soname.
4. The roles of environment variables like LIBRARY_PATH and LD_LIBRARY_PATH in locating libraries.
C is a procedural programming language commonly used for system and application development. It uses functions and globally visible variables. Functions are declared before use. The main() function is the program entry point. Programs are compiled and linked separately. The C preprocessor handles includes and macros. Functions are defined with declarations and definitions. Control structures like if/else and loops are similar to other languages. Standard input/output functions handle file and terminal I/O. Formatted printing and scanning uses format specifiers. Type conversions must be explicitly cast.
The document discusses the Rust programming language, highlighting its features like concurrency, safety, and package management. It covers Rust's syntax including expressions, attributes, pattern matching and generics. The document also discusses how Rust handles concurrency through tasks and channels to enable safe parallelism and communication between threads.
The document discusses deep learning applications design, development and deployment in IoT edge. It describes using a Power9 system to train artificial neural network models using the MNIST dataset. It also covers building inference engines for Android phones and deploying visual recognition models to IBM Watson Studio.
BeagleBone Black: Platform Bring-Up with Upstream ComponentsGlobalLogic Ukraine
This document is intended to give the user overall instructions on how to obtain, build and flash upstream software to the BeagleBone Black board, with detailed explanation of all related features and components.
Please find the additional details in this deck: https://www.slideshare.net/GlobalLogicUkraine/beaglebone-black-with-upstream-software
The respective workshop was held by Victoriia Taraniuk (Associate Manager, Quality Assurance, Consultant, GlobalLogic) at GlobalLogic Mykolaiv Embedded TechTalk #1 on May 25, 2018.
The document discusses the Go programming language, including its history as a project at Google from 2007-2009, its goals of making programming fun again while having a safe static type system. It provides an overview of Go's syntax features like variables, functions, flow control statements, types, methods and interfaces, concurrency using goroutines and channels.
The document provides an overview of the GIFT-VT tools framework. It describes the different levels and types of tools, the classes and inheritance used to implement tools, modules and services, how tools are executed by the server by loading the shared library and calling functions, and examples of tool configuration files and Makefiles.
The document discusses different approaches to implementing GPU-like programming on CPUs using C++AMP. It covers using setjmp/longjmp to implement coroutines for "fake threading", using ucontext for coroutine context switching, and how to pass lambda functions and non-integer arguments to makecontext. Implementing barriers on CPUs requires synchronizing threads with an atomic counter instead of GPU shared memory. Overall, the document shows it is possible to run GPU-like programming models on CPUs by simulating the GPU programming model using language features for coroutines and threading.
Please write it in C, not python
/*------------------------------------------------------------------
File: plotFunctions.c
Author: Gilbert Arbez, Fall 2016
Description: Allows the user to plot a number of functions for
different ranges.
---------------------------------------------------------------------*/
#include <stdio.h>
#include <gng1106plplot.h> // provides definitions for using PLplot library
#include <math.h>
#include <float.h>
// Some definitions
#define NUM_POINTS 500 // Number of points used for plotting
#define X_IX 0 // Row index for storing x values
#define FX_IX 1 // Row index for storing f(x) values
#define TRUE 1
#define FALSE 0
// Structure for user input
typedef struct
{
int fNumber; // function number
double x0; // first value of x to plot
double xf; // final value of x to plot
} F_SELECT;
// function prototypes
void selectFunction(F_SELECT *);
void computeDataPoints(F_SELECT *fsPtr, int n, double [][n]);
double calcFx(double, int);
void plot(int n, double [][n]);
double getMinDouble(double [], int);
double getMaxDouble(double [], int);
/*---------------------------------------------------------------------
Function: main
Description: This function computes a set of points for plotting. The
function calcFx is called to computes the value of f(x) .
Modify calcFx to compute the values of f(x) desired.
In this template, the sin function is used.
------------------------------------------------------------------------*/
void main(void)
{
// Variable declarations
F_SELECT fselect;
double points[2][NUM_POINTS]; // row 0 contains values of x
// Get user input
selectFunction(&fselect);
// Compute the data points and save in array
computeDataPoints(&fselect, NUM_POINTS, points);
// Call plot function to plot
plot(NUM_POINTS, points);
}
/*-----------------------------------------------------------------------
Function: selectFunction
Parameters:
sfPtr - Pointer to F_SELECT structure variable to store input data.
Description: Prompts the user to get x0 and xf (range of x for plotting)
and to select a function to plot.
------------------------------------------------------------------------*/
void selectFunction(F_SELECT *sfPtr)
{
// Variable Declarations
int flag;
// Display function menu
printf("1) f(x) = sqrt(|x-1|) + 1n");
printf("2) f(x) = exp(-x)n");
printf("3) f(x) = sqrt(x^2+1) - xn");
printf("4) f(x) = [exp(-x) - 1)]/xn");
printf("5) f(x) = sin(x)+0.1*cos(10.0*x)n");
// Select a function
// Select a range of x for plotting
}
/*-----------------------------------------------------------------------
Function: computeDataPoints
Parameters:
fsPtr - Pointer to F_SELECT structure variable with input data.
n - number of points in the 2D array (i.e. number of columns)
points - 2D array that contains the data points - row X_IX with x values
and row FX_IX with the f(x) values.
Description: Calculates NUM_POINTS points of the function f(x) (selected by the
the user and computed with calcFx), and stored in the
2D array points. points[X.
This document provides information about a project to solve the eight queens puzzle using backtracking algorithms. It includes an introduction describing the puzzle, intended audience, and project scope. It also includes sections on the project overview describing the algorithm and operating environment, as well as modules, source code, and conclusions.
This document provides an introduction to game programming using C++ and the Simple DirectMedia Layer (SDL) library. It outlines the basic structure and modules of video games, including the fundamental game loop of input, update, and output. It then explains how to set up an SDL project in Xcode, implement the basic game loop, and use SDL functions to initialize graphics, handle input events, and display output. The goal is to familiarize students with building the core framework of a video game using industry standard tools and techniques.
The document describes a laboratory manual for Programming Laboratory - III. It contains 18 assignments divided into three groups - A, B, and C. The assignments include developing applications using a BeagleBone Black board to simulate operations like a lift and traffic lights, implementing a calculator using concurrent Lisp, applying software engineering methodologies to assignments, designing mathematical models, analyzing requirements and creating UML diagrams. It provides the setup instructions, relevant theory, and procedures to complete the assignments.
Here is The code in C language:
/*------------------------------------------------------------------
File: plotFunctions.c
Author: Gilbert Arbez, Fall 2016
Description: Allows the user to plot a number of functions for
different ranges.
---------------------------------------------------------------------*/
#include <stdio.h>
#include <gng1106plplot.h> // provides definitions for using PLplot library
#include <math.h>
#include <float.h>
// Some definitions
#define NUM_POINTS 500 // Number of points used for plotting
#define X_IX 0 // Row index for storing x values
#define FX_IX 1 // Row index for storing f(x) values
#define TRUE 1
#define FALSE 0
// Structure for user input
typedef struct
{
int fNumber; // function number
double x0; // first value of x to plot
double xf; // final value of x to plot
} F_SELECT;
// function prototypes
void selectFunction(F_SELECT *);
void computeDataPoints(F_SELECT *fsPtr, int n, double [][n]);
double calcFx(double, int);
void plot(int n, double [][n]);
double getMinDouble(double [], int);
double getMaxDouble(double [], int);
/*---------------------------------------------------------------------
Function: main
Description: This function computes a set of points for plotting. The
function calcFx is called to computes the value of f(x) .
Modify calcFx to compute the values of f(x) desired.
In this template, the sin function is used.
------------------------------------------------------------------------*/
void main(void)
{
// Variable declarations
F_SELECT fselect;
double points[2][NUM_POINTS]; // row 0 contains values of x
// Get user input
selectFunction(&fselect);
// Compute the data points and save in array
computeDataPoints(&fselect, NUM_POINTS, points);
// Call plot function to plot
plot(NUM_POINTS, points);
}
/*-----------------------------------------------------------------------
Function: selectFunction
Parameters:
sfPtr - Pointer to F_SELECT structure variable to store input data.
Description: Prompts the user to get x0 and xf (range of x for plotting)
and to select a function to plot.
------------------------------------------------------------------------*/
void selectFunction(F_SELECT *sfPtr)
{
// Variable Declarations
int flag;
// Display function menu
printf("1) f(x) = sqrt(|x-1|) + 1n");
printf("2) f(x) = exp(-x)n");
printf("3) f(x) = sqrt(x^2+1) - xn");
printf("4) f(x) = [exp(-x) - 1)]/xn");
printf("5) f(x) = sin(x)+0.1*cos(10.0*x)n");
// Select a function
// Select a range of x for plotting
}
/*-----------------------------------------------------------------------
Function: computeDataPoints
Parameters:
fsPtr - Pointer to F_SELECT structure variable with input data.
n - number of points in the 2D array (i.e. number of columns)
points - 2D array that contains the data points - row X_IX with x values
and row FX_IX with the f(x) values.
Description: Calculates NUM_POINTS points of the function f(x) (selected by the
the user and computed with calcFx), and stored in the
2D array points. points[X_.
This document provides instructions for installing and using the Code::Blocks integrated development environment (IDE) to write, compile, debug and run C++ programs. It explains how to download and install Code::Blocks, create a new project, add and remove files from a project, compile and run a project, and use the debugger to step through code line-by-line and watch variable values. The debugger is a key tool for finding and fixing bugs in programs. The document aims to help students learn programming skills like organizing code and debugging techniques.
This document describes a new type of battery that is safer and longer lasting than current lithium-ion batteries. It works by using sodium ions rather than lithium ions and two different metals as the electrodes. Sodium ions are abundant and inexpensive. Tests show this battery maintains over 90% capacity after 250 charge/discharge cycles and it is not as flammable as conventional lithium-ion batteries. This new design could enable safer, more affordable energy storage and help large-scale adoption of electric vehicles and other technologies.
This document describes version 1.3 of the OpenGL Graphics System Utility Library (GLU). It provides routines for mipmapping, matrix manipulation, polygon tessellation, quadrics, NURBS, and error handling to complement the OpenGL graphics system. The document outlines the initialization, functions, and versions of the GLU library.
Updated curriculum vitae, (detailed resume) for Paul W. Warshauer. He is a real estate developer, grandevenues.com entertainer and long time operator of Murders4Fun.com. nationwide.
<P>专业制作海外大学文凭西班牙文凭巴利亚多利德大学成绩单?【q微1954292140】Buy Universidad de Valladolid Diploma购买美国毕业证,购买英国毕业证,购买澳洲毕业证,购买加拿大毕业证,以及德国毕业证,购买法国毕业证(q微1954292140)购买荷兰毕业证、购买瑞士毕业证、购买日本毕业证、购买韩国毕业证、购买新西兰毕业证、购买新加坡毕业证、购买西班牙毕业证、购买马来西亚毕业证等。包括了本科毕业证,硕士毕业证。【q微1954292140】巴利亚多利德大学毕业证办理,巴利亚多利德大学文凭办理,巴利亚多利德大学成绩单办理和真实留信认证、留服认证、巴利亚多利德大学学历认证。学院文凭定制,巴利亚多利德大学原版文凭补办,扫描件文凭定做,100%文凭复刻。<BR>主营项目:<BR>1、真实教育部国外学历学位认证《西班牙毕业文凭证书快速办理巴利亚多利德大学官方办理文凭》【q微1954292140】《论文没过巴利亚多利德大学正式成绩单》,教育部存档,教育部留服网站100%可查.<BR>2、办理UVa毕业证,改成绩单《UVa毕业证明办理巴利亚多利德大学毕业证办理》【Q/WeChat:1954292140】Buy Universidad de Valladolid Certificates《正式成绩单论文没过》,巴利亚多利德大学Offer、在读证明、学生卡、信封、证明信等全套材料,从防伪到印刷,从水印到钢印烫金,高精仿度跟学校原版100%相同.<BR>3、真实使馆认证(即留学人员回国证明),使馆存档可通过大使馆查询确认.<BR>4、留信网认证,国家专业人才认证中心颁发入库证书,留信网存档可查.<BR>《巴利亚多利德大学学位证定制西班牙毕业证书办理UVa国外文凭购买》【q微1954292140】学位证1:1完美还原海外各大学毕业材料上的工艺:水印,阴影底纹,钢印LOGO烫金烫银,LOGO烫金烫银复合重叠。文字图案浮雕、激光镭射、紫外荧光、温感、复印防伪等防伪工艺。<BR>【q微1954292140】办理巴利亚多利德大学毕业证(UVa毕业证书)毕业证成绩单购买【q微1954292140】巴利亚多利德大学offer/学位证、留信官方学历认证(永久存档真实可查)采用学校原版纸张、特殊工艺完全按照原版一比一制作</P>
<P>特殊原因导致无法毕业,也可以联系我们帮您办理相关材料:<BR>1:在巴利亚多利德大学挂科了,不想读了,成绩不理想怎么办???<BR>2:打算回国了,找工作的时候,需要提供认证《UVa成绩单购买办理巴利亚多利德大学毕业证书范本》【Q/WeChat:1954292140】Buy Universidad de Valladolid Diploma《正式成绩单论文没过》有文凭却得不到认证。又该怎么办???西班牙毕业证购买,西班牙文凭购买,<BR>3:回国了找工作没有巴利亚多利德大学文凭怎么办?有本科却要求硕士又怎么办?<BR>帮您解决在西班牙巴利亚多利德大学未毕业难题(Universidad de Valladolid)文凭购买、毕业证购买、大学文凭购买、大学毕业证购买、买文凭、日韩文凭、英国大学文凭、美国大学文凭、澳洲大学文凭、加拿大大学文凭(q微1954292140)新加坡大学文凭、新西兰大学文凭、爱尔兰文凭、西班牙文凭、德国文凭、教育部认证,买毕业证,毕业证购买,买大学文凭,购买日韩毕业证、英国大学毕业证、美国大学毕业证、澳洲大学毕业证、加拿大大学毕业证(q微1954292140)新加坡大学毕业证、新西兰大学毕业证、爱尔兰毕业证、西班牙毕业证、德国毕业证,回国证明,留信网认证,留信认证办理,学历认证。从而完成就业。</P>
<P>如果您在英、加、美、澳、欧洲等留学过程中或回国后:<BR>1、在校期间因各种原因未能顺利毕业《UVa成绩单工艺详解》【Q/WeChat:1954292140】《Buy Universidad de Valladolid Transcript快速办理巴利亚多利德大学教育部学历认证书毕业文凭证书》,拿不到官方毕业证;<BR>2、面对父母的压力,希望尽快拿到;<BR>3、不清楚认证流程以及材料该如何准备;<BR>4、回国时间很长,忘记办理;<BR>5、回国马上就要找工作《正式成绩单巴利亚多利德大学购买毕业证流程》【q微1954292140】《文凭购买UVa假成绩单购买》办给用人单位看; <BR>6、企事业单位必须要求办理的;<BR>7、需要报考公务员、购买免税车、落转户口、申请留学生创业基金。<BR>西班牙文凭巴利亚多利德大学成绩单,UVa毕业证【q微1954292140】办理西班牙巴利亚多利德大学毕业证(UVa毕业证书)【q微1954292140】文凭定制您的学术成就巴利亚多利德大学offer/学位证毕业证成绩单购买、留信官方学历认证(永久存档真实可查)采用学校原版纸张、特殊工艺完全按照原版一比一制作。帮你解决巴利亚多利德大学学历学位认证难题。<BR>西班牙文凭购买,西班牙文凭定制,西班牙文凭补办。专业在线定制西班牙大学文凭,定做西班牙本科文凭,【q微1954292140】复制西班牙Universidad de Valladolid completion letter。在线快速补办西班牙本科毕业证、硕士文凭证书,购买西班牙学位证、巴利亚多利德大学Offer,西班牙大学文凭在线购买。高仿真还原西班牙文凭证书和外壳,定制西班牙巴利亚多利德大学成绩单和信封。专业定制国外毕业证书UVa毕业证【q微1954292140】办理西班牙巴利亚多利德大学毕业证(UVa毕业证书)【q微1954292140】展示成绩单模板巴利亚多利德大学offer/学位证在线制作本科学位证书、留信官方学历认证(永久存档真实可查)采用学校原版纸张、特殊工艺完全按照原版一比一制作。帮你解决巴利亚多利德大学学历学位认证难题。</P>
Research Project csi1 - This presentation compares popular web browsers such ...bomisung0207
This presentation compares popular web browsers such as Chrome, Safari, Firefox, and Edge.
Topics include speed, security, compatibility, and overall user experience.
2025年新版美国毕业证纽约州立大学德里分校文凭【q微1954292140】办理纽约州立大学德里分校毕业证(SUNYD毕业证书)买大学毕业证|买大学文凭【q微1954292140】纽约州立大学德里分校offer/学位证、留信官方学历认证(永久存档真实可查)采用学校原版纸张、特殊工艺完全按照原版一比一制作【q微1954292140】Buy State University of New York, College of Technology at Delhi Diploma购买美国毕业证,购买英国毕业证,购买澳洲毕业证,购买加拿大毕业证,以及德国毕业证,购买法国毕业证(q微1954292140)购买荷兰毕业证、购买瑞士毕业证、购买日本毕业证、购买韩国毕业证、购买新西兰毕业证、购买新加坡毕业证、购买西班牙毕业证、购买马来西亚毕业证等。包括了本科毕业证,硕士毕业证。
主营项目:
1、真实教育部国外学历学位认证《美国毕业文凭证书快速办理纽约州立大学德里分校毕业证定购》【q微1954292140】《论文没过纽约州立大学德里分校正式成绩单》,教育部存档,教育部留服网站100%可查.
2、办理SUNYD毕业证,改成绩单《SUNYD毕业证明办理纽约州立大学德里分校毕业证书样本》【Q/WeChat:1954292140】Buy State University of New York, College of Technology at Delhi Certificates《正式成绩单论文没过》,纽约州立大学德里分校Offer、在读证明、学生卡、信封、证明信等全套材料,从防伪到印刷,从水印到钢印烫金,高精仿度跟学校原版100%相同.
3、真实使馆认证(即留学人员回国证明),使馆存档可通过大使馆查询确认.
4、留信网认证,国家专业人才认证中心颁发入库证书,留信网存档可查.
《纽约州立大学德里分校成绩单如何办理申请?美国毕业证书办理SUNYD学历证书申请》【q微1954292140】学位证1:1完美还原海外各大学毕业材料上的工艺:水印,阴影底纹,钢印LOGO烫金烫银,LOGO烫金烫银复合重叠。文字图案浮雕、激光镭射、紫外荧光、温感、复印防伪等防伪工艺。
高仿真还原美国文凭证书和外壳,定制美国纽约州立大学德里分校成绩单和信封。研究生offer在线制作SUNYD毕业证【q微1954292140】办理美国纽约州立大学德里分校毕业证(SUNYD毕业证书)【q微1954292140】成绩单定制纽约州立大学德里分校offer/学位证学历认证失败怎么办、留信官方学历认证(永久存档真实可查)采用学校原版纸张、特殊工艺完全按照原版一比一制作。帮你解决纽约州立大学德里分校学历学位认证难题。
美国文凭纽约州立大学德里分校成绩单,SUNYD毕业证【q微1954292140】办理美国纽约州立大学德里分校毕业证(SUNYD毕业证书)【q微1954292140】国外文凭制作代办流程纽约州立大学德里分校offer/学位证毕业证丢失怎么购买、留信官方学历认证(永久存档真实可查)采用学校原版纸张、特殊工艺完全按照原版一比一制作。帮你解决纽约州立大学德里分校学历学位认证难题。
美国文凭购买,美国文凭定制,美国文凭补办。专业在线定制美国大学文凭,定做美国本科文凭,【q微1954292140】复制美国State University of New York, College of Technology at Delhi completion letter。在线快速补办美国本科毕业证、硕士文凭证书,购买美国学位证、纽约州立大学德里分校Offer,美国大学文凭在线购买。
如果您在英、加、美、澳、欧洲等留学过程中或回国后:
1、在校期间因各种原因未能顺利毕业《SUNYD成绩单工艺详解》【Q/WeChat:1954292140】《Buy State University of New York, College of Technology at Delhi Transcript快速办理纽约州立大学德里分校教育部学历认证书毕业文凭证书》,拿不到官方毕业证;
2、面对父母的压力,希望尽快拿到;
3、不清楚认证流程以及材料该如何准备;
4、回国时间很长,忘记办理;
5、回国马上就要找工作《正式成绩单纽约州立大学德里分校修改成绩单GPA》【q微1954292140】《学位证和毕业证SUNYD购买毕业证流程》办给用人单位看;
6、企事业单位必须要求办理的;
7、需要报考公务员、购买免税车、落转户口、申请留学生创业基金。
【q微1954292140】帮您解决在美国纽约州立大学德里分校未毕业难题(State University of New York, College of Technology at Delhi)文凭购买、毕业证购买、大学文凭购买、大学毕业证购买、买文凭、日韩文凭、英国大学文凭、美国大学文凭、澳洲大学文凭、加拿大大学文凭(q微1954292140)新加坡大学文凭、新西兰大学文凭、爱尔兰文凭、西班牙文凭、德国文凭、教育部认证,买毕业证,毕业证购买,买大学文凭,购买日韩毕业证、英国大学毕业证、美国大学毕业证、澳洲大学毕业证、加拿大大学毕业证(q微1954292140)新加坡大学毕业证、新西兰大学毕业证、爱尔兰毕业证、西班牙毕业证、德国毕业证,回国证明,留信网认证,留信认证办理,学历认证。从而完成就业。纽约州立大学德里分校毕业证办理,纽约州立大学德里分校文凭办理,纽约州立大学德里分校成绩单办理和真实留信认证、留服认证、纽约州立大学德里分校学历认证。学院文凭定制,纽约州立大学德里分校原版文凭补办,扫描件文凭定做,100%文凭复刻。
特殊原因导致无法毕业,也可以联系我们帮您办理相关材料:
1:在纽约州立大学德里分校挂科了,不想读了,成绩不理想怎么办???
2:打算回国了,找工作的时候,需要提供认证《SUNYD成绩单购买办理纽约州立大学德里分校毕业证书范本》【Q/WeChat:1954292140】Buy State University of New York, College of Technology at Delhi Diploma《正式成绩单论文没过》有文凭却得不到认证。又该怎么办???美国毕业证购买,美国文凭购买,
3:回国了找工作没有纽约州立大学德里分校文凭怎么办?有本科却要求硕士又怎么办?
Delhi is home to some of the finest business schools in India, offering world-class management education, excellent placement opportunities, and a dynamic learning environment. Whether you aspire to become an entrepreneur, a financial analyst, or a corporate leader, choosing the right business school is crucial.
https://medium.com/@top10privatecollegesindelhi/top-business-schools-in-delhi-a-comprehensive-guide-e97d283efe53
Huckel_Molecular orbital _Theory_8_Slides.pptxstudy2022bsc
Ad
main.pdf java programming practice for programs
1. Page 1 of 16
main.cpp 12/05/2011 23:06
/****
ELE 8050 - Computer Graphics
Sebastian Krezel (29043024)
Advanced Visualisation / Computer Graphics Course Work 2010/2011
The purpose of the course work is to reinforce your understanding of, and your ability to use,
the OpenGL 3D graphics programming library, and the platform independent utility toolkit (the GLUT).
The coursework task is:
Make an interactive version of ‘the Towers of Hanoi game’ (See next page),
Make the simulation using the OpenGL and GLUT libraries,
and provide an elementary user interface so that the game operated from the keyboard
and visualised interactively from different points of view.
Write a formal report in the software engineering style outlining the key steps in designing and building
the program and discuss enhancements you would like to see added to it.
The basic shapes can be build using standard primitives.
Try and augment the visual appearance by placing the model on a mirrored surface,
possibly add shadows and/or make the material take on a coloured metallic lustre using a reflection map,
and/or or use a surface image map or GPU shader to give the material the appearance of wood.
Provide some animation of the moves and facilitate basic interactivity via the keyboard or mouse.
(e.g. to change the viewpoint and select disks to be moved) You will need to think about your user interface design,
e.g. how is the user going to choose the piece to move.
You can generally find a pre-built version of the GLUT library already installed.
But it may be necessary to build the library from its source code.
You may also need to install a development environment,
Visual Studio can be obtained through the MSDNAA. GNU-C/C++ can be obtained for Window and Unix/Linux platforms,
and XCODE is free if you wish to develop on an Apple Mac
If you wanted to be really really adventurous it should possible to develop a version for an
iPhone or Android smart-phone platform. – using their simulators.
This coursework carries 40% of the total marks for the module:
■ 15% for the report and enhancement suggestions
■ 15% for the code design, layout and annotation
■ 10% for the usability and appearance of the finished program
|===3===| | |
|====2====| | |
|=====1=====| | |
--------------------------------------------------
TOWER OF HANOI
****/
#ifdef WIN32
#include "windows.h"
#else
#define WORD unsigned short
#define DWORD unsigned long
#define LONG long
// Structure - BMP file header
typedef struct tagBITMAPFILEHEADER {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER;
// Structure - BMP Info header
typedef struct tagBITMAPINFOHEADER {
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} BITMAPINFOHEADER;
#endif
#if __APPLE__
/*
Tested on: Mac OSX 10.6.4
2. Page 2 of 16
main.cpp 12/05/2011 23:06
XcodeVersion 3.2.4 (64-bit)
Component versions
Xcode IDE: 1708.0
Xcode Core: 1705.0
ToolSupport: 1591.0
Built-In (GPU)
Intel GMA 950:
64MB of Shared System Memory
OenGL ver: 2.1
*/
//Include libraries
#include <stdio.h>
#include <GLUT/glut.h>
#include <iostream>
#include <math.h>
#include <string.h>
#include <ctime>
//PC to MAC bit conversion
unsigned long pc2mac(unsigned long a){
unsigned long b;
b= a & (0x000000ff) << 24;
b |= a & (0x0000ff00) << 8 ;
b |= a & (0x00ff0000) >> 8 ;
b |= a & (0xff000000) >> 24 ;
return b;
}
#else
//Note: Other system has not been tested
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#endif
//Read short int from the file
unsigned short readShortInt(FILE *f){
unsigned short a,b;
fread((char*)&a,2,1,f);
b=a&(0x00ff) << 8;
b |= a&(0xff00) >> 8;
return b;
}
//Read long int from the file
unsigned long readLongInt(FILE *f){
unsigned long a,b;
fread((char*)&a,4,1,f);
b= a & (0x000000ff) << 24;
b |= a & (0x0000ff00) << 8 ;
b |= a & (0x00ff0000) >> 8 ;
b |= a & (0xff000000) >> 24 ;
return b;
}
//Loading BMP file - Use in texturing
unsigned char *LoadBmp(char *fn, int *wi, int *hi){
BITMAPFILEHEADER bmfh;
BITMAPINFOHEADER bmih;
WORD bits;
FILE *t24;
unsigned char *lpBitmapBits;
long imagesize,nc;
// read the bitmap
t24=fopen((char *)fn,"rb");
if(t24 == NULL){printf("Could not open input file [%s]n",fn); exit(0);}
readShortInt(t24);
bmfh.bfSize=readLongInt(t24);
readShortInt(t24);
readShortInt(t24);
bmfh.bfOffBits=readLongInt(t24);
fread((char *)&bmih,sizeof(BITMAPINFOHEADER),1,t24);
if(bmih.biClrUsed != 0)nc=bmih.biClrUsed;
else{
bits = bmih.biBitCount;
switch (bits){
case 1: nc=2; break;
case 4: nc=16; break;
case 8: nc=256; break;
default: nc=0; break;
}
}
if(nc > 0) {
3. Page 3 of 16
main.cpp 12/05/2011 23:06
printf("Cannot handle paletted imagen");
exit(0);
}
imagesize = bmfh.bfSize - bmfh.bfOffBits;
printf("You have to allocate %ld n", imagesize);
lpBitmapBits = (unsigned char *)malloc(imagesize);
if(lpBitmapBits == NULL) {
printf("Cannot allocate memoryn");
fclose(t24);
exit (0);
}
fread((char *)lpBitmapBits,imagesize,1,t24);
fclose(t24);
#if __APPLE__
*wi=pc2mac(bmih.biWidth); *hi=pc2mac(bmih.biHeight);
#else
*wi=bmih.biWidth; *hi=bmih.biHeight;
#endif
return lpBitmapBits;
}
//Use standard namespace
using namespace std;
///////////////////////////////////////////////////////////
// Global variables
//This size fit nice (not hiding the dock )
//on my current resolution 1280 x 800
GLint WindowWidth = 1240; //1280;
GLint WindowHeight = 680; //800;
//to indicate rotate angle (board, light source)
GLfloat rtri = 0.0, Rlight = 0.0, rtrBoard = 0.0;
//Variables used in options (menu)
GLboolean menu_light = false;
GLboolean menu_texture = false;
GLboolean menu_solve = false;
GLboolean menu_restart = false;
GLboolean menu_surface = false;
GLboolean menu_restart_view = false;
GLboolean menu_details = false;
//Indicator of intro animation
GLboolean Gintro = true;
//Used in displaying details
GLint min_steps;
GLint no_steps;
//Time counter
time_t tstart = time(0), tend, tcount;
struct tm *current;
//Buffer for string conversions
char buffer [40];
//Light details
GLfloat fAmbLight[] = { 0.9f, 0.9f, 0.9f, 0.0f };
GLfloat fDiffLight[] = { 1.0f, 1.0f, 1.0f, 0.0f };
GLfloat fSpecLight[] = { 0.9f, 0.9f, 0.9f, 0.0f };
GLfloat lightPos[] = {1.67f, 1.0f,-2.0f, 1.0f };
GLfloat border = 1; // used in light_move()
//Texturing
GLuint nTexture[7];
//Handle information about disk on each peg
GLint *peg_A, *peg_B, *peg_C;
//Game level, number of disk
GLint no_of_disk;
//Camera set up point
GLfloat camera_x = 4.3,
camera_y = 6,
camera_z = 7.25;
//Camera set up point for intro
GLfloat intro_camera_x = -48.5,
intro_camera_y = 20,
intro_camera_z = 7.25;
GLdouble posX, posY, posZ, //Handle mouse position in 3d space
4. Page 4 of 16
main.cpp 12/05/2011 23:06
ghostX, ghostY; //position of animated disk (ghost disk)
//Approximation of round objects
const GLfloat ROUND = 30;
//Hight from reflective surface
GLfloat HEIGHT = 0.0f;
//Details of the disk movement
GLint from = 0, to = 0;
//Mouse movement
GLfloat moveX = 0.0;
//Quadric - cylinders, spheres
GLUquadricObj *IDquadric;
//Mouse button is holed
bool lbuttonDown = false;
///////////////////////////////////////////////
// Tesselate floor
void drawFloor(void) {
float x, y, d = 1.0;
// Draw ground.
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, nTexture[6]);
glTranslatef(0.0, 0.1, 0.0);
glNormal3f(0,1,0);
// Tesselate floor so lighting looks more reasonable.
for (x=-8; x<=7; x+=d) {
glBegin(GL_QUAD_STRIP);
for (y=-8; y<=8; y+=d) {
glTexCoord2f(x+1, y);
glVertex3f(x+1, 0, y);
glTexCoord2f(x, y);
glVertex3f(x, 0, y);
}
glEnd();
}
glDisable(GL_TEXTURE_2D);
}
///////////////////////////////////////////////////////////
// Check if you win
bool win() {
int count = 0;
//Calculate who many disk you have on peg_C
for(int i = 0; i < no_of_disk; i++) {
if (peg_C[i] == i+1) count += 1;
}
//If all disk are on "C" you win
if (count == no_of_disk) {
return true;
}else return false;
}
///////////////////////////////////////////////////////////
// Initialize game details
void init_hanoi() {
//First clean up
delete [] peg_A;
delete [] peg_B;
delete [] peg_C;
//Allocate tables plus one cell to store index of the top disk
peg_A = new int[no_of_disk + 1];
peg_B = new int[no_of_disk + 1];
peg_C = new int[no_of_disk + 1];
for (int i = 0; i < no_of_disk; i++) {
//Put all disk at the first peg and clear others
peg_A[i] = i+1;
peg_B[i] = 0;
peg_C[i] = 0;
}
//Put the proper flag at the end of the table
peg_A[no_of_disk] = no_of_disk;
peg_B[no_of_disk] = 0;
5. Page 5 of 16
main.cpp 12/05/2011 23:06
peg_C[no_of_disk] = 0;
//Init variables used in Details
no_steps = 0;
min_steps = pow(2, no_of_disk) - 1;
if (lbuttonDown) tstart = time(0);
}
///////////////////////////////////////////////////////////
// Conversion between window and openGL
// return the correct OpenGL coordinates from mouse coordinates
void GetOGLPos(int x, int y) {
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
winX = (float)x;
winY = (float)viewport[3] - (float)y;
glReadPixels(x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
}
///////////////////////////////////////////////////////////
// Move peg from S-source to D-destination peg
bool move_it(int *S, int *D) {
int S_index, D_index;
//Check if you have disk to be moved
if (S[no_of_disk] == 0) {
return false;
} else {
S_index = S[no_of_disk] - 1;
//Peg is empty so we can put disk on it
if ((D[no_of_disk] == 0)) {
D[0] = S[S_index];
S[S_index] = 0;
S[no_of_disk] -= 1;
D[no_of_disk] += 1;
no_steps +=1; //Count this move
return true;
} else D_index = D[no_of_disk];
//Check if possible to move
if (S[S_index] > D[D_index - 1]) {
D[D_index] = S[S_index];
S[S_index] = 0;
S[no_of_disk] -= 1;
D[no_of_disk] += 1;
no_steps +=1; //Count this move
return true;
} else {
//You cant put bigger on smaller
return false;
}
}
}
///////////////////////////////////////////////////////////
// This function shows game details in the console
// It was used for testing purposes while implementing "solve_it()" function
//
// Example:
//
//
// //Test legal move between A and B Track solving steps:
// if (!move_it(B, C)) { [ 3 ][ 0 ][ 1 ]
// move_it(C,B); [ 0 ][ 0 ][ 2 ]
// console_hanoi(A,B,C); [ 0 ][ 0 ][ 0 ]
// } else console_hanoi(A,B,C); ___________________
// [ 1 ][ 0 ][ 2 ]
//
// currently not used to keep final code clear
6. Page 6 of 16
main.cpp 12/05/2011 23:06
void console_hanoi (int *A, int *B, int *C) {
cout << "Track solving steps:" << endl;
//For simplicity show it up side down
for (int i = 0; i < no_of_disk + 1; i++) {
if (i == no_of_disk) cout << "___________________" << endl;
//Display flags, number of disk on the peg
cout << "[ " << A[i] << " ]" << "[ " << B[i] << " ]" << "[ " << C[i] << " ]" << endl;
}
cout << endl << endl;
}
///////////////////////////////////////////////////////////
// Function is solving the game
void solve_it(int *A, int *B, int *C) {
//Use iterative solution
//In each case (even,odd), a total of 2n-1 moves are made.
//For an even number of disks:
if (no_of_disk % 2 == 0) {
//make the legal move between pegs A and B
if (!move_it(A,B)) move_it(B,A);
//make the legal move between pegs A and C
if (!move_it(A, C)) move_it(C,A);
//make the legal move between pegs B and C
if (!move_it(B, C)) move_it(C,B);
//For odd number of disk
} else {
//make the legal move between pegs A and C
if (!move_it(A,C)) move_it(C,A);
else {
//If solved just go out from this function
if (win()) return;
}
//make the legal move between pegs A and B
if (!move_it(A,B)) move_it(B,A);
//make the legal move between pegs B and C
if (!move_it(B,C)) move_it(C,B);
}
}
///////////////////////////////////////////////////////////
// Draw "ghost" disk to help track user movement and improve interface
void ghost_disk (GLfloat x, GLfloat y) {
int index;
//GLfloat h = 0; //hight position
GLfloat radius = 0, r_max = 1.1; //declare radius var
GLfloat r_step = 0.9 / no_of_disk; //calculate difference in radius between disks
switch (from) {
case 1:
if (peg_A[no_of_disk] != 0) {
index = peg_A[no_of_disk] -1;
radius = r_max - ((peg_A[index] - 1) * r_step);
radius += 0.01; //Make it a bit bigger then original
}
break;
case 2:
if (peg_B[no_of_disk] != 0) {
index = peg_B[no_of_disk] -1;
radius = r_max - ((peg_B[index] - 1) * r_step);
radius += 0.01; //Make it a bit bigger then original
}
break;
case 3:
if (peg_C[no_of_disk] != 0) {
index = peg_C[no_of_disk] -1;
radius = r_max - ((peg_C[index] - 1) * r_step);
radius += 0.01; //Make it a bit bigger then original
}
break;
default:
break;
}
//Draw the ghost disk with proper radius and place on proper height
glPushMatrix();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, nTexture[4]);
glRotatef(90, 1.0f, 0.0, 0.0);
glTranslatef(x, 0.0, 0.0);
7. Page 7 of 16
main.cpp 12/05/2011 23:06
gluCylinder(IDquadric, radius, radius, 0.30f, ROUND, ROUND);
gluDisk(IDquadric, 0.125f, radius, ROUND, ROUND);
//Bottom circle of the disk - not really visible
//so we don't have to draw it
glDisable(GL_TEXTURE_2D);
glPopMatrix();
}
///////////////////////////////////////////////////////////
//Mouse button is clicked/hold...
//defining drag and drop disk movement
void mouse(int button, int state, int x, int y) {
//Use only left mouse button to drag and drop disk
if (button == GLUT_LEFT_BUTTON) {
if (state == GLUT_DOWN) {
lbuttonDown = true;
GetOGLPos(x,y);
//Check what peg you "drag"
if (posX > -4.0 and posX < -1.34 and posY > 0) from = 1; //peg_A
if (posX > -1.3 and posX < 1.32 and posY > 0) from = 2; //peg_B
if (posX > 1.32 and posX < 4 and posY > 0) from = 3; //peg_C
if (win()) {
//Go to next level, Put limit of 13 disk
//It fit nice on pegs
if (no_of_disk < 13) no_of_disk += 1;
//Initialise new level
init_hanoi();
//go back to normal view - stop spinning
rtri = 0;
}
}
else {
lbuttonDown = false;
GetOGLPos(x,y);
//If drop disk on peg A
if (posX > -4.0 and posX < -1.34 and posY > 0) {
to = 1; //peg_A
switch (from) {
case 1:
break;
case 2:
move_it(peg_B, peg_A);
break;
case 3:
move_it(peg_C, peg_A);
break;
}
}
//If drop disk on peg B
if (posX > -1.3 and posX < 1.32 and posY > 0) {
to = 2; //peg_B
switch (from) {
case 1:
move_it(peg_A, peg_B);
break;
case 2:
break;
case 3:
move_it(peg_C, peg_B);
break;
}
}
//If drop disk on peg C
if (posX > 1.32 and posX < 4 and posY > 0) {
to = 3; //peg_C
switch (from) {
case 1:
move_it(peg_A, peg_C);
break;
case 2:
move_it(peg_B, peg_C);
break;
case 3:
break;
}
}
}
}
}
8. Page 8 of 16
main.cpp 12/05/2011 23:06
///////////////////////////////////////////////////////////
//Mouse motion
void motion(int x, int y) {
//If you hold left button and move mouse
//Update position of the cursor to refresh
//Animation of "ghost disk"
if (lbuttonDown) {
GetOGLPos(x, y);
}
}
///////////////////////////////////////////////////////////
// Defining key action
void processSpecialKeys(int key, int x, int y) {
switch(key) {
case GLUT_KEY_F1:
menu_restart = !menu_restart;
tstart = time(0);
break;
case GLUT_KEY_F2:
//Place disks on start position Before solving
//Avoid infinitive loops in iterative algorithm
menu_restart = true;
menu_solve = !menu_solve;
break;
case GLUT_KEY_F3:
menu_texture = !menu_texture;
break;
case GLUT_KEY_F4:
menu_surface = !menu_surface;
break;
case GLUT_KEY_F5:
menu_light = !menu_light;
break;
case GLUT_KEY_F6:
menu_restart_view = !menu_restart_view;
break;
case GLUT_KEY_F7:
menu_details = !menu_details;
break;
}
}
///////////////////////////////////////////////////////////
// Defining key action
void processNormalKeys(unsigned char key, int x, int y) {
//Light settings
if(key == 'q') lightPos[2] -= 0.25;
if(key == 'a') lightPos[2] += 0.25;
if(key == 'f') lightPos[0] += 0.25;
if(key == 's') lightPos[0] -= 0.25;
if(key == 'e') lightPos[1] += 0.25;
if(key == 'd') lightPos[1] -= 0.25;
//Camera positions
if (key == 'p') camera_z -= 0.25f;
if (key == ';') camera_z += 0.25f;
if (key == 'o')
//Don't go to low
//don't show whats under the board
if (camera_y > 0.5) camera_y -= 0.5f;
if (key == 'l') camera_y += 0.25f;
if (key == 'i') camera_x -= 0.25f;
if (key == 'k') camera_x += 0.25f;
if(key == 27) exit(0);
// Refresh the Window
glutPostRedisplay();
}
///////////////////////////////////////////////////////////////////////////////
// Reset flags as appropriate in response to menu selections
void ProcessMenu(int value) {
switch(value) {
case 1:
menu_restart = !menu_restart;
tstart = time(0);
break;
case 2:
//Place disks on start position Before solving
//Avoid infinitive loops in iterative algorithm
9. Page 9 of 16
main.cpp 12/05/2011 23:06
menu_restart = true;
menu_solve = !menu_solve;
break;
case 3:
menu_texture = !menu_texture;
break;
case 4:
menu_surface = !menu_surface;
break;
case 5:
menu_light = !menu_light;
break;
case 6:
menu_restart_view = !menu_restart_view;
break;
case 7:
menu_details = !menu_details;
break;
default:
break;
}
glutPostRedisplay();
}
///////////////////////////////////////////////////////////////////////////////
//process submenu - chose number of disk on board
void num_disk(int value) {
no_of_disk = value;
//Initialise with new number
init_hanoi();
tstart = time(0);
glutPostRedisplay();
}
///////////////////////////////////////////////////////////
// Called to clean quadric
void cleanupQuadric(void) {
gluDeleteQuadric(IDquadric);
cout << "cleanupQuadric completed" << endl;
}
///////////////////////////////////////////////////////////
// Called to clean up arrays
void cleanupArrays(void) {
delete [] peg_A;
delete [] peg_B;
delete [] peg_C;
peg_A = NULL;
peg_B = NULL;
peg_C = NULL;
cout << "cleanupArray completed" << endl;
}
///////////////////////////////////////////////////////////
// Called to draw a mirrored surface
void Surface() {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, nTexture[1]);
glBegin(GL_POLYGON);
glNormal3f(0.0, 1.0, 0.0);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 8.0f, 0.15f,-8.0f); // Top Right Of The Quad (Top)
glTexCoord2f(0.0f, 1.0f); glVertex3f(-8.0f, 0.15f,-8.0f); // Top Left Of The Quad (Top)
glTexCoord2f(0.0f, 0.0f); glVertex3f(-8.0f, 0.15f, 8.0f); // Bottom Left Of The Quad (Top)
glTexCoord2f(1.0f, 0.0f); glVertex3f( 8.0f, 0.15f, 8.0f); // Bottom Right Of The Quad (Top)
glEnd();
glDisable(GL_TEXTURE_2D);
}
///////////////////////////////////////////////////////////
// Called to draw disk
// Depends of parameter type it draws disk with different textures
void draw_disk (GLfloat radius, GLfloat x, GLfloat h, GLboolean type) {
//Rough wood looking disks
//Use two different textures
if (type) {
glPushMatrix();
10. Page 10 of 16
main.cpp 12/05/2011 23:06
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, nTexture[4]);
glRotatef(90, 1.0f, 0.0, 0.0);
glTranslatef(x, 0.0, -h -0.6);
//Main part of the disk
gluCylinder(IDquadric,radius,radius,0.30f,ROUND, ROUND);
glDisable(GL_TEXTURE_2D);
//Top cover of the disk
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, nTexture[3]);
gluDisk(IDquadric,0.125f,radius,ROUND,ROUND);
//Bottom circle of the disk - not really visible
//so we don't have to draw it
glDisable(GL_TEXTURE_2D);
glPopMatrix();
//Use one texture for drawing
} else {
glPushMatrix();
glRotatef(90, 1.0f, 0.0, 0.0);
glTranslatef(x, 0.0, -h -0.4);
//Main part of the disk
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, nTexture[0]);
gluCylinder(IDquadric,radius,radius,0.30f,ROUND, ROUND);
gluDisk(IDquadric, 0.125f, radius, ROUND, ROUND);
//Bottom not visible
glDisable(GL_TEXTURE_2D);
glPopMatrix();
}
}
///////////////////////////////////////////////////////////
// Called to draw peg
void draw_peg(GLfloat x) {
glEnable(GL_TEXTURE_2D);
if (menu_texture)
glBindTexture(GL_TEXTURE_2D, nTexture[5]);
else
glBindTexture(GL_TEXTURE_2D, nTexture[0]);
glPushMatrix();
glTranslatef(x,0,0);
glRotatef(270.0, 1.0f, 0.0f, 0.0f);
gluCylinder(IDquadric, 0.15f, //base radius
0.1f, //top radius
4.0f, //height
ROUND, //approximation
ROUND //...
);
glTranslatef(0,0,4);
gluSphere(IDquadric,0.1f,ROUND,ROUND);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
///////////////////////////////////////////////////////////
// Called to draw game board
void draw_board() {
glEnable(GL_TEXTURE_2D);
if (menu_texture) glBindTexture(GL_TEXTURE_2D, nTexture[5]);
else glBindTexture(GL_TEXTURE_2D, nTexture[0]);
glBegin(GL_QUADS); // Start Drawing Hanoi board
glNormal3f(0.0, 1.0, 0.0); //Use to point proper sides for lighting
glTexCoord2f(1.0f, 1.0f); glVertex3f( 4.0f, 0.15f,-2.0f); // Top Right Of The Quad (Top)
glTexCoord2f(0.0f, 1.0f); glVertex3f(-4.0f, 0.15f,-2.0f); // Top Left Of The Quad (Top)
glTexCoord2f(0.0f, 0.0f); glVertex3f(-4.0f, 0.15f, 2.0f); // Bottom Left Of The Quad (Top)
glTexCoord2f(1.0f, 0.0f); glVertex3f( 4.0f, 0.15f, 2.0f); // Bottom Right Of The Quad (Top)
glNormal3f(0.0, -1.0, 0.0);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 4.0f,-0.15f, 2.0f); // Top Right Of The Quad (Bottom)
glTexCoord2f(0.0f, 1.0f); glVertex3f(-4.0f,-0.15f, 2.0f); // Top Left Of The Quad (Bottom)
glTexCoord2f(0.0f, 0.0f); glVertex3f(-4.0f,-0.15f,-2.0f); // Bottom Left Of The Quad (Bottom)
glTexCoord2f(1.0f, 0.0f); glVertex3f( 4.0f,-0.15f,-2.0f); // Bottom Right Of The Quad (Bottom)
glNormal3f(0.0, 0.0, 1.0);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 4.0f, 0.15f, 2.0f); // Top Right Of The Quad (Front)
11. Page 11 of 16
main.cpp 12/05/2011 23:06
glTexCoord2f(1.0f, 0.0f); glVertex3f(-4.0f, 0.15f, 2.0f); // Top Left Of The Quad (Front)
glTexCoord2f(1.0f, 1.0f); glVertex3f(-4.0f,-0.15f, 2.0f); // Bottom Left Of The Quad (Front)
glTexCoord2f(0.0f, 1.0f); glVertex3f( 4.0f,-0.15f, 2.0f); // Bottom Right Of The Quad (Front)
glNormal3f(0.0, 0.0, -1.0);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 4.0f,-0.15f,-2.0f); // Bottom Left Of The Quad (Back)
glTexCoord2f(1.0f, 1.0f); glVertex3f(-4.0f,-0.15f,-2.0f); // Bottom Right Of The Quad (Back)
glTexCoord2f(0.0f, 1.0f); glVertex3f(-4.0f, 0.15f,-2.0f); // Top Right Of The Quad (Back)
glTexCoord2f(0.0f, 0.0f); glVertex3f( 4.0f, 0.15f,-2.0f); // Top Left Of The Quad (Back)
glNormal3f(-1.0, 0.0, 0.0);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-4.0f, 0.15f, 2.0f); // Top Right Of The Quad (Left)
glTexCoord2f(1.0f, 0.0f); glVertex3f(-4.0f, 0.15f,-2.0f); // Top Left Of The Quad (Left)
glTexCoord2f(1.0f, 1.0f); glVertex3f(-4.0f,-0.15f,-2.0f); // Bottom Left Of The Quad (Left)
glTexCoord2f(0.0f, 1.0f); glVertex3f(-4.0f,-0.15f, 2.0f); // Bottom Right Of The Quad (Left)
glNormal3f(1.0, 0.0, 0.0);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 4.0f, 0.15f,-2.0f); // Top Right Of The Quad (Right)
glTexCoord2f(1.0f, 1.0f); glVertex3f( 4.0f, 0.15f, 2.0f); // Top Left Of The Quad (Right)
glTexCoord2f(0.0f, 1.0f); glVertex3f( 4.0f,-0.15f, 2.0f); // Bottom Left Of The Quad (Right)
glTexCoord2f(0.0f, 0.0f); glVertex3f( 4.0f,-0.15f,-2.0f); // Bottom Right Of The Quad (Right)
glEnd(); // Done Drawing
glDisable(GL_TEXTURE_2D);
}
///////////////////////////////////////////////////////////
//Functions draws all disks in the game radius depends of numbers
//of disk in the game
void draw_all_disks () {
GLfloat h = 0; //hight position
GLfloat r, r_max = 1.1; //declare radius var
GLfloat r_step = 0.9 / no_of_disk; //calculate difference in radius between disks
for (int i = 0; i < no_of_disk; i++) {
//draw on peg A
if (peg_A[i] != 0) {
//Calculate radius of the disk
r = r_max - ((peg_A[i] - 1) * r_step);
draw_disk (r, -2.5, h, menu_texture);
}
//draw on peg B
if (peg_B[i] != 0) {
//Calculate radius of the disk
r = r_max - ((peg_B[i] - 1) * r_step);
draw_disk (r, 0.0, h, menu_texture);
}
//draw on peg C
if (peg_C[i] != 0) {
//Calculate radius of the disk
r = r_max - ((peg_C[i] - 1) * r_step);
draw_disk (r, 2.5, h, menu_texture);
}
h += 0.3; //Move it up
}
}
///////////////////////////////////////////////////////////
//Function draw light source
//on the scene
void Draw_Light_Source () {
glPushMatrix();
glTranslatef(lightPos[0], lightPos[1], lightPos[2]);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, nTexture[2]);
glPushMatrix();
glRotatef(Rlight, 1.0, 1.0, 1.0);
gluSphere(IDquadric,0.15f,ROUND,ROUND);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glPopMatrix();
}
//////////////////////////////////////////////////////////////////////////
// To move light stripe slowly
void light_move() {
//Move just on y and z axis
lightPos[1] = 8.5;
lightPos[2] = -15.75;
//Set up range of movement
if (border == 1) {
12. Page 12 of 16
main.cpp 12/05/2011 23:06
lightPos[0] += 0.1;
if (lightPos[0] > 20.0) border = 0;
} else {
lightPos[0] -= 0.1;
if (lightPos[0] < -20.0) border = 1;
}
}
///////////////////////////////////////////////////////////
//Function combine all objets that have to be draw
void Draw_Hanoi () {
glPushMatrix();
draw_board(); //main board
draw_peg(0); //first stick
draw_peg(-2.5); //second stick
draw_peg(2.5); //third stick
draw_all_disks(); //draw disks
glPopMatrix();
}
///////////////////////////////////////////////////////////////////
//Function calculate camera position for intro animation purpose
bool intro() {
if (intro_camera_x < 3.5) intro_camera_x += 0.8;
//camera_x = -48.5,
if (intro_camera_y > 6) {
intro_camera_y -= 0.15;
return true;
} else return false;
}
///////////////////////////////////////////////////////////////////
//Function Display the text (r,g,b colours) on "viewing plane"
void DrawText(GLint x, GLint y, char* s, GLfloat r, GLfloat g, GLfloat b)
{
int lines;
char* p;
glDisable(GL_LIGHTING); //To get proper colour
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
//Change to Ortho
glOrtho(0.0, glutGet(GLUT_WINDOW_WIDTH),
0.0, glutGet(GLUT_WINDOW_HEIGHT), -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glColor3f(r,g,b);
glRasterPos2i(x, y);
for(p = s, lines = 0; *p; p++) {
if (*p == 'n') {
lines++;
glRasterPos2i(x, y-(lines*18));
}
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *p);
}
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glEnable(GL_LIGHTING); //Turn it back
}
///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glLoadIdentity(); //Re-set the view
glEnable(GL_NORMALIZE);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
//If flag is set up show light source
if (menu_light) Draw_Light_Source();
if (!intro())
13. Page 13 of 16
main.cpp 12/05/2011 23:06
gluLookAt(camera_x, camera_y, camera_z, // look from camera XYZ
0, 0, 0, // look at the origin
0, 1, 0 // positive Y up vector
);
else gluLookAt(intro_camera_x, intro_camera_y, intro_camera_z, 0, 0, 0, 0, 1, 0);
glScaled(1.1, 1.1, 1.1); //Make it a bit bigger
glRotatef(rtri,0.0f,1.0f,0.0f); //Rotate if Win
Draw_Hanoi(); //Draw board with disks
if (menu_surface) HEIGHT = 0.2;
else HEIGHT = 0;
glTranslatef(0.0f, -HEIGHT-0.3, 0.0f); //Place on surface
glEnable(GL_STENCIL_TEST); //Enable using the stencil buffer
glColorMask(0, 0, 0, 0); //Disable drawing colours to the screen
glDisable(GL_DEPTH_TEST); //Disable depth testing
glStencilFunc(GL_ALWAYS, 1, 1); //Make the stencil test always pass
//Make pixels in the stencil buffer be set to 1 when the stencil test passes
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
//Set all of the pixels covered by the floor to be 1 in the stencil buffer
//Draw mirrored plane
if (menu_surface) drawFloor();
else Surface();
glColorMask(1, 1, 1, 1); //Enable drawing colours to the screen
glEnable(GL_DEPTH_TEST); //Enable depth testing
//Make the stencil test pass only when the pixel is 1 in the stencil buffer
glStencilFunc(GL_EQUAL, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); //Make the stencil buffer not change
//Draw Game board, reflected vertically, at all pixels where the stencil buffer is 1
glPushMatrix();
glScalef(1, -1, 1);
glTranslatef(0, HEIGHT, 0);
Draw_Hanoi();
glPopMatrix();
glDisable(GL_STENCIL_TEST); //Disable stencil buffer
//Blend the floor onto the screen
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glColor4f(1, 1, 1, 0.9f);
//Draw mirrored plane
if (menu_surface) drawFloor();
else Surface();
glDisable(GL_BLEND);
//If left button is pressed render move tracking disk
if (lbuttonDown) {
glPushMatrix();
glEnable (GL_BLEND);
glDepthMask (GL_FALSE);
glBlendFunc (GL_SRC_ALPHA, GL_ONE);
//Move if you point the game board
if (posX > -4 && posX < 4) {
if (posZ > -2 && posZ < 2) {
glTranslatef(posX, 1.0, posZ);
glColor4f(1, 1, 1, 0.5f);
ghost_disk(0.0, 4.0);
}
}
glDepthMask (GL_TRUE);
glDisable (GL_BLEND);
glPopMatrix();
}
//If you win display a message
if (win()) {
char tmp[50] = "You Solve it, Click to Next Level";
DrawText((glutGet(GLUT_WINDOW_WIDTH) /2) - 140, glutGet(GLUT_WINDOW_HEIGHT) /2, tmp, 1.0, 1.0, 1.0);
}
//If required display dame details
if (menu_details) {
sprintf(buffer, "Number of disks = %d", no_of_disk);
DrawText(20, glutGet(GLUT_WINDOW_HEIGHT) -30, buffer, 0.56, 0.34, 0.05);
sprintf(buffer, "Minimum to solve = %d", min_steps);
DrawText(20, glutGet(GLUT_WINDOW_HEIGHT) -50, buffer, 0.56, 0.34, 0.05);
sprintf(buffer, "Your moves: %d", no_steps);
DrawText(20, glutGet(GLUT_WINDOW_HEIGHT) -70, buffer, 0.56, 0.34, 0.05);
14. Page 14 of 16
main.cpp 12/05/2011 23:06
//Display time
current = localtime(&tcount);
sprintf(buffer, "Time: %02d:%02d:%02dn", current->tm_hour, current->tm_min, current->tm_sec);
DrawText(20, glutGet(GLUT_WINDOW_HEIGHT) -90, buffer, 0.56, 0.34, 0.05);
}
glColor3f(1.0, 1.0, 10.0);
glutSwapBuffers();
}
//////////////////////////////////////////////////////////////////////////
// Change viewing volume and viewport. Called when window is resized
void ChangeSize(int w, int h) {
GLfloat fAspect;
// Prevent a divide by zero
if(h == 0) h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
fAspect = (GLfloat)w/(GLfloat)h;
// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Produce the perspective projection
gluPerspective(60.0f, fAspect, 1.0, 400.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
///////////////////////////////////////////////////////////
// Called by GLUT library when idle
void TimerFunction(int value) {
//If you show light object it will spin
Rlight +=1.2f;
//If you win current level board will spin until mouse button pressed
if (win()) {
rtri+=1.2f;
menu_solve = false;
lightPos[0] = 0.42;
lightPos[1] = 9.75;
lightPos[2] = -22;
}
//If chose run light movement
if (menu_surface) light_move();
//If chose solve puzzles
if (menu_solve) solve_it(peg_A, peg_B, peg_C);
//If restart level
if (menu_restart) {
init_hanoi();
menu_restart = !menu_restart;
}
//Restart view
if (menu_restart_view) {
camera_x = 4.3;
camera_y = 6;
camera_z = 7.25;
menu_restart_view = !menu_restart_view;
}
if (!win()) tend = time(0);
tcount = difftime(tend, tstart);
//Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(1,TimerFunction, 1);
}
///////////////////////////////////////////////////////////
// Setting up texture
void SetupTexture (char *name, int nT) {
unsigned char *pix;
GLint w,h;
glBindTexture(GL_TEXTURE_2D, nT);
15. Page 15 of 16
main.cpp 12/05/2011 23:06
pix = LoadBmp(name,&w,&h);
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, w, h,
0, GL_BGR_EXT, GL_UNSIGNED_BYTE, pix);
free(pix);
pix = NULL;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
///////////////////////////////////////////////////////////
// Setup the rendering state
void SetupRC(void) {
char tmp[50];
glShadeModel(GL_SMOOTH); //Enables Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //Background
IDquadric=gluNewQuadric(); //Create A Pointer To The Quadric Object
gluQuadricNormals(IDquadric, GLU_SMOOTH); //Create Smooth Normals
gluQuadricTexture(IDquadric, GL_TRUE); //Create Texture Coords
no_of_disk = 3; //Game start level
init_hanoi(); //Initialize data
glClearDepth(1.0f); //Depth Buffer Setup
glEnable(GL_DEPTH_TEST); //Enables Depth Testing
glDepthFunc(GL_LEQUAL); //The Type Of Depth Test To Do
// Set up lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FRONT, GL_SPECULAR, fDiffLight);
glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 64);
//Set up blending function
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLightfv(GL_LIGHT0, GL_AMBIENT, fAmbLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, fDiffLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, fSpecLight);
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
//Perspective Calculations
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
//Texturing
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glGenTextures(6, nTexture);
//Prepare all textures for use
//To avoid conversion warning use strcpy
strcpy (tmp,"tex1.bmp"); SetupTexture(tmp, nTexture[0]);
strcpy (tmp,"tex2.bmp"); SetupTexture(tmp, nTexture[1]);
strcpy (tmp,"tex3.bmp"); SetupTexture(tmp, nTexture[2]);
strcpy (tmp,"tex4.bmp"); SetupTexture(tmp, nTexture[3]);
strcpy (tmp,"tex5.bmp"); SetupTexture(tmp, nTexture[4]);
strcpy (tmp,"tex6.bmp"); SetupTexture(tmp, nTexture[5]);
strcpy (tmp,"tex7.bmp"); SetupTexture(tmp, nTexture[6]);
//Clean up at exit
atexit(cleanupQuadric);
atexit(cleanupArrays);
}
///////////////////////////////////////////////////////////
// Main program entry point
int main(int argc, char* argv[]) {
GLint sub;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(WindowWidth, WindowHeight);
glutInitWindowPosition(0, 0); //Place window on left top corner
glutCreateWindow("Tower of Hanoi - Sebastian Krezel - Courswork");
//No of disk - sub menu
sub = glutCreateMenu(num_disk);
glutAddMenuEntry("3", 3);
glutAddMenuEntry("4", 4);
glutAddMenuEntry("5", 5);
glutAddMenuEntry("6", 6);
16. Page 16 of 16
main.cpp 12/05/2011 23:06
glutAddMenuEntry("7", 7);
glutAddMenuEntry("8", 8);
glutAddMenuEntry("9", 9);
glutAddMenuEntry("10", 10);
glutAddMenuEntry("11", 11);
glutAddMenuEntry("12", 12);
glutAddMenuEntry("13", 13);
//Create the Menu
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Restart this level" ,1);
glutAddSubMenu("Pick-up no of disk" ,sub);
glutAddMenuEntry("Solve it for me!" ,2);
glutAddMenuEntry("Change Textures" ,3);
glutAddMenuEntry("Change Surface and Light",4);
glutAddMenuEntry("Show Light Opject" ,5);
glutAddMenuEntry("Restart view" ,6);
glutAddMenuEntry("Show details" ,7);
glutAttachMenu(GLUT_RIGHT_BUTTON);
SetupRC();
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
//Keyboard controls
glutKeyboardFunc(processNormalKeys);
glutSpecialFunc(processSpecialKeys);
//Mouse controls
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutTimerFunc(33, TimerFunction, 1);
glutMainLoop();
return 0;
}