diff --git a/.travis.yml b/.travis.yml index 41f47f09..3f36db8a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,13 +21,17 @@ install: - sudo apt-get update -qq - sudo apt-get install -qq -y ros-hydro-desktop ros-hydro-roscpp-tutorials ros-hydro-rostest ros-hydro-catkin python-catkin-tools - sudo apt-get install -qq -y ros-hydro-roseus + - sudo apt-get install -qq -y liborbit2 liborbit2-dev + - sudo apt-get install -qq -y ros-hydro-move-base-msgs + - sudo apt-get install -qq -y swi-prolog - source /opt/ros/hydro/setup.bash before_script: - ls - - for dir in 20*; do echo "checking $dir"; pkg_dir=`catkin_topological_order $dir`; pkg="${pkg_dir% *}"; src="${pkg_dir##* }"; if [ -e "$dir/$src" ] ; then cp $dir/check*.* $dir/$src; fi; done; + - for dir in 20*; do echo "checking $dir"; pkg_dir=`catkin_topological_order $dir`; pkg="${pkg_dir% *}"; src="${pkg_dir##* }"; check=`ls $dir/check*.* 2>/dev/null`; if [ -e "$dir/$src" -a "$check" ] ; then cp $dir/check*.* $dir/$src; fi; done; + - find . -iname *.test - rdir=`pwd` script: - - for dir in 20*; do echo "checking $dir"; pkg_dir=`catkin_topological_order $dir`; pkg="${pkg_dir% *}"; src="${pkg_dir##* }"; if [ -e "$dir/$src" ] ; then source /opt/ros/hydro/setup.bash; cd $dir; catkin build -v -i; source devel/setup.bash; rospack list; cd $src; EXIT_STATUS=0; for test_file in check*.test; do rostest $pkg $test_file || EXIT_STATUS=1; done; cd $rdir; fi; done; [ $EXIT_STATUS == 0 ] + - for dir in 20*; do echo "checking $dir"; pkg_dir=`catkin_topological_order $dir`; pkg="${pkg_dir% *}"; src="${pkg_dir##* }"; check=`ls $dir/check*.* 2>/dev/null`; if [ -e "$dir/$src" -a "$check" ] ; then source /opt/ros/hydro/setup.bash; cd $dir; catkin build -v -i; source devel/setup.bash; rospack list; cd $src; EXIT_STATUS=0; for test_file in check*.test; do rostest $pkg $test_file || EXIT_STATUS=1; done; cd $rdir; fi; done; [ $EXIT_STATUS == 0 ] after_failure: - find src/ -type d -name .git -prune -o -type f -exec ls -l {} \; - rostest -t beginner_tutorials check1.test diff --git a/20151111/src/enshu_20151111/CMakeLists.txt b/20151111/src/enshu_20151111/CMakeLists.txt new file mode 100644 index 00000000..5936ce29 --- /dev/null +++ b/20151111/src/enshu_20151111/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 2.8.3) +project(enshu_20151111) + +find_package(catkin REQUIRED COMPONENTS) +catkin_package() + +execute_process(COMMAND make -C ${PROJECT_SOURCE_DIR}) + + + diff --git a/20151111/src/enshu_20151111/ExampleMain.java b/20151111/src/enshu_20151111/ExampleMain.java new file mode 100644 index 00000000..49da7f35 --- /dev/null +++ b/20151111/src/enshu_20151111/ExampleMain.java @@ -0,0 +1,8 @@ +public class ExampleMain { + public static void main(String[] args) { + System.loadLibrary("ffi-class_wrap"); + Example e = new Example(); + e.Hello("world"); + e.Sinc(1.0); + } +} diff --git a/20151111/src/enshu_20151111/ExampleMain2.java b/20151111/src/enshu_20151111/ExampleMain2.java new file mode 100644 index 00000000..735b6958 --- /dev/null +++ b/20151111/src/enshu_20151111/ExampleMain2.java @@ -0,0 +1,16 @@ +import com.sun.jna.Library; +import com.sun.jna.Native; + +public class ExampleMain2 { + public interface CLibrary extends Library { + CLibrary INSTANCE = (CLibrary) + Native.loadLibrary("ffi-c", CLibrary.class); + void hello(String str); + double sinc(double x); + } + + public static void main( String[] args) { + CLibrary.INSTANCE.hello("world"); + System.out.println("sinc(1.0) = " + CLibrary.INSTANCE.sinc(1.0)); + } +} diff --git a/20151111/src/enshu_20151111/Makefile b/20151111/src/enshu_20151111/Makefile new file mode 100644 index 00000000..a9705c04 --- /dev/null +++ b/20151111/src/enshu_20151111/Makefile @@ -0,0 +1,63 @@ +all: ffi-c libffiJava.so ffi-c.so callc.so + +ffi-c++.o: ffi-c++.cpp + gcc -c ffi-c++.cpp + +ffi-c++-main.o: ffi-c++-main.c + gcc -c ffi-c++-main.c + +ffi-c: ffi-c++.o ffi-c++-main.o + gcc -o ffi-c $^ -lm + +ffiJava.class: + javac ffiJava.java + +ffiJava.h: ffiJava.class + javah -jni ffiJava + +JAVA_HOME=/usr/lib/jvm/java-6-openjdk-amd64/ +libffiJava.so: ffiJava.h + gcc -shared -fPIC -I${JAVA_HOME}/include -o libffiJava.so ffiJava.c + LD_LIBRARY_PATH=./:${LD_LIBRARY_PATH} java ffiJava + +ffi-c.so: ffi-c.c + gcc -shared -fPIC -o ffi-c.so ffi-c.c -lm + python ffi_python.py + eusgl ffi.l + +callc.so: callc.c + gcc -fPIC -shared -o callc.so callc.c + eusgl callc.l + +_ffi_c.so: + swig -python ffi-c.i + gcc -I/usr/include/python2.7 -shared -fPIC -o _ffi_c.so ffi-c.c ffi-c_wrap.c + python -c 'import ffi_c; ffi_c.hello("hello"); print ffi_c.sinc(1.0)' + +ffi_c.java: + swig -java ffi-c.i + gcc -shared -fPIC -I${JAVA_HOME}/include -o libffi-c_wrap.so ffi-c_wrap.c ffi-c.c + javac ffi_c.java + javac ffi_main.java + LD_LIBRARY_PATH=./:${LD_LIBRARY_PATH} java ffi_main + +libffi-class_wrap.so: + swig -c++ -java ffi-class.i + g++ -shared -fPIC -I ./ -I${JAVA_HOME}/include -o libffi-class_wrap.so ffi-class_wrap.cxx ffi-class.cpp -lm -lstdc++ + javac ffi_class.java ffi_classJNI.java + javac ExampleMain.java + LD_LIBRARY_PATH=./:${LD_LIBRARY_PATH} java ExampleMain + +libffi-c.so: + gcc -shared -fPIC -o libffi-c.so ffi-c.c -lm + javac -classpath .:/usr/share/java/jna-3.2.7.jar ExampleMain2.java + LD_LIBRARY_PATH=./:${LD_LIBRARY_PATH} java -classpath .:/usr/share/java/jna-3.2.7.jar ExampleMain2 + +ffi_cython.so: + python setup.py build_ext --inplace + python -c 'import ffi_cython; ffi_cython.hello2("world"); ffi_cython.sinc2(1.0)' + +.PHONY: callc.c + +clean: + rm *.so *.o *.class ffi_c.java ffiJava.h ffi-c_wrap.c ffi_c.java ffi_cJNI.java ffi_class.java ffi_classJNI.java Example.java libffi-c.so ffi_cython.so ffi-c ffi-class_wrap.cxx ffi_c.py ffi_c.pyc ffi_cython.c diff --git a/20151111/src/enshu_20151111/callc.c b/20151111/src/enshu_20151111/callc.c new file mode 100644 index 00000000..aa9a8189 --- /dev/null +++ b/20151111/src/enshu_20151111/callc.c @@ -0,0 +1,10 @@ +static int (*g)(); + +int setlfunc(int (*f)()) { + g = f; +} + +int callfunc(x) +{ + return ((*g)(x)); +} diff --git a/20151111/src/enshu_20151111/callc.l b/20151111/src/enshu_20151111/callc.l new file mode 100644 index 00000000..edcb1e55 --- /dev/null +++ b/20151111/src/enshu_20151111/callc.l @@ -0,0 +1,12 @@ +(setq m (load-foreign "./callc.so")) + +(defforeign setlfunc m "setlfunc" (:integer) :integer) +(defforeign callfunc m "callfunc" (:integer) :integer) + +(defun-c-callable TEST ((a :integer)) :integer + (format t "TEST is called, arg is ~A~%" a) + (* a a)) + +(setlfunc (pod-address (intern "TEST"))) +(callfunc 12) +(exit) diff --git a/20151111/src/enshu_20151111/ffi-c++-main.c b/20151111/src/enshu_20151111/ffi-c++-main.c new file mode 100644 index 00000000..cd48c040 --- /dev/null +++ b/20151111/src/enshu_20151111/ffi-c++-main.c @@ -0,0 +1,9 @@ +#include + +double sinc(double x); + +int main () { + double f = 1.0; + fprintf(stderr, "sinc(%f) = %f\n", f, sinc(f)); + return 0; +} diff --git a/20151111/src/enshu_20151111/ffi-c++.cpp b/20151111/src/enshu_20151111/ffi-c++.cpp new file mode 100644 index 00000000..6c069774 --- /dev/null +++ b/20151111/src/enshu_20151111/ffi-c++.cpp @@ -0,0 +1,11 @@ +#include + +int f (int) { return 0; } +int f (void) { return 1; } +int g (void) { int i = f(), j = f(0); } + +extern "C" { + double sinc(double x) { + return(sin(x)/x); + } +} diff --git a/20151111/src/enshu_20151111/ffi-c.c b/20151111/src/enshu_20151111/ffi-c.c new file mode 100644 index 00000000..9c228786 --- /dev/null +++ b/20151111/src/enshu_20151111/ffi-c.c @@ -0,0 +1,10 @@ +#include +#include + +void hello(char *str) { + fprintf(stdout, "%s !!\n", str); +} + +double sinc(double x) { + return(sin(x)/x); +} diff --git a/20151111/src/enshu_20151111/ffi-c.i b/20151111/src/enshu_20151111/ffi-c.i new file mode 100644 index 00000000..bae19d1c --- /dev/null +++ b/20151111/src/enshu_20151111/ffi-c.i @@ -0,0 +1,7 @@ +%module ffi_c +%{ + extern void hello(char *str); + extern double sinc(double x); +%} +%include "ffi-c.c" + diff --git a/20151111/src/enshu_20151111/ffi-class.cpp b/20151111/src/enshu_20151111/ffi-class.cpp new file mode 100644 index 00000000..4f466a8c --- /dev/null +++ b/20151111/src/enshu_20151111/ffi-class.cpp @@ -0,0 +1,18 @@ +/* ffi-class.cpp */ +#include +#include +#include + +class Example +{ +public: + Example(void) {}; + ~Example(void) {}; + + void Hello(char *str) { + std::cerr << "hello " << str << "!!" << std::endl; + } + void Sinc(double x){ + std::cerr << "sinc = " << sin(x)/x << std::endl; + } +}; diff --git a/20151111/src/enshu_20151111/ffi-class.i b/20151111/src/enshu_20151111/ffi-class.i new file mode 100644 index 00000000..b29b62f9 --- /dev/null +++ b/20151111/src/enshu_20151111/ffi-class.i @@ -0,0 +1,5 @@ +%module ffi_class +%{ + #include "ffi-class.cpp" +%} +%include "ffi-class.cpp" diff --git a/20151111/src/enshu_20151111/ffi.l b/20151111/src/enshu_20151111/ffi.l new file mode 100755 index 00000000..ff511a90 --- /dev/null +++ b/20151111/src/enshu_20151111/ffi.l @@ -0,0 +1,10 @@ +#!/usr/bin/env eusgl + +(setq m (load-foreign "./ffi-c.so")) +(defforeign sinc m "sinc" (:float) :float) +(defforeign hello m "hello" (:string) :integer) +(format t "sinc=~A~%" (sinc 1.0)) +(format t "hello ")(finish-output t) +(hello "world") +(exit) + diff --git a/20151111/src/enshu_20151111/ffiJava.c b/20151111/src/enshu_20151111/ffiJava.c new file mode 100644 index 00000000..8196a45c --- /dev/null +++ b/20151111/src/enshu_20151111/ffiJava.c @@ -0,0 +1,15 @@ +#include "ffiJava.h" +#include + +JNIEXPORT jdouble JNICALL Java_ffiJava_sinc +(JNIEnv * env, jobject obj, jdouble d) { + d = sin(d)/d; + return d; +} + +JNIEXPORT void JNICALL Java_ffiJava_hello +(JNIEnv *env, jobject obj, jstring s) { + const char *str = (*env)->GetStringUTFChars(env, s, 0); + fprintf(stdout, "%s !\n", str); + (*env)->ReleaseStringUTFChars(env, s, str); +} diff --git a/20151111/src/enshu_20151111/ffiJava.java b/20151111/src/enshu_20151111/ffiJava.java new file mode 100644 index 00000000..d48e3cfd --- /dev/null +++ b/20151111/src/enshu_20151111/ffiJava.java @@ -0,0 +1,13 @@ +import java.io.*; + +public class ffiJava { + private native double sinc(double d); + private native void hello(String str); + + public static void main(String argv[]){ + ffiJava t = new ffiJava(); + System.loadLibrary("ffiJava"); + System.out.print("hello "); t.hello("world"); + System.out.println("sinc(1) = " + t.sinc(1.0f)); + } +} \ No newline at end of file diff --git a/20151111/src/enshu_20151111/ffi_cython.pyx b/20151111/src/enshu_20151111/ffi_cython.pyx new file mode 100644 index 00000000..a0872cb8 --- /dev/null +++ b/20151111/src/enshu_20151111/ffi_cython.pyx @@ -0,0 +1,11 @@ +cdef extern int hello( char *) +cdef extern double sinc(double) + +def hello2(name): + bname = name.encode("utf-8") + cdef char * cname = bname + hello(cname) + + +def sinc2(x): + return sinc(x) diff --git a/20151111/src/enshu_20151111/ffi_euslisp.l b/20151111/src/enshu_20151111/ffi_euslisp.l new file mode 100644 index 00000000..9925bd42 --- /dev/null +++ b/20151111/src/enshu_20151111/ffi_euslisp.l @@ -0,0 +1,6 @@ +(setq m (load-foreign "./ffi-c.so")) +(defforeign sinc m "sinc" (:float) :float) +(defforeign hello m "hello" (:string) :integer) +(format t "sinc~A~%" (sinc 1.0)) +(format t "hello ") +(hello "world") diff --git a/20151111/src/enshu_20151111/ffi_main.java b/20151111/src/enshu_20151111/ffi_main.java new file mode 100644 index 00000000..6d1b62de --- /dev/null +++ b/20151111/src/enshu_20151111/ffi_main.java @@ -0,0 +1,8 @@ +// ffi_main.java +public class ffi_main { + public static void main(String[] args) { + System.loadLibrary("ffi-c_wrap"); + ffi_c.hello("world"); + System.out.println("sinc(1) = " + ffi_c.sinc(1.0)); + } +} diff --git a/20151111/src/enshu_20151111/ffi_python.py b/20151111/src/enshu_20151111/ffi_python.py new file mode 100755 index 00000000..3547ce65 --- /dev/null +++ b/20151111/src/enshu_20151111/ffi_python.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python + +import ctypes +ffi = ctypes.CDLL('./ffi-c.so') +print "hello ", +ffi.hello("world") + +ffi.sinc.argtypes = [ctypes.c_double] +ffi.sinc.restype = ctypes.c_double +print ffi.sinc(1.0) diff --git a/20151111/src/enshu_20151111/glut/Makefile b/20151111/src/enshu_20151111/glut/Makefile new file mode 100644 index 00000000..0f19e9cb --- /dev/null +++ b/20151111/src/enshu_20151111/glut/Makefile @@ -0,0 +1,34 @@ +.SUFFIXES: .c .exe + +OS = $(shell /bin/uname | sed s/-.*//) + +ifeq ($(OS),Cygwin) +CFLAGS = -I/usr/X11R6/include +LIBDIR = -L/usr/X11R6/lib +GLLIBS = -lX11 -L/usr/X11R6/lib -lgl -lglu -lglut +else +CFLAGS = -I/usr/X11R6/include +LIBDIR = -L/usr/X11R6/lib +GLLIBS = -lX11 -L/usr/X11R6/lib -lGL -lGLU -lglut -lm +endif + +all: auxdemo.exe auxdemo-offline.exe cube.exe scube.exe dinoshade.exe + +.l.c: + @echo ""; + +.c.exe: + gcc -g -o $@ $(CFLAGS) $< $(LIBDIR) $(GLLIBS) + +auxdemo-offline.exe: auxdemo.c + gcc -g -o $@ -DOFFLINE_RENDERING $(CFLAGS) $< $(LIBDIR) $(GLLIBS) +auxdemo.exe: auxdemo.c +cube.exe: cube.c +scube.exe: scube.c +dinoshade.exe: dinoshade.c +screendoor.exe: screendoor.c +molehil.exe: molehil.c + +clean: + rm -f *~ *.exe *.exe.stackdump *.ppm + chmod a-x * diff --git a/20151111/src/enshu_20151111/glut/auxdemo.c b/20151111/src/enshu_20151111/glut/auxdemo.c new file mode 100644 index 00000000..0b2c8b1f --- /dev/null +++ b/20151111/src/enshu_20151111/glut/auxdemo.c @@ -0,0 +1,277 @@ +/* http://msdn.microsoft.com/library/default.asp?url=/library/en-us/opengl/oglport_0b71.asp */ + +/* + * Example of an X Window System OpenGL program. + * OpenGL code is taken from auxdemo.c in the Platform SDK + */ +#include +#include +#include +#include +#include +#include +#include + +/* X globals, defines, and prototypes */ +Display *dpy; +Window glwin; +//static int attributes[] = {GLX_DEPTH_SIZE, 16, GLX_DOUBLEBUFFER, None}; +//static int attributes[] = {GLX_RGBA, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_DOUBLEBUFFER, GLX_DEPTH_SIZE, 1, 0}; +static int attributes[] = {GLX_RGBA, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_DEPTH_SIZE, 1, 0}; + +#define SWAPBUFFERS glXSwapBuffers(dpy, glwin) +#define BLACK_INDEX 0 +#define RED_INDEX 1 +#define GREEN_INDEX 2 +#define BLUE_INDEX 4 +#define WIDTH 300 +#define HEIGHT 200 + + +/* OpenGL globals, defines, and prototypes */ +GLfloat latitude, longitude, latinc, longinc; +GLdouble radius; + +#define GLOBE 1 +#define CYLINDER 2 +#define CONE 3 + +GLvoid resize(GLsizei, GLsizei); +GLvoid initializeGL(GLsizei, GLsizei); +GLvoid drawScene(GLvoid); +void polarView( GLdouble, GLdouble, GLdouble, GLdouble); + +static Bool WaitForMapNotify(Display *d, XEvent *e, char *arg) +{ + if ((e->type == MapNotify) && (e->xmap.window == (Window)arg)) { + return GL_TRUE; + } + return GL_FALSE; +} + +void +main(int argc, char **argv) +{ + XVisualInfo *vi; + Colormap cmap; + XSetWindowAttributes swa; + GLXContext cx; + XEvent event; + GLboolean needRedraw = GL_FALSE, recalcModelView = GL_TRUE; + int dummy; + + dpy = XOpenDisplay(NULL); + if (dpy == NULL){ + fprintf(stderr, "could not open display\n"); + exit(1); + } + + if(!glXQueryExtension(dpy, &dummy, &dummy)){ + fprintf(stderr, "could not open display"); + exit(1); + } + + /* find an OpenGL-capable Color Index visual with depth buffer */ + vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributes); + if (vi == NULL) { + fprintf(stderr, "could not get visual\n"); + exit(1); + } + + /* create an OpenGL rendering context */ + cx = glXCreateContext(dpy, vi, None, GL_TRUE); + if (cx == NULL) { + fprintf(stderr, "could not create rendering context\n"); + exit(1); + } + + /* create an X colormap since probably not using default visual */ +#ifndef OFFLINE_RENDERING + cmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen), + vi->visual, AllocNone); + swa.colormap = cmap; + swa.border_pixel = 0; + swa.event_mask = ExposureMask | KeyPressMask | StructureNotifyMask; + glwin = XCreateWindow(dpy, RootWindow(dpy, vi->screen), 0, 0, WIDTH, + HEIGHT, 0, vi->depth, InputOutput, vi->visual, + CWBorderPixel | CWColormap | CWEventMask, &swa); + XSetStandardProperties(dpy, glwin, "xogl", "xogl", None, argv, + argc, NULL); +#else + glwin = glXCreateGLXPixmap(dpy, vi, XCreatePixmap(dpy, RootWindow(dpy, vi->screen), WIDTH, HEIGHT, vi->depth)); +#endif + glXMakeCurrent(dpy, glwin, cx); + +#ifndef OFFLINE_RENDERING + XMapWindow(dpy, glwin); + XIfEvent(dpy, &event, WaitForMapNotify, (char *)glwin); +#endif + + initializeGL(WIDTH, HEIGHT); + resize(WIDTH, HEIGHT); + + /* Animation loop */ + while (1) { + KeySym key; + + while (XPending(dpy)) { + XNextEvent(dpy, &event); + switch (event.type) { + case KeyPress: + XLookupString((XKeyEvent *)&event, NULL, 0, &key, NULL); + switch (key) { + case XK_Left: + longinc += 0.5; + break; + case XK_Right: + longinc -= 0.5; + break; + case XK_Up: + latinc += 0.5; + break; + case XK_Down: + latinc -= 0.5; + break; + } + break; + case ConfigureNotify: + resize(event.xconfigure.width, event.xconfigure.height); + break; + } + } + drawScene(); + } +} + +/* OpenGL code */ + +GLvoid resize( GLsizei width, GLsizei height ) +{ + GLfloat aspect; + + glViewport( 0, 0, width, height ); + + aspect = (GLfloat) width / height; + + glMatrixMode( GL_PROJECTION ); + glLoadIdentity(); + gluPerspective( 45.0, aspect, 3.0, 7.0 ); + glMatrixMode( GL_MODELVIEW ); +} + +GLvoid createObjects() +{ + GLUquadricObj *quadObj; + + glNewList(GLOBE, GL_COMPILE); + quadObj = gluNewQuadric (); + gluQuadricDrawStyle (quadObj, GLU_LINE); + gluSphere (quadObj, 1.5, 16, 16); + glEndList(); + + glNewList(CONE, GL_COMPILE); + quadObj = gluNewQuadric (); + gluQuadricDrawStyle (quadObj, GLU_FILL); + gluQuadricNormals (quadObj, GLU_SMOOTH); + gluCylinder(quadObj, 0.3, 0.0, 0.6, 15, 10); + glEndList(); + + glNewList(CYLINDER, GL_COMPILE); + glPushMatrix (); + glRotatef ((GLfloat)90.0, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); + glTranslatef ((GLfloat)0.0, (GLfloat)0.0, (GLfloat)-1.0); + quadObj = gluNewQuadric (); + gluQuadricDrawStyle (quadObj, GLU_FILL); + gluQuadricNormals (quadObj, GLU_SMOOTH); + gluCylinder (quadObj, 0.3, 0.3, 0.6, 12, 2); + glPopMatrix (); + glEndList(); +} + +GLvoid initializeGL(GLsizei width, GLsizei height) +{ + GLfloat maxObjectSize, aspect; + GLdouble near_plane, far_plane; + + glClearIndex( (GLfloat)BLACK_INDEX); + glClearDepth( 1.0 ); + + glEnable(GL_DEPTH_TEST); + + glMatrixMode( GL_PROJECTION ); + aspect = (GLfloat) width / height; + gluPerspective( 45.0, aspect, 3.0, 7.0 ); + glMatrixMode( GL_MODELVIEW ); + + near_plane = 3.0; + far_plane = 7.0; + maxObjectSize = 3.0F; + radius = near_plane + maxObjectSize/2.0; + + latitude = 0.0F; + longitude = 0.0F; + latinc = 6.0F; + longinc = 2.5F; + + createObjects(); +} + +void polarView(GLdouble radius, GLdouble twist, GLdouble latitude, + GLdouble longitude) +{ + glTranslated(0.0, 0.0, -radius); + glRotated(-twist, 0.0, 0.0, 1.0); + glRotated(-latitude, 1.0, 0.0, 0.0); + glRotated(longitude, 0.0, 0.0, 1.0); + +} + +GLvoid drawScene(GLvoid) +{ + glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + + glPushMatrix(); + + latitude += latinc; + longitude += longinc; + + // polarView( radius, 0, latitude, longitude ); + polarView( radius, 0, latitude/50.0f, longitude/50.0f ); + + glIndexi(RED_INDEX); + glCallList(CONE); + + glIndexi(BLUE_INDEX); + glCallList(GLOBE); + + glIndexi(GREEN_INDEX); + glPushMatrix(); + glTranslatef(0.8F, -0.65F, 0.0F); + glRotatef(30.0F, 1.0F, 0.5F, 1.0F); + glCallList(CYLINDER); + glPopMatrix(); + + glPopMatrix(); + +#ifdef OFFLINE_RENDERING + { + static int i = 0; + char imgbuf[WIDTH*HEIGHT*3]; + glReadBuffer(GL_FRONT); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(0, 0, WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, imgbuf); + + char filename[256]; + sprintf(filename, "test%08d.ppm", i++); + fprintf(stderr, "writing to %s (%7.3f %7.3f)\n", filename, latitude, longitude); + + FILE *fp = fopen(filename, "w+"); + fprintf(fp, "P6\n"); + fprintf(fp, "#\n"); + fprintf(fp, "%d %d 255\n", WIDTH, HEIGHT); + fwrite(imgbuf, 1, WIDTH*HEIGHT*3, fp); + fclose(fp); + } +#endif + SWAPBUFFERS; +} diff --git a/20151111/src/enshu_20151111/glut/auxdemo.l b/20151111/src/enshu_20151111/glut/auxdemo.l new file mode 100644 index 00000000..e299a4ab --- /dev/null +++ b/20151111/src/enshu_20151111/glut/auxdemo.l @@ -0,0 +1,229 @@ +;; http://msdn.microsoft.com/library/default.asp?url=/library/en-us/opengl/oglport_0b71.asp + +;; +;; Example of an X Window System OpenGL program. +;; OpenGL code is taken from auxdemo.c in the Platform SDK +;; + +(in-package "GL") + +;; X globals, defines, and prototypes +(setq attributes + (integer-vector GLX_RGBA GLX_RED_SIZE 8 GLX_GREEN_SIZE 8 + GLX_BLUE_SIZE 8 GLX_DOUBLEBUFFER GLX_DEPTH_SIZE 1 0)) + +(defun SWAPBUFFERS nil (glxSwapBuffers dpy glwin)) +(setq BLACK_INDEX 0) +(setq RED_INDEX 1) +(setq GREEN_INDEX 2) +(setq BLUE_INDEX 4) +(setq WIDTH 300) +(setq HEIGHT 200) + +;; OpenGL globals, defines, and prototypes +(setq *latitude* 0 *longitude* 0 *latinc* 0 *longinc* 0 *radius* 0) +(setq GLOBE 1) +(setq CYLINDER 2) +(setq CONE 3) + +(defun WaitForMapNotify (d e arg) + (if (and (eq (event-type e) :MapNotify) + (eq (event-window arg))) + GL_TRUE GL_FALSE)) + +(defun main nil + (let (vi cmap swa cx + (event (instance x::Xevent)) + (needredraw GL_FALSE) + (recalcmodelview GL_TRUE) + dummy) + + (setq dpy (x::OpenDisplay 0)) + (if (= dpy 0) + (warn "could not open display")) + + (setq dummy 0) + (if (= (glXQueryExtension dpy dummy dummy) 0) + (warn "could not open display")) + + ;; find an OpenGL-capable Color Index visual with depth buffer + (setq vi (glXChooseVisual dpy (x::DefaultScreen dpy) attributes)) + (if (= vi 0) + (warn "could not get visual")) + + ;; create an OpenGL rendering context + (setq cx (glXCreateContext dpy vi 0 GL_TRUE)) + (if (= cx 0) + (warn "could not create rendering context\n")) + + ;; create an X colormap since probably not using default visual + (setq vi-visual (sys:peek vi :long)) +#-:x86_64 + (setq vi-depth (sys:peek (+ vi 12) :long)) +#+:x86_64 + (setq vi-depth (sys:peek (+ vi 20) :integer)) + (setq cmap (x::CreateColormap dpy (x::DefaultRootWindow dpy) + vi-visual 0)) + (setq swa (instance x::SetWindowAttributes)) + (setf (x::SetWindowAttributes-colormap swa) cmap) + (setf (x::SetWindowAttributes-border_pixel swa) 0) + (setf (x::SetWindowAttributes-event_mask swa) + (logior x::ExposureMask x::KeyPressMask x::StructureNotifyMask)) + + (setq glwin (x::CreateWindow dpy + (x::DefaultRootWindow dpy) + 0 0 WIDTH HEIGHT 0 + vi-depth 1 vi-visual + #x2808 swa)) +;;; XSetStandardProperties(dpy, glwin, "xogl", "xogl", None, argv, +;;; argc, NULL); + ;;(x::SetStandardProperties dpy glwin "xogl" "xogl" 0 0 0 0) + + (glXMakeCurrent dpy glwin cx) + + (x::MapWindow dpy glwin) +;;; XIfEvent(dpy, &event, WaitForMapNotify, (char *)glwin); + + (initializeGL WIDTH HEIGHT) + (resize WIDTH HEIGHT) + + ;; Animation loop + (while t + (setq key (make-string 3)) + (while (/= (x::Pending dpy) 0) + (x::NextEvent dpy event) + ;;(drawScene) + (print (x::event-type event)) + (case (x::event-type event) + (:KeyPress + (x::LookupString event 0 0 key 0) + (case (sys::peek key 0 :integer) + (#xff51 ;; XK_Left + (setq *longinc* (+ *longinc* 0.5))) + (#xff53 ;; XK_Right + (setq *longinc* (- *longinc* 0.5))) + (#xff52 ;; XK_Up + (setq *latinc* (+ *latinc* 0.5))) + (#xff54 ;; XK_Down + (setq *latinc* (- *latinc* 0.5))))) + (:ConfigureNotify + (resize (x::event-width event) (x::event-height event))))) + (drawScene) + ) + )) +;; for event debug +(defun p-event (ev) + (dotimes (i (/ (length ev) 4)) + (format t "~8,8X~A" + (sys::peek (+ (sys::address ev) +#-:x86_64 +(+ 8 (* 4 i)) +#+:x86_64 +(+ 16 (* 4 i)) + ) :integer) + (if (= (mod (+ i 1) 8) 0) (format nil "~%") " ")) + )) + +;; OpenGL code +(defun resize (width height) + (let (aspect) + (glViewport 0 0 width height) + (setq aspect (/ (float width) height)) + + (glMatrixMode GL_PROJECTION) + (glLoadIdentity) + ;;(gluPerspective 45.0 aspect 3.0 7.0 ) + (gluPerspectivefv (float-vector 45.0 aspect 3.0 7.0 )) + (glMatrixMode GL_MODELVIEW) + )) + +(defun createObjects nil + (let (quadObj) + (glNewList GLOBE GL_COMPILE) + (setq quadObj (gluNewQuadric)) + (gluQuadricDrawStyle quadObj GLU_LINE) + (gluSphere quadObj 1.5 16 16) + (glEndList) + + (glNewList CONE GL_COMPILE) + (setq quadObj (gluNewQuadric)) + (gluQuadricDrawStyle quadObj GLU_FILL) + (gluQuadricNormals quadObj GLU_SMOOTH) + (gluCylinder quadObj 0.3 0.0 0.6 15 10) + (glEndList) + + (glNewList CYLINDER GL_COMPILE) + (glPushMatrix) + (glRotated 90.0 1.0 0.0 0.0) + (glTranslated 0.0 0.0 -1.0) + (setq quadObj (gluNewQuadric)) + (gluQuadricDrawStyle quadObj GLU_FILL) + (gluQuadricNormals quadObj GLU_SMOOTH) + (gluCylinder quadObj 0.3 0.3 0.6 12 2) + (glPopMatrix) + (glEndList) + )) + +(defun initializeGL (width height) + (let (maxObjectSize aspect near_plane far_plane) + (glClearIndexfv (float-vector BLACK_INDEX)) + (glClearDepth 1.0) + + (glEnable GL_DEPTH_TEST) + + (glMatrixMode GL_PROJECTION) + (setq aspect (/ (float width) height)) + (gluPerspectivefv (float-vector 45.0 aspect 3.0 7.0)) + (glMatrixMode GL_MODELVIEW) + + (setq near_plane 3.0 + far_plane 7.0 + maxObjectSize 3.0F + *radius* (+ near_plane (/ maxObjectSize 2.0))) + + (setq *latitude* 0.0 + *longitude* 0.0 + *latinc* 6.0 + *longinc* 2.5) + + (createObjects) + )) + +(defun polarView (radius twist latitude longitude) + (glTranslated 0.0 0.0 (- radius)) + (glRotated (- twist) 0.0 0.0 1.0) + (glRotated (- latitude) 1.0 0.0 0.0) + (glRotated longitude 0.0 0.0 1.0)) + +(defun drawScene () + (glClear (logior GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT)) + + (glPushMatrix) + + (format t "~A > ~A / ~A > ~A~%" *latitude* *latinc* *longitude* *longinc*) + (setq *latitude* (+ *latitude* *latinc*)) + (setq *longitude* (+ *longitude* *longinc*)) + + ;; polarView( radius, 0, latitude, longitude ); + (polarView *radius* 0 *latitude* *longitude*) + + (glIndexi RED_INDEX) + (glCallList CONE) + + (glIndexi BLUE_INDEX) + (glCallList GLOBE) + + (glIndexi GREEN_INDEX) + (glPushMatrix) + (glTranslated 0.8 -0.65 0.0) + (glRotated 30.0 1.0 0.5 1.0) + (glCallList CYLINDER) + (glPopMatrix) + + (glPopMatrix) + + (SWAPBUFFERS)) + +(in-package "USER") + +(gl::main) \ No newline at end of file diff --git a/20151111/src/enshu_20151111/glut/cube.c b/20151111/src/enshu_20151111/glut/cube.c new file mode 100644 index 00000000..9bf41cd1 --- /dev/null +++ b/20151111/src/enshu_20151111/glut/cube.c @@ -0,0 +1,95 @@ + +/* Copyright (c) Mark J. Kilgard, 1997. */ + +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or + implied. This program is -not- in the public domain. */ + +/* This program was requested by Patrick Earl; hopefully someone else + will write the equivalent Direct3D immediate mode program. */ + +#include + +GLfloat light_diffuse[] = {1.0, 0.0, 0.0, 1.0}; /* Red diffuse light. */ +GLfloat light_position[] = {1.0, 1.0, 1.0, 0.0}; /* Infinite light location. */ +GLfloat n[6][3] = { /* Normals for the 6 faces of a cube. */ + {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, + {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0} }; +GLint faces[6][4] = { /* Vertex indices for the 6 faces of a cube. */ + {0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4}, + {4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} }; +GLfloat v[8][3]; /* Will be filled in with X,Y,Z vertexes. */ + +void +drawBox(void) +{ + int i; + + for (i = 0; i < 6; i++) { + glBegin(GL_QUADS); + glNormal3fv(&n[i][0]); + glVertex3fv(&v[faces[i][0]][0]); + glVertex3fv(&v[faces[i][1]][0]); + glVertex3fv(&v[faces[i][2]][0]); + glVertex3fv(&v[faces[i][3]][0]); + glEnd(); + } +} + +void +display(void) +{ + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + drawBox(); + glutSwapBuffers(); +} + +void +init(void) +{ + /* Setup cube vertex data. */ + v[0][0] = v[1][0] = v[2][0] = v[3][0] = -1; + v[4][0] = v[5][0] = v[6][0] = v[7][0] = 1; + v[0][1] = v[1][1] = v[4][1] = v[5][1] = -1; + v[2][1] = v[3][1] = v[6][1] = v[7][1] = 1; + v[0][2] = v[3][2] = v[4][2] = v[7][2] = 1; + v[1][2] = v[2][2] = v[5][2] = v[6][2] = -1; + + /* Enable a single OpenGL light. */ + glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); + glLightfv(GL_LIGHT0, GL_POSITION, light_position); + glEnable(GL_LIGHT0); + glEnable(GL_LIGHTING); + + /* Use depth buffering for hidden surface elimination. */ + glEnable(GL_DEPTH_TEST); + + /* Setup the view of the cube. */ + glMatrixMode(GL_PROJECTION); + gluPerspective( 40.0, /* field of view in degree */ + 1.0, /* aspect ratio */ + 1.0, /* Z near */ + 10.0 /* Z far */ + ); + glMatrixMode(GL_MODELVIEW); + gluLookAt(0.0, 0.0, 5.0, /* eye is at (0,0,5) */ + 0.0, 0.0, 0.0, /* center is at (0,0,0) */ + 0.0, 1.0, 0.); /* up is in positive Y direction */ + + /* Adjust cube position to be asthetic angle. */ + glTranslatef(0.0, 0.0, -1.0); + glRotatef(60, 1.0, 0.0, 0.0); + glRotatef(-20, 0.0, 0.0, 1.0); +} + +int +main(int argc, char **argv) +{ + glutInit(&argc, argv); + glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); + glutCreateWindow("red 3D lighted cube"); + glutDisplayFunc(display); + init(); + glutMainLoop(); + return 0; /* ANSI C requires main to return int. */ +} diff --git a/20151111/src/enshu_20151111/glut/cube.l b/20151111/src/enshu_20151111/glut/cube.l new file mode 100644 index 00000000..44268e22 --- /dev/null +++ b/20151111/src/enshu_20151111/glut/cube.l @@ -0,0 +1,99 @@ +#| +/* Copyright (c) Mark J. Kilgard, 1997. */ + +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or + implied. This program is -not- in the public domain. */ + +/* This program was requested by Patrick Earl; hopefully someone else + will write the equivalent Direct3D immediate mode program. */ +|# + +;; porting to euslisp by Kei Okada + +(in-package "GL") +(load "glut.l") + +(setq light_diffuse #f(1.0 0.0 0.0 1.0)) ;; Red diffuse light. +(setq light_position #f(1.0 1.0 1.0 0.0)) ;; Infinite light location. +(setq n (make-matrix 6 3 + (list (list -1 0 0) (list 0 1 0) (list 1 0 0) + (list 0 -1 0) (list 0 0 1) (list 0 0 -1)))) +(setq faces (make-matrix 6 4 + (list (list 0 1 2 3) (list 3 2 6 7) (list 7 6 5 4) + (list 4 5 1 0) (list 5 6 2 1) (list 7 4 0 3)))) +(setq v (make-matrix 8 3)) + +(defun drawBox nil + (dotimes (i 6) + (glBegin GL_QUADS) + (glNormal3fv (matrix-row n i)) + (glVertex3fv (matrix-row v (round (aref faces i 0)))) + (glVertex3fv (matrix-row v (round (aref faces i 1)))) + (glVertex3fv (matrix-row v (round (aref faces i 2)))) + (glVertex3fv (matrix-row v (round (aref faces i 3)))) + (glEnd) + )) + +(defun-c-callable display () :integer + (glClear (logior GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT)) + (drawBox) + (glutSwapBuffers) + ) + +(defun init nil + ;; Setup cube vertex data. + (setf (aref v 0 0) -1 (aref v 1 0) -1 (aref v 2 0) -1 (aref v 3 0) -1) + (setf (aref v 4 0) 1 (aref v 5 0) 1 (aref v 6 0) 1 (aref v 7 0) 1) + (setf (aref v 0 1) -1 (aref v 1 1) -1 (aref v 4 1) -1 (aref v 5 1) -1) + (setf (aref v 2 1) 1 (aref v 3 1) 1 (aref v 6 1) 1 (aref v 7 1) 1) + (setf (aref v 0 2) 1 (aref v 3 2) 1 (aref v 4 2) 1 (aref v 7 2) 1) + (setf (aref v 1 2) -1 (aref v 2 2) -1 (aref v 5 2) -1 (aref v 6 2) -1) + + ;; Enable a single OpenGL light. + (glLightfv GL_LIGHT0 GL_DIFFUSE light_diffuse) + (glLightfv GL_LIGHT0 GL_POSITION light_position) + (glEnable GL_LIGHT0) + (glEnable GL_LIGHTING) + + ;; Use depth buffering for hidden surface elimination. + (glEnable GL_DEPTH_TEST) + + ;; Setup the view of the cube. + (glMatrixMode GL_PROJECTION) + (gluPerspective 40.0 ;; field of view in degree + 1.0 ;; aspect ratio + 1.0 ;; Z near + 10.0 ;;Z far + ) + (glMatrixMode GL_MODELVIEW) + (gluLookAt 0.0 0.0 5.0 ;; eye is at (0,0,5) + 0.0 0.0 0.0 ;; center is at (0,0,0) + 0.0 1.0 0.0);; up is in positive Y direction + + ;; Adjust cube position to be asthetic angle. + (glTranslatefv #f(0.0 0.0 -1.0)) + (glRotatefv #f(60.0 1.0 0.0 0.0)) + (glRotatefv #f(-20.0 0.0 0.0 1.0)) + ) + +(defun main nil + (let ((argc "0") + (argv "0") (argv0 (unix::malloc lisp::sizeof-*)) argv1 + (str "red 3D lighted cube")) + (sys::poke 1 argc 0 :integer) + (setq argv1 (make-foreign-string argv0 lisp::sizeof-*)) + (setf (elt argv1 0) 0) + (sys::poke argv0 argv 0 :integer) + (glutInit argc argv) + (glutInitDisplayMode (logior GLUT_DOUBLE GLUT_RGB GLUT_DEPTH)) + (glutCreateWindow (+ (sys:address str) (* lisp::sizeof-* 2))) + (glutDisplayFunc (pod-address 'display)) + (init) + (glutMainLoop) + )) + + +(in-package "USER") + +(gl::main) diff --git a/20151111/src/enshu_20151111/glut/cube1.l b/20151111/src/enshu_20151111/glut/cube1.l new file mode 100644 index 00000000..09cc1a10 --- /dev/null +++ b/20151111/src/enshu_20151111/glut/cube1.l @@ -0,0 +1,37 @@ +;; porting to euslisp by Kei Okada + +(in-package "GL") +(load "cube.l") + +(defun drawBox1 nil + (let (b) + (setq b (make-cube 2 2 2)) + (dolist (f (send b :faces)) + (glBegin GL_QUADS) + (glNormal3fv (send f :normal)) + (dolist (v (cdr (send f :vertices))) + (glVertex3fv v)) + (glEnd) + ) + )) + +(defun-c-callable display1 () :integer + (glClear (logior GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT)) + (drawBox) + (glutSwapBuffers) + ) + +(in-package "USER") +(setq argc "0" + (argv "0") (argv0 (unix::malloc lisp::sizeof-*)) argv1 + (str "red 3D lighted cube")) +(sys::poke 1 argc 0 :integer) +(setq argv1 (make-foreign-string argv0 lisp::sizeof-*)) +(setf (elt argv1 0) 0) +(sys::poke argv0 argv 0 :integer) +(gl::glutInit argc argv) +(gl::glutInitDisplayMode (logior GLUT_DOUBLE GLUT_RGB GLUT_DEPTH)) +(gl::glutCreateWindow (+ (sys:address str) (* lisp::sizeof-* 2))) +(gl::glutDisplayFunc (pod-address 'gl::display1)) +(gl::init) +(glutMainLoop) diff --git a/20151111/src/enshu_20151111/glut/dinoshade.c b/20151111/src/enshu_20151111/glut/dinoshade.c new file mode 100644 index 00000000..911a7111 --- /dev/null +++ b/20151111/src/enshu_20151111/glut/dinoshade.c @@ -0,0 +1,892 @@ + +/* Copyright (c) Mark J. Kilgard, 1994, 1997. */ + +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or + implied. This program is -not- in the public domain. */ + +/* Example for PC game developers to show how to *combine* texturing, + reflections, and projected shadows all in real-time with OpenGL. + Robust reflections use stenciling. Robust projected shadows + use both stenciling and polygon offset. PC game programmers + should realize that neither stenciling nor polygon offset are + supported by Direct3D, so these real-time rendering algorithms + are only really viable with OpenGL. + + The program has modes for disabling the stenciling and polygon + offset uses. It is worth running this example with these features + toggled off so you can see the sort of artifacts that result. + + Notice that the floor texturing, reflections, and shadowing + all co-exist properly. */ + +/* When you run this program: Left mouse button controls the + view. Middle mouse button controls light position (left & + right rotates light around dino; up & down moves light + position up and down). Right mouse button pops up menu. */ + +/* Check out the comments in the "redraw" routine to see how the + reflection blending and surface stenciling is done. You can + also see in "redraw" how the projected shadows are rendered, + + including the use of stenciling and polygon offset. */ + +/* This program is derived from glutdino.c */ + +/* Compile: cc -o dinoshade dinoshade.c -lglut -lGLU -lGL -lXmu -lXext -lX11 -lm */ + +#include +#include +#include +#include /* for cos(), sin(), and sqrt() */ +#include /* OpenGL Utility Toolkit header */ + +/* Some files do not define M_PI... */ +#ifndef M_PI +#define M_PI 3.14159265 +#endif + +/* Variable controlling various rendering modes. */ +static int stencilReflection = 1, stencilShadow = 1, offsetShadow = 1; +static int renderShadow = 1, renderDinosaur = 1, renderReflection = 1; +static int linearFiltering = 0, useMipmaps = 0, useTexture = 1; +static int reportSpeed = 0; +static int animation = 1; +static GLboolean lightSwitch = GL_TRUE; +static int directionalLight = 1; +static int forceExtension = 0; + +/* Time varying or user-controled variables. */ +static float jump = 0.0; +static float lightAngle = 0.0, lightHeight = 20; +GLfloat angle = -150; /* in degrees */ +GLfloat angle2 = 30; /* in degrees */ + +int moving, startx, starty; +int lightMoving = 0, lightStartX, lightStartY; + +enum { + MISSING, EXTENSION, ONE_DOT_ONE +}; +int polygonOffsetVersion; + +static GLdouble bodyWidth = 3.0; +/* *INDENT-OFF* */ +static GLfloat body[][2] = { {0, 3}, {1, 1}, {5, 1}, {8, 4}, {10, 4}, {11, 5}, + {11, 11.5}, {13, 12}, {13, 13}, {10, 13.5}, {13, 14}, {13, 15}, {11, 16}, + {8, 16}, {7, 15}, {7, 13}, {8, 12}, {7, 11}, {6, 6}, {4, 3}, {3, 2}, + {1, 2} }; +static GLfloat arm[][2] = { {8, 10}, {9, 9}, {10, 9}, {13, 8}, {14, 9}, {16, 9}, + {15, 9.5}, {16, 10}, {15, 10}, {15.5, 11}, {14.5, 10}, {14, 11}, {14, 10}, + {13, 9}, {11, 11}, {9, 11} }; +static GLfloat leg[][2] = { {8, 6}, {8, 4}, {9, 3}, {9, 2}, {8, 1}, {8, 0.5}, {9, 0}, + {12, 0}, {10, 1}, {10, 2}, {12, 4}, {11, 6}, {10, 7}, {9, 7} }; +static GLfloat eye[][2] = { {8.75, 15}, {9, 14.7}, {9.6, 14.7}, {10.1, 15}, + {9.6, 15.25}, {9, 15.25} }; +static GLfloat lightPosition[4]; +static GLfloat lightColor[] = {0.8, 1.0, 0.8, 1.0}; /* green-tinted */ +static GLfloat skinColor[] = {0.1, 1.0, 0.1, 1.0}, eyeColor[] = {1.0, 0.2, 0.2, 1.0}; +/* *INDENT-ON* */ + +/* Nice floor texture tiling pattern. */ +static char *circles[] = { + "....xxxx........", + "..xxxxxxxx......", + ".xxxxxxxxxx.....", + ".xxx....xxx.....", + "xxx......xxx....", + "xxx......xxx....", + "xxx......xxx....", + "xxx......xxx....", + ".xxx....xxx.....", + ".xxxxxxxxxx.....", + "..xxxxxxxx......", + "....xxxx........", + "................", + "................", + "................", + "................", +}; + +static void +makeFloorTexture(void) +{ + GLubyte floorTexture[16][16][3]; + GLubyte *loc; + int s, t; + + /* Setup RGB image for the texture. */ + loc = (GLubyte*) floorTexture; + for (t = 0; t < 16; t++) { + for (s = 0; s < 16; s++) { + if (circles[t][s] == 'x') { + /* Nice green. */ + loc[0] = 0x1f; + loc[1] = 0x8f; + loc[2] = 0x1f; + } else { + /* Light gray. */ + loc[0] = 0xaa; + loc[1] = 0xaa; + loc[2] = 0xaa; + } + loc += 3; + } + } + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + if (useMipmaps) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + GL_LINEAR_MIPMAP_LINEAR); + gluBuild2DMipmaps(GL_TEXTURE_2D, 3, 16, 16, + GL_RGB, GL_UNSIGNED_BYTE, floorTexture); + } else { + if (linearFiltering) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + } else { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + } + glTexImage2D(GL_TEXTURE_2D, 0, 3, 16, 16, 0, + GL_RGB, GL_UNSIGNED_BYTE, floorTexture); + } +} + +enum { + X, Y, Z, W +}; +enum { + A, B, C, D +}; + +/* Create a matrix that will project the desired shadow. */ +void +shadowMatrix(GLfloat shadowMat[4][4], + GLfloat groundplane[4], + GLfloat lightpos[4]) +{ + GLfloat dot; + + /* Find dot product between light position vector and ground plane normal. */ + dot = groundplane[X] * lightpos[X] + + groundplane[Y] * lightpos[Y] + + groundplane[Z] * lightpos[Z] + + groundplane[W] * lightpos[W]; + + shadowMat[0][0] = dot - lightpos[X] * groundplane[X]; + shadowMat[1][0] = 0.f - lightpos[X] * groundplane[Y]; + shadowMat[2][0] = 0.f - lightpos[X] * groundplane[Z]; + shadowMat[3][0] = 0.f - lightpos[X] * groundplane[W]; + + shadowMat[X][1] = 0.f - lightpos[Y] * groundplane[X]; + shadowMat[1][1] = dot - lightpos[Y] * groundplane[Y]; + shadowMat[2][1] = 0.f - lightpos[Y] * groundplane[Z]; + shadowMat[3][1] = 0.f - lightpos[Y] * groundplane[W]; + + shadowMat[X][2] = 0.f - lightpos[Z] * groundplane[X]; + shadowMat[1][2] = 0.f - lightpos[Z] * groundplane[Y]; + shadowMat[2][2] = dot - lightpos[Z] * groundplane[Z]; + shadowMat[3][2] = 0.f - lightpos[Z] * groundplane[W]; + + shadowMat[X][3] = 0.f - lightpos[W] * groundplane[X]; + shadowMat[1][3] = 0.f - lightpos[W] * groundplane[Y]; + shadowMat[2][3] = 0.f - lightpos[W] * groundplane[Z]; + shadowMat[3][3] = dot - lightpos[W] * groundplane[W]; + +} + +/* Find the plane equation given 3 points. */ +void +findPlane(GLfloat plane[4], + GLfloat v0[3], GLfloat v1[3], GLfloat v2[3]) +{ + GLfloat vec0[3], vec1[3]; + + /* Need 2 vectors to find cross product. */ + vec0[X] = v1[X] - v0[X]; + vec0[Y] = v1[Y] - v0[Y]; + vec0[Z] = v1[Z] - v0[Z]; + + vec1[X] = v2[X] - v0[X]; + vec1[Y] = v2[Y] - v0[Y]; + vec1[Z] = v2[Z] - v0[Z]; + + /* find cross product to get A, B, and C of plane equation */ + plane[A] = vec0[Y] * vec1[Z] - vec0[Z] * vec1[Y]; + plane[B] = -(vec0[X] * vec1[Z] - vec0[Z] * vec1[X]); + plane[C] = vec0[X] * vec1[Y] - vec0[Y] * vec1[X]; + + plane[D] = -(plane[A] * v0[X] + plane[B] * v0[Y] + plane[C] * v0[Z]); +} + +void +extrudeSolidFromPolygon(GLfloat data[][2], unsigned int dataSize, + GLdouble thickness, GLuint side, GLuint edge, GLuint whole) +{ + static GLUtriangulatorObj *tobj = NULL; + GLdouble vertex[3], dx, dy, len; + int i; + int count = (int) (dataSize / (2 * sizeof(GLfloat))); + + if (tobj == NULL) { + tobj = gluNewTess(); /* create and initialize a GLU + polygon tesselation object */ + gluTessCallback(tobj, GLU_BEGIN, (GLvoid (*) ())glBegin); + gluTessCallback(tobj, GLU_VERTEX, (GLvoid (*) ())glVertex2fv); /* semi-tricky */ + gluTessCallback(tobj, GLU_END, (GLvoid (*) ())glEnd); + } + glNewList(side, GL_COMPILE); + glShadeModel(GL_SMOOTH); /* smooth minimizes seeing + tessellation */ + gluBeginPolygon(tobj); + for (i = 0; i < count; i++) { + vertex[0] = data[i][0]; + vertex[1] = data[i][1]; + vertex[2] = 0; + gluTessVertex(tobj, vertex, data[i]); + } + gluEndPolygon(tobj); + glEndList(); + glNewList(edge, GL_COMPILE); + glShadeModel(GL_FLAT); /* flat shade keeps angular hands + from being "smoothed" */ + glBegin(GL_QUAD_STRIP); + for (i = 0; i <= count; i++) { + /* mod function handles closing the edge */ + glVertex3f(data[i % count][0], data[i % count][1], 0.0); + glVertex3f(data[i % count][0], data[i % count][1], thickness); + /* Calculate a unit normal by dividing by Euclidean + distance. We * could be lazy and use + glEnable(GL_NORMALIZE) so we could pass in * arbitrary + normals for a very slight performance hit. */ + dx = data[(i + 1) % count][1] - data[i % count][1]; + dy = data[i % count][0] - data[(i + 1) % count][0]; + len = sqrt(dx * dx + dy * dy); + glNormal3f(dx / len, dy / len, 0.0); + } + glEnd(); + glEndList(); + glNewList(whole, GL_COMPILE); + glFrontFace(GL_CW); + glCallList(edge); + glNormal3f(0.0, 0.0, -1.0); /* constant normal for side */ + glCallList(side); + glPushMatrix(); + glTranslatef(0.0, 0.0, thickness); + glFrontFace(GL_CCW); + glNormal3f(0.0, 0.0, 1.0); /* opposite normal for other side */ + glCallList(side); + glPopMatrix(); + glEndList(); +} + +/* Enumerants for refering to display lists. */ +typedef enum { + RESERVED, BODY_SIDE, BODY_EDGE, BODY_WHOLE, ARM_SIDE, ARM_EDGE, ARM_WHOLE, + LEG_SIDE, LEG_EDGE, LEG_WHOLE, EYE_SIDE, EYE_EDGE, EYE_WHOLE +} displayLists; + +static void +makeDinosaur(void) +{ + extrudeSolidFromPolygon(body, sizeof(body), bodyWidth, + BODY_SIDE, BODY_EDGE, BODY_WHOLE); + extrudeSolidFromPolygon(arm, sizeof(arm), bodyWidth / 4, + ARM_SIDE, ARM_EDGE, ARM_WHOLE); + extrudeSolidFromPolygon(leg, sizeof(leg), bodyWidth / 2, + LEG_SIDE, LEG_EDGE, LEG_WHOLE); + extrudeSolidFromPolygon(eye, sizeof(eye), bodyWidth + 0.2, + EYE_SIDE, EYE_EDGE, EYE_WHOLE); +} + +static void +drawDinosaur(void) + +{ + glPushMatrix(); + /* Translate the dinosaur to be at (0,8,0). */ + glTranslatef(-8, 0, -bodyWidth / 2); + glTranslatef(0.0, jump, 0.0); + glMaterialfv(GL_FRONT, GL_DIFFUSE, skinColor); + glCallList(BODY_WHOLE); + glTranslatef(0.0, 0.0, bodyWidth); + glCallList(ARM_WHOLE); + glCallList(LEG_WHOLE); + glTranslatef(0.0, 0.0, -bodyWidth - bodyWidth / 4); + glCallList(ARM_WHOLE); + glTranslatef(0.0, 0.0, -bodyWidth / 4); + glCallList(LEG_WHOLE); + glTranslatef(0.0, 0.0, bodyWidth / 2 - 0.1); + glMaterialfv(GL_FRONT, GL_DIFFUSE, eyeColor); + glCallList(EYE_WHOLE); + glPopMatrix(); +} + +static GLfloat floorVertices[4][3] = { + { -20.0, 0.0, 20.0 }, + { 20.0, 0.0, 20.0 }, + { 20.0, 0.0, -20.0 }, + { -20.0, 0.0, -20.0 }, +}; + +/* Draw a floor (possibly textured). */ +static void +drawFloor(void) +{ + glDisable(GL_LIGHTING); + + if (useTexture) { + glEnable(GL_TEXTURE_2D); + } + + glBegin(GL_QUADS); + glTexCoord2f(0.0, 0.0); + glVertex3fv(floorVertices[0]); + glTexCoord2f(0.0, 16.0); + glVertex3fv(floorVertices[1]); + glTexCoord2f(16.0, 16.0); + glVertex3fv(floorVertices[2]); + glTexCoord2f(16.0, 0.0); + glVertex3fv(floorVertices[3]); + glEnd(); + + if (useTexture) { + glDisable(GL_TEXTURE_2D); + } + + glEnable(GL_LIGHTING); +} + +static GLfloat floorPlane[4]; +static GLfloat floorShadow[4][4]; + +static void +redraw(void) +{ + int start, end; + + if (reportSpeed) { + start = glutGet(GLUT_ELAPSED_TIME); + } + + /* Clear; default stencil clears to zero. */ + if ((stencilReflection && renderReflection) || (stencilShadow && renderShadow)) { + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + } else { + /* Avoid clearing stencil when not using it. */ + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + } + + /* Reposition the light source. */ + lightPosition[0] = 12*cos(lightAngle); + lightPosition[1] = lightHeight; + lightPosition[2] = 12*sin(lightAngle); + if (directionalLight) { + lightPosition[3] = 0.0; + } else { + lightPosition[3] = 1.0; + } + + shadowMatrix(floorShadow, floorPlane, lightPosition); + + glPushMatrix(); + /* Perform scene rotations based on user mouse input. */ + glRotatef(angle2, 1.0, 0.0, 0.0); + glRotatef(angle, 0.0, 1.0, 0.0); + + /* Tell GL new light source position. */ + glLightfv(GL_LIGHT0, GL_POSITION, lightPosition); + + if (renderReflection) { + if (stencilReflection) { + /* We can eliminate the visual "artifact" of seeing the "flipped" + dinosaur underneath the floor by using stencil. The idea is + draw the floor without color or depth update but so that + a stencil value of one is where the floor will be. Later when + rendering the dinosaur reflection, we will only update pixels + with a stencil value of 1 to make sure the reflection only + lives on the floor, not below the floor. */ + + /* Don't update color or depth. */ + glDisable(GL_DEPTH_TEST); + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + + /* Draw 1 into the stencil buffer. */ + glEnable(GL_STENCIL_TEST); + glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); + glStencilFunc(GL_ALWAYS, 1, 0xffffffff); + + /* Now render floor; floor pixels just get their stencil set to 1. */ + drawFloor(); + + /* Re-enable update of color and depth. */ + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glEnable(GL_DEPTH_TEST); + + /* Now, only render where stencil is set to 1. */ + glStencilFunc(GL_EQUAL, 1, 0xffffffff); /* draw if ==1 */ + glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); + } + + glPushMatrix(); + + /* The critical reflection step: Reflect dinosaur through the floor + (the Y=0 plane) to make a relection. */ + glScalef(1.0, -1.0, 1.0); + + /* Reflect the light position. */ + glLightfv(GL_LIGHT0, GL_POSITION, lightPosition); + + /* To avoid our normals getting reversed and hence botched lighting + on the reflection, turn on normalize. */ + glEnable(GL_NORMALIZE); + glCullFace(GL_FRONT); + + /* Draw the reflected dinosaur. */ + drawDinosaur(); + + /* Disable noramlize again and re-enable back face culling. */ + glDisable(GL_NORMALIZE); + glCullFace(GL_BACK); + + glPopMatrix(); + + /* Switch back to the unreflected light position. */ + glLightfv(GL_LIGHT0, GL_POSITION, lightPosition); + + if (stencilReflection) { + glDisable(GL_STENCIL_TEST); + } + } + + /* Back face culling will get used to only draw either the top or the + bottom floor. This let's us get a floor with two distinct + appearances. The top floor surface is reflective and kind of red. + The bottom floor surface is not reflective and blue. */ + + /* Draw "bottom" of floor in blue. */ + glFrontFace(GL_CW); /* Switch face orientation. */ + glColor4f(0.1, 0.1, 0.7, 1.0); + drawFloor(); + glFrontFace(GL_CCW); + + if (renderShadow) { + if (stencilShadow) { + /* Draw the floor with stencil value 3. This helps us only + draw the shadow once per floor pixel (and only on the + floor pixels). */ + glEnable(GL_STENCIL_TEST); + glStencilFunc(GL_ALWAYS, 3, 0xffffffff); + glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + } + } + + /* Draw "top" of floor. Use blending to blend in reflection. */ + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(0.7, 0.0, 0.0, 0.3); + glColor4f(1.0, 1.0, 1.0, 0.3); + drawFloor(); + glDisable(GL_BLEND); + + if (renderDinosaur) { + /* Draw "actual" dinosaur, not its reflection. */ + drawDinosaur(); + } + + if (renderShadow) { + + /* Render the projected shadow. */ + + if (stencilShadow) { + + /* Now, only render where stencil is set above 2 (ie, 3 where + the top floor is). Update stencil with 2 where the shadow + gets drawn so we don't redraw (and accidently reblend) the + shadow). */ + glStencilFunc(GL_LESS, 2, 0xffffffff); /* draw if ==1 */ + glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); + } + + /* To eliminate depth buffer artifacts, we use polygon offset + to raise the depth of the projected shadow slightly so + that it does not depth buffer alias with the floor. */ + if (offsetShadow) { + switch (polygonOffsetVersion) { + case EXTENSION: +#ifdef GL_EXT_polygon_offset + glEnable(GL_POLYGON_OFFSET_EXT); + break; +#endif +#ifdef GL_VERSION_1_1 + case ONE_DOT_ONE: + glEnable(GL_POLYGON_OFFSET_FILL); + break; +#endif + case MISSING: + /* Oh well. */ + break; + } + } + + /* Render 50% black shadow color on top of whatever the + floor appareance is. */ + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_LIGHTING); /* Force the 50% black. */ + glColor4f(0.0, 0.0, 0.0, 0.5); + + glPushMatrix(); + /* Project the shadow. */ + glMultMatrixf((GLfloat *) floorShadow); + drawDinosaur(); + glPopMatrix(); + + glDisable(GL_BLEND); + glEnable(GL_LIGHTING); + + if (offsetShadow) { + switch (polygonOffsetVersion) { +#ifdef GL_EXT_polygon_offset + case EXTENSION: + glDisable(GL_POLYGON_OFFSET_EXT); + break; +#endif +#ifdef GL_VERSION_1_1 + case ONE_DOT_ONE: + glDisable(GL_POLYGON_OFFSET_FILL); + break; +#endif + case MISSING: + /* Oh well. */ + break; + } + } + if (stencilShadow) { + glDisable(GL_STENCIL_TEST); + } + } + + glPushMatrix(); + glDisable(GL_LIGHTING); + glColor3f(1.0, 1.0, 0.0); + if (directionalLight) { + /* Draw an arrowhead. */ + glDisable(GL_CULL_FACE); + glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]); + glRotatef(lightAngle * -180.0 / M_PI, 0, 1, 0); + glRotatef(atan(lightHeight/12) * 180.0 / M_PI, 0, 0, 1); + glBegin(GL_TRIANGLE_FAN); + glVertex3f(0, 0, 0); + glVertex3f(2, 1, 1); + glVertex3f(2, -1, 1); + glVertex3f(2, -1, -1); + glVertex3f(2, 1, -1); + glVertex3f(2, 1, 1); + glEnd(); + /* Draw a white line from light direction. */ + glColor3f(1.0, 1.0, 1.0); + glBegin(GL_LINES); + glVertex3f(0, 0, 0); + glVertex3f(5, 0, 0); + glEnd(); + glEnable(GL_CULL_FACE); + } else { + /* Draw a yellow ball at the light source. */ + glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]); + glutSolidSphere(1.0, 5, 5); + } + glEnable(GL_LIGHTING); + glPopMatrix(); + + glPopMatrix(); + + if (reportSpeed) { + glFinish(); + end = glutGet(GLUT_ELAPSED_TIME); + printf("Speed %.3g frames/sec (%d ms)\n", 1000.0/(end-start), end-start); + } + + glutSwapBuffers(); +} + +/* ARGSUSED2 */ +static void +mouse(int button, int state, int x, int y) +{ + if (button == GLUT_LEFT_BUTTON) { + if (state == GLUT_DOWN) { + moving = 1; + startx = x; + starty = y; + } + if (state == GLUT_UP) { + moving = 0; + } + } + if (button == GLUT_MIDDLE_BUTTON) { + if (state == GLUT_DOWN) { + lightMoving = 1; + lightStartX = x; + lightStartY = y; + } + if (state == GLUT_UP) { + lightMoving = 0; + } + } +} + +/* ARGSUSED1 */ +static void +motion(int x, int y) +{ + if (moving) { + angle = angle + (x - startx); + angle2 = angle2 + (y - starty); + startx = x; + starty = y; + glutPostRedisplay(); + } + if (lightMoving) { + lightAngle += (x - lightStartX)/40.0; + lightHeight += (lightStartY - y)/20.0; + lightStartX = x; + lightStartY = y; + glutPostRedisplay(); + } +} + +/* Advance time varying state when idle callback registered. */ +static void +idle(void) +{ + static float time = 0.0; + + time = glutGet(GLUT_ELAPSED_TIME) / 500.0; + + jump = 4.0 * fabs(sin(time)*0.5); + if (!lightMoving) { + lightAngle += 0.03; + } + glutPostRedisplay(); +} + +enum { + M_NONE, M_MOTION, M_LIGHT, M_TEXTURE, M_SHADOWS, M_REFLECTION, M_DINOSAUR, + M_STENCIL_REFLECTION, M_STENCIL_SHADOW, M_OFFSET_SHADOW, + M_POSITIONAL, M_DIRECTIONAL, M_PERFORMANCE +}; + +static void +controlLights(int value) +{ + switch (value) { + case M_NONE: + return; + case M_MOTION: + animation = 1 - animation; + if (animation) { + glutIdleFunc(idle); + } else { + glutIdleFunc(NULL); + } + break; + case M_LIGHT: + lightSwitch = !lightSwitch; + if (lightSwitch) { + glEnable(GL_LIGHT0); + } else { + glDisable(GL_LIGHT0); + } + break; + case M_TEXTURE: + useTexture = !useTexture; + break; + case M_SHADOWS: + renderShadow = 1 - renderShadow; + break; + case M_REFLECTION: + renderReflection = 1 - renderReflection; + break; + case M_DINOSAUR: + renderDinosaur = 1 - renderDinosaur; + break; + case M_STENCIL_REFLECTION: + stencilReflection = 1 - stencilReflection; + break; + case M_STENCIL_SHADOW: + stencilShadow = 1 - stencilShadow; + break; + case M_OFFSET_SHADOW: + offsetShadow = 1 - offsetShadow; + break; + case M_POSITIONAL: + directionalLight = 0; + break; + case M_DIRECTIONAL: + directionalLight = 1; + break; + case M_PERFORMANCE: + reportSpeed = 1 - reportSpeed; + break; + } + glutPostRedisplay(); +} + +/* When not visible, stop animating. Restart when visible again. */ +static void +visible(int vis) +{ + if (vis == GLUT_VISIBLE) { + if (animation) + glutIdleFunc(idle); + } else { + if (!animation) + glutIdleFunc(NULL); + } +} + +/* Press any key to redraw; good when motion stopped and + performance reporting on. */ +/* ARGSUSED */ +static void +key(unsigned char c, int x, int y) +{ + if (c == 27) { + exit(0); /* IRIS GLism, Escape quits. */ + } + glutPostRedisplay(); +} + +/* Press any key to redraw; good when motion stopped and + performance reporting on. */ +/* ARGSUSED */ +static void +special(int k, int x, int y) +{ + glutPostRedisplay(); +} + +static int +supportsOneDotOne(void) +{ + const char *version; + int major, minor; + + version = (char *) glGetString(GL_VERSION); + if (sscanf(version, "%d.%d", &major, &minor) == 2) + return major >= 1 && minor >= 1; + return 0; /* OpenGL version string malformed! */ +} + +int +main(int argc, char **argv) +{ + int i; + + glutInit(&argc, argv); + + for (i=1; i=2 rgb double depth"); +#endif + + glutCreateWindow("Shadowy Leapin' Lizards"); + + if (glutGet(GLUT_WINDOW_STENCIL_SIZE) <= 1) { + printf("dinoshade: Sorry, I need at least 2 bits of stencil.\n"); + exit(1); + } + + /* Register GLUT callbacks. */ + glutDisplayFunc(redraw); + glutMouseFunc(mouse); + glutMotionFunc(motion); + glutVisibilityFunc(visible); + glutKeyboardFunc(key); + glutSpecialFunc(special); + + glutCreateMenu(controlLights); + + glutAddMenuEntry("Toggle motion", M_MOTION); + glutAddMenuEntry("-----------------------", M_NONE); + glutAddMenuEntry("Toggle light", M_LIGHT); + glutAddMenuEntry("Toggle texture", M_TEXTURE); + glutAddMenuEntry("Toggle shadows", M_SHADOWS); + glutAddMenuEntry("Toggle reflection", M_REFLECTION); + glutAddMenuEntry("Toggle dinosaur", M_DINOSAUR); + glutAddMenuEntry("-----------------------", M_NONE); + glutAddMenuEntry("Toggle reflection stenciling", M_STENCIL_REFLECTION); + glutAddMenuEntry("Toggle shadow stenciling", M_STENCIL_SHADOW); + glutAddMenuEntry("Toggle shadow offset", M_OFFSET_SHADOW); + glutAddMenuEntry("----------------------", M_NONE); + glutAddMenuEntry("Positional light", M_POSITIONAL); + glutAddMenuEntry("Directional light", M_DIRECTIONAL); + glutAddMenuEntry("-----------------------", M_NONE); + glutAddMenuEntry("Toggle performance", M_PERFORMANCE); + glutAttachMenu(GLUT_RIGHT_BUTTON); + makeDinosaur(); + +#ifdef GL_VERSION_1_1 + if (supportsOneDotOne() && !forceExtension) { + polygonOffsetVersion = ONE_DOT_ONE; + glPolygonOffset(-2.0, -1.0); + } else +#endif + { +#ifdef GL_EXT_polygon_offset + /* check for the polygon offset extension */ + if (glutExtensionSupported("GL_EXT_polygon_offset")) { + polygonOffsetVersion = EXTENSION; + glPolygonOffsetEXT(-0.1, -0.002); + } else +#endif + { + polygonOffsetVersion = MISSING; + printf("\ndinoshine: Missing polygon offset.\n"); + printf(" Expect shadow depth aliasing artifacts.\n\n"); + } + } + + glEnable(GL_CULL_FACE); + glEnable(GL_DEPTH_TEST); + glEnable(GL_TEXTURE_2D); + glLineWidth(3.0); + + glMatrixMode(GL_PROJECTION); + gluPerspective( /* field of view in degree */ 40.0, + /* aspect ratio */ 1.0, + /* Z near */ 20.0, /* Z far */ 100.0); + glMatrixMode(GL_MODELVIEW); + gluLookAt(0.0, 8.0, 60.0, /* eye is at (0,8,60) */ + 0.0, 8.0, 0.0, /* center is at (0,8,0) */ + 0.0, 1.0, 0.); /* up is in postivie Y direction */ + + glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1); + glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor); + glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1); + glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05); + glEnable(GL_LIGHT0); + glEnable(GL_LIGHTING); + + makeFloorTexture(); + + /* Setup floor plane for projected shadow calculations. */ + findPlane(floorPlane, floorVertices[1], floorVertices[2], floorVertices[3]); + + glutMainLoop(); + return 0; /* ANSI C requires main to return int. */ +} diff --git a/20151111/src/enshu_20151111/glut/glut.l b/20151111/src/enshu_20151111/glut/glut.l new file mode 100644 index 00000000..e80b6ecf --- /dev/null +++ b/20151111/src/enshu_20151111/glut/glut.l @@ -0,0 +1,362 @@ +#+:cygwin +(setq m (load-foreign "/usr/X11R6/bin/cygglut-3.dll")) +#-:cygwin +(setq m (load-foreign "/usr/lib/x86_64-linux-gnu/libglut.so")) + + +;; Display mode bit masks. +(defconstant GLUT_RGB 0) +(defconstant GLUT_RGBA GLUT_RGB) +(defconstant GLUT_INDEX 1) +(defconstant GLUT_SINGLE 0) +(defconstant GLUT_DOUBLE 2) +(defconstant GLUT_ACCUM 4) +(defconstant GLUT_ALPHA 8) +(defconstant GLUT_DEPTH 16) +(defconstant GLUT_STENCIL 32) +(defconstant GLUT_MULTISAMPLE 128) +(defconstant GLUT_STEREO 256) +(defconstant GLUT_LUMINANCE 512) + + +;; Mouse buttons. +(defconstant GLUT_LEFT_BUTTON 0) +(defconstant GLUT_MIDDLE_BUTTON 1) +(defconstant GLUT_RIGHT_BUTTON 2) + +;; Mouse button state. +(defconstant GLUT_DOWN 0) +(defconstant GLUT_UP 1) + +;; function keys +(defconstant GLUT_KEY_F1 1) +(defconstant GLUT_KEY_F2 2) +(defconstant GLUT_KEY_F3 3) +(defconstant GLUT_KEY_F4 4) +(defconstant GLUT_KEY_F5 5) +(defconstant GLUT_KEY_F6 6) +(defconstant GLUT_KEY_F7 7) +(defconstant GLUT_KEY_F8 8) +(defconstant GLUT_KEY_F9 9) +(defconstant GLUT_KEY_F10 10) +(defconstant GLUT_KEY_F11 11) +(defconstant GLUT_KEY_F12 12) +;; directional keys +(defconstant GLUT_KEY_LEFT 100) +(defconstant GLUT_KEY_UP 101) +(defconstant GLUT_KEY_RIGHT 102) +(defconstant GLUT_KEY_DOWN 103) +(defconstant GLUT_KEY_PAGE_UP 104) +(defconstant GLUT_KEY_PAGE_DOWN 105) +(defconstant GLUT_KEY_HOME 106) +(defconstant GLUT_KEY_END 107) +(defconstant GLUT_KEY_INSERT 108) + +;; Entry/exit state. +(defconstant GLUT_LEFT 0) +(defconstant GLUT_ENTERED 1) + +;; Menu usage state. +(defconstant GLUT_MENU_NOT_IN_USE 0) +(defconstant GLUT_MENU_IN_USE 1) + +;; Visibility state. +(defconstant GLUT_NOT_VISIBLE 0) +(defconstant GLUT_VISIBLE 1) + +;;Window status state. +(defconstant GLUT_HIDDEN 0) +(defconstant GLUT_FULLY_RETAINED 1) +(defconstant GLUT_PARTIALLY_RETAINED 2) +(defconstant GLUT_FULLY_COVERED 3) + +;; Color index component selection values. +(defconstant GLUT_RED 0) +(defconstant GLUT_GREEN 1) +(defconstant GLUT_BLUE 2) + +;; Stroke font constants (use these in GLUT program). +(defconstant GLUT_STROKE_ROMAN 0) +(defconstant GLUT_STROKE_MONO_ROMAN 1) + +;;Bitmap font constants (use these in GLUT program). +(defconstant GLUT_BITMAP_9_BY_15 2) +(defconstant GLUT_BITMAP_8_BY_13 3) +(defconstant GLUT_BITMAP_TIMES_ROMAN_10 4) +(defconstant GLUT_BITMAP_TIMES_ROMAN_24 5) +(defconstant GLUT_BITMAP_HELVETICA_10 6) +(defconstant GLUT_BITMAP_HELVETICA_12 7) +(defconstant GLUT_BITMAP_HELVETICA_18 8) + +;; glutGet parameters. +(defconstant GLUT_WINDOW_X 100) +(defconstant GLUT_WINDOW_Y 101) +(defconstant GLUT_WINDOW_WIDTH 102) +(defconstant GLUT_WINDOW_HEIGHT 103) +(defconstant GLUT_WINDOW_BUFFER_SIZE 104) +(defconstant GLUT_WINDOW_STENCIL_SIZE 105) +(defconstant GLUT_WINDOW_DEPTH_SIZE 106) +(defconstant GLUT_WINDOW_RED_SIZE 107) +(defconstant GLUT_WINDOW_GREEN_SIZE 108) +(defconstant GLUT_WINDOW_BLUE_SIZE 109) +(defconstant GLUT_WINDOW_ALPHA_SIZE 110) +(defconstant GLUT_WINDOW_ACCUM_RED_SIZE 111) +(defconstant GLUT_WINDOW_ACCUM_GREEN_SIZE 112) +(defconstant GLUT_WINDOW_ACCUM_BLUE_SIZE 113) +(defconstant GLUT_WINDOW_ACCUM_ALPHA_SIZE 114) +(defconstant GLUT_WINDOW_DOUBLEBUFFER 115) +(defconstant GLUT_WINDOW_RGBA 116) +(defconstant GLUT_WINDOW_PARENT 117) +(defconstant GLUT_WINDOW_NUM_CHILDREN 118) +(defconstant GLUT_WINDOW_COLORMAP_SIZE 119) +(defconstant GLUT_WINDOW_NUM_SAMPLES 120) +(defconstant GLUT_WINDOW_STEREO 121) +(defconstant GLUT_WINDOW_CURSOR 122) +(defconstant GLUT_SCREEN_WIDTH 200) +(defconstant GLUT_SCREEN_HEIGHT 201) +(defconstant GLUT_SCREEN_WIDTH_MM 202) +(defconstant GLUT_SCREEN_HEIGHT_MM 203) +(defconstant GLUT_MENU_NUM_ITEMS 300) +(defconstant GLUT_DISPLAY_MODE_POSSIBLE 400) +(defconstant GLUT_INIT_WINDOW_X 500) +(defconstant GLUT_INIT_WINDOW_Y 501) +(defconstant GLUT_INIT_WINDOW_WIDTH 502) +(defconstant GLUT_INIT_WINDOW_HEIGHT 503) +(defconstant GLUT_INIT_DISPLAY_MODE 504) +(defconstant GLUT_ELAPSED_TIME 700) +(defconstant GLUT_WINDOW_FORMAT_ID 123) + +;; glutDeviceGet parameters. +(defconstant GLUT_HAS_KEYBOARD 600) +(defconstant GLUT_HAS_MOUSE 601) +(defconstant GLUT_HAS_SPACEBALL 602) +(defconstant GLUT_HAS_DIAL_AND_BUTTON_BOX 603) +(defconstant GLUT_HAS_TABLET 604) +(defconstant GLUT_NUM_MOUSE_BUTTONS 605) +(defconstant GLUT_NUM_SPACEBALL_BUTTONS 606) +(defconstant GLUT_NUM_BUTTON_BOX_BUTTONS 607) +(defconstant GLUT_NUM_DIALS 608) +(defconstant GLUT_NUM_TABLET_BUTTONS 609) +(defconstant GLUT_DEVICE_IGNORE_KEY_REPEAT 610) +(defconstant GLUT_DEVICE_KEY_REPEAT 611) +(defconstant GLUT_HAS_JOYSTICK 612) +(defconstant GLUT_OWNS_JOYSTICK 613) +(defconstant GLUT_JOYSTICK_BUTTONS 614) +(defconstant GLUT_JOYSTICK_AXES 615) +(defconstant GLUT_JOYSTICK_POLL_RATE 616) + +;; glutLayerGet parameters. +(defconstant GLUT_OVERLAY_POSSIBLE 800) +(defconstant GLUT_LAYER_IN_USE 801) +(defconstant GLUT_HAS_OVERLAY 802) +(defconstant GLUT_TRANSPARENT_INDEX 803) +(defconstant GLUT_NORMAL_DAMAGED 804) +(defconstant GLUT_OVERLAY_DAMAGED 805) + +;; glutVideoResizeGet parameters. +(defconstant GLUT_VIDEO_RESIZE_POSSIBLE 900) +(defconstant GLUT_VIDEO_RESIZE_IN_USE 901) +(defconstant GLUT_VIDEO_RESIZE_X_DELTA 902) +(defconstant GLUT_VIDEO_RESIZE_Y_DELTA 903) +(defconstant GLUT_VIDEO_RESIZE_WIDTH_DELTA 904) +(defconstant GLUT_VIDEO_RESIZE_HEIGHT_DELTA 905) +(defconstant GLUT_VIDEO_RESIZE_X 906) +(defconstant GLUT_VIDEO_RESIZE_Y 907) +(defconstant GLUT_VIDEO_RESIZE_WIDTH 908) +(defconstant GLUT_VIDEO_RESIZE_HEIGHT 909) + +;; glutUseLayer parameters. +(defconstant GLUT_NORMAL 0) +(defconstant GLUT_OVERLAY 1) + +;; glutGetModifiers return mask. +(defconstant GLUT_ACTIVE_SHIFT 1) +(defconstant GLUT_ACTIVE_CTRL 2) +(defconstant GLUT_ACTIVE_ALT 4) + +;; glutSetCursor parameters. +;; Basic arrows. +(defconstant GLUT_CURSOR_RIGHT_ARROW 0) +(defconstant GLUT_CURSOR_LEFT_ARROW 1) +;; Symbolic cursor shapes. +(defconstant GLUT_CURSOR_INFO 2) +(defconstant GLUT_CURSOR_DESTROY 3) +(defconstant GLUT_CURSOR_HELP 4) +(defconstant GLUT_CURSOR_CYCLE 5) +(defconstant GLUT_CURSOR_SPRAY 6) +(defconstant GLUT_CURSOR_WAIT 7) +(defconstant GLUT_CURSOR_TEXT 8) +(defconstant GLUT_CURSOR_CROSSHAIR 9) +;; Directional cursors. +(defconstant GLUT_CURSOR_UP_DOWN 10) +(defconstant GLUT_CURSOR_LEFT_RIGHT 11) +;; Sizing cursors. +(defconstant GLUT_CURSOR_TOP_SIDE 12) +(defconstant GLUT_CURSOR_BOTTOM_SIDE 13) +(defconstant GLUT_CURSOR_LEFT_SIDE 14) +(defconstant GLUT_CURSOR_RIGHT_SIDE 15) +(defconstant GLUT_CURSOR_TOP_LEFT_CORNER 16) +(defconstant GLUT_CURSOR_TOP_RIGHT_CORNER 17) +(defconstant GLUT_CURSOR_BOTTOM_RIGHT_CORNER 18) +(defconstant GLUT_CURSOR_BOTTOM_LEFT_CORNER 19) +;; Inherit from parent window. +(defconstant GLUT_CURSOR_INHERIT 100) +;; Blank cursor. +(defconstant GLUT_CURSOR_NONE 101) +;; Fullscreen crosshair (if available). +(defconstant GLUT_CURSOR_FULL_CROSSHAIR 102) + +;; GLUT initialization subAPI. +(defforeign glutInit m "glutInit" () :integer) +(defforeign glutInitDisplayMode m "glutInitDisplayMode" () :integer) +(defforeign glutInitWindowPosition m "glutInitWindowPosition" () :integer) +(defforeign glutInitWindowSize m "glutInitWindowSize" () :integer) +(defforeign glutMainLoop m "glutMainLoop" () :integer) + +;; GLUT window sub-API. +(defforeign glutCreateWindow m "glutCreateWindow" () :integer) +(defforeign glutCreateSubWindow m "glutCreateSubWindow" () :integer) +(defforeign glutDestroyWindow m "glutDestroyWindow" () :integer) +(defforeign glutPostRedisplay m "glutPostRedisplay" () :integer) +(defforeign glutPostWindowRedisplay m "glutPostWindowRedisplay" () :integer) +(defforeign glutSwapBuffers m "glutSwapBuffers" () :integer) +(defforeign glutGetWindow m "glutGetWindow" () :integer) +(defforeign glutSetWindow m "glutSetWindow" () :integer) +(defforeign glutSetWindowTitle m "glutSetWindowTitle" () :integer) +(defforeign glutSetIconTitle m "glutSetIconTitle" () :integer) +(defforeign glutPositionWindow m "glutPositionWindow" () :integer) +(defforeign glutReshapeWindow m "glutReshapeWindow" () :integer) +(defforeign glutPopWindow m "glutReshapeWindow" () :integer) +(defforeign glutPushWindow m "glutPushWindow" () :integer) +(defforeign glutIconifyWindow m "glutIconifyWindow" () :integer) +(defforeign glutShowWindow m "glutShowWindow" () :integer) +(defforeign glutHideWindow m "glutHideWindow" () :integer) +(defforeign glutFullScreen m "glutFullScreen" () :integer) +(defforeign glutSetCursor m "glutSetCursor" () :integer) +(defforeign glutWarpPointer m "glutWarpPointer" () :integer) + +;; GLUT overlay sub-API. +(defforeign glutEstablishOverlay m "glutEstablishOverlay" () :integer) +(defforeign glutRemoveOverlay m "glutRemoveOverlay" () :integer) +(defforeign glutUseLayer m "glutUseLayer" () :integer) +(defforeign glutPostOverlayRedisplay m "glutPostOverlayRedisplay" () :integer) +(defforeign glutPostWindowOverlayRedisplay m "glutPostWindowOverlayRedisplay" () :integer) +(defforeign glutShowOverlay m "glutShowOverlay" () :integer) +(defforeign glutHideOverlay m "glutHideOverlay" () :integer) + +;; GLUT menu sub-API. +(defforeign glutCreateMenu m "glutCreateMenu" () :integer) +(defforeign glutDestroyMenu m "glutDestroyMenu" () :integer) +(defforeign glutGetMenu m "glutGetMenu" () :integer) +(defforeign glutSetMenu m "glutSetMenu" () :integer) +(defforeign glutAddMenuEntry m "glutAddMenuEntry" () :integer) +(defforeign glutAddSubMenu m "glutAddSubMenu" () :integer) +(defforeign glutChangeToMenuEntry m "glutChangeToMenuEntry" () :integer) +(defforeign glutChangeToSubMenu m "glutChangeToSubMenu" () :integer) +(defforeign glutRemoveMenuItem m "glutRemoveMenuItem" () :integer) +(defforeign glutAttachMenu m "glutAttachMenu" () :integer) +(defforeign glutDetachMenu m "glutDetachMenu" () :integer) + +;; GLUT window callback sub-API. +(defforeign glutDisplayFunc m "glutDisplayFunc" () :integer) +(defforeign glutReshapeFunc m "glutReshapeFunc" () :integer) +(defforeign glutKeyboardFunc m "glutKeyboardFunc" () :integer) +(defforeign glutMouseFunc m "glutMouseFunc" () :integer) +(defforeign glutMotionFunc m "glutMotionFunc" () :integer) +(defforeign glutPassiveMotionFunc m "glutPassiveMotionFunc" () :integer) +(defforeign glutEntryFunc m "glutEntryFunc" () :integer) +(defforeign glutVisibilityFunc m "glutVisibilityFunc" () :integer) +(defforeign glutIdleFunc m "glutIdleFunc" () :integer) +(defforeign glutTimerFunc m "glutTimerFunc" () :integer) +(defforeign glutMenuStateFunc m "glutMenuStateFunc" () :integer) +(defforeign glutSpecialFunc m "glutSpecialFunc" () :integer) +(defforeign glutSpaceballMotionFunc m "glutSpaceballMotionFunc" () :integer) +(defforeign glutSpaceballRotateFunc m "glutSpaceballRotateFunc" () :integer) +(defforeign glutSpaceballButtonFunc m "glutSpaceballButtonFunc" () :integer) +(defforeign glutButtonBoxFunc m "glutButtonBoxFunc" () :integer) +(defforeign glutDialsFunc m "glutDialsFunc" () :integer) +(defforeign glutTabletMotionFunc m "glutTabletMotionFunc" () :integer) +(defforeign glutTabletButtonFunc m "glutTabletButtonFunc" () :integer) +(defforeign glutMenuStatusFunc m "glutMenuStatusFunc" () :integer) +(defforeign glutOverlayDisplayFunc m "glutOverlayDisplayFunc" () :integer) +(defforeign glutWindowStatusFunc m "glutWindowStatusFunc" () :integer) +(defforeign glutKeyboardUpFunc m "glutKeyboardUpFunc" () :integer) +(defforeign glutSpecialUpFunc m "glutSpecialUpFunc" () :integer) +(defforeign glutJoystickFunc m "glutJoystickFunc" () :integer) + +;; GLUT color index sub-API. +(defforeign glutSetColor m "glutSetColor" () :integer) +(defforeign glutGetColor m "glutGetColor" () :integer) +(defforeign glutCopyColormap m "glutCopyColormap" () :integer) + +;; GLUT state retrieval sub-API. +(defforeign glutGet m "glutGet" () :integer) +(defforeign glutDeviceGet m "glutDeviceGet" () :integer) +(defforeign glutExtensionSupported m "glutExtensionSupported" () :integer) +(defforeign glutGetModifiers m "glutGetModifiers" () :integer) +(defforeign glutLayerGet m "glutLayerGet" () :integer) + +;; GLUT font sub-API +(defforeign glutBitmapCharacter m "glutBitmapCharacter" () :integer) +(defforeign glutBitmapWidth m "glutBitmapWidth" () :integer) +(defforeign glutStrokeCharacter m "glutStrokeCharacter" () :integer) +(defforeign glutStrokeWidth m "glutStrokeWidth" () :integer) +(defforeign glutBitmapLength m "glutBitmapLength" () :integer) +(defforeign glutStrokeLength m "glutStrokeLength" () :integer) + +;; GLUT pre-built models sub-API +(defforeign glutWireSphere m "glutWireSphere" () :integer) +(defforeign glutSolidSphere m "glutSolidSphere" () :integer) +(defforeign glutWireCone m "glutWireCone" () :integer) +(defforeign glutSolidCone m "glutSolidCone" () :integer) +(defforeign glutWireCube m "glutWireCube" () :integer) +(defforeign glutSolidCube m "glutSolidCube" () :integer) +(defforeign glutWireTorus m "glutWireTorus" () :integer) +(defforeign glutSolidTorus m "glutSolidTorus" () :integer) +(defforeign glutWireDodecahedron m "glutWireDodecahedron" () :integer) +(defforeign glutSolidDodecahedron m "glutSolidDodecahedron" () :integer) +(defforeign glutWireTeapot m "glutWireTeapot" () :integer) +(defforeign glutSolidTeapot m "glutSolidTeapot" () :integer) +(defforeign glutWireOctahedron m "glutWireOctahedron" () :integer) +(defforeign glutSolidOctahedron m "glutSolidOctahedron" () :integer) +(defforeign glutWireTetrahedron m "glutWireTetrahedron" () :integer) +(defforeign glutSolidTetrahedron m "glutSolidTetrahedron" () :integer) +(defforeign glutWireIcosahedron m "glutWireIcosahedron" () :integer) +(defforeign glutSolidIcosahedron m "glutSolidIcosahedron" () :integer) + +;; GLUT video resize sub-API. +(defforeign glutVideoResizeGet m "glutVideoResizeGet" () :integer) +(defforeign glutSetupVideoResizing m "glutSetupVideoResizing" () :integer) +(defforeign glutStopVideoResizing m "glutStopVideoResizing" () :integer) +(defforeign glutVideoResize m "glutVideoResize" () :integer) +(defforeign glutVideoPan m "glutVideoPan" () :integer) + +;; GLUT debugging sub-API. +(defforeign glutReportErrors m "glutReportErrors" () :integer) + +;; GLUT device control sub-API. +;; glutSetKeyRepeat modes. +(defconstant GLUT_KEY_REPEAT_OFF 0) +(defconstant GLUT_KEY_REPEAT_ON 1) +(defconstant GLUT_KEY_REPEAT_DEFAULT 2) + +;; Joystick button masks. +(defconstant GLUT_JOYSTICK_BUTTON_A 1) +(defconstant GLUT_JOYSTICK_BUTTON_B 2) +(defconstant GLUT_JOYSTICK_BUTTON_C 4) +(defconstant GLUT_JOYSTICK_BUTTON_D 8) + +(defforeign glutIgnoreKeyRepeat m "glutIgnoreKeyRepeat" () :integer) +(defforeign glutSetKeyRepeat m "glutSetKeyRepeat" () :integer) +(defforeign glutForceJoystickFunc m "glutForceJoystickFunc" () :integer) + +;; GLUT game mode sub-API. +;; glutGameModeGet. +(defconstant GLUT_GAME_MODE_ACTIVE 0) +(defconstant GLUT_GAME_MODE_POSSIBLE 1) +(defconstant GLUT_GAME_MODE_WIDTH 2) +(defconstant GLUT_GAME_MODE_HEIGHT 3) +(defconstant GLUT_GAME_MODE_PIXEL_DEPTH 4) +(defconstant GLUT_GAME_MODE_REFRESH_RATE 5) +(defconstant GLUT_GAME_MODE_DISPLAY_CHANGED 6) + diff --git a/20151111/src/enshu_20151111/glut/scube.c b/20151111/src/enshu_20151111/glut/scube.c new file mode 100644 index 00000000..6d52807a --- /dev/null +++ b/20151111/src/enshu_20151111/glut/scube.c @@ -0,0 +1,703 @@ + +/* Copyright (c) Mark J. Kilgard, 1994. */ + +/** + * (c) Copyright 1993, 1994, Silicon Graphics, Inc. + * ALL RIGHTS RESERVED + * Permission to use, copy, modify, and distribute this software for + * any purpose and without fee is hereby granted, provided that the above + * copyright notice appear in all copies and that both the copyright notice + * and this permission notice appear in supporting documentation, and that + * the name of Silicon Graphics, Inc. not be used in advertising + * or publicity pertaining to distribution of the software without specific, + * written prior permission. + * + * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" + * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR + * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON + * GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, + * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY + * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, + * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF + * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN + * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE + * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. + * + * US Government Users Restricted Rights + * Use, duplication, or disclosure by the Government is subject to + * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph + * (c)(1)(ii) of the Rights in Technical Data and Computer Software + * clause at DFARS 252.227-7013 and/or in similar or successor + * clauses in the FAR or the DOD or NASA FAR Supplement. + * Unpublished-- rights reserved under the copyright laws of the + * United States. Contractor/manufacturer is Silicon Graphics, + * Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311. + * + * OpenGL(TM) is a trademark of Silicon Graphics, Inc. + */ + +/* + * 1992 David G Yu -- Silicon Graphics Computer Systems + */ + +#include +#include +#include +#include +#include + +static int useRGB = 1; +static int useLighting = 1; +static int useFog = 0; +static int useDB = 1; +static int useLogo = 0; +static int useQuads = 1; + +static int tick = -1; +static int moving = 1; + +#define GREY 0 +#define RED 1 +#define GREEN 2 +#define BLUE 3 +#define CYAN 4 +#define MAGENTA 5 +#define YELLOW 6 +#define BLACK 7 + +static float materialColor[8][4] = +{ + {0.8, 0.8, 0.8, 1.0}, + {0.8, 0.0, 0.0, 1.0}, + {0.0, 0.8, 0.0, 1.0}, + {0.0, 0.0, 0.8, 1.0}, + {0.0, 0.8, 0.8, 1.0}, + {0.8, 0.0, 0.8, 1.0}, + {0.8, 0.8, 0.0, 1.0}, + {0.0, 0.0, 0.0, 0.6}, +}; + +static float lightPos[4] = +{2.0, 4.0, 2.0, 1.0}; +#if 0 +static float lightDir[4] = +{-2.0, -4.0, -2.0, 1.0}; +#endif +static float lightAmb[4] = +{0.2, 0.2, 0.2, 1.0}; +static float lightDiff[4] = +{0.8, 0.8, 0.8, 1.0}; +static float lightSpec[4] = +{0.4, 0.4, 0.4, 1.0}; + +static float groundPlane[4] = +{0.0, 1.0, 0.0, 1.499}; +static float backPlane[4] = +{0.0, 0.0, 1.0, 0.899}; + +static float fogColor[4] = +{0.0, 0.0, 0.0, 0.0}; +static float fogIndex[1] = +{0.0}; + +static unsigned char shadowPattern[128] = +{ + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, /* 50% Grey */ + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, + 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55 +}; + +static unsigned char sgiPattern[128] = +{ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* SGI Logo */ + 0xff, 0xbd, 0xff, 0x83, 0xff, 0x5a, 0xff, 0xef, + 0xfe, 0xdb, 0x7f, 0xef, 0xfd, 0xdb, 0xbf, 0xef, + 0xfb, 0xdb, 0xdf, 0xef, 0xf7, 0xdb, 0xef, 0xef, + 0xfb, 0xdb, 0xdf, 0xef, 0xfd, 0xdb, 0xbf, 0x83, + 0xce, 0xdb, 0x73, 0xff, 0xb7, 0x5a, 0xed, 0xff, + 0xbb, 0xdb, 0xdd, 0xc7, 0xbd, 0xdb, 0xbd, 0xbb, + 0xbe, 0xbd, 0x7d, 0xbb, 0xbf, 0x7e, 0xfd, 0xb3, + 0xbe, 0xe7, 0x7d, 0xbf, 0xbd, 0xdb, 0xbd, 0xbf, + 0xbb, 0xbd, 0xdd, 0xbb, 0xb7, 0x7e, 0xed, 0xc7, + 0xce, 0xdb, 0x73, 0xff, 0xfd, 0xdb, 0xbf, 0xff, + 0xfb, 0xdb, 0xdf, 0x87, 0xf7, 0xdb, 0xef, 0xfb, + 0xf7, 0xdb, 0xef, 0xfb, 0xfb, 0xdb, 0xdf, 0xfb, + 0xfd, 0xdb, 0xbf, 0xc7, 0xfe, 0xdb, 0x7f, 0xbf, + 0xff, 0x5a, 0xff, 0xbf, 0xff, 0xbd, 0xff, 0xc3, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff +}; + +static float cube_vertexes[6][4][4] = +{ + { + {-1.0, -1.0, -1.0, 1.0}, + {-1.0, -1.0, 1.0, 1.0}, + {-1.0, 1.0, 1.0, 1.0}, + {-1.0, 1.0, -1.0, 1.0}}, + + { + {1.0, 1.0, 1.0, 1.0}, + {1.0, -1.0, 1.0, 1.0}, + {1.0, -1.0, -1.0, 1.0}, + {1.0, 1.0, -1.0, 1.0}}, + + { + {-1.0, -1.0, -1.0, 1.0}, + {1.0, -1.0, -1.0, 1.0}, + {1.0, -1.0, 1.0, 1.0}, + {-1.0, -1.0, 1.0, 1.0}}, + + { + {1.0, 1.0, 1.0, 1.0}, + {1.0, 1.0, -1.0, 1.0}, + {-1.0, 1.0, -1.0, 1.0}, + {-1.0, 1.0, 1.0, 1.0}}, + + { + {-1.0, -1.0, -1.0, 1.0}, + {-1.0, 1.0, -1.0, 1.0}, + {1.0, 1.0, -1.0, 1.0}, + {1.0, -1.0, -1.0, 1.0}}, + + { + {1.0, 1.0, 1.0, 1.0}, + {-1.0, 1.0, 1.0, 1.0}, + {-1.0, -1.0, 1.0, 1.0}, + {1.0, -1.0, 1.0, 1.0}} +}; + +static float cube_normals[6][4] = +{ + {-1.0, 0.0, 0.0, 0.0}, + {1.0, 0.0, 0.0, 0.0}, + {0.0, -1.0, 0.0, 0.0}, + {0.0, 1.0, 0.0, 0.0}, + {0.0, 0.0, -1.0, 0.0}, + {0.0, 0.0, 1.0, 0.0} +}; + +static void +usage(void) +{ + printf("\n"); + printf("usage: scube [options]\n"); + printf("\n"); + printf(" display a spinning cube and its shadow\n"); + printf("\n"); + printf(" Options:\n"); + printf(" -geometry window size and location\n"); + printf(" -c toggle color index mode\n"); + printf(" -l toggle lighting\n"); + printf(" -f toggle fog\n"); + printf(" -db toggle double buffering\n"); + printf(" -logo toggle sgi logo for the shadow pattern\n"); + printf(" -quads toggle use of GL_QUADS to draw the checkerboard\n"); + printf("\n"); +#ifndef EXIT_FAILURE /* should be defined by ANSI C + */ +#define EXIT_FAILURE 1 +#endif + exit(EXIT_FAILURE); +} + +void +buildColormap(void) +{ + if (useRGB) { + return; + } else { + int mapSize = 1 << glutGet(GLUT_WINDOW_BUFFER_SIZE); + int rampSize = mapSize / 8; + int entry; + int i; + + for (entry = 0; entry < mapSize; ++entry) { + int hue = entry / rampSize; + GLfloat val = (entry % rampSize) * (1.0 / (rampSize - 1)); + GLfloat red, green, blue; + + red = (hue == 0 || hue == 1 || hue == 5 || hue == 6) ? val : 0; + green = (hue == 0 || hue == 2 || hue == 4 || hue == 6) ? val : 0; + blue = (hue == 0 || hue == 3 || hue == 4 || hue == 5) ? val : 0; + + glutSetColor(entry, red, green, blue); + } + + for (i = 0; i < 8; ++i) { + materialColor[i][0] = i * rampSize + 0.2 * (rampSize - 1); + materialColor[i][1] = i * rampSize + 0.8 * (rampSize - 1); + materialColor[i][2] = i * rampSize + 1.0 * (rampSize - 1); + materialColor[i][3] = 0.0; + } + + fogIndex[0] = -0.2 * (rampSize - 1); + } +} + +static void +setColor(int c) +{ + if (useLighting) { + if (useRGB) { + glMaterialfv(GL_FRONT_AND_BACK, + GL_AMBIENT_AND_DIFFUSE, &materialColor[c][0]); + } else { + glMaterialfv(GL_FRONT_AND_BACK, + GL_COLOR_INDEXES, &materialColor[c][0]); + } + } else { + if (useRGB) { + glColor4fv(&materialColor[c][0]); + } else { + glIndexf(materialColor[c][1]); + } + } +} + +static void +drawCube(int color) +{ + int i; + + setColor(color); + + for (i = 0; i < 6; ++i) { + glNormal3fv(&cube_normals[i][0]); + glBegin(GL_POLYGON); + glVertex4fv(&cube_vertexes[i][0][0]); + glVertex4fv(&cube_vertexes[i][1][0]); + glVertex4fv(&cube_vertexes[i][2][0]); + glVertex4fv(&cube_vertexes[i][3][0]); + glEnd(); + } +} + +static void +drawCheck(int w, int h, int evenColor, int oddColor) +{ + static int initialized = 0; + static int usedLighting = 0; + static GLuint checklist = 0; + + if (!initialized || (usedLighting != useLighting)) { + static float square_normal[4] = + {0.0, 0.0, 1.0, 0.0}; + static float square[4][4]; + int i, j; + + if (!checklist) { + checklist = glGenLists(1); + } + glNewList(checklist, GL_COMPILE_AND_EXECUTE); + + if (useQuads) { + glNormal3fv(square_normal); + glBegin(GL_QUADS); + } + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + square[0][0] = -1.0 + 2.0 / w * i; + square[0][1] = -1.0 + 2.0 / h * (j + 1); + square[0][2] = 0.0; + square[0][3] = 1.0; + + square[1][0] = -1.0 + 2.0 / w * i; + square[1][1] = -1.0 + 2.0 / h * j; + square[1][2] = 0.0; + square[1][3] = 1.0; + + square[2][0] = -1.0 + 2.0 / w * (i + 1); + square[2][1] = -1.0 + 2.0 / h * j; + square[2][2] = 0.0; + square[2][3] = 1.0; + + square[3][0] = -1.0 + 2.0 / w * (i + 1); + square[3][1] = -1.0 + 2.0 / h * (j + 1); + square[3][2] = 0.0; + square[3][3] = 1.0; + + if (i & 1 ^ j & 1) { + setColor(oddColor); + } else { + setColor(evenColor); + } + + if (!useQuads) { + glBegin(GL_POLYGON); + } + glVertex4fv(&square[0][0]); + glVertex4fv(&square[1][0]); + glVertex4fv(&square[2][0]); + glVertex4fv(&square[3][0]); + if (!useQuads) { + glEnd(); + } + } + } + + if (useQuads) { + glEnd(); + } + glEndList(); + + initialized = 1; + usedLighting = useLighting; + } else { + glCallList(checklist); + } +} + +static void +myShadowMatrix(float ground[4], float light[4]) +{ + float dot; + float shadowMat[4][4]; + + dot = ground[0] * light[0] + + ground[1] * light[1] + + ground[2] * light[2] + + ground[3] * light[3]; + + shadowMat[0][0] = dot - light[0] * ground[0]; + shadowMat[1][0] = 0.0 - light[0] * ground[1]; + shadowMat[2][0] = 0.0 - light[0] * ground[2]; + shadowMat[3][0] = 0.0 - light[0] * ground[3]; + + shadowMat[0][1] = 0.0 - light[1] * ground[0]; + shadowMat[1][1] = dot - light[1] * ground[1]; + shadowMat[2][1] = 0.0 - light[1] * ground[2]; + shadowMat[3][1] = 0.0 - light[1] * ground[3]; + + shadowMat[0][2] = 0.0 - light[2] * ground[0]; + shadowMat[1][2] = 0.0 - light[2] * ground[1]; + shadowMat[2][2] = dot - light[2] * ground[2]; + shadowMat[3][2] = 0.0 - light[2] * ground[3]; + + shadowMat[0][3] = 0.0 - light[3] * ground[0]; + shadowMat[1][3] = 0.0 - light[3] * ground[1]; + shadowMat[2][3] = 0.0 - light[3] * ground[2]; + shadowMat[3][3] = dot - light[3] * ground[3]; + + glMultMatrixf((const GLfloat *) shadowMat); +} + +static char *windowNameRGBDB = "shadow cube (OpenGL RGB DB)"; +static char *windowNameRGB = "shadow cube (OpenGL RGB)"; +static char *windowNameIndexDB = "shadow cube (OpenGL Index DB)"; +static char *windowNameIndex = "shadow cube (OpenGL Index)"; + +void +idle(void) +{ + tick++; + if (tick >= 120) { + tick = 0; + } + glutPostRedisplay(); +} + +/* ARGSUSED1 */ +void +keyboard(unsigned char ch, int x, int y) +{ + switch (ch) { + case 27: /* escape */ + exit(0); + break; + case 'L': + case 'l': + useLighting = !useLighting; + useLighting ? glEnable(GL_LIGHTING) : + glDisable(GL_LIGHTING); + glutPostRedisplay(); + break; + case 'F': + case 'f': + useFog = !useFog; + useFog ? glEnable(GL_FOG) : glDisable(GL_FOG); + glutPostRedisplay(); + break; + case '1': + glFogf(GL_FOG_MODE, GL_LINEAR); + glutPostRedisplay(); + break; + case '2': + glFogf(GL_FOG_MODE, GL_EXP); + glutPostRedisplay(); + break; + case '3': + glFogf(GL_FOG_MODE, GL_EXP2); + glutPostRedisplay(); + break; + case ' ': + if (!moving) { + idle(); + glutPostRedisplay(); + } + } +} + +void +display(void) +{ + GLfloat cubeXform[4][4]; + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glPushMatrix(); + glTranslatef(0.0, -1.5, 0.0); + glRotatef(-90.0, 1, 0, 0); + glScalef(2.0, 2.0, 2.0); + + drawCheck(6, 6, BLUE, YELLOW); /* draw ground */ + glPopMatrix(); + + glPushMatrix(); + glTranslatef(0.0, 0.0, -0.9); + glScalef(2.0, 2.0, 2.0); + + drawCheck(6, 6, BLUE, YELLOW); /* draw back */ + glPopMatrix(); + + glPushMatrix(); + glTranslatef(0.0, 0.2, 0.0); + glScalef(0.3, 0.3, 0.3); + glRotatef((360.0 / (30 * 1)) * tick, 1, 0, 0); + glRotatef((360.0 / (30 * 2)) * tick, 0, 1, 0); + glRotatef((360.0 / (30 * 4)) * tick, 0, 0, 1); + glScalef(1.0, 2.0, 1.0); + glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat *) cubeXform); + + drawCube(RED); /* draw cube */ + glPopMatrix(); + + glDepthMask(GL_FALSE); + if (useRGB) { + glEnable(GL_BLEND); + } else { + glEnable(GL_POLYGON_STIPPLE); + } + if (useFog) { + glDisable(GL_FOG); + } + glPushMatrix(); + myShadowMatrix(groundPlane, lightPos); + glTranslatef(0.0, 0.0, 2.0); + glMultMatrixf((const GLfloat *) cubeXform); + + drawCube(BLACK); /* draw ground shadow */ + glPopMatrix(); + + glPushMatrix(); + myShadowMatrix(backPlane, lightPos); + glTranslatef(0.0, 0.0, 2.0); + glMultMatrixf((const GLfloat *) cubeXform); + + drawCube(BLACK); /* draw back shadow */ + glPopMatrix(); + + glDepthMask(GL_TRUE); + if (useRGB) { + glDisable(GL_BLEND); + } else { + glDisable(GL_POLYGON_STIPPLE); + } + if (useFog) { + glEnable(GL_FOG); + } + if (useDB) { + glutSwapBuffers(); + } else { + glFlush(); + } +} + +void +fog_select(int fog) +{ + glFogf(GL_FOG_MODE, fog); + glutPostRedisplay(); +} + +void +menu_select(int mode) +{ + switch (mode) { + case 1: + moving = 1; + glutIdleFunc(idle); + break; + case 2: + moving = 0; + glutIdleFunc(NULL); + break; + case 3: + useFog = !useFog; + useFog ? glEnable(GL_FOG) : glDisable(GL_FOG); + glutPostRedisplay(); + break; + case 4: + useLighting = !useLighting; + useLighting ? glEnable(GL_LIGHTING) : + glDisable(GL_LIGHTING); + glutPostRedisplay(); + break; + case 5: + exit(0); + break; + } +} + +void +visible(int state) +{ + if (state == GLUT_VISIBLE) { + if (moving) + glutIdleFunc(idle); + } else { + if (moving) + glutIdleFunc(NULL); + } +} + +int +main(int argc, char **argv) +{ + int width = 350, height = 350; + int i; + char *name; + int fog_menu; + + glutInitWindowSize(width, height); + glutInit(&argc, argv); + /* process commmand line args */ + for (i = 1; i < argc; ++i) { + if (!strcmp("-c", argv[i])) { + useRGB = !useRGB; + } else if (!strcmp("-l", argv[i])) { + useLighting = !useLighting; + } else if (!strcmp("-f", argv[i])) { + useFog = !useFog; + } else if (!strcmp("-db", argv[i])) { + useDB = !useDB; + } else if (!strcmp("-logo", argv[i])) { + useLogo = !useLogo; + } else if (!strcmp("-quads", argv[i])) { + useQuads = !useQuads; + } else { + usage(); + } + } + + /* choose visual */ + if (useRGB) { + if (useDB) { + glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); + name = windowNameRGBDB; + } else { + glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); + name = windowNameRGB; + } + } else { + if (useDB) { + glutInitDisplayMode(GLUT_DOUBLE | GLUT_INDEX | GLUT_DEPTH); + name = windowNameIndexDB; + } else { + glutInitDisplayMode(GLUT_SINGLE | GLUT_INDEX | GLUT_DEPTH); + name = windowNameIndex; + } + } + + glutCreateWindow(name); + + buildColormap(); + + glutKeyboardFunc(keyboard); + glutDisplayFunc(display); + glutVisibilityFunc(visible); + + fog_menu = glutCreateMenu(fog_select); + glutAddMenuEntry("Linear fog", GL_LINEAR); + glutAddMenuEntry("Exp fog", GL_EXP); + glutAddMenuEntry("Exp^2 fog", GL_EXP2); + + glutCreateMenu(menu_select); + glutAddMenuEntry("Start motion", 1); + glutAddMenuEntry("Stop motion", 2); + glutAddMenuEntry("Toggle fog", 3); + glutAddMenuEntry("Toggle lighting", 4); + glutAddSubMenu("Fog type", fog_menu); + glutAddMenuEntry("Quit", 5); + glutAttachMenu(GLUT_RIGHT_BUTTON); + + /* setup context */ + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 3.0); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0.0, 0.0, -2.0); + + glEnable(GL_DEPTH_TEST); + + if (useLighting) { + glEnable(GL_LIGHTING); + } + glEnable(GL_LIGHT0); + glLightfv(GL_LIGHT0, GL_POSITION, lightPos); + glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmb); + glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiff); + glLightfv(GL_LIGHT0, GL_SPECULAR, lightSpec); +#if 0 + glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, lightDir); + glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 80); + glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 25); +#endif + + glEnable(GL_NORMALIZE); + + if (useFog) { + glEnable(GL_FOG); + } + glFogfv(GL_FOG_COLOR, fogColor); + glFogfv(GL_FOG_INDEX, fogIndex); + glFogf(GL_FOG_MODE, GL_EXP); + glFogf(GL_FOG_DENSITY, 0.5); + glFogf(GL_FOG_START, 1.0); + glFogf(GL_FOG_END, 3.0); + + glEnable(GL_CULL_FACE); + glCullFace(GL_BACK); + + glShadeModel(GL_SMOOTH); + + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + if (useLogo) { + glPolygonStipple((const GLubyte *) sgiPattern); + } else { + glPolygonStipple((const GLubyte *) shadowPattern); + } + + glClearColor(0.0, 0.0, 0.0, 1); + glClearIndex(0); + glClearDepth(1); + + glutMainLoop(); + return 0; /* ANSI C requires main to return int. */ +} diff --git a/20151111/src/enshu_20151111/glut/scube.l b/20151111/src/enshu_20151111/glut/scube.l new file mode 100644 index 00000000..46ea9fcb --- /dev/null +++ b/20151111/src/enshu_20151111/glut/scube.l @@ -0,0 +1,708 @@ +#| +/* Copyright (c) Mark J. Kilgard, 1994. */ + +/** + * (c) Copyright 1993, 1994, Silicon Graphics, Inc. + * ALL RIGHTS RESERVED + * Permission to use, copy, modify, and distribute this software for + * any purpose and without fee is hereby granted, provided that the above + * copyright notice appear in all copies and that both the copyright notice + * and this permission notice appear in supporting documentation, and that + * the name of Silicon Graphics, Inc. not be used in advertising + * or publicity pertaining to distribution of the software without specific, + * written prior permission. + * + * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" + * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR + * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON + * GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, + * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY + * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, + * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF + * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN + * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE + * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. + * + * US Government Users Restricted Rights + * Use, duplication, or disclosure by the Government is subject to + * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph + * (c)(1)(ii) of the Rights in Technical Data and Computer Software + * clause at DFARS 252.227-7013 and/or in similar or successor + * clauses in the FAR or the DOD or NASA FAR Supplement. + * Unpublished-- rights reserved under the copyright laws of the + * United States. Contractor/manufacturer is Silicon Graphics, + * Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311. + * + * OpenGL(TM) is a trademark of Silicon Graphics, Inc. + */ + +/* + * 1992 David G Yu -- Silicon Graphics Computer Systems + */ +|# + +;; porting to euslisp by Kei Okada + +(in-package "GL") +(load "glut.l") + +(defvar useRGB t) +(defvar useLighting t) +(defvar useFog nil) +(defvar useDB t) +(defvar useLogo nil) +(defvar useQuads t) + +(defvar tick -1) +(defvar moving t) + +(defconstant GREY 0) +(defconstant RED 1) +(defconstant GREEN 2) +(defconstant BLUE 3) +(defconstant CYAN 4) +(defconstant MAGENTA 5) +(defconstant YELLOW 6) +(defconstant BLACK 7) + +(setq materialColor + (make-matrix 8 4 + (list (list 0.8 0.8 0.8 1.0) + (list 0.8 0.0 0.0 1.0) + (list 0.0 0.8 0.0 1.0) + (list 0.0 0.0 0.8 1.0) + (list 0.0 0.8 0.8 1.0) + (list 0.8 0.0 0.8 1.0) + (list 0.8 0.8 0.0 1.0) + (list 0.0 0.0 0.0 0.6) + ))) + +(setq lightPos #f(2.0 4.0 2.0 1.0)) +;;; (setq lightDir #f(-2.0 -4.0 -2.0 1.0)) +(setq lightAmb #f(0.2 0.2 0.2 1.0)) +(setq lightDiff #f(0.8 0.8 0.8 1.0)) +(setq lightSpec #f(0.4 0.4 0.4 1.0)) + +(setq groundPlane #f(0.0 1.0 0.0 1.499)) +(setq backPlane #f(0.0 0.0 1.0 0.899)) + +(setq fogColor #f(0.0 0.0 0.0 0.0)) +(setq fogIndex #f(0.0)) + +(setq shadowPattern + #i(#xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 ;; /* 50% Grey */ + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + #xaa #xaa #xaa #xaa #x55 #x55 #x55 #x55 + )) + +(setq sgiPattern + #i(#xff #xff #xff #xff #xff #xff #xff #xff ;; /* SGI Logo */ + #xff #xbd #xff #x83 #xff #x5a #xff #xef + #xfe #xdb #x7f #xef #xfd #xdb #xbf #xef + #xfb #xdb #xdf #xef #xf7 #xdb #xef #xef + #xfb #xdb #xdf #xef #xfd #xdb #xbf #x83 + #xce #xdb #x73 #xff #xb7 #x5a #xed #xff + #xbb #xdb #xdd #xc7 #xbd #xdb #xbd #xbb + #xbe #xbd #x7d #xbb #xbf #x7e #xfd #xb3 + #xbe #xe7 #x7d #xbf #xbd #xdb #xbd #xbf + #xbb #xbd #xdd #xbb #xb7 #x7e #xed #xc7 + #xce #xdb #x73 #xff #xfd #xdb #xbf #xff + #xfb #xdb #xdf #x87 #xf7 #xdb #xef #xfb + #xf7 #xdb #xef #xfb #xfb #xdb #xdf #xfb + #xfd #xdb #xbf #xc7 #xfe #xdb #x7f #xbf + #xff #x5a #xff #xbf #xff #xbd #xff #xc3 + #xff #xff #xff #xff #xff #xff #xff #xff + )) + +(setq cube-vertexes + (list + #2f((-1.0 -1.0 -1.0 1.0) + (-1.0 -1.0 1.0 1.0) + (-1.0 1.0 1.0 1.0) + (-1.0 1.0 -1.0 1.0)) + #2f((1.0 1.0 1.0 1.0) + (1.0 -1.0 1.0 1.0) + (1.0 -1.0 -1.0 1.0) + (1.0 1.0 -1.0 1.0)) + #2f((-1.0 -1.0 -1.0 1.0) + (1.0 -1.0 -1.0 1.0) + (1.0 -1.0 1.0 1.0) + (-1.0 -1.0 1.0 1.0)) + #2f((1.0 1.0 1.0 1.0) + (1.0 1.0 -1.0 1.0) + (-1.0 1.0 -1.0 1.0) + (-1.0 1.0 1.0 1.0)) + #2f((-1.0 -1.0 -1.0 1.0) + (-1.0 1.0 -1.0 1.0) + (1.0 1.0 -1.0 1.0) + (1.0 -1.0 -1.0 1.0)) + #2f((1.0 1.0 1.0 1.0) + (-1.0 1.0 1.0 1.0) + (-1.0 -1.0 1.0 1.0) + (1.0 -1.0 1.0 1.0)) + )) + +(setq cube-normals + (make-matrix 6 4 + (list + (list -1.0 0.0 0.0 0.0) + (list 1.0 0.0 0.0 0.0) + (list 0.0 -1.0 0.0 0.0) + (list 0.0 1.0 0.0 0.0) + (list 0.0 0.0 -1.0 0.0) + (list 0.0 0.0 1.0 0.0)) + )) + +(defun usage + () + (print "") + (print "usage: scube [options]") + (print "") + (print " display a spinning cube and its shadow") + (print "") + (print " Options:") + (print " -geometry window size and location") + (print " -c toggle color index mode") + (print " -l toggle lighting") + (print " -f toggle fog") + (print " -db toggle double buffering") + (print " -logo toggle sgi logo for the shadow pattern") + (print " -quads toggle use of GL_QUADS to draw the checkerboard") + (print "") + (if (not (boundp 'EXIT_FAILURE)) + (setq EXIT_FAILURE 1)) + (exit EXIT_FAILURE) + ) + +(defun buildColormap + () + (if useRGB + (return-from buildColormap nil) + (progn + (setq mapSize (ash 1 (glutGet GLUT_WINDOW_BUFFER_SIZE))) + (setq rampSize (/ mapSize 8.0)) + + (dolist (entry mapSize) + (setq hue (/ entry rampSize)) + (setq val (* (mod entry rampSize) (/ 1.0 (- rampSize 1)))) + + (setq red (if (or (= hue 0) (= hue 1) (= hue 5) (= hue 6)) val 0)) + (setq green (if (or (= hue 0) (= hue 2) (= hue 4) (= hue 6)) val 0)) + (setq blue (if (or (hue 0) (= hue 3) (= hue 4) (= hue 5)) val 0)) + + (glutSetColor entry red green blue) + ) + + (dotimes (i 8) + (setf (aref materialColor i 0) (* i (+ rampSize 0.2) (- rampSize 1))) + (setf (aref materialColor i 1) (* i (+ rampSize 0.8) (- rampSize 1))) + (setf (aref materialColor i 2) (* i (+ rampSize 1.0) (- rampSize 1))) + (setf (aref materialColor i 3) 0.0)) + + (setf (aref fogIndex 0) (* -0.2 (- rampSize 1.0))) + )) + ) + +(defun setColor + (c) + (if useLighting + (if useRGB + (glMaterialfv GL_FRONT_AND_BACK + GL_AMBIENT_AND_DIFFUSE (matrix-row materialColor c)) + (glMaterialfv GL_FRONT_AND_BACK + GL_COLOR_INDEXES (matrix-row materialColor c))) + (if useRGB + (glColor4fv (matrix-row materialColor c)) + (glIndexf (aref materialColor c 1))) + )) + +(defun drawCube + (color) + (setColor color) + (dotimes (i 6) + (glNormal3fv (matrix-row cube-normals i)) + (glBegin GL_POLYGON) + (glVertex4fv (matrix-row (elt cube-vertexes i) 0)) + (glVertex4fv (matrix-row (elt cube-vertexes i) 1)) + (glVertex4fv (matrix-row (elt cube-vertexes i) 2)) + (glVertex4fv (matrix-row (elt cube-vertexes i) 3)) + (glEnd) + )) + +(setq initialized nil + usedLighting nil + checklist nil) + +(defun drawCheck + (w h evenColor oddColor) + (if (or (null initialized) + (not (eq usedLighting useLighting))) + (progn + (setq square-normal #f(0.0 0.0 1.0 0.0)) + (setq square (make-matrix 4 4)) + + (if (not checklist) + (setq checklist (glGenLists 1)) + ) + (glNewList checklist GL_COMPILE_AND_EXECUTE) + + (when useQuads + (glNormal3fv square-normal) + (glBegin GL_QUADS) + ) + + (dotimes (j h) + (dotimes (i w) + (setf (aref square 0 0) (+ -1.0 (* (/ 2.0 w) i))) + (setf (aref square 0 1) (+ -1.0 (* (/ 2.0 w) (+ j 1)))) + (setf (aref square 0 2) 0.0) + (setf (aref square 0 3) 1.0) + + (setf (aref square 1 0) (+ -1.0 (* (/ 2.0 w) i))) + (setf (aref square 1 1) (+ -1.0 (* (/ 2.0 w) j))) + (setf (aref square 1 2) 0.0) + (setf (aref square 1 3) 1.0) + + (setf (aref square 2 0) (+ -1.0 (* (/ 2.0 w) (+ i 1)))) + (setf (aref square 2 1) (+ -1.0 (* (/ 2.0 w) j))) + (setf (aref square 2 2) 0.0) + (setf (aref square 2 3) 1.0) + + (setf (aref square 3 0) (+ -1.0 (* (/ 2.0 w) (+ i 1)))) + (setf (aref square 3 1) (+ -1.0 (* (/ 2.0 w) (+ j 1)))) + (setf (aref square 3 2) 0.0) + (setf (aref square 3 3) 1.0) + + (if (= (logxor (logand i 1) (logand j 1)) 1) + (setColor oddColor) + (setColor evenColor)) + + (if useQuads + (glBegin GL_POLYGON) + ) + (glVertex4fv (matrix-row square 0)) + (glVertex4fv (matrix-row square 1)) + (glVertex4fv (matrix-row square 2)) + (glVertex4fv (matrix-row square 3)) + (if (not useQuads) + (glEnd) + ) + )) + + (if useQuads + (glEnd)) + + (glEndList) + + (setq initialized t) + (setq usedLighting useLighting) + ) + (glCallList checklist) + ) + ) + +(defun myShadowMatrix + (ground light) + (setq shadowMat (make-matrix 4 4)) + + (setq dot (+ (* (elt ground 0) (elt light 0)) + (* (elt ground 1) (elt light 1)) + (* (elt ground 2) (elt light 2)) + (* (elt ground 3) (elt light 3)))) + + (setf (aref shadowMat 0 0) (- dot (* (elt light 0) (elt ground 0)))) + (setf (aref shadowMat 1 0) (- 0 (* (elt light 0) (elt ground 1)))) + (setf (aref shadowMat 2 0) (- 0 (* (elt light 0) (elt ground 2)))) + (setf (aref shadowMat 3 0) (- 0 (* (elt light 0) (elt ground 3)))) + + (setf (aref shadowMat 0 1) (- 0 (* (elt light 1) (elt ground 0)))) + (setf (aref shadowMat 1 1) (- dot (* (elt light 1) (elt ground 1)))) + (setf (aref shadowMat 2 1) (- 0 (* (elt light 1) (elt ground 2)))) + (setf (aref shadowMat 3 1) (- 0 (* (elt light 1) (elt ground 3)))) + + (setf (aref shadowMat 0 2) (- 0 (* (elt light 2) (elt ground 0)))) + (setf (aref shadowMat 1 2) (- 0 (* (elt light 2) (elt ground 1)))) + (setf (aref shadowMat 2 2) (- dot (* (elt light 2) (elt ground 2)))) + (setf (aref shadowMat 3 2) (- 0 (* (elt light 2) (elt ground 3)))) + + (setf (aref shadowMat 0 3) (- 0 (* (elt light 3) (elt ground 0)))) + (setf (aref shadowMat 1 3) (- 0 (* (elt light 3) (elt ground 1)))) + (setf (aref shadowMat 2 3) (- 0 (* (elt light 3) (elt ground 2)))) + (setf (aref shadowMat 3 3) (- dot (* (elt light 3) (elt ground 3)))) + + (glMultMatrixf (array-entity shadowMat)) + ) + +(setq windowNameRGBDB "shadow cube (OpenGL RGB DB)") +(setq windowNameRGB "shadow cube (OpenGL RGB)") +(setq windowNameIndexDB "shadow cube (OpenGL Index DB)") +(setq windowNameIndex "shadow cube (OpenGL Index)") + +(defun-c-callable idle2 () :integer + (incf tick) + (if (>= tick 20) + (setq tick 0) + ) + (glutPostRedisplay) + ) + +(defun-c-callable keyboard (ch x y) :integer + (case ch + (27 ;; escape + (exit 0)) + (#\l + (setq useLighting (not useLighting)) + (if useLighting + (glEnable GL_LIGHTING) + (glDisable GL_LIGHTING)) + (glutPostRedisplay)) + (#\f + (setq useFog (not useFog)) + (if useFog + (glEnable GL_FOG) + (glDisable GL_FOG)) + (glutPostRedisplay)) + (#\1 + (glFogf GL_FOG_MODE (float GL_LINEAR)) + (glutPostRedisplay)) + (#\2 + (glFogf GL_FOG_MODE (float GL_EXP)) + (glutPostRedisplay)) + (#\3 + (glFogf GL_FOG_MODE (float GL_EXP2)) + (glutPostRedisplay)) + (#\ + (when (not moving) + (idle2) + (glutPostRedisplay)) + ) + )) + +(setq n (make-matrix 6 3 + (list (list -1 0 0) (list 0 1 0) (list 1 0 0) + (list 0 -1 0) (list 0 0 1) (list 0 0 -1)))) +(setq faces (make-matrix 6 4 + (list (list 0 1 2 3) (list 3 2 6 7) (list 7 6 5 4) + (list 4 5 1 0) (list 5 6 2 1) (list 7 4 0 3)))) +(setq v (make-matrix 8 3)) + +(defun drawBox nil + (dotimes (i 6) + (glBegin GL_QUADS) + (glNormal3fv (matrix-row n i)) + (glVertex3fv (matrix-row v (round (aref faces i 0)))) + (glVertex3fv (matrix-row v (round (aref faces i 1)))) + (glVertex3fv (matrix-row v (round (aref faces i 2)))) + (glVertex3fv (matrix-row v (round (aref faces i 3)))) + (glEnd) + )) +(defun-c-callable display () :integer + (setq cubeXform (make-matrix 4 4)) + + (glClear (logior GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT)) + +; (drawBox) + + (glPushMatrix) + (glTranslatefv #f(0.0 -1.5 0.0)) + (glRotatefv #f(-90.0 1 0 0)) + (glScalefv #f(2.0 2.0 2.0)) + +; (drawCheck 6 6 BLUE YELLOW) ;; draw ground + (glPopMatrix) + + (glPushMatrix) + (glTranslatefv #f(0.0 0.0 -0.9)) + (glScalefv #f(2.0 2.0 2.0)) + +; (drawCheck 6 6 BLUE YELLOW) ;; draw back + (glPopMatrix) + + (glPushMatrix) + (glTranslatefv #f(0.0 0.2 0.0)) + (glScalefv #f(0.3 0.3 0.3)) + (glRotatefv (float-vector (* (/ 360.0 (* 30.0 1)) tick) 1 0 0)) + (glRotatefv (float-vector (* (/ 360.0 (* 30.0 2)) tick) 0 1 0)) + (glRotatefv (float-vector (* (/ 360.0 (* 30.0 3)) tick) 0 0 1)) + ;;(format t "~A~%" (float-vector (* (/ 360.0 (* 30.0 1)) tick) 1 0 0)) + (glScalefv #f(1.0 2.0 1.0)) + (glGetFloatv GL_MODELVIEW_MATRIX (array-entity cubeXform)) + + (drawCube RED) ;; draw cube + (glPopMatrix) +#| + + (glDepthMask GL_FALSE) + (if useRGB + (glEnable GL_BLEND) + (glEnable GL_POLYGON_STIPPLE) + ) + (if useFog + (glDisable GL_FOG) + ) + (glPushMatrix) + (myShadowMatrix groundPlane lightPos) + (glTranslatefv #f(0.0 0.0 2.0)) + (glMultMatrixf (array-entity cubeXform)) + + (drawCube BLACK) ;; draw ground shadow + (glPopMatrix) + + (glPushMatrix) + (myShadowMatrix backPlane lightPos) + (glTranslatefv #f(0.0 0.0 2.0)) + (glMultMatrixf (array-entity cubeXform)) + + (drawCube BLACK) ;; draw back shadow + (glPopMatrix) + + (glDepthMask GL_TRUE) + + (if useRGB + (glDisable GL_BLEND) + (glDisable GL_POLYGON_STIPPLE) + ) +|# + (if useFog + (glEnable GL_FOG) + ) + (if useDB + (glutSwapBuffers) + (glFlush) + ) +) + +(defun-c-callable fog_select (fog) :integer + (glFogf GL_FOG_MODE fog) + (glutPostRedisplay) + ) + +(defun-c-callable menu_select (mode) :integer + (case mode + (1 + (setq moving t) + (glutIdleFunc (pod-address 'idle2)) + ) + (2 + (setq moving nil) + (glutIdleFunc 0) + ) + (3 + (setq useFog (not useFog)) + (if useFog + (glEnable GL_FOG) + (glDisable GL_FOG)) + (glutPostRedisplay) + ) + (4 + (setq useLighting (not useLighting)) + (if useLighting + (glEnable GL_LIGHTING) + (glDisable GL_LIGHTING)) + (glutPostRedisplay) + ) + (5 + (exit 0) + ) + )) + +(defun-c-callable visible (state) :integer + (if (= state GLUT_VISIBLE) + (if moving (glutIdleFunc (pod-address 'idle2))) + (if moving (glutIdleFunc 0))) + ) + +(defun main nil + (let ((argc "0") + (argv "0") (argv0 (unix::malloc lisp::sizeof-*)) argv1 + (width 350) (height 350)) + (glutInitWindowSize width height) + + (sys::poke 1 argc 0 :integer) + (setq argv1 (make-foreign-string argv0 lisp::sizeof-*)) + (setf (elt argv1 0) 0) + (sys::poke argv0 argv 0 :integer) + (glutInit argc argv) + + ;; choose visual + (if useRGB + (if useDB + (progn + (glutInitDisplayMode (logior GLUT_DOUBLE GLUT_RGB GLUT_DEPTH)) + (setq name windowNameRGBDB)) + (progn + (glutInitDisplayMode (logior GLUT_SINGLE GLUT_RGB GLUT_DEPTH)) + (setq name windowNameRGB))) + (if useDB + (progn + (glutInitDisplayMode (logior GLUT_DOUBLE GLUT_INDEX GLUT_DEPTH)) + (setq name windowNameIndexDB)) + (progn + (glutInitDisplayMode (logior GLUT_SINGLE GLUT_INDEX GLUT_DEPTH)) + (setq name windowNameIndex))) + ) + + (glutCreateWindow name) + + (buildColormap) + + (glutKeyboardFunc (pod-address 'keyboard)) + (glutDisplayFunc (pod-address 'display)) + (glutVisibilityFunc (pod-address 'visible)) + + (setq fog_menu (glutCreateMenu (pod-address 'fog_select))) + (glutAddMenuEntry "Linear fog" GL_LINEAR) + (glutAddMenuEntry "Exp fog" GL_EXP) + (glutAddMenuEntry "Exp^2 fog" GL_EXP2) + + (glutCreateMenu (pod-address 'menu_select)) + (glutAddMenuEntry "Start motion" 1) + (glutAddMenuEntry "Stop motion" 2) + (glutAddMenuEntry "Toggle fog" 3) + (glutAddMenuEntry "Toggle lighting" 4) + (glutAddSubMenu "Fog type" fog_menu) + (glutAddMenuEntry "Quit" 5) + (glutAttachMenu GLUT_RIGHT_BUTTON) + + ;; setup context + ;; Setup the view of the cube. + (glMatrixMode GL_PROJECTION) + (gluPerspective 40.0 ;; field of view in degree + 1.0 ;; aspect ratio + 1.0 ;; Z near + 10.0 ;;Z far + ) + (glMatrixMode GL_MODELVIEW) + (gluLookAt 0.0 0.0 5.0 ;; eye is at (0,0,5) + 0.0 0.0 0.0 ;; center is at (0,0,0) + 0.0 1.0 0.0);; up is in positive Y direction + +; (glMatrixMode GL_PROJECTION) +; (glLoadIdentity) +; (glFrustum -1.0 1.0 -1.0 1.0 1.0 3.0) + +; (glMatrixMode GL_MODELVIEW) +; (glLoadIdentity) + ; (glTranslatefv #(0.0 0.0 -2.0)) + + ;; Adjust cube position to be asthetic angle. + (glTranslatefv #f(0.0 0.0 -1.0)) + (glRotatefv #f(60.0 1.0 0.0 0.0)) + (glRotatefv #f(-20.0 0.0 0.0 1.0)) + + (glEnable GL_DEPTH_TEST) + + (if useLighting + (glEnable GL_LIGHTING) + ) + (glEnable GL_LIGHT0) + (glLightfv GL_LIGHT0 GL_POSITION lightPos) + (glLightfv GL_LIGHT0 GL_AMBIENT lightAmb) + (glLightfv GL_LIGHT0 GL_DIFFUSE lightDiff) + (glLightfv GL_LIGHT0 GL_SPECULAR lightSpec) + +;;; (glLightfv GL_LIGHT0 GL_SPOT_DIRECTION lightDir) +;;; (glLightf GL_LIGHT0 GL_SPOT_EXPONENT 80) +;;; (glLightf GL_LIGHT0 GL_SPOT_CUTOFF 25) + + (glEnable GL_NORMALIZE) + + (if useFog + (glEnable GL_FOG) + ) + + (glFogfv GL_FOG_COLOR fogColor) + (glFogfv GL_FOG_INDEX fogIndex) + (glFogf GL_FOG_MODE (float GL_EXP)) + (glFogf GL_FOG_DENSITY 0.5) + (glFogf GL_FOG_START 1.0) + (glFogf GL_FOG_END 3.0) + + (glEnable GL_CULL_FACE) + (glCullFace GL_BACK) + + (glShadeModel GL_SMOOTH) + + (glBlendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA) + (if useLogo + (glPolygonStipple sgiPattern) + (glPolygonStipple shadowPattern)) + + (glClearColor 0.0 0.0 0.0 1) + (glClearIndex 0) +; (glClearDepth 1) + + (glutMainLoop) + )) + +(setq light_diffuse #f(1.0 0.0 0.0 1.0)) ;; Red diffuse light. +(setq light_position #f(1.0 1.0 1.0 0.0)) ;; Infinite light location. + +(defun init nil + ;; Setup cube vertex data. + (setf (aref v 0 0) -1 (aref v 1 0) -1 (aref v 2 0) -1 (aref v 3 0) -1) + (setf (aref v 4 0) 1 (aref v 5 0) 1 (aref v 6 0) 1 (aref v 7 0) 1) + (setf (aref v 0 1) -1 (aref v 1 1) -1 (aref v 4 1) -1 (aref v 5 1) -1) + (setf (aref v 2 1) 1 (aref v 3 1) 1 (aref v 6 1) 1 (aref v 7 1) 1) + (setf (aref v 0 2) 1 (aref v 3 2) 1 (aref v 4 2) 1 (aref v 7 2) 1) + (setf (aref v 1 2) -1 (aref v 2 2) -1 (aref v 5 2) -1 (aref v 6 2) -1) + + ;; Enable a single OpenGL light. + (glLightfv GL_LIGHT0 GL_DIFFUSE light_diffuse) + (glLightfv GL_LIGHT0 GL_POSITION light_position) + (glEnable GL_LIGHT0) + (glEnable GL_LIGHTING) + + ;; Use depth buffering for hidden surface elimination. + (glEnable GL_DEPTH_TEST) + + ;; Setup the view of the cube. + (glMatrixMode GL_PROJECTION) + (gluPerspective 40.0 ;; field of view in degree + 1.0 ;; aspect ratio + 1.0 ;; Z near + 10.0 ;;Z far + ) + (glMatrixMode GL_MODELVIEW) + (gluLookAt 0.0 0.0 5.0 ;; eye is at (0,0,5) + 0.0 0.0 0.0 ;; center is at (0,0,0) + 0.0 1.0 0.0);; up is in positive Y direction + + ;; Adjust cube position to be asthetic angle. + (glTranslatefv #f(0.0 0.0 -1.0)) + (glRotatefv #f(60.0 1.0 0.0 0.0)) + (glRotatefv #f(-20.0 0.0 0.0 1.0)) + ) + +(defun main nil + (let ((argc "0") + (argv "0") (argv0 (unix::malloc lisp::sizeof-*)) argv1 + (str "red 3D lighted cube")) + (sys::poke 1 argc 0 :integer) + (setq argv1 (make-foreign-string argv0 lisp::sizeof-*)) + (setf (elt argv1 0) 0) + (sys::poke argv0 argv 0 :integer) + (glutInit argc argv) + (glutInitDisplayMode (logior GLUT_DOUBLE GLUT_RGB GLUT_DEPTH)) + (glutCreateWindow (+ (sys:address str) (* lisp::sizeof-* 2))) + (glutDisplayFunc (pod-address 'display)) + (init) + (glutMainLoop) + )) + +(main) diff --git a/20151111/src/enshu_20151111/package.xml b/20151111/src/enshu_20151111/package.xml new file mode 100644 index 00000000..6d7ba8e8 --- /dev/null +++ b/20151111/src/enshu_20151111/package.xml @@ -0,0 +1,52 @@ + + + enshu_20151111 + 0.0.0 + The enshu_20151111 package + + + + + k-okada + + + + + + TODO + + + + + + + + + + + + + + + + + + + + + + + + + + catkin + euslisp + euslisp + + + + + + + + diff --git a/20151111/src/enshu_20151111/setup.py b/20151111/src/enshu_20151111/setup.py new file mode 100644 index 00000000..0bcc7807 --- /dev/null +++ b/20151111/src/enshu_20151111/setup.py @@ -0,0 +1,14 @@ +from distutils.core import setup +from distutils.extension import Extension +from Cython.Distutils import build_ext + +ext_modules=[ + Extension("ffi_cython", + ["ffi_cython.pyx","ffi-c.c"], + libraries=["m"])] +setup( + name = "ffi cython test", + cmdclass = {"build_ext": build_ext}, + ext_modules = ext_modules +) + diff --git a/20151118/check1.test b/20151118/check1.test new file mode 100644 index 00000000..115eebda --- /dev/null +++ b/20151118/check1.test @@ -0,0 +1,9 @@ + + + + + diff --git a/20151118/check2.test b/20151118/check2.test new file mode 100644 index 00000000..8e83e0d1 --- /dev/null +++ b/20151118/check2.test @@ -0,0 +1,3 @@ + + + diff --git a/20151118/check3.test b/20151118/check3.test new file mode 100644 index 00000000..ed686b40 --- /dev/null +++ b/20151118/check3.test @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/20151118/check4.test b/20151118/check4.test new file mode 100644 index 00000000..dd6e3d1d --- /dev/null +++ b/20151118/check4.test @@ -0,0 +1,5 @@ + + + + + diff --git a/20151118/src/enshu_20151118/CMakeLists.txt b/20151118/src/enshu_20151118/CMakeLists.txt new file mode 100644 index 00000000..0e8b34a2 --- /dev/null +++ b/20151118/src/enshu_20151118/CMakeLists.txt @@ -0,0 +1,28 @@ +cmake_minimum_required(VERSION 2.8.3) +project(enshu_20151118) + +find_package(catkin REQUIRED COMPONENTS) +catkin_package() + +add_custom_command(OUTPUT ${PROJECT_SOURCE_DIR}/echo-common.c ${PROJECT_SOURCE_DIR}/echo-skels.c ${PROJECT_SOURCE_DIR}/echo-skelimpl.c ${PROJECT_SOURCE_DIR}/echo-stubs.c + COMMAND orbit-idl-2 echo.idl --skeleton-impl + DEPENDS echo.idl + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + ) + +include(FindPkgConfig) +pkg_check_modules(orbit REQUIRED ORBit-2.0) +pkg_check_modules(orbit_cosname REQUIRED ORBit-CosNaming-2.0) +include_directories(${orbit_INCLUDE_DIRS} ${orbit_cosname_INCLUDE_DIRS}) +link_directories(${orbit_LIBRARY_DIRS} ${orbit_cosname_LIBRARY_DIRS}) + +add_executable(echo-server echo-server.c echo-common.c echo-skels.c examples-toolkit.c) +add_executable(echo-client echo-client.c echo-common.c echo-stubs.c examples-toolkit.c) + +target_link_libraries(echo-server ${orbit_LIBRARIES} ${orbit_cosname_LIBRARIES}) +target_link_libraries(echo-client ${orbit_LIBRARIES} ${orbit_cosname_LIBRARIES}) + + + + + diff --git a/20151118/src/enshu_20151118/EchoClient.java b/20151118/src/enshu_20151118/EchoClient.java new file mode 100644 index 00000000..e149cdd5 --- /dev/null +++ b/20151118/src/enshu_20151118/EchoClient.java @@ -0,0 +1,31 @@ +// http://sdc.sun.co.jp/java/docs/j2se/1.4/ja/docs/ja/guide/idl/tutorial/GSapp.html +import EchoApp.*; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.CORBA.*; + +public class EchoClient +{ + static Echo echoImpl; + public static void main(String args[]) + { + try { + // create and initialize the ORB + ORB orb = ORB.init(args, null); + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + // Use NamingContextExt instead of NamingContext. This is + // part of the Interoperable naming Service. + NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); + // resolve the Object Reference in Naming + String name = "EchoApp/Echo"; + echoImpl = EchoHelper.narrow(ncRef.resolve_str(name)); + System.out.println("Obtained a handle on server object: " + echoImpl); + echoImpl.echoString("hello world this is test"); + } catch (Exception e) { + System.out.println("ERROR : " + e); + e.printStackTrace(System.out); + } + } +} diff --git a/20151118/src/enshu_20151118/EchoServer.java b/20151118/src/enshu_20151118/EchoServer.java new file mode 100644 index 00000000..2e624f40 --- /dev/null +++ b/20151118/src/enshu_20151118/EchoServer.java @@ -0,0 +1,57 @@ +// http://sdc.sun.co.jp/java/docs/j2se/1.4/ja/docs/ja/guide/idl/tutorial/GSserver.html +import EchoApp.*; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.CORBA.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POA; +import java.util.Properties; + +class EchoImpl extends EchoApp.EchoPOA{ + private ORB orb; + public void setORB(ORB orb_val){ + orb = orb_val; + } + // implement echoString() method + public void echoString(String input){ + } + // implement shutdown() method + public void shutdown(){ + orb.shutdown(false); + } +} + +public class EchoServer{ + public static void main(String args[]) { + try { + // create and initialize the ORB + ORB orb = ORB.init(args, null); + // get reference to rootpoa & activate the POAManager + POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); + rootpoa.the_POAManager().activate(); + // create servant and register it with the ORB + EchoImpl echoImpl = new EchoImpl(); + echoImpl.setORB(orb); + // get object reference from the servant + org.omg.CORBA.Object ref = rootpoa.servant_to_reference(echoImpl); + Echo href = EchoHelper.narrow(ref); + // get the root naming context + org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); + // Use NamingContextExt which is part of the Interoperable + // Naming Service (INS) specification. + NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); + // bind the Object Reference in Naming + String name = "EchoApp/Echo"; + NameComponent path[] = ncRef.to_name( name ); + ncRef.rebind(path, href); + System.out.println("EchoServer ready and waiting ..."); + // wait for invocations from clients + orb.run(); + } + catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + } + System.out.println("EchoServer Exiting ..."); + } +} diff --git a/20151118/src/enshu_20151118/echo-client.c b/20151118/src/enshu_20151118/echo-client.c new file mode 100644 index 00000000..262c5d99 --- /dev/null +++ b/20151118/src/enshu_20151118/echo-client.c @@ -0,0 +1,62 @@ +/* << echo-client.c >> + * Echo client program.. Hacked by Ewan Birney + * from echo test suite, update for ORBit2 by Frank Rehberger + * + */ + +#include +#include +#include +#include +#include + +#include "echo.h" +#include "examples-toolkit.h" /* ie. etk_abort_if_exception() */ + +CORBA_ORB global_orb = CORBA_OBJECT_NIL; /* global orb */ + +static void client_run (EchoApp_Echo echo_service, CORBA_Environment *ev) { + char filebuffer[1024+1]; + g_print("Type messages to the server\n" + "a single dot in line will terminate input\n"); + while( fgets(filebuffer,1024,stdin) ) { + if( filebuffer[0] == '.' && filebuffer[1] == '\n' ) + break; + /* chop the newline off */ + filebuffer[strlen(filebuffer)-1] = '\0'; + /* using the echoString method in the Echo object + * this is defined in the echo.h header, compiled from + * echo.idl */ + EchoApp_Echo_echoString(echo_service,filebuffer,ev); + if (etk_raised_exception (ev)) return; + } +} + +int main(int argc, char* argv[]) { + EchoApp_Echo echo_service = CORBA_OBJECT_NIL; + CosNaming_NamingContext name_service = CORBA_OBJECT_NIL; + + gchar *id[] = {"EchoApp", "Echo", NULL}; + + CORBA_Environment ev[1]; + CORBA_exception_init(ev); + + client_init (&argc, argv, &global_orb, ev); + etk_abort_if_exception(ev, "init failed"); + + g_print ("Resolving service reference from neme-service with id\"%s\"\n", id[0]); + + name_service = etk_get_name_service (global_orb, ev); + etk_abort_if_exception(ev, "failed resolving name-service"); + + echo_service = (EchoApp_Echo) etk_name_service_resolve (name_service, id, ev); + etk_abort_if_exception(ev, "failed resolving anme service at name-service"); + + client_run (echo_service, ev); + etk_abort_if_exception(ev, "service not reachable"); + + client_cleanup (global_orb, echo_service, ev); + etk_abort_if_exception(ev, "cleanup failed"); + + exit (0); +} diff --git a/20151118/src/enshu_20151118/echo-server.c b/20151118/src/enshu_20151118/echo-server.c new file mode 100644 index 00000000..cff1b7c8 --- /dev/null +++ b/20151118/src/enshu_20151118/echo-server.c @@ -0,0 +1,60 @@ +/* << echo-server.c >> + * echo-server program. Hacked from Echo test suite by + * , ORBit2 udpate by Frank Rehberger + * + */ + +#include +#include +#include +#include +#include + +#include "echo-skelimpl.c" +#include "examples-toolkit.h" + +CORBA_ORB global_orb = CORBA_OBJECT_NIL; /* global orb */ +PortableServer_POA root_poa = CORBA_OBJECT_NIL; /* root POA */ + +CORBA_Object server_activate_service(CORBA_ORB orb, PortableServer_POA poa, + CORBA_Environment *ev) { + EchoApp_Echo ref = CORBA_OBJECT_NIL; + + ref = impl_EchoApp_Echo__create (poa, ev); + if (etk_raised_exception(ev)) + return CORBA_OBJECT_NIL; + return ref; +} + +int main (int argc, char *argv[]) { + CORBA_Object servant = CORBA_OBJECT_NIL; + CosNaming_NamingContext name_service = CORBA_OBJECT_NIL; + + gchar *id[] = {"EchoApp", "Echo", NULL}; + + CORBA_Environment ev[1]; + CORBA_exception_init(ev); + + server_init (&argc, argv, &global_orb, &root_poa, ev); + etk_abort_if_exception(ev, "failed ORB init"); + + servant = server_activate_service (global_orb, root_poa, ev); + etk_abort_if_exception(ev, "failed activating service"); + + g_print ("Binding service reference from neme-service with id\"%s\"\n", id[0]); + + name_service = etk_get_name_service (global_orb, ev); + etk_abort_if_exception(ev, "failed resolveing name-service"); + + etk_name_service_bind(name_service, servant, id, ev); + etk_abort_if_exception(ev, "failed binding of service"); + + server_run (global_orb, ev); + etk_abort_if_exception(ev, "failed entering main loop"); + + server_cleanup (global_orb, root_poa, servant, ev); + etk_abort_if_exception(ev, "failed cleanup"); + + exit (0); +} + diff --git a/20151118/src/enshu_20151118/echo.idl b/20151118/src/enshu_20151118/echo.idl new file mode 100644 index 00000000..3eb8c80d --- /dev/null +++ b/20151118/src/enshu_20151118/echo.idl @@ -0,0 +1,5 @@ +module EchoApp { + interface Echo { + void echoString(in string input); + }; +}; diff --git a/20151118/src/enshu_20151118/examples-toolkit.c b/20151118/src/enshu_20151118/examples-toolkit.c new file mode 100644 index 00000000..65f16a64 --- /dev/null +++ b/20151118/src/enshu_20151118/examples-toolkit.c @@ -0,0 +1,524 @@ +#include +#include +#include "examples-toolkit.h" + +/** + * test @ev for exception + */ +gboolean +etk_raised_exception(CORBA_Environment *ev) +{ + return ((ev)->_major != CORBA_NO_EXCEPTION); +} + +/** + * test @ev for exception + */ +gboolean +etk_raised_exception_is_a (CORBA_Environment *ev, CORBA_char* id) +{ + return ((ev)->_major != CORBA_NO_EXCEPTION) && + strcmp(id, CORBA_exception_id(ev)) == 0; +} + +/** + * + */ +void +etk_abort_if_exception (CORBA_Environment *ev, const char* mesg) +{ + if (etk_raised_exception (ev)) { + g_error ("%s %s", mesg, CORBA_exception_id (ev)); + CORBA_exception_free (ev); + abort(); + } +} + +/** + * + */ +void +etk_ignore_if_exception (CORBA_Environment *ev, const char* mesg) +{ + if (etk_raised_exception (ev)) { + g_warning ("%s %s", mesg, CORBA_exception_id (ev)); + CORBA_exception_free (ev); + } +} + + +/** + * + */ +void +etk_export_object_to_stream (CORBA_ORB orb, + CORBA_Object servant, + FILE *stream, + CORBA_Environment *ev) +{ + CORBA_char *objref = NULL; + + /* write objref to file */ + + objref = CORBA_ORB_object_to_string (orb, servant, ev); + if (etk_raised_exception(ev)) return; + + /* print ior to terminal */ + fprintf (stream, "%s\n", objref); + fflush (stream); + + CORBA_free (objref); +} + + +/* Writes stringified object reference of @servant to file + * @filename. If error occures @ev points to exception object on + * return. + */ +void +etk_export_object_to_file (CORBA_ORB orb, + CORBA_Object servant, + char *filename, + CORBA_Environment *ev) +{ + CORBA_char *objref = NULL; + FILE *file = NULL; + + /* write objref to file */ + + if ((file=fopen(filename, "w"))==NULL) + g_error ("could not open %s\n", filename); + + /* print ior to stream */ + etk_export_object_to_stream (orb, servant, file, ev); + + fclose (file); +} + + +/** + * + */ +static gchar* +etk_read_string_from_stream (FILE *stream) +{ + gulong length = 4*1024; /* should suffice ordinary IOR string */ + gchar *objref = g_malloc0 (length*sizeof(gchar)); /* empty string */ + int c = 0; + int i = 0; + + /* skip leading white space */ + while((c=fgetc(stream))!=EOF && g_ascii_isspace(c)); + /* POST: c==EOF or c=first character */ + + if (c!=EOF) + /* PRE: c=first character */ + /* append c to string while more c exist and c not white space */ + do { + /* check size */ + if (i>=(length-1)) { + length*=2; + objref=g_realloc (objref, length); + } + objref[i++] = c; + } while ((c=fgetc(stream))!=EOF && !g_ascii_isspace(c)); + /* POST: first string read */ + + /* terminate string with \0 */ + objref[i] = '\0'; + + /* INV: objref valid string, #objref>=0 */ + + return objref; +} + +/** + * + */ +CORBA_Object +etk_import_object_from_stream (CORBA_ORB orb, + FILE *stream, + CORBA_Environment *ev) +{ + CORBA_Object obj = CORBA_OBJECT_NIL; + gchar *objref=etk_read_string_from_stream (stream); + + if (!objref || strlen (objref)==0) { + g_warning ("empty object reference"); + if (objref) + g_free (objref); + return CORBA_OBJECT_NIL; + } + + obj = (CORBA_Object) CORBA_ORB_string_to_object (orb, + objref, + ev); + free (objref); + + return obj; +} + +/** + * + */ +CORBA_Object +etk_import_object_from_file (CORBA_ORB orb, + CORBA_char *filename, + CORBA_Environment *ev) +{ + CORBA_Object obj = NULL; + FILE *file = NULL; + + /* write objref to file */ + + if ((file=fopen(filename, "r"))==NULL) + g_error ("could not open %s\n", filename); + + obj= etk_import_object_from_stream (orb, file, ev); + + if (obj==CORBA_OBJECT_NIL) + g_warning ("object is NIL"); + + fclose (file); + + return obj; +} + +/** + */ +CosNaming_NamingContext +etk_get_name_service (CORBA_ORB orb, + CORBA_Environment *ev) +{ + CORBA_char *str=NULL; + CORBA_Object ref + = (CORBA_Object) CORBA_ORB_resolve_initial_references(orb, + "NameService", + ev); + if (etk_raised_exception(ev)) return CORBA_OBJECT_NIL; + + return (CosNaming_NamingContext) ref; +} + +/** calculate length of NULL terminated string vector */ +static +guint +id_vec_len (char *id_vec[]) +{ + gint i=0; + for (i = 0; id_vec[i]; ++i); + return i; +} + +/* binds @servant object reference to unique @name at + * @name_service. If error occures @ev points to exception object on + * return. + */ +void +etk_name_service_bind (CosNaming_NamingContext name_service, + CORBA_Object servant, + gchar *id_vec[], + CORBA_Environment *ev) +{ + gint i = 0; + gint len = id_vec_len (id_vec); + + /* Allocate a CosNaming::Name (sequence of CosNaming::NameComponent) */ + CosNaming_Name *name = CosNaming_Name__alloc(); + + name->_buffer = CORBA_sequence_CosNaming_NameComponent_allocbuf(len); + name->_maximum = len; + name->_length = 0; + + /* Relinquish ownership of the NameComponent to the + * sequence. When CORBA_free is called on it later, the + * NameComponent will be freed */ + CORBA_sequence_set_release (name, TRUE); + + /* iterate components of name and create sub-context + * (directory) if needed */ + for (i = 0; i < len; ++i) { + name->_length = i+1; + name->_buffer[i].id = CORBA_string_dup(id_vec[i]); + name->_buffer[i].kind = CORBA_string_dup(""); + /* don't know what 'kind' shall be good for */ + + if (name->_length < len) + { + /* create a sub-context */ + CosNaming_NamingContext nc = + CosNaming_NamingContext_bind_new_context (name_service, + name, + ev); + if (etk_raised_exception_is_a (ev, + ex_CosNaming_NamingContext_AlreadyBound)) + { + /* ignore - ctx allread exists, this + * is not dramatic */ + CORBA_exception_free (ev); + } + else if (etk_raised_exception (ev)) + { + /* critical - unexpected exception */ + CORBA_free (name); + return; + } + } + else + { + /* Bind object to last context - use 'rebind' + * operation in case the name has been + * registered allready in context - note, this + * might interfere with other service choosing + * same name */ + CosNaming_NamingContext_rebind (name_service, + name, + servant, + ev); + if (etk_raised_exception(ev)) { + /* critical - can not bind object */ + CORBA_free (name); + return; + } + } + } + + CORBA_free (name); + return; +} + +CORBA_Object +etk_name_service_resolve (CosNaming_NamingContext name_service, + gchar *id_vec[], + CORBA_Environment *ev) +{ + CORBA_Object retval = CORBA_OBJECT_NIL; + gint i = 0; + gint len = id_vec_len (id_vec); + + /* Allocate a CosNaming::Name (sequence of CosNaming::NameComponent) */ + CosNaming_Name *name = CosNaming_Name__alloc(); + + g_assert (id_vec_len (id_vec) > 0); + + name->_buffer = CORBA_sequence_CosNaming_NameComponent_allocbuf(len); + name->_maximum = len; + name->_length = 0; + + /* Relinquish ownership of the NameComponent to the + * sequence. When CORBA_free is called on it later, the + * NameComponent will be freed */ + CORBA_sequence_set_release (name, TRUE); + + /* iterate components of name and create sub-context + * (directory) if needed */ + for (i = 0; i < len; ++i) { + name->_length = i+1; + name->_buffer[i].id = CORBA_string_dup(id_vec[i]); + name->_buffer[i].kind = CORBA_string_dup(""); + /* don't know what 'kind' shall be good for */ + } + + retval = CosNaming_NamingContext_resolve (name_service, + name, + ev); + + if (etk_raised_exception (ev)) { + CORBA_free (name); + return CORBA_OBJECT_NIL; + } + + return retval; +} + +/* server */ + +/* Is called in case of process signals. it invokes CORBA_ORB_shutdown() + * function, which will terminate the processes main loop. + */ +static +void +server_shutdown (int sig) +{ + CORBA_Environment local_ev[1]; + CORBA_exception_init(local_ev); + + if (global_orb != CORBA_OBJECT_NIL) + { + CORBA_ORB_shutdown (global_orb, FALSE, local_ev); + etk_abort_if_exception (local_ev, "caught exception"); + } +} + +/* Inits ORB @orb using @argv arguments for configuration. For each + * ORBit options consumed from vector @argv the counter of @argc_ptr + * will be decremented. Signal handler is set to call + * echo_server_shutdown function in case of SIGINT and SIGTERM + * signals. If error occures @ev points to exception object on + * return. + */ +void +server_init (int *argc_ptr, + char *argv[], + CORBA_ORB *orb, + PortableServer_POA *poa, + CORBA_Environment *ev) +{ + PortableServer_POAManager poa_manager = CORBA_OBJECT_NIL; + + CORBA_Environment local_ev[1]; + CORBA_exception_init(local_ev); + + /* init signal handling */ + signal(SIGINT, server_shutdown); + signal(SIGTERM, server_shutdown); + + /* create Object Request Broker (ORB) */ + (*orb) = CORBA_ORB_init(argc_ptr, argv, "orbit-local-mt-orb", ev); + if (etk_raised_exception(ev)) + goto failed_orb; + + (*poa) = (PortableServer_POA) + CORBA_ORB_resolve_initial_references(*orb, "RootPOA", ev); + if (etk_raised_exception(ev)) + goto failed_poa; + + poa_manager = PortableServer_POA__get_the_POAManager(*poa, ev); + if (etk_raised_exception(ev)) + goto failed_poamanager; + + PortableServer_POAManager_activate(poa_manager, ev); + if (etk_raised_exception(ev)) + goto failed_activation; + + CORBA_Object_release ((CORBA_Object) poa_manager, ev); + return; + + failed_activation: + failed_poamanager: + CORBA_Object_release ((CORBA_Object) poa_manager, local_ev); + failed_poa: + CORBA_ORB_destroy(*orb, local_ev); + failed_orb: + return; +} + +/* Entering main loop @orb handles incoming request and delegates to + * servants. If error occures @ev points to exception object on + * return. + */ +void +server_run (CORBA_ORB orb, + CORBA_Environment *ev) +{ + /* enter main loop until SIGINT or SIGTERM */ + + CORBA_ORB_run(orb, ev); + if (etk_raised_exception(ev)) return; + + /* user pressed SIGINT or SIGTERM and in signal handler + * CORBA_ORB_shutdown(.) has been called */ +} + +/* Releases @servant object and finally destroys @orb. If error + * occures @ev points to exception object on return. + */ +void +server_cleanup (CORBA_ORB orb, + PortableServer_POA poa, + CORBA_Object ref, + CORBA_Environment *ev) +{ + PortableServer_ObjectId *objid = NULL; + + objid = PortableServer_POA_reference_to_id (poa, ref, ev); + if (etk_raised_exception(ev)) return; + + /* Servant: deactivatoin - will invoke __fini destructor */ + PortableServer_POA_deactivate_object (poa, objid, ev); + if (etk_raised_exception(ev)) return; + + PortableServer_POA_destroy (poa, TRUE, FALSE, ev); + if (etk_raised_exception(ev)) return; + + CORBA_free (objid); + + CORBA_Object_release ((CORBA_Object) poa, ev); + if (etk_raised_exception(ev)) return; + + CORBA_Object_release (ref, ev); + if (etk_raised_exception(ev)) return; + + /* ORB: tear down the ORB */ + if (orb != CORBA_OBJECT_NIL) + { + /* going to destroy orb.. */ + CORBA_ORB_destroy(orb, ev); + if (etk_raised_exception(ev)) return; + } +} + +/* client */ + +/* Is called in case of process signals. it invokes CORBA_ORB_shutdown() + * function, which will terminate the processes main loop. + */ +void +client_shutdown (int sig) +{ + CORBA_Environment local_ev[1]; + CORBA_exception_init(local_ev); + + if (global_orb != CORBA_OBJECT_NIL) + { + CORBA_ORB_shutdown (global_orb, FALSE, local_ev); + etk_abort_if_exception (local_ev, "caught exception"); + } +} + + +/* Inits ORB @orb using @argv arguments for configuration. For each + * ORBit options consumed from vector @argv the counter of @argc_ptr + * will be decremented. Signal handler is set to call + * echo_client_shutdown function in case of SIGINT and SIGTERM + * signals. If error occures @ev points to exception object on + * return. + */ +void +client_init (int *argc_ptr, + char *argv[], + CORBA_ORB *orb, + CORBA_Environment *ev) +{ + /* init signal handling */ + + signal(SIGINT, client_shutdown); + signal(SIGTERM, client_shutdown); + + /* create Object Request Broker (ORB) */ + + (*orb) = CORBA_ORB_init(argc_ptr, argv, "orbit-local-orb", ev); + if (etk_raised_exception(ev)) return; +} + +/* Releases @servant object and finally destroys @orb. If error + * occures @ev points to exception object on return. + */ +void +client_cleanup (CORBA_ORB orb, + CORBA_Object service, + CORBA_Environment *ev) +{ + /* releasing managed object */ + CORBA_Object_release(service, ev); + if (etk_raised_exception(ev)) return; + + /* tear down the ORB */ + if (orb != CORBA_OBJECT_NIL) + { + /* going to destroy orb.. */ + CORBA_ORB_destroy(orb, ev); + if (etk_raised_exception(ev)) return; + } +} + diff --git a/20151118/src/enshu_20151118/examples-toolkit.h b/20151118/src/enshu_20151118/examples-toolkit.h new file mode 100644 index 00000000..0f80fab7 --- /dev/null +++ b/20151118/src/enshu_20151118/examples-toolkit.h @@ -0,0 +1,108 @@ + +#ifndef __EXAMPLES_TOOLKIT__ +#define __EXAMPLES_TOOLKIT__ + +#include +#include +#include + +/* extracts type of exception: Three return Values are possible: + * CORBA_NO_EXCEPTION, CORBA_USER_EXCEPTION, CORBA_SYSTEM_EXCEPTION:/ +*/ +#define etk_exception_type(ev) (ev->_major) + +/** + * test @ev for any exception + */ +gboolean +etk_raised_exception (CORBA_Environment *ev); + +/** + * test @ev for specific exception @ex + */ +gboolean +etk_raised_exception_is_a (CORBA_Environment *ev, CORBA_char* ex); + +/** + * in case of any exception this operation will abort the process + */ +void +etk_abort_if_exception(CORBA_Environment *ev, const char* mesg); + +/** + * in case of any exception this operation will only free allocated resources + */ +void +etk_ignore_if_exception(CORBA_Environment *ev, const char* mesg); + +/** + * + */ +void +etk_export_object_to_stream (CORBA_ORB orb, + CORBA_Object servant, + FILE *stream, + CORBA_Environment *ev); + + +/* Writes stringified object reference of @servant to file + * @filename. If error occures @ev points to exception object on + * return. + */ +void +etk_export_object_to_file (CORBA_ORB orb, + CORBA_Object servant, + char *filename, + CORBA_Environment *ev); + +/** + * + */ +CORBA_Object +etk_import_object_from_stream (CORBA_ORB orb, + FILE *stream, + CORBA_Environment *ev); + +/** + * + */ +CORBA_Object +etk_import_object_from_file (CORBA_ORB orb, + CORBA_char *filename, + CORBA_Environment *ev); + + +/** resolves default name-service, usually given to application as + * command line argument "-ORBInitRef NameService=IOR:0100000028..", + * or since release 2.8.0 corbalocs in form of URL can be used, eg: + * "-ORBInitRef NameService=corbaloc:iiop:HOSTNAME:PORT/NameService%00" + */ +CosNaming_NamingContext +etk_get_name_service (CORBA_ORB orb, + CORBA_Environment *ev); + + +/* binds @servant object reference to unique @name at + * @name_service. @name is a NULL terminated list of strings + * (CORBA_char*). If error occures @ev points to exception object on + * return. + */ +void +etk_name_service_bind (CosNaming_NamingContext name_service, + CORBA_Object servant, + gchar *id_vec[], + CORBA_Environment *ev); + +/* resolves object reference @return with unique @name at + * @name_service. @name is a NULL terminated list of strings + * (CORBA_char*). If error occures @ev points to * exception object + * on return. + */ +CORBA_Object +etk_name_service_resolve (CosNaming_NamingContext name_service, + gchar *id_vec[], + CORBA_Environment *ev); + + +extern CORBA_ORB global_orb; /* global orb */ +#endif diff --git a/20151118/src/enshu_20151118/listener.l b/20151118/src/enshu_20151118/listener.l new file mode 100755 index 00000000..d02a17fa --- /dev/null +++ b/20151118/src/enshu_20151118/listener.l @@ -0,0 +1,36 @@ +#!/usr/bin/env roseus +;;; +;;; euslisp version of ros_tutorials/rospy_tutorials/001_talker_listener +;;; + +(ros::load-ros-manifest "roseus") +;;; + +;;; +;;; +(ros::roseus "listener") +;;(setq sys::*gc-hook* #'(lambda (a b) (format t ";; gc ~A ~A~%" a b))) + +;; callback function +;(defun string-cb (msg) (print (list 'cb (sys::thread-self) (send msg :data)))) +;(ros::subscribe "chatter" std_msgs::string #'string-cb) + +; lambda function +;(ros::subscribe "chatter" std_msgs::string +; #'(lambda (msg) (ros::ros-info +; (format nil "I heard ~A" (send msg :data))))) + +;; method call +(defclass string-cb-class + :super propertied-object + :slots ()) +(defmethod string-cb-class + (:init () (ros::subscribe "chatter" std_msgs::string #'send self :string-cb)) + (:string-cb (msg) (print (list 'cb self (send msg :data))))) +(setq m (instance string-cb-class :init)) + +(do-until-key + (ros::spin-once) + ;;(sys::gc) +) +;(ros::spin) diff --git a/20151118/src/enshu_20151118/package.xml b/20151118/src/enshu_20151118/package.xml new file mode 100644 index 00000000..35622393 --- /dev/null +++ b/20151118/src/enshu_20151118/package.xml @@ -0,0 +1,52 @@ + + + enshu_20151118 + 0.0.0 + The enshu_20151118 package + + + + + k-okada + + + + + + TODO + + + + + + + + + + + + + + + + + + + + + + + + + + catkin + euslisp + euslisp + + + + + + + + diff --git a/20151118/src/enshu_20151118/sample.py b/20151118/src/enshu_20151118/sample.py new file mode 100755 index 00000000..00cbedaf --- /dev/null +++ b/20151118/src/enshu_20151118/sample.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python + +import xmlrpclib +server =xmlrpclib.Server('http://xmlrpc-c.sourceforge.net/api/sample.ph') +result = server.sample.add(1,2) +print result diff --git a/20151118/src/enshu_20151118/talker.l b/20151118/src/enshu_20151118/talker.l new file mode 100755 index 00000000..019ba464 --- /dev/null +++ b/20151118/src/enshu_20151118/talker.l @@ -0,0 +1,23 @@ +#!/usr/bin/env roseus +;;; +;;; euslisp version of ros_tutorials/rospy_tutorials/001_talker_listener +;;; + +(ros::load-ros-manifest "roseus") +;;; + +;;; +;;; +(ros::roseus "talker") +(ros::advertise "chatter" std_msgs::string 1) +(ros::rate 100) +(while (ros::ok) + (setq msg (instance std_msgs::string :init)) + (send msg :data (format nil "hello world ~a" (send (ros::time-now) :sec-nsec))) + (ros::ros-info "msg [~A]" (send msg :data)) + (ros::publish "chatter" msg) + (ros::sleep) + ) +(ros::roseus "shutdown") +(exit) + diff --git a/20151118/src/enshu_20151118/zeromq_pub.py b/20151118/src/enshu_20151118/zeromq_pub.py new file mode 100755 index 00000000..57f2b87d --- /dev/null +++ b/20151118/src/enshu_20151118/zeromq_pub.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python + +import zmq +import time +context = zmq.Context() + +publisher = context.socket (zmq.PUB) +publisher.bind ("tcp://127.0.0.1:8888") + +i = 0 +while True: + message = str(i) + " hello world" + print(message) + publisher.send (message) + i = 0 if ( i >= 10) else i + 1 + time.sleep(0.2) diff --git a/20151118/src/enshu_20151118/zeromq_sub.py b/20151118/src/enshu_20151118/zeromq_sub.py new file mode 100755 index 00000000..0c8b40d1 --- /dev/null +++ b/20151118/src/enshu_20151118/zeromq_sub.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python + +import zmq +import time +context = zmq.Context() + +subscriber = context.socket (zmq.SUB) +subscriber.connect ("tcp://127.0.0.1:8888") +subscriber.setsockopt(zmq.SUBSCRIBE, "4") + +while True: + message = subscriber.recv() + print message diff --git a/20151125/check1.test b/20151125/check1.test new file mode 100644 index 00000000..07057e66 --- /dev/null +++ b/20151125/check1.test @@ -0,0 +1,6 @@ + + + + diff --git a/20151125/src/enshu_20151125/CMakeLists.txt b/20151125/src/enshu_20151125/CMakeLists.txt new file mode 100644 index 00000000..585a2fd4 --- /dev/null +++ b/20151125/src/enshu_20151125/CMakeLists.txt @@ -0,0 +1,5 @@ +cmake_minimum_required(VERSION 2.8.3) +project(enshu_20151125) + +find_package(catkin REQUIRED COMPONENTS) +catkin_package() diff --git a/20151125/src/enshu_20151125/append.swi b/20151125/src/enshu_20151125/append.swi new file mode 100755 index 00000000..37d9e4e5 --- /dev/null +++ b/20151125/src/enshu_20151125/append.swi @@ -0,0 +1,10 @@ +#!/usr/bin/env prolog + +% check with +% prolog -f ./append.swi -t 'my_append("[a,b,c]", "[d,e,f]", X).' + + +my_append([a,b,c], [d,e,f], X). +% X == [a,b,c,f,e,f]. + + diff --git a/20151125/src/enshu_20151125/like.swi b/20151125/src/enshu_20151125/like.swi new file mode 100755 index 00000000..e47474f2 --- /dev/null +++ b/20151125/src/enshu_20151125/like.swi @@ -0,0 +1,8 @@ +#!/usr/bin/env prolog + +% check with +% prolog -f ./like.swi -t 'like(X,Y).' + + + + diff --git a/20151125/src/enshu_20151125/package.xml b/20151125/src/enshu_20151125/package.xml new file mode 100644 index 00000000..bb3d8bff --- /dev/null +++ b/20151125/src/enshu_20151125/package.xml @@ -0,0 +1,52 @@ + + + enshu_20151125 + 0.0.0 + The enshu_20151125 package + + + + + k-okada + + + + + + TODO + + + + + + + + + + + + + + + + + + + + + + + + + + catkin + euslisp + euslisp + + + + + + + + diff --git a/20151202/src/enshu_20151202/CMakeLists.txt b/20151202/src/enshu_20151202/CMakeLists.txt new file mode 100644 index 00000000..7a9029c5 --- /dev/null +++ b/20151202/src/enshu_20151202/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 2.8.3) +project(enshu_20151202) + +find_package(catkin REQUIRED COMPONENTS) +catkin_package() + +add_executable(GCTest src/GCTest.cpp) +target_link_libraries(GCTest pthread gtest) + +if(NOT EXISTS GCTest.gc.log) + message(FATAL "java -cp src -verbosegc -Xloggc:GCTest.gc.log GCTest") +endif() +if(NOT EXISTS GCTest.incgc.log) + message(FATAL "java -cp src -Xincgc -verbosegc -Xloggc:GCTest.incgc.log GCTest") +endif() diff --git a/20151202/src/enshu_20151202/check1.test b/20151202/src/enshu_20151202/check1.test new file mode 100644 index 00000000..e4d728aa --- /dev/null +++ b/20151202/src/enshu_20151202/check1.test @@ -0,0 +1,3 @@ + + + diff --git a/20151202/src/enshu_20151202/package.xml b/20151202/src/enshu_20151202/package.xml new file mode 100644 index 00000000..b88ecb5e --- /dev/null +++ b/20151202/src/enshu_20151202/package.xml @@ -0,0 +1,52 @@ + + + enshu_20151202 + 0.0.0 + The enshu_20151202 package + + + + + k-okada + + + + + + TODO + + + + + + + + + + + + + + + + + + + + + + + + + + catkin + euslisp + euslisp + + + + + + + + diff --git a/20151202/src/enshu_20151202/src/GCTest.cpp b/20151202/src/enshu_20151202/src/GCTest.cpp new file mode 100644 index 00000000..4c3fd214 --- /dev/null +++ b/20151202/src/enshu_20151202/src/GCTest.cpp @@ -0,0 +1,167 @@ +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +void *_ThreadStart(void *arg); +class Thread { +public: + Thread(){}; + int Start(){ + Setup(); + int code = pthread_create(&ThreadId_, NULL, _ThreadStart, (void *)this); + return code; + } + int Join(){ + int code = pthread_join(ThreadId_, NULL); + return code; + } + virtual void Setup(){}; + virtual void Execute(){}; +private: + pthread_t ThreadId_; + void * Arg_; +}; +void *_ThreadStart(void *arg){ + ((Thread *)arg)->Execute(); +} + + +/// +/// +/// + +bool do_delete = true; + + +typedef vector Elem; +typedef vector* ElemPtr; +typedef vector* ElemPtrVec; + +class Mutator : public Thread { + bool loop; +public: + Mutator(){} + void Setup (){ + loop = true; + } + void Execute(){ + while (loop) { + ElemPtrVec v = ElemPtrVec(new vector()); + // mutator + for (int k = 0; k < 2000; k++) { + v->push_back(ElemPtr(new Elem(1000000))); + } + // +#if 0 // usually we need this + if ( do_delete ) { + for (vector::iterator i = v->begin(); + i != v->end(); i++){ + delete (*i); + } + delete v; + } +#endif + usleep(0); + cout << '\b' << "-"; + } + } + + void end() { + loop = false; + } +}; + + +class Sort : public Thread { + struct timeval tv; + struct timezone tz; + float time; + + void print_arr(vector a){ + for (int i = 0; i< a.size(); i+=1000) { + cout << a[i]; + } + gettimeofday(&tv, &tz); + float elapsedtime = tv.tv_sec*1000 + tv.tv_usec/1000.0; + cout << " " << (elapsedtime-time) << " ms" << endl;; + time = elapsedtime; + } + + void scramble(vector *a) { + double f = 10.0 / (double) a->size(); + for (int i = a->size()-1; --i >= 0;) { + (*a)[i] = (int)(i * f); + } + for (int i = a->size()-1; --i >= 0;) { + int j = (int)(i * (float)random()/RAND_MAX); + int t = (*a)[i]; + (*a)[i] = (*a)[j]; + (*a)[j] = t; + } + } + + void sort(vector *a) { + for (int i = a->size()-1; --i>=0; ) { + bool swapped = false; + for (int j = 0; j (*a)[j+1]) { + int T = (*a)[j]; + (*a)[j] = (*a)[j+1]; + (*a)[j+1] = T; + swapped = true; + } + } + if ( i % 10 == 0 ) print_arr(*a); + if (!swapped) + return; + } + } + +public: + vector arr; + Sort(){} + void Setup (){ + arr.resize(50000); + } + void Execute(){ + cout << "** start Sort *****" << endl; + scramble(&arr); + print_arr(arr); + sort(&arr); + print_arr(arr); + cout << "** done Sort ********" << endl; + } +}; + +#include +// Declare a test +TEST(TestSuite, testCase1) +{ + // dummy test +} + +int main(int argc, char *argv[]){ + cout << argc << endl; + if ( argc > 1) if (!strcmp(argv[1], "--no-delete")) { + do_delete = false; + cerr << "NO DELETE mode" << endl; + } + Sort *sort = new Sort(); + Mutator *mutator = new Mutator(); + sort->Start(); + mutator->Start(); + sort->Join(); + mutator->end(); + mutator->Join(); + + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); + return 0; +} + diff --git a/20151202/src/enshu_20151202/src/GCTest.java b/20151202/src/enshu_20151202/src/GCTest.java new file mode 100644 index 00000000..48e6cc18 --- /dev/null +++ b/20151202/src/enshu_20151202/src/GCTest.java @@ -0,0 +1,103 @@ +import java.util.*; + +class Mutator extends Thread { + boolean loop = true; + + public void run() { + while ( loop ) { + Vector v = new Vector(); + // mutator + for (int k = 0; k < 1000; k++) { + Vector e = new Vector(); + for (int l = 0; l < 10000; l++) { + e.addElement(new Integer(l)); + } + Thread.yield(); + v.addElement(e); + } + // + System.out.print('\b'+"-"); + v = null; + } + } + + public void end() { + loop = false; + } +} + +class Sort extends Thread { + static int arr[]; + static long time; + + public static void print_arr(){ + for (int i = 0; i< arr.length; i+=300) { + System.out.print(arr[i]); + } + System.out.println(" " + (System.currentTimeMillis()-time) + " ms"); + time = System.currentTimeMillis(); + } + + static void scramble() { + int a[] = new int[21000]; + double f = 10.0 / (double) a.length; + for (int i = a.length; --i >= 0;) { + a[i] = (int)(i * f); + } + for (int i = a.length; --i >= 0;) { + int j = (int)(i * Math.random()); + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } + arr = a; + } + + static void sort(int a[]) throws Exception { + int y = 0; + for (int i = a.length; --i>=0; ) { + boolean swapped = false; + for (int j = 0; j a[j+1]) { + int T = a[j]; + a[j] = a[j+1]; + a[j+1] = T; + swapped = true; + } + } + Thread.yield(); + if ( i % 50 == 0 ) print_arr(); + if (!swapped) + return; + } + } + public void run(){ + System.out.println("** start Sort *****"); + scramble(); + print_arr(); + try { + sort(arr); + } catch(Exception e) { + } + print_arr(); + System.out.println("** done Sort ********"); + } +} + +class GCTest { + + public static void main(String[] args) { + Sort sort = new Sort(); + Mutator mutator = new Mutator(); + sort.start(); + mutator.start(); + try { + sort.join(); + mutator.end(); + sort.print_arr(); + } catch (InterruptedException e) { + System.out.println(e); + } + } +} + diff --git a/20151209/check1.test b/20151209/check1.test new file mode 100644 index 00000000..2956036b --- /dev/null +++ b/20151209/check1.test @@ -0,0 +1,4 @@ + + + diff --git a/20151209/src/enshu_20151209/CMakeLists.txt b/20151209/src/enshu_20151209/CMakeLists.txt new file mode 100644 index 00000000..398dbd89 --- /dev/null +++ b/20151209/src/enshu_20151209/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 2.8.3) +project(enshu_20151209) + +find_package(catkin REQUIRED COMPONENTS) +catkin_package() + +add_executable(graphsearch src/graphsearch.cpp) diff --git a/20151209/src/enshu_20151209/data/romania.dat b/20151209/src/enshu_20151209/data/romania.dat new file mode 100644 index 00000000..0b302c0c --- /dev/null +++ b/20151209/src/enshu_20151209/data/romania.dat @@ -0,0 +1,23 @@ +# Romanian Cities and Road Network Graph +# (See Russell & Norvig Chapter 3 ) +# +Oradea Zerind Sibiu +Arad Zerind Sibiu Timisoara +Zerind Arad Oradea +Timisoara Arad Lugoj +Sibiu Oradea Arad Fagaras Rimnicu-Vilcea +Lugoj Timisoara Mehadia +Mehadia Lugoj Dobreta +Dobreta Mehadia Craiova +Craiova Rimnicu-Vilcea Pitesti Dobreta +Pitesti Rimnicu-Vilcea Craiova Bucharest +Rimnicu-Vilcea Sibiu Craiova Pitesti +Fagaras Sibiu Bucharest +Bucharest Fagaras Giurgiu Urziceni Pitesti +Giurgiu Bucharest +Urziceni Bucharest Hirsova Vaslui +Vaslui Iasi Urziceni +Iasi Neamt Vaslui +Neamt Iasi +Hirsova Urziceni Eforie +Eforie Hirsova diff --git a/20151209/src/enshu_20151209/package.xml b/20151209/src/enshu_20151209/package.xml new file mode 100644 index 00000000..8d19d59b --- /dev/null +++ b/20151209/src/enshu_20151209/package.xml @@ -0,0 +1,52 @@ + + + enshu_20151209 + 0.0.0 + The enshu_20151209 package + + + + + k-okada + + + + + + TODO + + + + + + + + + + + + + + + + + + + + + + + + + + catkin + euslisp + euslisp + + + + + + + + diff --git a/20151209/src/enshu_20151209/src/8puzzle.py b/20151209/src/enshu_20151209/src/8puzzle.py new file mode 100644 index 00000000..8256fba6 --- /dev/null +++ b/20151209/src/enshu_20151209/src/8puzzle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +#coding: utf-8 + +import random +import math +import copy +from heapq import heappush, heappop + +class Eight_puzzle: + state = [] + size = 3 + def __init__(self): + self.state = [] + for y in range(1,self.size+1): + state_temp = [x for x in range((y-1)*self.size+1 , y*self.size+1)] + self.state.append(state_temp) + self.state[self.size-1][self.size-1] = 0 + #シャッフル + for i in range(100): + rand = random.randint(0,3) + if(rand == 0) : self.up() + if(rand == 1) : self.down() + if(rand == 2) : self.right() + if(rand == 3) : self.left() + self.start_state_x = [0 for i in range(self.size**2)] + self.start_state_y = [0 for i in range(self.size**2)] + self.history = [] + self.history.append(copy.deepcopy(self.state)) + for x in range(self.size): + for y in range(self.size): + self.start_state_x[self.state[y][x]] = x + self.start_state_y[self.state[y][x]] = y + self.step = 0 + return + def move(self,direction): + if(direction == 0) : result = self.up() + if(direction == 1) : result = self.down() + if(direction == 2) : result = self.right() + if(direction == 3) : result = self.left() + if result == 0: + self.history.append(copy.deepcopy(self.state)) + self.step = self.step + 1 + return result + def up(self): + for y_list in self.state: + if(0 in y_list): + x = y_list.index(0) + y = self.state.index(y_list) + break + if(y <= 0): + #print "上に移動はできません" + return 1 + self.state[y][x], self.state[y-1][x] = self.state[y-1][x], self.state[y][x] + return 0 + def down(self): + for y_list in self.state: + if(0 in y_list): + x = y_list.index(0) + y = self.state.index(y_list) + break + if(y >= self.size-1): + #print "下に移動はできません" + return 1 + self.state[y][x], self.state[y+1][x] = self.state[y+1][x], self.state[y][x] + return 0 + def left(self): + for y_list in self.state: + if(0 in y_list): + x = y_list.index(0) + y = self.state.index(y_list) + break + if(x <= 0): + #print "左に移動はできません" + return 1 + self.state[y][x], self.state[y][x-1] = self.state[y][x-1], self.state[y][x] + return 0 + def right(self): + for y_list in self.state: + if(0 in y_list): + x = y_list.index(0) + y = self.state.index(y_list) + break + if(x >= self.size-1): + #print "右に移動はできません" + return 1 + self.state[y][x], self.state[y][x+1] = self.state[y][x+1], self.state[y][x] + return 0 + #ヒューリスティクス関数(正解からのマンハッタン距離) + def calc_h(self): + self.h = 0 + for y in range(self.size): + for x in range(self.size): + val = self.state[y][x] + if val == 0 : + val_correct_x = self.size-1 + val_correct_y = self.size-1 + else: + val_correct_x = (val-1)%self.size + val_correct_y = int(math.ceil(val*1.0/self.size)-1) + self.h = self.h + abs(val_correct_x - x) + abs(val_correct_y - y) + return self.h + def calc_g(self): + self.g = 0 + now_state_x = [0 for i in range(self.size**2)] + now_state_y = [0 for i in range(self.size**2)] + for x in range(self.size): + for y in range(self.size): + now_state_x[self.state[y][x]] = x + now_state_y[self.state[y][x]] = y + for i in range(self.size**2): + self.g = self.g + abs(self.start_state_x[i] - now_state_x[i]) + abs(self.start_state_y[i] - now_state_y[i]) + return self.g + def print_state(self): + for i in range(self.size): + print self.state[i] + print "" +def main(): + puzzle = Eight_puzzle() + Astar_search(puzzle) + return + +def Astar_search(puzzle): + search_queue = [] + #優先度付きキューに格納 + heappush(search_queue, (puzzle.calc_h() - 0,puzzle)) + for i in range(100000): + search_puzzle = heappop(search_queue)[1] + #上下左右探索 + for direction in range(4): + puzzle_tmp = copy.deepcopy(search_puzzle) + result = puzzle_tmp.move(direction) + if result == 0: + #移動成功したらステップ数+hの優先度で格納 + heappush(search_queue, (puzzle_tmp.calc_h()+puzzle_tmp.step,puzzle_tmp)) + #print puzzle_tmp.history + #もしゴールに到達(h=0)したら抜ける + if puzzle_tmp.calc_h() == 0: + print puzzle_tmp.step + hist = puzzle_tmp.history + for i in hist: + for j in range(puzzle_tmp.size): + print i[j] + print + return 0 diff --git a/20151209/src/enshu_20151209/src/graphsearch.cpp b/20151209/src/enshu_20151209/src/graphsearch.cpp new file mode 100644 index 00000000..28b03374 --- /dev/null +++ b/20151209/src/enshu_20151209/src/graphsearch.cpp @@ -0,0 +1,451 @@ +/*--------------------------------------------- + * + * A Tree Search kit for experimenting with graph + * formulated or network problems such as the + * Romanian road network problem as described in + * Russell and Norvig, Chapter 3. + * + * Last Modified: 28.7.04, KAH + * + * $Id: graphsearch.cpp,v 1.1 2010-01-22 03:35:47 k-okada Exp $ + *---------------------------------------------*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +class Node { +public: + + int state; + // previous or parent node instance in the search tree + Node *parentptr; + // not yet used - could be used as child index + int action; + //depth in the tree root is 1 + int depth; + // same as depth at present + int pathCost; + // normal constructor + Node(int s, Node * p) { + state = s; + parentptr = p; + if (parentptr == NULL) { + depth = 1; + } else { + depth = parentptr->depth + 1; + } + } + ~Node() { + } // destructor + Node(const Node & node) { // copy constructor + state = node.state; + parentptr = node.parentptr; + depth = node.depth; + } + Node * parent() { + // return a pointer to this instance's parent instance + if (parentptr != NULL) + return parentptr; + + else + return this; + } + // count of all instances created by factory + static int count; + // all factory-created instances + static vector < Node * >all; + static Node *factory() { + return factory(-1, NULL); + } + static Node *factory(int s) { + return factory(s, NULL); + } + static Node *factory(int s, Node * p) { + Node * retval = new Node(s, p); + all.push_back(retval); + count++; + return retval; + } + + // free up memory from all factory-created instances + static void freeall() { + for (int i = 0; i < all.size(); i++) + delete all[i]; + all.clear(); + } + + bool operator==(const Node & n) { + return (state == n.state); + } + bool operator!=(const Node & n) { + return (state == n.state); + } +}; +int Node::count = 0; +// internal list of all factory-created instances +vector < Node * >Node::all; + +/*------------------------------------------------*/ +// Suitable for a graph like proble such as +// the Romanian road network problem such as +// in Russell and Norvig, 2nd Edition, Chapter 3. +class Problem { + // map of string-names to integer indices i=map[string] + public:map < string, int >indices; + // names of the vertices (cities) string=names[i] + vector < string > names; + // k=successors[i][j] is jth successor of ith vertex + vector < vector < int > > successors; + // w=weights[i][j] is jth weight of arc to ith vertex + vector < vector < int > > weights; + + // number of vertices (cities) in the graph (roadnetwork) + int n() { + return names.size(); + } + int nSuccessors(int i) { + return successors[i].size(); + } // out-degree of ith vertex + Problem() { + } // constructor + ~Problem() { + } // destructor + void addSuccessor(string src, string dst, int w) { + successors[indices[src]].push_back(indices[dst]); + weights[indices[src]].push_back(w); + } + + void addSuccessorPair(string a, string b, int w) { + addSuccessor(a, b, w); + addSuccessor(b, a, w); + } + + void readFile(string filename) { + // currently wired with test data + + // first pass to get city names only: + ifstream in(filename.c_str()); + assert(in); + names.clear(); + char line[1024]; + while (in.getline(line, sizeof(line), '\n')) { + // ignore comment lines in the file + if (line[0] != '#') { + // whitespace possible delimiters + char *delimiters = " \t\n"; + int wordcount = 0; + char *wordptr; + // tokenize string + wordptr = strtok(line, delimiters); + string source(wordptr); + addName(source); // add if it exists + while ((wordptr = strtok(NULL, delimiters)) + != NULL) { + wordcount++; + string destination(wordptr); + addName(destination); // add if it exists + } + } + } + in.close(); + for (int i = 0; i < names.size(); i++) { + indices[names[i]] = i; + } vector < int >dummy; // an empty vector + // sets up 1st dimension with n() copies of dummy + successors.assign(n(), dummy); + // sets up 1st dimension with n() copies of dummy + weights.assign(n(), dummy); + + // second pass to get arcs: + ifstream in2(filename.c_str()); + assert(in2); + while (in2.getline(line, sizeof(line), '\n')) { + // ignore comment lines in the file + if (line[0] != '#') { + // whitespace possible delimiters + char *delimiters = " \t\n"; + int wordcount = 0; + char *wordptr; + // tokenize string + wordptr = strtok(line, delimiters); + string source(wordptr); + // should already exist + assert(nameExists(source)); + while ((wordptr = strtok(NULL, delimiters)) != NULL) { + wordcount++; + string destination(wordptr); + // should already exist + assert(nameExists(destination)); + addSuccessor(source, destination, 1); + } + } + } + in2.close(); + } + bool nameExists(string name) { + // does a name alredy exist in vocabulary of names? + for (vector < string >::iterator it = names.begin(); + it != names.end(); it++) { + if (name == *it) + return true; + } + return false; + } + void addName(string name) { // add name to names only if it is + // not already in vocabulary + if (!nameExists(name)) { + names.push_back(name); + } + } + void testProblem() { + addName(string("Arad")); // get all the city names on first pass + addName(string("Zerend")); + addName(string("Oradea")); + addName(string("Sibiu")); + addName(string("Fagaras")); + addName(string("Bucharest")); + for (int i = 0; i < names.size(); i++) { + indices[names[i]] = i; + } + vector < int >dummy; // an empty vector + +// sets up 1st dimension with n() copies of dummy + successors.assign(n(), dummy); + // sets up 1st dimension with n() copies of dummy + weights.assign(n(), dummy); + + // uniform (unity) for the weights + addSuccessor(string("Arad"), string("Zerend"), 1); + addSuccessor(string("Arad"), string("Sibiu"), 1); + addSuccessor(string("Zerend"), string("Arad"), 1); + addSuccessor(string("Zerend"), string("Oradea"), 1); + addSuccessor(string("Oradea"), string("Zerend"), 1); + addSuccessor(string("Oradea"), string("Sibiu"), 1); + addSuccessor(string("Sibiu"), string("Arad"), 1); + addSuccessor(string("Sibiu"), string("Oradea"), 1); + addSuccessor(string("Sibiu"), string("Fagaras"), 1); + addSuccessor(string("Fagaras"), string("Sibiu"), 1); + addSuccessor(string("Fagaras"), string("Bucharest"), 1); + addSuccessor(string("Bucharest"), string("Fagaras"), 1); + } + // printout problem graph for check purposes - writes out each + // vertex, its out-degree, and its list of successor vertices. + void print() { + int bmax = 0; + for (int i = 0; i < n(); i++) { + cout << names[i] << " (" << nSuccessors(i) << "):: "; + bmax = bmax > nSuccessors(i) ? bmax : nSuccessors(i); + for (int j = 0; j < nSuccessors(i); j++) { + cout << names[successors[i][j]] << ","; + } cout << endl; + } cout << "Max breadth b " << bmax << endl; + } +}; + + +/*------------------------------------------------*/ +class Queue:public deque < Node * > { +public:virtual Node * First() { +}; + virtual void Insert(Node * n) { + }; + virtual Node * RemoveFirst() { + }; +}; + +class FIFOQueue:public Queue { + // a FIFO Queue +public:Node * First() { + return back(); +} + void Insert(Node * n) { + return push_front(n); + } + Node * RemoveFirst() { + Node * r = First(); + pop_back(); + return r; + } +}; + +class LIFOQueue:public Queue { + // a LIFO Queue +public:Node * First() { + return front(); +} + void Insert(Node * n) { + return push_front(n); + } + Node * RemoveFirst() { + Node * r = First(); + pop_front(); + return r; + } +}; + + +/*------------------------------------------------*/ +int main(int argc, char *argv[]) +{ + int c; + char *fname = NULL; + enum { BFS, DFS, DLS, IDS } search_algorithm = BFS; + bool recursive_check = false; + int depth_limit = 1; + while ((c = getopt(argc, argv, "f:bdl:igr")) != -1) { + switch (c) { + case 'f': + fname = optarg; + break; + case 'b': + search_algorithm = BFS; + break; + case 'd': + search_algorithm = DFS; + break; + case 'l': + search_algorithm = DLS; + depth_limit = atoi(optarg); + break; + case 'i': + search_algorithm = IDS; + break; + case 'r': + recursive_check = true; + break; + default: + cerr << "Unknown option " << c << endl; + exit(1); + } + } + cout << ";; Selecting "; + switch (search_algorithm) { + case BFS: + cout << "Breadth-first Search"; + break; + case DFS: + cout << "Depth-first Searach"; + break; + case DLS: + cout << "Depth-limited Search " << depth_limit; + break; + case IDS: + cout << "Iterative Deppting Search"; + break; + } + cout << endl << endl;; + Problem problem; + if (fname) { + problem.readFile(string(fname)); + } else { + problem.testProblem(); + } + problem.print(); + cout << endl; + string goalName("Bucharest"); + string startName("Arad"); + Queue * fringe; + switch (search_algorithm) { + case BFS: + fringe = new FIFOQueue(); + break; + case DFS: + case DLS: + case IDS: + fringe = new LIFOQueue(); + break; + } + vector < Node > closed; + IDS_RESTART: + Node * nodeptr = + (Node::factory(problem.indices[startName])); + fringe->Insert(nodeptr); + bool success = false; + while (!success) { + if (fringe->empty()) + break; // IF-EMPTY -> FAILURE + nodeptr = fringe->RemoveFirst(); // REMOVE-FIRST + cout << "considering " << + problem.names[nodeptr->state] << endl; + + // GOAL-TEST + int i = nodeptr->state; + if (problem.names[i] == goalName) { + success = true; + break; + } + + // DEPTH-TEST + if ((search_algorithm == DLS || + search_algorithm == IDS) + &&nodeptr->depth >= depth_limit) { + success = false; + break; + } + + // state is not in cloased + if (recursive_check == false + || find(closed.begin(), closed.end(), + *nodeptr) == closed.end()) { + closed.push_back(*nodeptr); + for (int j = 0; j < problem.nSuccessors(i); j++) { // EXPAND + Node *nextnode = + Node::factory(problem.successors[i][j], + nodeptr); + // diagnostics + cout << " " + << problem.names[problem.successors[i][j]] + << " from " + << problem.names[i] <Insert(nextnode); + } + } + } if (search_algorithm == IDS && !success) { + closed.clear(); + depth_limit++; + cerr << ">> Deeping ... " << depth_limit << endl; + goto IDS_RESTART; + } + + // report on the solution path found by back tracing parent pointers + if (!success) { + cout << "Failure!" << endl; + } else { + cout << endl << "Solution: " << endl; + while (problem.names[nodeptr->state] != startName) { + cout << problem.names[nodeptr-> + state] << "(depth " << nodeptr-> + depth << ")" << endl; + nodeptr = (nodeptr->parent()); + } + cout << startName << "(depth " << nodeptr->depth << ")" << endl; + } + Node::freeall(); // free up space + cout << endl << Node::all.size() << " Nodes left" << endl; + cout << endl << Node::count << " Nodes created" << endl; +} + + +/*------------------------------------------------ + Development Notes: + + The C++ STL queue with pop and front implements + a FIFO queue. This gives a BFS tree search. + + The C++ Stack is a LIFO - use top and pop. + + Both implement push which pushes onto end of the Queue. + + @KAH 2004--------------------------------------*/ +