repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
SethRobinson/ardumanarduman_arduboylib11
ardu_main.h
#ifndef ardu_main_h__ #define ardu_main_h__ //game settings #ifdef _DEBUG #define SKIP_INTRO #endif //#define SHOW_PELLET_COUNT //#define CHEAT_ALWAYS_HAVE_POWER_PILL //the highscore system is the same as the breakout example - pick an unused eeprom slot! #define EEPROM_HIGH_SCORE_SAVE_SLOT 8 #define LIVES_COUNT 3 #define PLAYER_FAST_SPEED 0.6f #define PLAYER_SLOW_SPEED 0.48f //when eating pellets #define GHOST_SPEED 0.5f #define GHOST_MAX 4 #define STARTING_GHOSTS 4 #define GHOSTS_TO_ADD_EACH_LEVEL 0 //if not 0, we add to the total ghost count each level, allowing crazy bonuses #define GHOST_KILL_DELAY_MS 380 //the freeze when you "pop" a ghost #define TUNNEL_X 53 //top left of where the entity touches #define GHOST_CUBBY_HOLE_X 53 #define GHOST_CUBBY_HOLE_Y 23 #define GHOST_TUNNEL_SPEED_MOD 0.6f; //ghost speed is multiplied by this when in tunnel #define GHOST_START_Y 17 #define TOTAL_PELLETS 244 //arcade game has 240. Fruit at 70 and 170 #define C_POWER_PILL_TIME_MS 6000 #define POWER_WEAR_OFF_WARNING_MS 1000 #define GHOST_KILL_POINTS 200 #define PELLET_POINTS 10 #define POWER_PELLET_POINTS 50 void main_loop(); void main_setup(); void ClearAndRedrawLevel(); void DrawScore(); enum GAME_MODE { MODE_NONE, MODE_MENU, MODE_START, MODE_PLAYING, MODE_DYING, MODE_HIGHSCORES }; extern GAME_MODE g_mode; #endif // ardu_main_h__
payload-code/payload-ios
Payload/Payload.h
<reponame>payload-code/payload-ios // // Payload.h // Payload // // Created by Payload on 9/22/20. // #import <Foundation/Foundation.h> //! Project version number for Payload. FOUNDATION_EXPORT double PayloadVersionNumber; //! Project version string for Payload. FOUNDATION_EXPORT const unsigned char PayloadVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Payload/PublicHeader.h>
jonri/StuntPlayground
StuntPlayground/src/Prop.h
/* Stunt Playground Prop */ #ifndef _STUNTPLAYGROUND_PROP_ #define _STUNTPLAYGROUND_PROP_ #include <OgreNewt.h> #include <Ogre.h> #include "WorldRecorder.h" namespace StuntPlayground { /* Stunt Playground Prop class all in-game jumps and other physics props */ class Prop { private: // name Ogre::String m_Name; Ogre::String m_HitSound; // Rigid Body, the base of the class. OgreNewt::Body* m_Body; public: WorldRecorder::RecordableObject* mRecObj; private: Ogre::Real buffer[24]; public: Prop(); // constructor ~Prop(); // destructor void load( Ogre::String name, int count, OgreNewt::World* world, const OgreNewt::MaterialID* mat, Ogre::String& filename, Ogre::Quaternion& orient, Ogre::Vector3& pos, Ogre::SceneManager* mgr, Ogre::String hitsound ); void remove( Ogre::SceneManager* mgr ); const Ogre::String& getName() { return m_Name; } OgreNewt::Body* getNewtonBody() { return m_Body; } void setupRecording( Ogre::Real minwait ); Ogre::String getHitSound() { return m_HitSound; } static void transformCallback( OgreNewt::Body* me, const Ogre::Quaternion& orient, const Ogre::Vector3& pos ); }; } // end NAMESPACE StuntPlayground #endif _STUNTPLAYGROUND_PROP_
jonri/StuntPlayground
StuntPlayground/src/FollowCamera.h
<gh_stars>1-10 /* Stunt Playground FollowCamera */ #ifndef _STUNTPLAYGROUND_FOLLOWCAMERA_ #define _STUNTPLAYGROUND_FOLLOWCAMERA_ #include <Ogre.h> namespace StuntPlayground { /* my custom follow camera class. this class lets you "assign" a node to the camera, and it will follow it. it also has 2 follow modes. "JustFollow" simply follows a moving node, trying to maintain a certain distance. if justfollow is set to false, the camera maintains a certain angle, as defined by the Yaw and Pitch angles. */ class FollowCamera { private: // the camera! Ogre::Camera* mCamera; // the node we want to follow. const Ogre::Node* mGoalNode; // the (optional) node we want to look at const Ogre::Node* mLookNode; // goal distance we want to maintain from the node. Ogre::Real mDist; Ogre::Real mJustFollowHeight; // optional angles. Ogre::Radian mYaw; Ogre::Radian mPitch; // whether or not to use angles bool mJustFollow; // look position! Ogre::Vector3 mLookVec; // maximum delta to maintain stability. Ogre::Real mMaxDelta; public: FollowCamera( Ogre::Camera* cam ) : mDist(0), mYaw(0), mPitch(0), mJustFollowHeight(0), mMaxDelta(0.1f), mJustFollow(true) { mCamera = cam; mGoalNode = NULL; mLookNode = NULL; mLookVec = Ogre::Vector3::ZERO; } ~FollowCamera() { } // set the max delta time. void setMaxDelta( Ogre::Real val ) { mMaxDelta = val; } // main update command, this should be called each frame... void update( Ogre::Real deltat ); // set the goal node. void setGoalNode( const Ogre::Node* node ) { mGoalNode = node; } // set the goal distance. void setGoalDistance( Ogre::Real dist ) { mDist = dist; } // set the goal Yaw angle void setGoalYawAngle( Ogre::Radian angle ) { mYaw = angle; } // set the goal Pitch angle void setGoalPitchAngle( Ogre::Radian angle ) { mPitch = angle; } // just follow? false = respect angles as well. true = just follow. void setJustFollow( bool setting ) { mJustFollow = setting; } // get goal node. const Ogre::Node* getGoalNode() { return mGoalNode; } // get goal distance. Ogre::Real getGoalDistance() { return mDist; } // get goal Yaw angle Ogre::Radian getGoalYawAngle() { return mYaw; } // get goal Pitch angle Ogre::Radian getGoalPitchAngle() { return mPitch; } // get follow mode bool getJustFollow() { return mJustFollow; } // set the (optional) look node. void setLookNode( const Ogre::Node* node ) { mLookNode = node; } // remove the (optional look node) void removeLookNode() { mLookNode = NULL; } // get look node. const Ogre::Node* getLookNode() { return mLookNode; } // set a Y-offset for just follow mode. void setJustFollowHeight( Ogre::Real offset ) { mJustFollowHeight = offset; } }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_FOLLOWCAMERA_
jonri/StuntPlayground
StuntPlayground/include/WalaberOgreFrameListener.h
<gh_stars>1-10 /* WalaberOgreFrameListener basic frame listener, with mouse/keyboard input. nothing else :) */ #ifndef __WALABER_OGRE_FRAMELISTENER_H__ #define __WALABER_OGRE_FRAMELISTENER_H__ #include "Ogre.h" #include "OgreKeyEvent.h" #include "OgreEventListeners.h" #include "OgreStringConverter.h" #include "OgreException.h" using namespace Ogre; class WalaberOgreFrameListener: public FrameListener, public KeyListener { public: // Basic contructor. WalaberOgreFrameListener(RenderWindow* win) { mInputDevice = PlatformManager::getSingleton().createInputReader(); mInputDevice->initialise(win,true, true); mWindow = win; } virtual ~WalaberOgreFrameListener() { if (mInputDevice) PlatformManager::getSingleton().destroyInputReader( mInputDevice ); } // basic frameStarted function. must be overwritten. bool frameStarted(const FrameEvent& evt) { if(mWindow->isClosed()) return false; return true; } bool frameEnded(const FrameEvent& evt) { return true; } void keyClicked(KeyEvent* e) {} void keyPressed(KeyEvent* e) {} void keyReleased(KeyEvent* e) {} protected: InputReader* mInputDevice; RenderWindow* mWindow; }; #endif // __WALABER_OGRE_FRAMELISTENER_H__
jonri/StuntPlayground
StuntPlayground/src/PropListItem.h
/* Stunt Playground PropListItem */ #ifndef _STUNTPLAYGROUND_PROPLISTITEM_ #define _STUNTPLAYGROUND_PROPLISTITEM_ #include <CEGUI.h> #include "elements/CEGUIListboxTextItem.h" namespace StuntPlayground { class PropListItem : public CEGUI::ListboxTextItem { private: Ogre::String mBOD_File; CEGUI::String mImageset; CEGUI::String mImageName; CEGUI::String mMaterial; public: PropListItem( Ogre::String bod, CEGUI::String imageset, CEGUI::String image, CEGUI::String text, CEGUI::String material ) : ListboxTextItem(text) { mBOD_File = bod; mImageset = imageset; mImageName = image; mMaterial = material; using namespace CEGUI; // set default colors, etc. setTextColours( colour(0.8,0.8,0.8) ); setSelectionBrushImage((utf8*)"WindowsLook",(utf8*)"Background"); setSelectionColours( colour(1.0,0,0) ); } ~PropListItem() {} Ogre::String& getBODFile() { return mBOD_File; } CEGUI::String& getImageset() { return mImageset; } CEGUI::String& getImageName() { return mImageName; } CEGUI::String& getMaterial() { return mMaterial; } }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_PROPLISTITEM_
jonri/StuntPlayground
StuntPlayground/include/line3D.h
<gh_stars>1-10 #ifndef __LINE3D_H__ #define __LINE3D_H__ #include "Ogre.h" #include <vector> using namespace Ogre; using namespace std; #define POSITION_BINDING 0 #define TEXCOORD_BINDING 1 class Line3D:public SimpleRenderable { public: Line3D(void); ~Line3D(void); void addPoint(const Vector3 &p); const Vector3 &getPoint(unsigned short index) const; unsigned short getNumPoints(void) const; void updatePoint(unsigned short index, const Vector3 &value); void drawLine(Vector3 &start, Vector3 &end); void drawLines(void); Real getSquaredViewDepth(const Camera *cam) const; Real getBoundingRadius(void) const; protected: //void getWorldTransforms(Matrix4 *xform) const; const Quaternion &getWorldOrientation(void) const; const Vector3 &getWorldPosition(void) const; vector<Vector3> mPoints; bool mDrawn; }; #endif /* __LINE3D_H__ */
jonri/StuntPlayground
StuntPlayground/src/StuntPlaygroundApplication.h
/* Stunt Playground StuntPlaygroundApplication */ #ifndef _STUNTPLAYGROUNDAPPLICATION_ #define _STUNTPLAYGROUNDAPPLICATION_ #include "Prereq.h" #include "CEGUI.h" #include "OgreCEGUIRenderer.h" #include "OgreCEGUIResourceProvider.h" #include "WalaberOgreApplication.h" #include ".\CEGUIFrameListener.h" #include "OgreNewt.h" #include ".\StuntPlayground.h" #include "CollisionCallbacks.h" #include ".\Prop.h" #include ".\FollowCamera.h" #include ".\StandardButton.h" #include ".\DummyBody.h" #include ".\vehicle.h" #include ".\BodyIterators.h" #include ".\dialogs.h" #include ".\AABB.h" #include "Line3D.h" #include "settings.h" #include "ReflectionRenderTarget.h" #include "HighScore.h" #include <tinyxml.h> /////////////////////////////////////////////////////////////////////////////////////////////////////// namespace StuntPlayground { class Application : public WalaberOgreApplication { public: // class for camera angles class CameraAngle { public: Ogre::Radian mYawAngle; Ogre::Radian mPitchAngle; Ogre::Real mDist; Ogre::Vector3 mOffset; void setup( Ogre::Radian yaw, Ogre::Radian pitch, Ogre::Real dist, Ogre::Vector3 offset ) { mYawAngle = yaw; mPitchAngle = pitch; mDist = dist; mOffset = offset; } }; // class for reflection cameras class ReflectCam { public: Ogre::Camera* mCAM; Ogre::RenderTarget* mRT; }; static Application& getSingleton(); static Application* getSingletonPtr(); CEGUI::TabPane* getPane() { return mPane; } ReplayControls* getReplayControls() { return mReplayControls; } OgreNewt::World* getOgreNewtWorld() { return mWorld; } Application(void); ~Application(void); void makeDummy(); void setDummyCallback(); StuntPlayground::DummyBody* getDummy() { return mDummyBody; } StuntPlayground::MyAABB* getAABB() { return mAABB; } StuntPlayground::ProgState getProgState() { return mState; } void setProgState( StuntPlayground::ProgState state ) { mState = state; } void nextCar(); void prevCar(); void removeCar(); void goCamera(); void nextCamera(); void setCamera( CameraView ang ); unsigned int getCameraView() { return mCurrentCamAngle; } Ogre::SceneManager* getSceneMgr() { return mSceneMgr; } Ogre::SceneNode* getDirtParticlesNode() { return mDirtParticlesNode; } Ogre::ParticleSystem* getDirtParticles() { return mDirtParticles; } Ogre::SceneNode* getSparkParticlesNode() { return mSparkParticlesNode; } Ogre::ParticleSystem* getSparkParticles() { return mSparkParticles; } void showLOGO() { mLOGO->show(); } void hideLOGO() { mLOGO->hide(); } void showGUI(); void hideGUI(); void showGUI_REC(); void hideGUI_REC(); void updateOldMessages( Ogre::String text ); void possibleJumpRecord( Ogre::Real length, Ogre::Real time, Ogre::Real flips ); void possible2WheelRecord( Ogre::Real time ); void updateReflection(); void disableSaveReplay(); void enableSaveReplay(); void reflectionsON(); void reflectionsOFF(); void setDummyVisible( bool setting ); void restoreArena(); bool closeDialog(); bool addClicked( const CEGUI::EventArgs& e ); void showHint(Ogre::String& message ) { mHint->setText( (std::string)message ); } void showStandardHint(); // show an error message void showErrorMessage( Ogre::String msg, bool showCancel ); static void _cdecl updateProps( OgreNewt::Body* body ); #ifdef _SP_DEBUG Line3D* mDebugLines; Ogre::SceneNode* mDebugNode; #endif // _SP_DEBUG #ifdef _SP_DEBUG_LOG Ogre::Log* mDebugLog; #endif // _SP_DEBUG_LOG // various Newton materials; const OgreNewt::MaterialID* mMatArena; const OgreNewt::MaterialID* mMatCar; const OgreNewt::MaterialID* mMatProp; const OgreNewt::MaterialID* mMatDummy; const OgreNewt::MaterialID* mMatPlacer; StuntPlayground::Car* mCar; Ogre::Real mFollowCamOldDist; // XML node (for saving props) TiXmlElement* mXmlElement; protected: void createFrameListener(); void createScene(); void createMaterials(); void destroyScene(); void destroyMaterials(); void makeGUI(); void makeOnScreenGUI(); void setupGUI(); // CEGUI functions! bool handleQuit( const CEGUI::EventArgs& e ); bool ListboxChanged( const CEGUI::EventArgs& e ); bool goClicked( const CEGUI::EventArgs& e ); bool openClicked( const CEGUI::EventArgs& e ); bool saveClicked( const CEGUI::EventArgs& e ); bool newClicked( const CEGUI::EventArgs& e ); bool settingsClicked( const CEGUI::EventArgs& e ); bool loadReplayClicked( const CEGUI::EventArgs& e ); bool saveReplayClicked( const CEGUI::EventArgs& e ); bool clearScoresClicked( const CEGUI::EventArgs& e ); bool disablePane( const CEGUI::EventArgs& e ) { mPane->setEnabled(false); mPane2->setEnabled(false); return true; } bool enablePane( const CEGUI::EventArgs& e ) { mPane->setEnabled(true); mPane2->setEnabled(true); return true; } bool backFromLoad( const CEGUI::EventArgs& e ); bool backFromSave( const CEGUI::EventArgs& e ); bool backFromSetting( const CEGUI::EventArgs& e ); bool playClickSound( const CEGUI::EventArgs& e ); // car choosing functions... void makeCar(); // save / load the arena... void saveArena( Ogre::String filename ); void loadArena( Ogre::String filename ); // save / load replays void saveReplay( Ogre::String filename ); void loadReplay( Ogre::String filename ); // load the default camera angles void setDefaultCameraAngles(); // setup / init / update reflection cameras void makeReflectionCameras(); void killReflectionCameras(); void applyReflectionCameras(); void removeReflectionCameras(); // GameSettings! void loadGameSettings(); void saveGameSettings(); void applySettings(); // newton callbacks... static void dummyForceCallback( OgreNewt::Body* me ); static void clearProps( OgreNewt::Body* body ); static void saveProps( OgreNewt::Body* body ); private: // Newton World!! OgreNewt::World* mWorld; // CEGUI Ogre Renderer CEGUI::OgreCEGUIRenderer* mGUIRenderer; // CEGUI Frame Listener CEGUIFrameListener* mCEGUIListener; // main logo image CEGUI::StaticImage* mLOGO; // UI parts Ogre::Overlay* mGUI; Ogre::OverlayElement* mGUI_CAMERA; Ogre::OverlayElement* mGUI_REC; Ogre::OverlayElement* mGUI_JP_DISTt; Ogre::OverlayElement* mGUI_JP_TIMEt; Ogre::OverlayElement* mGUI_JP_FLIPSt; Ogre::OverlayElement* mGUI_JP_2WHt; // records! HighScore mScores; // main GUI window. CEGUI::TabPane* mPane; CEGUI::TabPane* mPane2; CEGUI::StaticText* mHint; // main preview image CEGUI::StaticImage* mPrevImg; // buttons! StandardButton* mButAdd; StandardButton* mButGo; StandardButton* mButQuit; StandardButton* mButOpen; StandardButton* mButSave; StandardButton* mButNew; StandardButton* mButSettings; StandardButton* mButLoadReplay; StandardButton* mButSaveReplay; StandardButton* mButClearScores; // program state StuntPlayground::ProgState mState; // my custom camera class. FollowCamera* mFollowCam; // base level Rigid Body OgreNewt::Body* mArenaBody; OgreNewt::Body* mWorldLimitsBody; // dummy body for prop placement DummyBody* mDummyBody; // AABB visualizer MyAABB* mAABB; // base scene node that holds all the props in the level. Ogre::SceneNode* mPropBaseNode; iteratorRemoveProps* mIteratorRemoveProps; // pointer to current selected node. StuntPlayground::Prop* mSelectedProp; // material pairs. OgreNewt::MaterialPair* mMatPairArenaVsCar; OgreNewt::MaterialPair* mMatPairCarVsProp; // newton callbacks CarArenaCallback* mCarArenaCallback; DummyCollisionCallback* mDummyCallback; PropCollision* mPropCallback; CarPropCollision* mCarPropCallback; // vehicle list. Ogre::FileInfoListPtr mVehicleList; unsigned short mCurrentVehicle; // dialog boxes. LoadDialog* mLoadDialog; SaveDialog* mSaveDialog; ErrorDialog* mErrorDialog; SettingDialog* mSettingDialog; ReplayControls* mReplayControls; // face indexes for car/arena collision unsigned int mArenaIDRoad; unsigned int mArenaIDRoadChecker; unsigned int mArenaIDGround; // all of the camera angles available. std::vector<CameraAngle> mCameraAngles; unsigned int mCurrentCamAngle; Ogre::ParticleSystem* mDirtParticles; Ogre::SceneNode* mDirtParticlesNode; Ogre::ParticleSystem* mSparkParticles; Ogre::SceneNode* mSparkParticlesNode; // Reflection Cameras. unsigned int mCurrentReflectCam; std::vector<ReflectCam> mReflectCams; std::vector<Ogre::String> mOldTextures; ReflectionRenderTarget* mReflectionListener; bool mReflectCamEnabled; // game settings GameSettings mSettings; float buffer[50]; }; } // end NAMESPACE StuntPlayground #endif
jonri/StuntPlayground
StuntPlayground/src/AABB.h
/* Stunt Playground DummyBody */ #ifndef _STUNTPLAYGROUND_AABB_ #define _STUNTPLAYGROUND_AABB_ #include <Ogre.h> namespace StuntPlayground { /* Stunt Playground AABB class simple AABB - visualizer, used to highliting objects, etc. */ class MyAABB { Ogre::SceneNode* mNode; Ogre::SceneManager* mSceneMgr; Ogre::AxisAlignedBox mBox; Ogre::String mMatName; public: MyAABB( Ogre::String name, Ogre::SceneManager* mgr, Ogre::String boxmesh, Ogre::String materialname ) { mSceneMgr = mgr; // create the entity, etc. Ogre::Entity* ent = mgr->createEntity(name, boxmesh); mNode = mgr->getRootSceneNode()->createChildSceneNode(); mNode->attachObject(ent); ent->setCastShadows(false); ent->setMaterialName( materialname ); mNode->setVisible(false); mMatName = ""; mBox = Ogre::AxisAlignedBox(0.0f,0.0f,0.0f,0.0f,0.0f,0.0f); } ~MyAABB() { // delete the scene node and entity. Ogre::Entity* ent = (Ogre::Entity*)mNode->detachObject(static_cast<unsigned short>(0)); mSceneMgr->SceneManager::destroyEntity( ent->getName() ); mNode->getParentSceneNode()->removeAndDestroyChild( mNode->getName() ); } void setSize( Ogre::Vector3 size ) { mNode->setScale( size ); } Ogre::Vector3 getSize() { return mNode->getScale(); } void setMaterial( Ogre::String matname ) { if (matname == mMatName) return; mMatName = matname; ((Ogre::Entity*)mNode->getAttachedObject(0))->setMaterialName(matname); } void setVisible( bool setting ) { mNode->setVisible(setting); } void setToAABB( Ogre::AxisAlignedBox box ) { Ogre::Vector3 center; Ogre::Vector3 size; if ((box.getMaximum() == mBox.getMaximum()) || (box.getMinimum() == mBox.getMinimum())) return; size = box.getMaximum() - box.getMinimum(); center = box.getMinimum() + (size/2.0); mNode->setPosition( center ); setSize( size ); } }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_AABB_
jonri/StuntPlayground
StuntPlayground/src/CEGUIFrameListener.h
/* Stunt Playground CEGUIFrameListener */ #ifndef _STUNTPLAYGROUND_CEGUIFRAMELISTENER_ #define _STUNTPLAYGROUND_CEGUIFRAMELISTENER_ #include "CEGUI.h" #include "WalaberOgreFrameListener.h" #include "OgreEventQueue.h" /////////////////////////////////////////////////////////////////////////////////////////////////////// namespace StuntPlayground { class CEGUIFrameListener : public WalaberOgreFrameListener, Ogre::MouseMotionListener, Ogre::MouseListener { public: CEGUIFrameListener(RenderWindow* win, Camera* cam, CEGUI::TabPane* pane, CEGUI::TabPane* pane2) : WalaberOgreFrameListener(win) { mInputDevice2 = mInputDevice; mEventProcessor = new EventProcessor(); mEventProcessor->initialise(win); mEventProcessor->startProcessingEvents(); mEventProcessor->addKeyListener(this); mEventProcessor->addMouseMotionListener(this); mEventProcessor->addMouseListener(this); mInputDevice = mEventProcessor->getInputReader(); mQuit = false; mSkipCount = 0; mUpdateFreq = 0; mPane = pane; mPane2 = pane2; } ~CEGUIFrameListener() { mEventProcessor->stopProcessingEvents(); mEventProcessor->removeKeyListener(this); mEventProcessor->removeMouseMotionListener(this); mEventProcessor->removeMouseListener(this); delete mEventProcessor; mInputDevice = mInputDevice2; } virtual void mouseMoved (MouseEvent *e) { CEGUI::Renderer* rend = CEGUI::System::getSingleton().getRenderer(); CEGUI::System::getSingleton().injectMouseMove(e->getRelX() * rend->getWidth(), e->getRelY() * rend->getHeight()); e->consume(); } virtual void mouseDragged (MouseEvent *e) { mouseMoved(e); } virtual void keyPressed (KeyEvent *e) { /* // give 'quitting' priority if (e->getKey() == KC_ESCAPE) { mQuit = true; e->consume(); return; } */ // do event injection CEGUI::System& cegui = CEGUI::System::getSingleton(); // key down cegui.injectKeyDown(e->getKey()); // now character cegui.injectChar(e->getKeyChar()); e->consume(); } virtual void keyReleased (KeyEvent *e) { CEGUI::System::getSingleton().injectKeyUp(e->getKey()); } virtual void mousePressed (MouseEvent *e) { CEGUI::System::getSingleton().injectMouseButtonDown(convertOgreButtonToCegui(e->getButtonID())); e->consume(); } virtual void mouseReleased (MouseEvent *e) { CEGUI::System::getSingleton().injectMouseButtonUp(convertOgreButtonToCegui(e->getButtonID())); e->consume(); } // do-nothing events virtual void keyClicked (KeyEvent *e) {} virtual void mouseClicked (MouseEvent *e) {} virtual void mouseEntered (MouseEvent *e) {} virtual void mouseExited (MouseEvent *e) {} bool frameStarted(const FrameEvent& evt); protected: CEGUI::MouseButton convertOgreButtonToCegui(int ogre_button_id) { switch (ogre_button_id) { case MouseEvent::BUTTON0_MASK: return CEGUI::LeftButton; break; case MouseEvent::BUTTON1_MASK: return CEGUI::RightButton; break; case MouseEvent::BUTTON2_MASK: return CEGUI::MiddleButton; break; case MouseEvent::BUTTON3_MASK: return CEGUI::X1Button; break; default: return CEGUI::LeftButton; break; } } protected: Ogre::EventProcessor* mEventProcessor; float mSkipCount; float mUpdateFreq; Ogre::InputReader* mInputDevice2; CEGUI::TabPane* mPane; CEGUI::TabPane* mPane2; bool mQuit; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_CEGUIFRAMELISTENER_
jonri/StuntPlayground
StuntPlayground/src/PropManager.h
/* Stunt Playground PropManager */ #ifndef _STUNTPLAYGROUND_PROPMANAGER_ #define _STUNTPLAYGROUND_PROPMANAGER_ #include "Prop.h" namespace StuntPlayground { // Prop manager - for adding/removing/managing props in the arena. class PropManager { public: struct PropDefinition { std::string mBodyFile; std::string mImageSet; std::string mImage; std::string mHitSound; }; typedef std::map<std::string, PropDefinition> PropDefinitionMap; typedef std::map<std::string, PropDefinition>::iterator PropDefinitionIterator; typedef std::list<Prop*>::iterator PropListIterator; static PropManager& getSingleton(); void init( Ogre::String proplisfile, OgreNewt::World* world, const OgreNewt::MaterialID* propmat, Ogre::SceneManager* mgr ); Prop* addProp( Ogre::String name, Ogre::Vector3 pos, Ogre::Quaternion orient ); void removeProp( Prop* prop ); PropDefinition getPropDefinition( std::string name ); PropDefinitionMap getPropDefinitionMap() { return mPropDefinitions; } PropListIterator getPropListIteratorBegin() { return mProps.begin(); } PropListIterator getPropListIteratorEnd() { return mProps.end(); } private: typedef std::list<Prop*> PropList; PropManager(); ~PropManager(); PropList mProps; PropDefinitionMap mPropDefinitions; Ogre::SceneManager* mSceneMgr; OgreNewt::World* mWorld; const OgreNewt::MaterialID* mPropMat; int count; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_PROPMANAGER_
jonri/StuntPlayground
StuntPlayground/src/MainFrameListener.h
/* Stunt Playground MainFrameListener */ #ifndef _MAINFRAMELISTENER_ #define _MAINFRAMELISTENER_ #include "WalaberOgreFrameListener.h" #include ".\StuntPlayground.h" #include ".\FollowCamera.h" namespace StuntPlayground { class MainFrameListener : public WalaberOgreFrameListener { protected: Ogre::SceneManager* mSceneMgr; Ogre::Camera* mCamera; FollowCamera* mFollowCam; OgreNewt::World* mWorld; bool mLMB; bool mRMB; bool mKeySU, mKeySD; bool mESCAPE; bool mLEFT, mRIGHT; bool mC; bool mSPACE; bool mREC; bool mR; Ogre::Timer mMouseStill; Ogre::Degree mRotDegree; std::vector<Ogre::Vector3> mBasicAxis; StuntPlayground::RotAxis mCurrentAxis; Ogre::Real mPlaybackTime; Ogre::OverlayElement* mMessage; Ogre::String mMessageText; Ogre::Real mMessageWidth; // should we update the physics? bool mUpdateNewton; int desired_framerate; Ogre::Real m_update, m_elapsed; Ogre::Real mMinCamDist; void userControls( Ogre::Real timeelapsed ); void updateMessage( Ogre::Real timestep ); #ifdef _SP_DEBUG_LOG Ogre::Real m_totalelapsed; unsigned int m_totalframes; unsigned int m_totalupdates; #endif // _SP_DEBUG_LOG public: MainFrameListener(RenderWindow* win, Camera* cam, SceneManager* mgr, FollowCamera* follow, OgreNewt::World* world, int desired_fps ); ~MainFrameListener(void); bool frameStarted(const FrameEvent &evt); void startReplayPlayback( Ogre::Real time ); }; } // end NAMESPACE StuntPlayground #endif // _MAINFRAMELISTENER_ guard
jonri/StuntPlayground
StuntPlayground/src/DummyBody.h
/* Stunt Playground DummyBody */ #ifndef _STUNTPLAYGROUND_DUMMYBODY_ #define _STUNTPLAYGROUND_DUMMYBODY_ #include <Ogre.h> #include <OgreNewt.h> #include <OgreNewt_Body.h> namespace StuntPlayground { /* Stunt Playground DummyBody class dummy rigid body, used for prop placement collision detection, etc. */ class DummyBody { private: //private member variables. // Rigid Body, the base of the class. OgreNewt::Body* m_Body; Ogre::Vector3 m_Size; Ogre::Vector3 mGoalPos; Ogre::Quaternion mGoalOrient; Ogre::Real mSpringConst; Ogre::Real mSpringDamp; const OgreNewt::MaterialID* m_MyMat; // attached body. OgreNewt::Body* m_Attached; const OgreNewt::MaterialID* m_AttachedMat; // possibly attached body. OgreNewt::Body* m_PossibleAttach; Ogre::SceneNode* mRotNode; void setCollision( const OgreNewt::Collision* newcollision, Ogre::Vector3 nodescale = Ogre::Vector3(1,1,1) ); public: DummyBody( OgreNewt::World* world, const OgreNewt::MaterialID* mat, Ogre::Vector3& size, Ogre::SceneManager* mgr ); ~DummyBody() { // delete the body! delete m_Body; } // attach the dummy to a specific Body void attachBody( OgreNewt::Body* body, const OgreNewt::MaterialID* tempMat ); // detach from the current attached body. void detach(); OgreNewt::Body* getAttached() { return m_Attached; } void setSize( Ogre::Vector3& size ); OgreNewt::Body* getNewtonBody() { return m_Body; } void setGoalPositionOrientation( Ogre::Vector3& pos, Ogre::Quaternion& orient ); void getGoalPositionOrientation( Ogre::Vector3& pos, Ogre::Quaternion& orient ); void setSpringConst( Ogre::Real constant ) { mSpringConst = constant; } Ogre::Real getSpringConst() { return mSpringConst; } void setSpringDamp( Ogre::Real damp ) { mSpringDamp = damp; } Ogre::Real getSpringDamp() { return mSpringDamp; } OgreNewt::Body* getPossibleAttach() { return m_PossibleAttach; } void setPossibleAttach( OgreNewt::Body* body ) { m_PossibleAttach = body; } void attachToCurrentPossible( const OgreNewt::MaterialID* material ); void setRotRingOrient( StuntPlayground::RotAxis axis ); }; } // end NAMESPACE StuntPlayground #endif _STUNTPLAYGROUND_DUMMYBODY_
jonri/StuntPlayground
StuntPlayground/src/CollisionCallbacks.h
<gh_stars>1-10 /* Stunt Playground Collision Callbacks */ #ifndef _STUNTPLAYGROUND_COLLISIONCALLBACKS_ #define _STUNTPLAYGROUND_COLLISIONCALLBACKS_ #include <OgreNewt.h> #include <Ogre.h> #include "SoundManager.h" namespace StuntPlayground { // collision calback for the DummyBody. class DummyCollisionCallback : public OgreNewt::ContactCallback { // user-defined functions. int userBegin(); int userProcess(); void userEnd() {} }; class CarArenaCallback : public OgreNewt::ContactCallback { public: void setIDs( unsigned int road, unsigned int ground, unsigned int roadchecker ) { mRoadID = road; mGroundID = ground; mRoadCheckerID = roadchecker; } void setCollisionSound( std::string name ) { mCarSnd = SoundManager::getSingleton().getSound( name ); } private: // user defined functions int userBegin() { return 1; } int userProcess(); void userEnd() {} Sound* mCarSnd; unsigned int mRoadID; unsigned int mRoadCheckerID; unsigned int mGroundID; }; class PropCollision : public OgreNewt::ContactCallback { int userBegin() ; int userProcess(); void userEnd(); Ogre::Real mNormSpeed; Ogre::Real mTangSpeed; Ogre::Vector3 mPosition; }; class CarPropCollision : public OgreNewt::ContactCallback { int userBegin(); int userProcess(); void userEnd(); bool mBodyHit; Ogre::Real mNormSpeed; Ogre::Real mTangSpeed; Ogre::Vector3 mPosition; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_COLLISIONCALLBACKS_
jonri/StuntPlayground
StuntPlayground/src/vehicle.h
<reponame>jonri/StuntPlayground /* Stunt Playground Vehicle */ #ifndef _STUNTPLAYGROUND_VEHICLE #define _STUNTPLAYGROUND_VEHICLE #include <OgreNewt.h> #include <Ogre.h> #include "StuntPlayground.h" #include "WorldRecorder.h" #include "SoundManager.h" namespace StuntPlayground { /* Car class! this is the basis for the entire vehicle system for Stunt Playground. */ class Car : public OgreNewt::Vehicle { public: enum VehicleState { VS_4ONFLOOR, VS_2WHEELS, VS_AIRBORNE, VS_UPSIDEDOWN }; enum TireState { TS_ONROAD, TS_ONDIRT, TS_ONPROP }; class MyTire : public OgreNewt::Vehicle::Tire { public: MyTire( Ogre::SceneManager* mgr, Ogre::SceneNode* parentnode, OgreNewt::Vehicle* vehicle, Ogre::Quaternion localorient, Ogre::Vector3 localpos, Ogre::Vector3 pin, Ogre::Real mass, Ogre::Real width, Ogre::Real radius, Ogre::Real susShock, Ogre::Real susSpring, Ogre::Real susLength, int colID = 0); ~MyTire(); void setSteer( int steer ) { mSteer = steer; } int getSteer() { return mSteer; } void setDrive( int drive ) { mDrive = drive; } int getDrive() { return mDrive; } void setGrip( Ogre::Real grip ) { mGrip = grip; } Ogre::Real getGrip() { return mGrip; } Ogre::Real getRadius() { return mRadius; } WorldRecorder::RecordableObject* mRecObj; private: Ogre::SceneManager* mSceneMgr; int mSteer; int mDrive; Ogre::Real mGrip; Ogre::Real mRadius; }; struct TorquePoint { Ogre::Real rpm; Ogre::Real torque; }; Car(); Car( OgreNewt::World* world, Ogre::SceneNode* parentnode, Ogre::SceneManager* mgr, Ogre::String filename, const OgreNewt::MaterialID* mat ); ~Car(); // my init function. void _init( OgreNewt::World* world, Ogre::SceneNode* parentnode, Ogre::SceneManager* mgr, Ogre::String filename, const OgreNewt::MaterialID* mat ); void setup(); void userCallback(); void setThrottleSteering( Ogre::Real throttle, Ogre::Real steering ) { mThrottle = throttle; mSteering = steering; } void shiftUp() { mCurrentGear++; mJustShifted = true; if (mCurrentGear > mGears.size()-1) { mCurrentGear = mGears.size()-1; mJustShifted = false; } } void shiftDown() { mCurrentGear--; mJustShifted = true; if (mCurrentGear <= 0) { if (mLastOmega <= 5.0) { mCurrentGear = 0; mJustShifted = false; } else { mCurrentGear = 1; } } } void setBrakes( bool onoff ) { mBrakesOn = onoff; } Ogre::SceneNode* getLookNode() { return mLookNode; } static void Transform( OgreNewt::Body* me, const Ogre::Quaternion& orient, const Ogre::Vector3& pos ); void setupRecording( Ogre::Real minwait ); WorldRecorder::RecordableObject* mRecObject; VehicleState getState() { return mState; } void incCollisions(); void setTireState( TireState state ) { mTireState = state; } TireState getTireState() { return mTireState; } Ogre::String getFilename() { return mFilename; } void setManualTransmission( bool setting ) { mManualTransmission = setting; } bool getManualTransmission() { return mManualTransmission; } void playEngine(); void stopEngine(); private: Ogre::SceneManager* mSceneMgr; Ogre::String mFilename; Ogre::String mName; std::vector<Ogre::Real> mGears; int mCurrentGear; Ogre::Real mShiftDelay; Ogre::Real mShiftTime; std::vector<TorquePoint> mTorqueCurve; Ogre::Real mBrakeStrength; Ogre::Real mDifferentialRatio; Ogre::Real mTransmissionEfficiency; Ogre::Real mDragCoefficient; Ogre::Real mEngineMass; StuntPlayground::Sound* mEngineSnd; StuntPlayground::Sound* mScreechSnd; Ogre::Real mMinRPM; Ogre::Real mMaxRPM; Ogre::Real mRPMRange; Ogre::Real mEngineBaseRPM; Ogre::Real mEngineScale; Ogre::Radian mSteerMaxAngle; Ogre::Radian mSteerSpeed; Ogre::Real mSteerLossPercent; Ogre::Real mSteerFromSpeed; Ogre::Real mSteerToSpeed; Ogre::Real mSteerSpeedRange; Ogre::Real mThrottle; Ogre::Real mSteering; Ogre::Radian mSteerAngle; bool mBrakesOn; Ogre::Real mLastOmega; Ogre::SceneNode* mLookNode; VehicleState mState; VehicleState mOldState; // Ogre::Timer mTimer; Ogre::Real mTimer; Ogre::Real mChangeTimer; bool mCheckingChange; Ogre::Real mShiftTimer; Ogre::Real mJustShiftedTimer; bool mJustShifted; Ogre::Vector3 mTakeOffPos; int mNumFlips; Ogre::Vector3 mLastY; unsigned int mCollisions; TireState mTireState; bool mManualTransmission; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_VEHICLE
jonri/StuntPlayground
StuntPlayground/src/ReflectionRenderTarget.h
/* Stunt Playground ReflectionRenderTarget */ #ifndef _STUNTPLAYGROUND_REFLECTION_RENDER_TARGET_ #define _STUNTPLAYGROUND_REFLECTION_RENDER_TARGET_ #include <Ogre.h> namespace StuntPlayground { class ReflectionRenderTarget : public Ogre::RenderTargetListener { public: ReflectionRenderTarget( Ogre::SceneManager* mgr, Ogre::Overlay* ov ) : Ogre::RenderTargetListener() { mSceneMgr = mgr; mOverlay = ov; } void preRenderTargetUpdate( const Ogre::RenderTargetEvent &evt); void postRenderTargetUpdate( const Ogre::RenderTargetEvent &evt ); void addHideNode( Ogre::SceneNode* node ) { mHideNodes.push_back(node); } void addHideParticle( Ogre::ParticleSystem* particle ); void clearHideNodes() { mHideNodes.clear(); mHideParticles.clear(); } private: struct ParticleHide { Ogre::ParticleSystem* m_particle; bool wasVisible; }; Ogre::SceneManager* mSceneMgr; Ogre::Overlay* mOverlay; bool overlayWasShown; Ogre::ShadowTechnique mOldShadowTech; std::vector<Ogre::SceneNode*> mHideNodes; std::vector<ParticleHide> mHideParticles; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_REFLECTION_RENDER_TARGET_
jonri/StuntPlayground
StuntPlayground/src/SoundManager.h
/* Stunt Playground SoundManager */ #ifndef _STUNTPLAYGROUND_SOUNDMANAGER_ #define _STUNTPLAYGROUND_SOUNDMANAGER_ #include <Ogre.h> #include <fmod.h> namespace StuntPlayground { // basic sound class, represents a short sound clip. class Sound { public: enum PlayState { PS_STOPPED, PS_PLAYING, PS_PAUSED }; Sound( std::string name, std::string filename ); ~Sound(); void play(); void play( int vol ); void play( int vol,const Ogre::Vector3& pos,const Ogre::Vector3& vel = Ogre::Vector3::ZERO ); void stop(); void pause(); bool isPlaying(); void setPositionVelocity( const Ogre::Vector3& pos, const Ogre::Vector3& vel = Ogre::Vector3::ZERO ); void getPositionVelocity( Ogre::Vector3& pos, Ogre::Vector3& vel ); void setVolume( int vol ); int getVolume(); void setFrequency( int freq ); int getFrequency(); void setLoop( bool onoff ); PlayState getState() { return mState; } std::string& getName() { return mName; } Ogre::Real getTimeSinceLastPlay() { return (mTimer.getMilliseconds()/1000.0); } private: int mChannel; PlayState mState; std::string mName; FSOUND_SAMPLE* mPtr; Ogre::Timer mTimer; }; // SoundManager singleton class! class SoundManager { public: enum MixRate { MR_22050 = 22050, MR_24000 = 24000, MR_44100 = 44100, MR_48000 = 48000 }; static SoundManager& getSingleton(); void Init( MixRate rate, int numSoftChannels ); Sound* addSound( std::string name, std::string filename ); void removeSound( std::string name ); void playSound( std::string name ); Sound* getSound( std::string name ); void encodeSound( std::string infile, std::string outfile ); void setListenerPosition( Ogre::Vector3& pos, Ogre::Vector3& vel, Ogre::Vector3& fdir, Ogre::Vector3& updir ); void setListenerPosition( Ogre::Camera* cam, Ogre::Vector3& vel ); void update3DSound() { FSOUND_Update(); } void setMasterSFXVolume( int vol ); private: typedef std::map<std::string, Sound*> SoundMap; typedef std::map<std::string, Sound*>::iterator SoundMapIterator; typedef std::pair<std::string, Sound*> SoundPair; SoundManager(); ~SoundManager(); SoundMap mSounds; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_SOUNDMANAGER_
jonri/StuntPlayground
StuntPlayground/src/BodyIterators.h
<gh_stars>1-10 /* Stunt Playground StuntPlayground:: BodyIterators */ #ifndef _STUNTPLAYGROUND_BODYITERATORS_ #define _STUNTPLAYGROUND_BODYITERATORS_ #include "OgreNewt.h" #include "OgreNewt_Body.h" namespace StuntPlayground { class iteratorRemoveProps : public OgreNewt::BodyIterator { public: iteratorRemoveProps() : BodyIterator() {} ~iteratorRemoveProps() {} void userIterator( OgreNewt::Body* body ) { if (body->getType() == StuntPlayground::BT_PROP) { Ogre::LogManager::getSingleton().logMessage(" ITERATOR - found prop"); } } }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_BODYITERATORS_
jonri/StuntPlayground
StuntPlayground/src/WorldRecorder.h
/* Stunt Playground WorldRecorder */ #ifndef _STUNTPLAYGROUND_WORLDRECORDER_ #define _STUNTPLAYGROUND_WORLDRECORDER_ #include <Ogre.h> #include <OgreNewt.h> #include <OgreNewt_Body.h> #include <tinyxml.h> namespace StuntPlayground { /* Stunt Playground WorldREcorder class Singleton class for recording the movements of bodies in the world, for playback later. */ class WorldRecorder { // basic keyframe class, holds all information for a single time/frame. class Keyframe { public: Keyframe() : mTime(0.0), mPos(0,0,0), mOrient(Ogre::Quaternion::IDENTITY) {} ~Keyframe() {} //tinyXML export function TiXmlElement getXMLElement(); //tinyXML import function void fromXMLElement( const TiXmlElement* elem ); // membe variables Ogre::Real mTime; Ogre::Vector3 mPos; Ogre::Quaternion mOrient; }; public: // basic class for redordable objects class RecordableObject { Ogre::SceneNode* mNode; Ogre::Real mLastTime; Ogre::Real mMinWaitTime; unsigned int mLastKeyframe; std::vector<Keyframe> mFrames; public: // these should not be called by the user, use the "add" function in the WorldRecorder RecordableObject() : mNode(NULL), mLastTime(0.0), mMinWaitTime(0) {} ~RecordableObject() {} void init( Ogre::SceneNode* node, Ogre::Real minwait ); // main function used to add a keyframe to the object. void addKeyframe(); // update the position, given a time value. void update( Ogre::Real time ); // remove all keyframes! void removeAllKeyframes(); Ogre::SceneNode* getNode() { return mNode; } // tinyXML export function. TiXmlElement getXMLElement(); // tinyXML import function. void fromXMLElement( const TiXmlElement* node ); }; private: WorldRecorder(); ~WorldRecorder(); Ogre::Real mMaxRecTime; Ogre::Real mTimer; Ogre::Real mTotalElapsed; Ogre::Real mTempMinWait; std::list<RecordableObject> mObjects; bool mRecording; bool mPlaying; bool mRecorded; public: static WorldRecorder& getSingleton(); void Init( Ogre::Real maxrectime ) { mMaxRecTime = maxrectime; } RecordableObject* addRecordableObject( Ogre::SceneNode* node, Ogre::Real minwait ); void removeRecordableObject( RecordableObject* obj ); void removeAllRecordableObjects(); void removeAllKeyframes(); void incTime( Ogre::Real deltat ) { mTimer += deltat; } void startRecording(); void stopRecording(); void startPlaying(); void stopPlaying(); void setTime( Ogre::Real time ); Ogre::Real getElapsed(); bool recording() { return mRecording; } bool playing() { return mPlaying; } bool recorded() { return mRecorded; } Ogre::Real getMaxRecTime() { return mMaxRecTime; } void collectProps( Ogre::Real minwait ); void saveToXML( std::string filename ); void bumpTotalElapsed( Ogre::Real time ) { if (time > mTotalElapsed) { mTotalElapsed = time; } } void recordedFromXML() { mRecorded = true; } static void collectPropsCallback( OgreNewt::Body* body ); }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_WORLDRECORDER_
jonri/StuntPlayground
StuntPlayground/src/Prereq.h
// stuff that goes at the top! # pragma warning (disable : 4018)
jonri/StuntPlayground
StuntPlayground/src/HighScore.h
<reponame>jonri/StuntPlayground /* Stunt Playground MainFrameListener */ #ifndef _STUNTPLAYGROUND_HIGHSCORE_ #define _STUNTPLAYGROUND_HIGHSCORE_ #include <Ogre.h> namespace StuntPlayground { // simple class for storing high scores. class HighScore { public: void load( std::string filename ); void save( std::string filename ); bool possibleJumpTime( Ogre::Real time ) { if (time > mTime) { mTime = time; return true; } return false; } bool possibleJumpDist( Ogre::Real dist ) { if (dist > mDist) { mDist = dist; return true; } return false; } bool possible2Wheels( Ogre::Real time ) { if (time > m2WH) { m2WH = time; return true; } return false; } bool possibleFlips( Ogre::Real flips ) { if (flips > mFlips) { mFlips = flips; return true; } return false; } Ogre::Real mTime; Ogre::Real mDist; Ogre::Real m2WH; Ogre::Real mFlips; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_HIGHSCORE_
jonri/StuntPlayground
StuntPlayground/src/Dialogs.h
/* Stunt Playground StuntPlaygroundApplication */ #ifndef _STUNTPLAYGROUND_DIALOGS_ #define _STUNTPLAYGROUND_DIALOGS_ #include <Ogre.h> #include "CEGUI.h" #include "StandardButton.h" #include "SoundManager.h" #include "Settings.h" namespace StuntPlayground { //////////////////////////////////////////////////////////////////////// // basic dialog! class BasicDialog { public: BasicDialog( CEGUI::Window* parentwin, Ogre::String& basename ); virtual ~BasicDialog(); virtual void show( Ogre::String& text ) { mWasOkClicked = false; mWindow->setText( (std::string)text ); mWindow->show(); } virtual void hide() { mWindow->hide(); } void setPlaySounds( bool setting ) { mPlaySounds = setting; } bool wasOkClicked() { return mWasOkClicked; } CEGUI::FrameWindow* getCEGUIWindow() { return mWindow; } private: bool okClicked( const CEGUI::EventArgs& e ) { mWasOkClicked = true; hide(); return true; } bool cancelClicked( const CEGUI::EventArgs& e ) { hide(); return true; } bool playClickSound( const CEGUI::EventArgs& e ) { if (mPlaySounds) SoundManager::getSingleton().playSound("Click1"); return true; } public: bool mWasOkClicked; bool mPlaySounds; CEGUI::FrameWindow* mWindow; StandardButton* mButtonOK; StandardButton* mButtonCancel; }; //////////////////////////////////////////////////////////////////////// class OpenListItem : public CEGUI::ListboxTextItem { public: OpenListItem( CEGUI::String text ) : ListboxTextItem(text) { using namespace CEGUI; // set default colors, etc. setTextColours( colour(0.8,0.8,0.8) ); setSelectionBrushImage((utf8*)"WindowsLook",(utf8*)"Background"); setSelectionColours( colour(1.0,0,0) ); } ~OpenListItem() {} }; class LoadDialog : public BasicDialog { public: enum LoadMode { LM_ARENA, LM_REPLAY }; LoadDialog( CEGUI::Window* parentwindow ); ~LoadDialog(); void setup( LoadMode mode ); LoadMode getMode() { return mLM; } CEGUI::Listbox* getCEGUIListbox() { return mListbox; } LoadMode mLM; private: CEGUI::Listbox* mListbox; }; //////////////////////////////////////////////////////////////////////// class SaveDialog : public BasicDialog { public: enum SaveMode { SM_ARENA, SM_REPLAY }; SaveDialog( CEGUI::Window* parentwin ); ~SaveDialog() {} void setSM( SaveMode mode ) { mSM = mode; } SaveMode getSM() { return mSM; } Ogre::String getText() { CEGUI::String txt = mEditbox->getText(); return Ogre::String( txt.c_str() ); } private: CEGUI::Editbox* mEditbox; SaveMode mSM; }; //////////////////////////////////////////////////////////////////////// class ErrorDialog : public BasicDialog { public: ErrorDialog( CEGUI::Window* parentwin ); ~ErrorDialog() {} void show( Ogre::String& text, bool showCancel = true ) { mWasOkClicked = false; mText->setText( (std::string)text ); if (!showCancel) mButtonCancel->getButton()->hide(); mWindow->show(); } private: CEGUI::StaticText* mText; }; //////////////////////////////////////////////////////////////////////// class SettingDialog : public BasicDialog { public: enum RADIO_GROUPS { RG_SHADOWS, RG_REFLECTIONS, RG_MANUAL, RG_RESTORE }; SettingDialog( CEGUI::Window* parentwin, Ogre::SceneManager* mgr ); ~SettingDialog() {} void show( const GameSettings set ); void hide() { mSettings.sfxVolume = mSoundSlider->getCurrentValue(); mWindow->hide(); } GameSettings getSettings() { return mSettings; } private: void setupRadio( CEGUI::RadioButton* rad ) { using namespace CEGUI; rad->setNormalTextColour( colour(0.8,0.8,0.8) ); rad->setPushedTextColour( colour(1,0.2,0.2) ); rad->setDisabledTextColour( colour(0.5,0.5,0.5) ); rad->setHoverTextColour( colour(1,1,1) ); } bool radioClicked( const CEGUI::EventArgs& e ); bool sliderMoved( const CEGUI::EventArgs& e ); Ogre::SceneManager* mSceneMgr; CEGUI::Slider* mSoundSlider; CEGUI::RadioButton* mRadShadON; CEGUI::RadioButton* mRadShadOFF; CEGUI::RadioButton* mRadReflON; CEGUI::RadioButton* mRadReflOFF; CEGUI::RadioButton* mRadManON; CEGUI::RadioButton* mRadManOFF; CEGUI::RadioButton* mRadRestON; CEGUI::RadioButton* mRadRestOFF; GameSettings mSettings; }; class ReplayControls { public: enum Mode { RM_TOP, RM_REWIND, RM_REWPLAY, RM_REWSLOW, RM_PAUSE, RM_PLAYSLOW, RM_PLAY, RM_FASTFORWARD, RM_END }; ReplayControls( CEGUI::Window* parentwin ); ~ReplayControls() { using namespace CEGUI; WindowManager::getSingleton().destroyWindow( mPane ); } void show() { mPane->show(); } void hide() { mPane->hide(); } void setMode( Mode m ); Mode getMode() { return mMode; } CEGUI::TabPane* getPane() { return mPane; } void setPlaySounds( bool setting ) { mPlaySounds = setting; } private: void wireImg( CEGUI::StaticImage* img ) { using namespace CEGUI; img->subscribeEvent( StaticImage::EventMouseClick, Event::Subscriber( &ReplayControls::imgClicked, this ) ); img->subscribeEvent( StaticImage::EventMouseEnters, Event::Subscriber( &ReplayControls::imgEnter, this ) ); img->subscribeEvent( StaticImage::EventMouseLeaves, Event::Subscriber( &ReplayControls::imgLeave, this ) ); } bool imgClicked( const CEGUI::EventArgs& e) { using namespace CEGUI; StaticImage* clicked = (StaticImage*)(((const CEGUI::WindowEventArgs&)e).window); setMode( (Mode)clicked->getID() ); if (mPlaySounds) SoundManager::getSingleton().playSound( "click" ); return true; } bool imgEnter( const CEGUI::EventArgs& e) { using namespace CEGUI; StaticImage* img = (StaticImage*)(((const CEGUI::WindowEventArgs&)e).window); if (mMode == img->getID()) { return true; } img->setFrameColours( colour(1,1,1) ); return true; } bool imgLeave( const CEGUI::EventArgs& e) { using namespace CEGUI; StaticImage* img = (StaticImage*)(((const CEGUI::WindowEventArgs&)e).window); if (mMode == img->getID()) { return true; } img->setFrameColours( colour(0.8,0.8,0.8) ); return true; } Mode mMode; bool mPlaySounds; CEGUI::TabPane* mPane; CEGUI::StaticImage* mImgTop; CEGUI::StaticImage* mImgRW; CEGUI::StaticImage* mImgRP; CEGUI::StaticImage* mImgRS; CEGUI::StaticImage* mImgPS; CEGUI::StaticImage* mImgFS; CEGUI::StaticImage* mImgFP; CEGUI::StaticImage* mImgFF; CEGUI::StaticImage* mImgEnd; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_DIALOGS_
jonri/StuntPlayground
StuntPlayground/src/Settings.h
<filename>StuntPlayground/src/Settings.h /* Stunt Playground Settings */ #ifndef _STUNTPLAYGROUND_SETTINGS_ #define _STUNTPLAYGROUND_SETTINGS_ #include "Ogre.h" namespace StuntPlayground { class GameSettings { public: void load( const Ogre::String& filename ); void save( const Ogre::String& filename ); std::string boolToString( bool setting ) { if (setting) { return std::string("on"); } else { return std::string("off"); } } bool useManualTransmission; bool useRealtimeReflections; Ogre::ShadowTechnique shadowTechnique; unsigned int sfxVolume; bool restoreArena; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_SETTINGS_
jonri/StuntPlayground
StuntPlayground/src/StandardButton.h
<reponame>jonri/StuntPlayground<gh_stars>1-10 /* Stunt Playground StandardButton */ #ifndef _STUNTPLAYGROUND_STANDARDBUTTON_ #define _STUNTPLAYGROUND_STANDARDBUTTON_ #include <CEGUI.h> namespace StuntPlayground { class StandardButton { CEGUI::PushButton* mButton; public: StandardButton( CEGUI::String name, CEGUI::String text ) { using namespace CEGUI; mButton = (PushButton*)WindowManager::getSingleton().createWindow((utf8*)"WindowsLook/Button", name ); mButton->setText( text ); mButton->setNormalTextColour( colour(0.8,0.8,0.8) ); mButton->setHoverTextColour( colour(1,1,1) ); mButton->setPushedTextColour( colour(1,0.3,0.3) ); } ~StandardButton() { using namespace CEGUI; WindowManager::getSingleton().destroyWindow( mButton ); } CEGUI::PushButton* getButton() { return mButton; } }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_STANDARDBUTTON_
jonri/StuntPlayground
StuntPlayground/src/StuntPlayground.h
#pragma once #ifndef _STUNTPLAYGROUND_ #define _STUNTPLAYGROUND_ namespace StuntPlayground { // ProgState is used to track the applications general state enum ProgState { PS_LOGO, PS_WAITING, PS_PLACING, PS_CHOOSING, PS_PLAYING, PS_REPLAYING }; // various general types for rigid bodies. enum BodyType { BT_ARENA, BT_PROP, BT_CAR, BT_DUMMY, BT_WORLD_LIMIT }; enum CollisionType { CT_CHASSIS, CT_TIRE }; enum PrimitiveType { BOX, ELLIPSOID, CYLINDER, CAPSULE, CONE, CHAMFER_CYLINDER, CONVEX_HULL, TREE }; enum CameraView { CV_FOLLOW, CV_FRONT, CV_LDOOR, CV_RDOOR, CV_LSIDE, CV_RSIDE, CV_WIDE_FOLLOW, CV_WIDE_LSIDE, CV_WIDE_RSIDE, CV_FREE, CV_SIZE }; enum RotAxis { AXIS_X, AXIS_Y, AXIS_Z }; } // end NAMESPACE StuntPlayground #endif /// _MAINFRAMELISTENER_ guard
jonri/StuntPlayground
StuntPlayground/src/RigidBodyLoader.h
<reponame>jonri/StuntPlayground /* Stunt Playground RigidBodyLoader function. */ #ifndef _STUNTPLAYGROUND_RIGIDBODYLOADER #define _STUNTPLAYGROUND_RIGIDBODYLOADER #include <OgreNewt.h> #include <Ogre.h> #include "StuntPlayground.h" namespace StuntPlayground { OgreNewt::Body* loadRigidBody( Ogre::String& filename, Ogre::String& entityname, OgreNewt::World* world, Ogre::SceneNode* parentnode, Ogre::SceneManager* mgr, int colID = 0 ); } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_RIGIDBODYLOADER
wangsjoy/Tipdip
Tipdip/AppDelegate.h
// // AppDelegate.h // Tipdip // // Created by <NAME> on 6/22/21. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @end
wangsjoy/Tipdip
Tipdip/TipdipViewController.h
// // TipdipViewController.h // Tipdip // // Created by <NAME> on 6/22/21. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface TipdipViewController : UIViewController @end NS_ASSUME_NONNULL_END
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Utility/RootPopViewController.h
// // RootPopViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/6. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> #import "ToolsImageView.h" @interface RootPopViewController : UIViewController @property (nonatomic, strong) ToolsImageView *toolsImageView; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Views/AlbumCell.h
<filename>guodegangjingxuanji/guodegangjingxuanji/Views/AlbumCell.h // // AlbumCell.h // guodegangjingxuanji // // Created by qianfeng on 15/9/7. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> #import "AlbumModel.h" @interface AlbumCell : UITableViewCell @property (nonatomic, strong) Album *model; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Views/ProgrammeHeadView.h
// // ProgrammeHeadView.h // guodegangjingxuanji // // Created by qianfeng on 15/9/7. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> #import "ProgrammeModel.h" @interface ProgrammeHeadView : UIView @property (nonatomic, strong) ProgrammeModel *model; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Utility/RootViewController.h
<gh_stars>0 // // RootViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/2. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> #import "TabBarImageView.h" #import "TabBarButtomView.h" @interface RootViewController : UIViewController @property (nonatomic, strong) TabBarImageView *tabbarBgImageView; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Utility/ToolsImageView.h
<reponame>lynnx4869/guodegangjingxuanji // // ToolsImageView.h // guodegangjingxuanji // // Created by qianfeng on 15/9/6. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> @interface ToolsImageView : UIImageView @property (nonatomic, strong) NSMutableArray *btnsArray; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/ViewControllers/MainTabbarViewController.h
<reponame>lynnx4869/guodegangjingxuanji // // MainTabbarViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/2. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> @interface MainTabbarViewController : UITabBarController @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Views/HomeCell.h
// // HomeCell.h // guodegangjingxuanji // // Created by qianfeng on 15/9/6. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> #import "HomeModel.h" @interface HomeCell : UITableViewCell @property (nonatomic, strong) HomeModel *model; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Utility/NavViewController.h
// // NavViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/6. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> @interface NavViewController : UINavigationController @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/ViewControllers/ProgrammeViewController.h
// // ProgrammeViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/7. // Copyright (c) 2015年 lyning. All rights reserved. // #import "RootPopViewController.h" @interface ProgrammeViewController : RootPopViewController @property (nonatomic, copy) NSString *albumId; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Utility/MyAudioPlayer.h
// // MyAudioPlayer.h // guodegangjingxuanji // // Created by qianfeng on 15/9/9. // Copyright (c) 2015年 lyning. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import "ProgrammeModel.h" @interface MyAudioPlayer : NSObject <AVAudioPlayerDelegate> + (instancetype)shareIntance; @property (nonatomic, strong) NSArray *currentList; @property (nonatomic, strong) Programme *currentPlayer; @property (nonatomic, assign) NSInteger currentIndex; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/ViewControllers/CategoryViewController.h
// // CategoryViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/2. // Copyright (c) 2015年 lyning. All rights reserved. // #import "RootViewController.h" @interface CategoryViewController : RootViewController @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/ViewControllers/AlbumViewController.h
<gh_stars>0 // // AlbumViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/6. // Copyright (c) 2015年 lyning. All rights reserved. // #import "RootPopViewController.h" @interface AlbumViewController : RootPopViewController @property (nonatomic, copy) NSString *uid; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Views/ProgrammeSectionView.h
<gh_stars>0 // // ProgrammeSectionView.h // guodegangjingxuanji // // Created by qianfeng on 15/9/7. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> @protocol SelectTabDelegate <NSObject> - (void)selectTabWithLeft:(BOOL)isLeft; @end @interface ProgrammeSectionView : UIView @property (nonatomic, strong) UIButton *leftBtn; @property (nonatomic, strong) UIButton *rightBtn; @property (nonatomic, weak) id<SelectTabDelegate> delegate; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/ViewControllers/DownloadViewController.h
<gh_stars>0 // // DownloadViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/2. // Copyright (c) 2015年 lyning. All rights reserved. // #import "RootViewController.h" @interface DownloadViewController : RootViewController @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Utility/TabBarImageView.h
<reponame>lynnx4869/guodegangjingxuanji // // TabBarImageView.h // guodegangjingxuanji // // Created by qianfeng on 15/9/2. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> @interface TabBarImageView : UIImageView @property (nonatomic, strong) NSMutableArray *btnsArray; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Views/ProgrammeCell.h
// // ProgrammeCell.h // guodegangjingxuanji // // Created by qianfeng on 15/9/7. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> #import "ProgrammeModel.h" @interface ProgrammeCell : UITableViewCell @property (nonatomic, strong) Programme *model; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Models/ProgrammeModel.h
// // ProgrammeModel.h // guodegangjingxuanji // // Created by qianfeng on 15/9/7. // Copyright (c) 2015年 lyning. All rights reserved. // #import <Foundation/Foundation.h> @interface ProgrammeModel : NSObject @property (nonatomic, copy) NSString *nickname; @property (nonatomic, copy) NSString *uid; @property (nonatomic, copy) NSString *smallLogo; @property (nonatomic, copy) NSString *albumId; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *coverSmall; @property (nonatomic, copy) NSString *coverLarge; @property (nonatomic, copy) NSString *intro; @property (nonatomic, copy) NSString *richIntro; @property (nonatomic, copy) NSString *updatedAt; @property (nonatomic, copy) NSString *playCount; @property (nonatomic, copy) NSString *tracks; @end @interface Programme : NSObject @property (nonatomic, copy) NSString *trackId; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *coverSmall; @property (nonatomic, copy) NSString *coverLarge; @property (nonatomic, copy) NSString *playtimes; @property (nonatomic, copy) NSString *playUrl32; @property (nonatomic, copy) NSString *playUrl64; @property (nonatomic, copy) NSString *mp3size_32; @property (nonatomic, copy) NSString *mp3size_64; @property (nonatomic, copy) NSString *albumId; @property (nonatomic, copy) NSString *albumUid; @property (nonatomic, copy) NSString *duration; @property (nonatomic, copy) NSString *createdAt; @property (nonatomic, copy) NSString *updatedAt; @property (nonatomic, copy) NSString *uid; @property (nonatomic, copy) NSString *intro; @property (nonatomic, copy) NSString *rich_intro; @property (nonatomic, copy) NSString *lyric; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/ViewControllers/SubscribeViewController.h
// // SubscribeViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/2. // Copyright (c) 2015年 lyning. All rights reserved. // #import "RootViewController.h" @interface SubscribeViewController : RootViewController @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Views/AlbumTopCell.h
// // AlbumTopCell.h // guodegangjingxuanji // // Created by qianfeng on 15/9/7. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> @interface AlbumTopCell : UITableViewCell @property (nonatomic, copy) NSString *largeLogo; @property (nonatomic, strong) UIButton *btn; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Utility/TabBarButtomView.h
<gh_stars>0 // // TabBarButtomView.h // guodegangjingxuanji // // Created by qianfeng on 15/9/2. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> @interface TabBarButtomView : UIView @property (nonatomic, assign) BOOL isSelected; @property (nonatomic, strong) UIImageView *image; @property (nonatomic, strong) UILabel *name; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Utility/MyUtil.h
<filename>guodegangjingxuanji/guodegangjingxuanji/Utility/MyUtil.h // // MyUtil.h // guodegangjingxuanji // // Created by qianfeng on 15/9/8. // Copyright (c) 2015年 lyning. All rights reserved. // #import <Foundation/Foundation.h> @interface MyUtil : NSObject + (NSString *)getDateFromTime:(NSString *)times; + (NSString *)getTimeFromTime:(NSString *)times; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/ViewControllers/PlayerViewController.h
<gh_stars>0 // // PlayerViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/8. // Copyright (c) 2015年 lyning. All rights reserved. // #import <UIKit/UIKit.h> @interface PlayerViewController : UIViewController @property (nonatomic, copy) NSString *trackId; @property (nonatomic, strong) NSArray *listArray; @property (nonatomic, assign) NSInteger curIndex; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Utility/Const.h
<filename>guodegangjingxuanji/guodegangjingxuanji/Utility/Const.h // // Const.h // guodegangjingxuanji // // Created by qianfeng on 15/9/2. // Copyright (c) 2015年 lyning. All rights reserved. // #ifndef guodegangjingxuanji_Const_h #define guodegangjingxuanji_Const_h //首页 #define lHomeUrl @"http://app.9nali.com/index/907?page_id=1&device=iPhone&version=1.3.2" //专辑界面(uid) #define lAlbumUrl @"http://app.9nali.com/907/bozhus/%@?page_id=1&device=iPhone&version=1.3.2" //节目界面(albumId, page, 降序(true, false)) #define lProgrammeUrl @"http://app.9nali.com/907/albums/%@?page_id=%d&isAsc=%@&device=iPhone&version=1.3.2" //播放界面(trackId) #define lPlayerUrl @"http://app.9nali.com/907/tracks/%@?device=iPhone&version=1.3.2" //分类界面 #define lClassifyUrl @"http://app.9nali.com/index/651?scale=2&page_id=1&device=iPhone&version=1.3.2" //分类细节(category_id) #define lClassifyDetailUrl @"http://app.9nali.com/907/category/%@/tags?page_id=1&device=iPhone&version=1.3.2" //分类具体专辑(name, 全部:all) #define lClassifyAlbumUrl @"http://app.9nali.com/907/common_tag/0/%@?page_id=1&device=iPhone&version=1.3.2" //搜索(搜索内容, page) #define lSearchUrl @"http://app.9nali.com/search/907/album?condition=%@&page=%@&device=iPhone&version=1.3.2" //即使搜索(搜索内容) #define lImmediatelyUrl @"http://app.9nali.com/search/907/album_suggest?condition=%@&device=iPhone&version=1.3.2" #endif
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Models/HomeModel.h
<reponame>lynnx4869/guodegangjingxuanji<filename>guodegangjingxuanji/guodegangjingxuanji/Models/HomeModel.h // // HomeModel.h // guodegangjingxuanji // // Created by qianfeng on 15/9/6. // Copyright (c) 2015年 lyning. All rights reserved. // #import <Foundation/Foundation.h> @interface HomeModel : NSObject @property (nonatomic, copy) NSString *uid; @property (nonatomic, copy) NSString *nickname; @property (nonatomic, copy) NSString *mediumLogo; @property (nonatomic, copy) NSString *personDescribe; @property (nonatomic, copy) NSString *albums; /* "uid": 1000202, "nickname": "郭德纲相声", "mediumLogo": "http://fdfs.xmcdn.com/group1/M00/0B/3D/wKgDrlESHqyTqakZAADewk1yMt8360_mobile_large.jpg", "personDescribe": "都是“真事儿”啊,很“三俗”", "albums": 15 */ @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/Models/AlbumModel.h
<gh_stars>0 // // AlbumModel.h // guodegangjingxuanji // // Created by qianfeng on 15/9/6. // Copyright (c) 2015年 lyning. All rights reserved. // #import <Foundation/Foundation.h> @interface AlbumModel : NSObject @property (nonatomic, copy) NSString *uid; @property (nonatomic, copy) NSString *nickname; @property (nonatomic, copy) NSString *largeLogo; @property (nonatomic, copy) NSString *personalSignature; @property (nonatomic, strong) NSMutableArray *albumsArray; @end @interface Album : NSObject @property (nonatomic, copy) NSString *albumId; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *coverSmall; @property (nonatomic, copy) NSString *tracks; @property (nonatomic, copy) NSString *updatedAt; @property (nonatomic, copy) NSString *finished; @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/ViewControllers/HomeViewController.h
// // HomeViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/2. // Copyright (c) 2015年 lyning. All rights reserved. // #import "RootViewController.h" @interface HomeViewController : RootViewController @end
lynnx4869/guodegangjingxuanji
guodegangjingxuanji/guodegangjingxuanji/ViewControllers/SynopsisViewController.h
<reponame>lynnx4869/guodegangjingxuanji // // SynopsisViewController.h // guodegangjingxuanji // // Created by qianfeng on 15/9/7. // Copyright (c) 2015年 lyning. All rights reserved. // #import "RootPopViewController.h" @interface SynopsisViewController : RootPopViewController @property (nonatomic, copy) NSString *navTitle; @property (nonatomic, copy) NSString *synopsis; @end
lgarithm/crystalnet
include/crystalnet.h
<reponame>lgarithm/crystalnet<filename>include/crystalnet.h #pragma once #include <stdint.h> #ifdef __cplusplus extern "C" { #endif extern const char *version(); typedef struct dtypes_t dtypes_t; struct dtypes_t { const uint8_t u8; const uint8_t i8; const uint8_t i16; const uint8_t i32; const uint8_t f32; const uint8_t f64; }; extern const dtypes_t dtypes; typedef struct context_t context_t; extern context_t *new_context(); extern void del_context(context_t *); typedef struct shape_t shape_t; typedef struct tensor_t tensor_t; typedef struct tensor_ref_t tensor_ref_t; typedef struct operator_t operator_t; extern const shape_t *new_shape(int, ...); extern void del_shape(const shape_t *); extern uint32_t shape_dim(const shape_t *); extern uint32_t shape_rank(const shape_t *); extern const shape_t *mk_shape(context_t *, int, ...); extern tensor_t *new_tensor(const shape_t *, uint8_t); extern void del_tensor(const tensor_t *); extern const tensor_ref_t *tensor_ref(const tensor_t *); extern void *tensor_data_ptr(const tensor_ref_t *); extern const shape_t *tensor_shape(const tensor_ref_t *); extern const uint8_t tensor_dtype(const tensor_ref_t *); // symbolic APIs typedef struct s_node_t s_node_t; typedef s_node_t *symbol; typedef struct s_model_t s_model_t; extern s_model_t *make_s_model(context_t *, s_node_t *, s_node_t *); extern s_node_t *var(context_t *, const shape_t *); extern s_node_t *covar(context_t *, const shape_t *); extern s_node_t *reshape(context_t *, const shape_t *, const s_node_t *); extern s_node_t *apply(context_t *, const operator_t *, symbol[]); // IO APIs extern void save_tensor(const char *, const tensor_ref_t *); extern tensor_t *_load_idx_file(const char *); extern void _idx_file_info(const char *); // high level APIs typedef struct dataset_t dataset_t; typedef struct optimizer_t optimizer_t; typedef struct s_trainer_t s_trainer_t; // dataset_t *new_dataset(); extern void del_dataset(dataset_t *); extern const shape_t *ds_image_shape(dataset_t *); extern const shape_t *ds_label_shape(dataset_t *); extern s_trainer_t *new_s_trainer(const s_model_t *, const operator_t *, const optimizer_t *); extern void del_s_trainer(s_trainer_t *); extern void s_trainer_run(s_trainer_t *, dataset_t *); extern void s_rtainer_test(s_trainer_t *, dataset_t *); // dataset extern dataset_t *load_mnist(const char *const); // train | t10k extern dataset_t *load_cifar(); // unstable APIs extern void s_experiment(s_trainer_t *, dataset_t *, dataset_t *, uint32_t); // operators extern const operator_t *op_add; extern const operator_t *op_mul; extern const operator_t *op_relu; extern const operator_t *op_softmax; extern const operator_t *op_xentropy; // unstable operators: extern const operator_t *op_conv_nhwc; extern const operator_t *op_pool2d_c_max; extern const operator_t *make_op_pool2d(uint32_t, uint32_t, uint32_t, uint32_t); extern const operator_t *make_op_conv2d(uint32_t, uint32_t, uint32_t, uint32_t); // optimizers extern const optimizer_t *opt_sgd; extern const optimizer_t *opt_adam; #ifdef __cplusplus } #endif
lgarithm/crystalnet
include/crystalnet-contrib/yolo/route_layer.h
<gh_stars>10-100 #pragma once #include <crystalnet-ext.h> #ifdef __cplusplus extern "C" { #endif extern symbol route_1(context_t *, symbol); extern symbol route_2(context_t *, symbol, symbol); #ifdef __cplusplus } #endif
lgarithm/crystalnet
include/crystalnet-contrib/yolo/pool_layer.h
<reponame>lgarithm/crystalnet #pragma once #include <crystalnet-ext.h> #ifdef __cplusplus extern "C" { #endif extern s_layer_t *pool(uint32_t /* size */, uint32_t /* stride */); #ifdef __cplusplus } #endif
lgarithm/crystalnet
src/crystalnet-contrib/yolo/yolov2.c
#include <stddef.h> #include <stdio.h> #include <crystalnet-contrib/yolo/conv_layer.h> #include <crystalnet-contrib/yolo/pool_layer.h> #include <crystalnet-contrib/yolo/region_layer.h> #include <crystalnet-contrib/yolo/reorg_layer.h> #include <crystalnet-contrib/yolo/route_layer.h> #include <crystalnet-contrib/yolo/yolo.h> #include <crystalnet-ext.h> const uint32_t yolov2_input_size = 416; s_model_t *yolov2(context_t *ctx) { const shape_t *input_shape = mk_shape(ctx, 3, 3, yolov2_input_size, yolov2_input_size); s_layer_t *max_pool2 = pool(2, 2); s_layer_t *reorg = make_reorg_layer(); s_layer_t *region = make_region_layer(13, 13, 5, 80, 4); symbol x = var(ctx, input_shape); symbol l16 = transform_all( // ctx, // (p_layer_t[]){ conv(32, 3, 1, 1), // 0 max_pool2, // 1 conv(64, 3, 1, 1), // 2 max_pool2, // 3 conv(128, 3, 1, 1), // 4 conv(64, 1, 1, 0), // 5 conv(128, 3, 1, 1), // 6 max_pool2, // 7 conv(256, 3, 1, 1), // 8 conv(128, 1, 1, 0), // 9 conv(256, 3, 1, 1), // 10 max_pool2, // 11 conv(512, 3, 1, 1), // 12 conv(256, 1, 1, 0), // 13 conv(512, 3, 1, 1), // 14 conv(256, 1, 1, 0), // 15 conv(512, 3, 1, 1), // 16 NULL, }, x); symbol l24 = transform_all( // ctx, (p_layer_t[]){ max_pool2, // 17 conv(1024, 3, 1, 1), // 18 conv(512, 1, 1, 0), // 19 conv(1024, 3, 1, 1), // 20 conv(512, 1, 1, 0), // 21 conv(1024, 3, 1, 1), // 22 conv(1024, 3, 1, 1), // 23 conv(1024, 3, 1, 1), // 24 NULL, // end }, l16); symbol l25 = route_1(ctx, l16); symbol l27 = transform_all( // ctx, // (p_layer_t[]){ conv(64, 1, 1, 0), // 26 reorg, // 27 NULL, // end }, l25); symbol l28 = route_2(ctx, l27, l24); symbol y = transform_all( // ctx, (p_layer_t[]){ conv(1024, 3, 1, 1), // 29 conv_linear_act(425, 1, 1, 0), // 30 region, // 31 NULL, // end }, l28); return make_s_model(ctx, x, y); }
lgarithm/crystalnet
examples/imagenet/src/alexnet.h
#pragma once #include <stdint.h> #include <crystalnet-ext.h> #ifdef __cplusplus extern "C" { #endif const uint32_t alexnet_image_size = 227; const uint32_t alexnet_class_number = 1000; // https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf s_model_t *alexnet(context_t *ctx, const shape_t *, uint32_t); #ifdef __cplusplus } #endif
lgarithm/crystalnet
include/crystalnet-contrib/yolo/reorg_layer.h
#pragma once #include <crystalnet-ext.h> #ifdef __cplusplus extern "C" { #endif extern s_layer_t *make_reorg_layer(); #ifdef __cplusplus } #endif
lgarithm/crystalnet
examples/imagenet/src/alexnet.c
<filename>examples/imagenet/src/alexnet.c #include <stdio.h> #include <crystalnet-ext.h> #include "alexnet.h" // https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf s_model_t *alexnet(context_t *ctx, const shape_t *image_shape, uint32_t arity) { s_layer_t *c1 = new_layer_conv2d( // mk_shape(ctx, 3, 11, 11, 96), // NULL, // default padding mk_shape(ctx, 2, 4, 4)); // s_layer_t *c2 = new_layer_conv2d( // mk_shape(ctx, 3, 5, 5, 256), // mk_shape(ctx, 2, 2, 2), // NULL); // default stride s_layer_t *c3_c4 = new_layer_conv2d( // mk_shape(ctx, 3, 3, 3, 384), // mk_shape(ctx, 2, 1, 1), // NULL); // s_layer_t *c5 = new_layer_conv2d( // mk_shape(ctx, 3, 3, 3, 256), // mk_shape(ctx, 2, 1, 1), // NULL); // s_layer_t *f4096 = new_layer_dense(4096); // s_layer_t *f_out = new_layer_dense(arity); // s_layer_t *pool = new_layer_pool2d( // mk_shape(ctx, 2, 3, 3), // mk_shape(ctx, 2, 2, 2)); // s_layer_t *relu = new_layer_relu(); // s_layer_t *out = new_layer_softmax(); // printf("[x] creating model\n"); symbol x = var(ctx, image_shape); symbol y = transform_all( // ctx, // (p_layer_t[]){ c1, relu, pool, // c2, relu, pool, // c3_c4, relu, c3_c4, relu, c5, relu, pool, // f4096, relu, f4096, relu, // f_out, out, // NULL, // }, x); del_s_layer(c1); del_s_layer(c2); del_s_layer(c3_c4); del_s_layer(c5); del_s_layer(f4096); del_s_layer(f_out); del_s_layer(pool); del_s_layer(relu); del_s_layer(out); printf("[y] creating model\n"); return make_s_model(ctx, x, y); }
lgarithm/crystalnet
examples/imagenet/src/vgg16.h
#pragma once #include <stdint.h> #include <crystalnet-ext.h> #ifdef __cplusplus extern "C" { #endif const uint32_t vgg16_image_size = 224; const uint32_t vgg16_class_number = 1000; // https://www.cs.toronto.edu/~frossard/post/vgg16/ s_model_t *vgg16(context_t *, const shape_t *, uint32_t); #ifdef __cplusplus } #endif
lgarithm/crystalnet
examples/imagenet/src/imagenet.h
#pragma once #include <crystalnet-ext.h> #include <opencv2/opencv.hpp> cv::Mat square_normalize(const cv::Mat &, int r); void info(const cv::Mat &, const std::string &); std::size_t to_hwc(const cv::Mat &, const tensor_ref_t *);
lgarithm/crystalnet
include/crystalnet-internal.h
<filename>include/crystalnet-internal.h #pragma once #include <crystalnet.h> #ifdef __cplusplus extern "C" { #endif typedef struct model_t model_t; typedef struct model_ctx_t model_ctx_t; typedef struct parameter_ctx_t parameter_ctx_t; extern model_t *realize(parameter_ctx_t *, const s_model_t *, uint32_t); // testing APIs extern parameter_ctx_t *new_parameter_ctx(); extern void del_parameter_ctx(const parameter_ctx_t *); extern void del_model(const model_t *); // unstable APIs typedef struct shape_list_t shape_list_t; extern const shape_list_t *mk_shape_list(context_t *, const shape_t *const p_shapes[]); // TODO: make it possible to add user defined operators typedef struct forward_ctx_t forward_ctx_t; typedef struct backward_ctx_t backward_ctx_t; typedef struct shape_func_t shape_func_t; typedef struct forward_func_t forward_func_t; typedef struct backward_func_t backward_func_t; extern const operator_t *register_op(const char *const, uint8_t, shape_func_t *, forward_func_t *, backward_func_t *); // eager APIs extern shape_t *infer(const operator_t *, const shape_list_t *); extern void eval(const operator_t *, const forward_ctx_t *); extern void grad(const operator_t *, const backward_ctx_t *); #ifdef __cplusplus } #endif
lgarithm/crystalnet
tests/src/crystalnet/core/tensor_test.c
<gh_stars>10-100 #include <stdint.h> // for uint8_t #include <crystalnet.h> void test_1() { const shape_t *shape = new_shape(4, 2, 3, 4, 5); tensor_t *tensor = new_tensor(shape, dtypes.f32); del_tensor(tensor); del_shape(shape); } int main() { test_1(); return 0; }
lgarithm/crystalnet
include/crystalnet-contrib/darknet/darknet.h
// https://github.com/pjreddie/darknet.git #pragma once #ifdef __cplusplus extern "C" { #endif extern void reorg_cpu(float *x, int w, int h, int c, int batch, int stride, int forward, float *out); #ifdef __cplusplus } #endif
lgarithm/crystalnet
src/crystalnet-contrib/darknet/darknet.c
// https://github.com/pjreddie/darknet.git #include <float.h> #include <crystalnet-contrib/darknet/darknet.h> // the original implementation, which is likely wrong. void reorg_cpu(float *x, int w, int h, int c, int batch, int stride, int forward, float *out) { int b, i, j, k; int out_c = c / (stride * stride); for (b = 0; b < batch; ++b) { for (k = 0; k < c; ++k) { for (j = 0; j < h; ++j) { for (i = 0; i < w; ++i) { int in_index = i + w * (j + h * (k + c * b)); int c2 = k % out_c; int offset = k / out_c; int w2 = i * stride + offset % stride; int h2 = j * stride + offset / stride; int out_index = w2 + w * stride * (h2 + h * stride * (c2 + out_c * b)); if (forward) out[out_index] = x[in_index]; else out[in_index] = x[out_index]; } } } } }
lgarithm/crystalnet
examples/c/mnist_cnn.c
#include <stddef.h> #include <stdint.h> #include <crystalnet-ext.h> // l1 = pool(relu(conv(x))) // l2 = pool(relu(conv(l1))) // y = softmax(dense(relu(dense(l2)))) typedef shape_t const *p_shape_t; s_model_t *cnn(context_t *ctx, const shape_t *image_shape, uint32_t arity) { s_layer_t *c1 = new_layer_conv_nhwc(5, 5, 32); s_layer_t *c2 = new_layer_conv_nhwc(5, 5, 64); s_layer_t *f1 = new_layer_dense(1024); s_layer_t *f2 = new_layer_dense(arity); s_layer_t *pool = new_layer_pool_max(); // s_layer_t *act = new_layer_relu(); // s_layer_t *out = new_layer_softmax(); symbol x = var(ctx, image_shape); symbol x_ = reshape(ctx, mk_shape(ctx, 3, 28, 28, 1), x); symbol y = transform_all(ctx, (p_layer_t[]){ c1, act, pool, c2, act, pool, f1, act, f2, out, NULL, }, x_); del_s_layer(c1); del_s_layer(c2); del_s_layer(f1); del_s_layer(f2); del_s_layer(pool); del_s_layer(act); del_s_layer(out); return make_s_model(ctx, x, y); } int main() { const uint32_t height = 28; const uint32_t width = 28; const uint32_t n = 10; context_t *ctx = new_context(); const shape_t *image_shape = mk_shape(ctx, 2, height, width); s_model_t *model = cnn(ctx, image_shape, n); s_trainer_t *trainer = new_s_trainer(model, op_xentropy, opt_adam); dataset_t *ds1 = load_mnist("train"); dataset_t *ds2 = load_mnist("t10k"); s_experiment(trainer, ds1, ds2, 10); del_dataset(ds1); del_dataset(ds2); del_s_trainer(trainer); del_context(ctx); return 0; }
lgarithm/crystalnet
examples/c/cifar_slp.c
<reponame>lgarithm/crystalnet #include <crystalnet.h> // y = softmax(flatten(x) * w + b) s_model_t *slp(context_t *ctx, const shape_t *image_shape, uint8_t arity) { symbol x = var(ctx, image_shape); symbol x_ = reshape(ctx, mk_shape(ctx, 1, shape_dim(image_shape)), x); symbol w = covar(ctx, mk_shape(ctx, 2, shape_dim(image_shape), arity)); symbol b = covar(ctx, mk_shape(ctx, 1, arity)); symbol op1 = apply(ctx, op_mul, (symbol[]){x_, w}); symbol op2 = apply(ctx, op_add, (symbol[]){op1, b}); symbol op3 = apply(ctx, op_softmax, (symbol[]){op2}); return make_s_model(ctx, x, op3); } int main() { int width = 32; int height = 32; int depth = 3; int n = 10; context_t *ctx = new_context(); const shape_t *image_shape = mk_shape(ctx, 3, depth, width, height); s_model_t *model = slp(ctx, image_shape, n); s_trainer_t *trainer = new_s_trainer(model, op_xentropy, opt_sgd); dataset_t *ds1 = load_cifar(); dataset_t *ds2 = load_cifar(); s_experiment(trainer, ds1, ds2, 10000); del_s_trainer(trainer); del_dataset(ds1); del_dataset(ds2); del_context(ctx); return 0; }
lgarithm/crystalnet
src/crystalnet-contrib/yolo/cmath.c
<reponame>lgarithm/crystalnet #include <math.h> #include <crystalnet-contrib/yolo/cmath.h> float c_exp(float x) { return exp(x); } float c_logistic(float x) { return 1. / (1. + exp(-x)); }
lgarithm/crystalnet
tests/src/crystalnet/ops/conv_test.c
#include <assert.h> #include <stdio.h> #include <crystalnet-internal.h> typedef shape_t const *p_shape_t; void test_1() { context_t *ctx = new_context(); const shape_list_t *shape_list = mk_shape_list( // ctx, (p_shape_t[]){ mk_shape(ctx, 3, 28, 28, 32), mk_shape(ctx, 4, 3, 3, 32, 64), NULL, }); const operator_t *op = make_op_conv2d(0, 0, 1, 1); shape_t *out_shape = infer(op, shape_list); assert(shape_rank(out_shape) == 3); assert(shape_dim(out_shape) == 26 * 26 * 64); del_shape(out_shape); del_context(ctx); } void test_2() { context_t *ctx = new_context(); const shape_list_t *shape_list = mk_shape_list( // ctx, (p_shape_t[]){ mk_shape(ctx, 4, 2, 28, 28, 32), mk_shape(ctx, 4, 3, 3, 32, 64), NULL, }); const operator_t *op = make_op_conv2d(0, 0, 1, 1); shape_t *out_shape = infer(op, shape_list); assert(shape_rank(out_shape) == 4); assert(shape_dim(out_shape) == 2 * 26 * 26 * 64); del_shape(out_shape); del_context(ctx); } int main() { test_1(); test_2(); return 0; }
lgarithm/crystalnet
examples/c/alexnet.c
<reponame>lgarithm/crystalnet #include <stdio.h> #include <crystalnet-ext.h> typedef shape_t const *p_shape_t; // https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf s_model_t *alexnet(context_t *ctx, const shape_t *image_shape, uint32_t arity) { s_layer_t *c1 = new_layer_conv2d( // mk_shape(ctx, 3, 11, 11, 96), // NULL, // default padding mk_shape(ctx, 2, 4, 4)); // s_layer_t *c2 = new_layer_conv2d( // mk_shape(ctx, 3, 5, 5, 256), // mk_shape(ctx, 2, 2, 2), // NULL); // default stride s_layer_t *c3_c4 = new_layer_conv2d( // mk_shape(ctx, 3, 3, 3, 384), // mk_shape(ctx, 2, 1, 1), // NULL); // s_layer_t *c5 = new_layer_conv2d( // mk_shape(ctx, 3, 3, 3, 256), // mk_shape(ctx, 2, 1, 1), // NULL); // s_layer_t *f4096 = new_layer_dense(4096); // s_layer_t *f_out = new_layer_dense(arity); // s_layer_t *pool = new_layer_pool2d( // mk_shape(ctx, 2, 3, 3), // mk_shape(ctx, 2, 2, 2)); // s_layer_t *relu = new_layer_relu(); // s_layer_t *out = new_layer_softmax(); printf("[x] creating model\n"); symbol x = var(ctx, image_shape); symbol y = transform_all( // ctx, // (p_layer_t[]){ c1, relu, pool, // c2, relu, pool, // c3_c4, relu, c3_c4, relu, c5, relu, pool, // f4096, relu, f4096, relu, // f_out, out, // NULL, // }, x); del_s_layer(c1); del_s_layer(c2); del_s_layer(c3_c4); del_s_layer(c5); del_s_layer(f4096); del_s_layer(f_out); del_s_layer(pool); del_s_layer(relu); del_s_layer(out); printf("[y] creating model\n"); return make_s_model(ctx, x, y); } const uint32_t height = 227; const uint32_t width = 227; const uint32_t class_number = 1000; dataset_t *fake_imagenet() { const shape_t *image_shape = new_shape(3, height, width, 3); dataset_t *p_ds = new_fake_dataset(image_shape, class_number); del_shape(image_shape); return p_ds; } int main() { context_t *ctx = new_context(); const shape_t *image_shape = mk_shape(ctx, 3, height, width, 3); s_model_t *model = alexnet(ctx, image_shape, class_number); s_model_info(model); s_trainer_t *trainer = new_s_trainer(model, op_xentropy, opt_adam); dataset_t *ds1 = fake_imagenet(); // dataset_t *ds2 = fake_imagenet(); const uint32_t batch_size = 2; s_experiment(trainer, ds1, NULL, batch_size); del_dataset(ds1); // del_dataset(ds2); del_s_trainer(trainer); del_context(ctx); return 0; }
lgarithm/crystalnet
tests/src/crystalnet/symbol/symbol_test.c
<reponame>lgarithm/crystalnet #include <assert.h> #include <crystalnet-internal.h> // y = softmax(flatten(x) * w + b) s_model_t *slp(context_t *ctx, const shape_t *image_shape, uint8_t arity) { const shape_t *lable_shape = new_shape(1, arity); const shape_t *weight_shape = new_shape(2, shape_dim(image_shape), arity); const shape_t *x_wrap_shape = new_shape(1, shape_dim(image_shape)); s_node_t *x = var(ctx, image_shape); s_node_t *x_ = reshape(ctx, x_wrap_shape, x); s_node_t *w = covar(ctx, weight_shape); s_node_t *b = covar(ctx, lable_shape); s_node_t *args1[] = {x_, w}; s_node_t *op1 = apply(ctx, op_mul, args1); s_node_t *args2[] = {op1, b}; s_node_t *op2 = apply(ctx, op_add, args2); s_node_t *args3[] = {op2}; s_node_t *op3 = apply(ctx, op_softmax, args3); del_shape(lable_shape); del_shape(weight_shape); del_shape(x_wrap_shape); return make_s_model(ctx, x, op3); } void test_1() { uint8_t arity = 10; const shape_t *image_shape = new_shape(2, 28, 28); context_t *ctx = new_context(); s_model_t *sm = slp(ctx, image_shape, arity); parameter_ctx_t *pc = new_parameter_ctx(); for (int i = 1; i <= 3; ++i) { model_t *pm = realize(pc, sm, i); del_model(pm); } del_parameter_ctx(pc); del_context(ctx); del_shape(image_shape); } int main() { test_1(); return 0; }
lgarithm/crystalnet
include/crystalnet-contrib/yolo/yolo.h
<reponame>lgarithm/crystalnet #pragma once #include <crystalnet-ext.h> #ifdef __cplusplus extern "C" { #endif extern const uint32_t yolov2_input_size; extern s_model_t *yolov2(context_t *); extern s_model_t *yolov3(context_t *); // TODO #ifdef __cplusplus } #endif
lgarithm/crystalnet
include/crystalnet-contrib/yolo/conv_layer.h
#pragma once #include <crystalnet-ext.h> #ifdef __cplusplus extern "C" { #endif extern s_layer_t *conv(uint32_t /* filters */, uint32_t /* size */, uint32_t /* stride */, uint32_t /* padding */); extern s_layer_t *conv_linear_act(uint32_t /* filters */, uint32_t /* size */, uint32_t /* stride */, uint32_t /* padding */); #ifdef __cplusplus } #endif
lgarithm/crystalnet
include/crystalnet-contrib/yolo/region_layer.h
<gh_stars>10-100 #pragma once #include <crystalnet-ext.h> #ifdef __cplusplus extern "C" { #endif s_layer_t *make_region_layer(int w, int h, int n, int classes, int coords); #ifdef __cplusplus } #endif
lgarithm/crystalnet
include/crystalnet-contrib/yolo/cmath.h
#pragma once #ifdef __cplusplus extern "C" { #endif extern float c_exp(float x); extern float c_logistic(float x); #ifdef __cplusplus } #endif
lgarithm/crystalnet
include/crystalnet-ext.h
<filename>include/crystalnet-ext.h #pragma once #include <stdint.h> #include <crystalnet.h> #ifdef __cplusplus extern "C" { #endif // layer APIs typedef struct s_layer_t s_layer_t; extern void del_s_layer(s_layer_t *); extern s_layer_t *const new_layer_dense(uint32_t /* n */); extern s_layer_t *const new_layer_relu(); extern s_layer_t *const new_layer_softmax(); extern s_layer_t *const new_layer_pool2d(const shape_t * /* filter shape */, const shape_t * /* stride shape */); extern s_layer_t *const new_layer_conv2d(const shape_t * /* filter shape */, const shape_t * /* padding shape */, const shape_t * /* stride shape */); // TODO: deprecate extern s_layer_t *const new_layer_conv_nhwc(uint32_t, uint32_t, uint32_t); extern s_layer_t *const new_layer_pool_max(); // layer combinators typedef s_layer_t const *p_layer_t; extern s_node_t *transform(context_t *, const s_layer_t *, s_node_t *); extern s_node_t *transform_all(context_t *, p_layer_t layers[], s_node_t *); // debug APIs extern void s_model_info(const s_model_t *); extern dataset_t *new_fake_dataset(const shape_t *, uint32_t); extern void debug_tensor(const char *, const tensor_ref_t *); // high level export APIs typedef s_model_t *(classification_model_func_t)(context_t *, const shape_t *, uint32_t); typedef struct classifier_t classifier_t; extern classifier_t *new_classifier(classification_model_func_t, const shape_t *, uint32_t); extern void del_classifier(const classifier_t *); extern void classifier_load(const classifier_t *, const char *, const tensor_ref_t *); extern uint32_t most_likely(const classifier_t *, const tensor_ref_t *); extern void top_likely(const classifier_t *, const tensor_ref_t *, uint32_t, int32_t *); #ifdef __cplusplus } #endif
lgarithm/crystalnet
examples/imagenet/src/vgg16.c
<reponame>lgarithm/crystalnet #include <stdio.h> #include <crystalnet-ext.h> #include "vgg16.h" // https://www.cs.toronto.edu/~frossard/post/vgg16/ s_model_t *vgg16(context_t *ctx, const shape_t *image_shape, uint32_t arity) { s_layer_t *c1 = new_layer_conv2d( // mk_shape(ctx, 3, 3, 3, 64), // mk_shape(ctx, 2, 1, 1), // NULL); // s_layer_t *c2 = new_layer_conv2d( // mk_shape(ctx, 3, 3, 3, 128), // mk_shape(ctx, 2, 1, 1), // NULL); // s_layer_t *c3 = new_layer_conv2d( // mk_shape(ctx, 3, 3, 3, 256), // mk_shape(ctx, 2, 1, 1), // NULL); // s_layer_t *c4_5 = new_layer_conv2d( // mk_shape(ctx, 3, 3, 3, 512), // mk_shape(ctx, 2, 1, 1), // NULL); // s_layer_t *f4096 = new_layer_dense(4096); // s_layer_t *f_out = new_layer_dense(arity); // s_layer_t *pool = new_layer_pool2d( // mk_shape(ctx, 2, 2, 2), // mk_shape(ctx, 2, 2, 2)); // s_layer_t *relu = new_layer_relu(); // s_layer_t *out = new_layer_softmax(); // printf("[x] creating model\n"); symbol x = var(ctx, image_shape); symbol y = transform_all( // ctx, // (p_layer_t[]){ c1, relu, c1, relu, pool, // c2, relu, c2, relu, pool, // c3, relu, c3, relu, c3, relu, pool, // c4_5, relu, c4_5, relu, c4_5, relu, pool, // c4_5, relu, c4_5, relu, c4_5, relu, pool, // f4096, relu, f4096, relu, // f_out, out, // NULL, // }, x); del_s_layer(c1); del_s_layer(c2); del_s_layer(c3); del_s_layer(c4_5); del_s_layer(f4096); del_s_layer(f_out); del_s_layer(pool); del_s_layer(relu); del_s_layer(out); printf("[y] creating model\n"); return make_s_model(ctx, x, y); }
lgarithm/crystalnet
tests/src/crystalnet/core/shape_test.c
#include <assert.h> #include <stdio.h> #include <crystalnet.h> void test_1() { { const shape_t *shape = new_shape(0); assert(shape_dim(shape) == 1); assert(shape_rank(shape) == 0); del_shape(shape); } { const shape_t *shape = new_shape(4, 2, 3, 4, 5); assert(shape_dim(shape) == 120); assert(shape_rank(shape) == 4); del_shape(shape); } } int main() { test_1(); return 0; }
lgarithm/crystalnet
tests/src/crystalnet/data/idx_test.c
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <crystalnet.h> tensor_t *_load_mnist(const char *const name) { const char *const prefix = "var/data/mnist"; char filename[1024]; sprintf(filename, "%s/%s/%s", getenv("HOME"), prefix, name); printf("%s\n", filename); tensor_t *t = _load_idx_file(filename); return t; } void test_1() { { tensor_t *t = _load_mnist("t10k-labels-idx1-ubyte"); const shape_t *s = tensor_shape(tensor_ref(t)); assert(shape_rank(s) == 1); assert(shape_dim(s) == 10000); del_tensor(t); } { tensor_t *t = _load_mnist("t10k-images-idx3-ubyte"); const shape_t *s = tensor_shape(tensor_ref(t)); assert(shape_rank(s) == 3); assert(shape_dim(s) == 28 * 28 * 10000); del_tensor(t); } } int main() { test_1(); return 0; }
lgarithm/crystalnet
tests/src/crystalnet/ops/pool_test.c
#include <assert.h> #include <stdio.h> #include <crystalnet-internal.h> typedef shape_t const *p_shape_t; void test_1() { context_t *ctx = new_context(); const shape_list_t *shape_list = mk_shape_list( // ctx, (p_shape_t[]){ mk_shape(ctx, 3, 28, 28, 32), NULL, }); const operator_t *op = make_op_pool2d(2, 2, 2, 2); shape_t *out_shape = infer(op, shape_list); assert(shape_rank(out_shape) == 3); assert(shape_dim(out_shape) == 14 * 14 * 32); del_shape(out_shape); del_context(ctx); } void test_2() { context_t *ctx = new_context(); const shape_list_t *shape_list = mk_shape_list( // ctx, (p_shape_t[]){ mk_shape(ctx, 4, 10, 28, 28, 32), NULL, }); const operator_t *op = make_op_pool2d(2, 2, 2, 2); shape_t *out_shape = infer(op, shape_list); assert(shape_rank(out_shape) == 4); assert(shape_dim(out_shape) == 10 * 14 * 14 * 32); del_shape(out_shape); del_context(ctx); } int main() { test_1(); test_2(); return 0; }
lgarithm/crystalnet
tests/src/crystalnet/layers/layers_test.c
#include <crystalnet-ext.h> void test_1() { s_layer_t *l1 = new_layer_dense(10); del_s_layer(l1); } int main() { test_1(); return 0; }
stbrumme/practical-string-searching
search.c
<gh_stars>1-10 // ////////////////////////////////////////////////////////// // search.c // Copyright (c) 2014,2019 <NAME>. All rights reserved. // see http://create.stephan-brumme.com/disclaimer.html // // compiles with: gcc -Wall // pretty much every decent C compiler should be able to eat this code, too // note: some warnings about C++ comments and mixing declarations and code when enabling -pedantic // but they all disappear in C99 mode #include "search.h" #include <string.h> // strlen #include <stdlib.h> // malloc / free /// naive approach (for C strings) const char* searchSimpleString(const char* haystack, const char* needle) { // detect invalid input if (!haystack || !needle) return NULL; // until the end of haystack (or a match, of course) while (*haystack) { // compare current haystack to needle size_t i = 0; while (needle[i]) { if (haystack[i] != needle[i]) break; i++; } // needle fully matched (reached terminating NUL-byte) if (!needle[i]) return haystack; // no match, step forward haystack++; } // not found return NULL; } /// naive approach (for non-text data) const char* searchSimple(const char* haystack, size_t haystackLength, const char* needle, size_t needleLength) { // detect invalid input if (!haystack || !needle || haystackLength < needleLength) return NULL; // match impossible if less than needleLength bytes left haystackLength -= needleLength - 1; // points beyond last considered start byte const char* haystackEnd = haystack + haystackLength; // until the end of haystack (or a match, of course ...) while (haystack != haystackEnd) { // compare current haystack to needle size_t i = 0; for (; i < needleLength; i++) if (haystack[i] != needle[i]) break; // needle fully matched if (i == needleLength) return haystack; // no match, step forward haystack++; } // not found return NULL; } // ////////////////////////////////////////////////////////// /// Knuth-Morris-Pratt algorithm (for C strings) const char* searchKnuthMorrisPrattString(const char* haystack, const char* needle) { // detect invalid input if (!haystack || !needle) return NULL; // empty needle matches everything size_t needleLength = strlen(needle); if (needleLength == 0) return haystack; // try to use stack instead of heap (avoid slow memory allocations if possible) const size_t MaxLocalMemory = 256; int localMemory[MaxLocalMemory]; int* skip = localMemory; // stack too small => allocate heap if (needleLength > MaxLocalMemory) { skip = (int*)malloc(needleLength * sizeof(int)); if (skip == NULL) return NULL; } // prepare skip table skip[0] = -1; int i; for (i = 0; needle[i]; i++) { skip[i + 1] = skip[i] + 1; while (skip[i + 1] > 0 && needle[i] != needle[skip[i + 1] - 1]) skip[i + 1] = skip[skip[i + 1] - 1] + 1; } // assume no match const char* result = NULL; int shift = 0; // search while (*haystack) { // look for a matching character while (shift >= 0 && *haystack != needle[shift]) shift = skip[shift]; // single step forward in needle and haystack haystack++; shift++; // reached end of needle => hit if (!needle[shift]) { result = haystack - shift; break; } } // clean up heap (if used) if (skip != localMemory) free(skip); // points to match position or NULL if not found return result; } /// Knuth-Morris-Pratt algorithm (for non-text data) const char* searchKnuthMorrisPratt(const char* haystack, size_t haystackLength, const char* needle, size_t needleLength) { // detect invalid input if (!haystack || !needle || haystackLength < needleLength) return NULL; // empty needle matches everything if (needleLength == 0) return haystack; // try to use stack instead of heap (avoid slow memory allocations if possible) const size_t MaxLocalMemory = 256; int localMemory[MaxLocalMemory]; int* skip = localMemory; // stack too small => allocate heap if (needleLength > MaxLocalMemory) { skip = (int*)malloc(needleLength * sizeof(int)); if (skip == NULL) return NULL; } // prepare skip table skip[0] = -1; size_t i; for (i = 0; i < needleLength; i++) { skip[i + 1] = skip[i] + 1; while (skip[i + 1] > 0 && needle[i] != needle[skip[i + 1] - 1]) skip[i + 1] = skip[skip[i + 1]-1] + 1; } // assume no match const char* result = NULL; const char* haystackEnd = haystack + haystackLength; int shift = 0; // search while (haystack != haystackEnd) { // look for a matching character while (shift >= 0 && *haystack != needle[shift]) shift = skip[shift]; // single step forward in needle and haystack haystack++; shift++; // reached end of needle => hit if ((size_t)shift == needleLength) { result = haystack - shift; break; } } // clean up heap (if used) if (skip != localMemory) free(skip); // points to match position or NULL if not found return result; } // ////////////////////////////////////////////////////////// /// Boyer-Moore-Horspool algorithm (for C strings) const char* searchBoyerMooreHorspoolString(const char* haystack, const char* needle) { // detect invalid input if (!haystack || !needle) return NULL; // call routine for non-text data return searchBoyerMooreHorspool(haystack, strlen(haystack), needle, strlen(needle)); } /// Boyer-Moore-Horspool algorithm (for non-text data) const char* searchBoyerMooreHorspool(const char* haystack, size_t haystackLength, const char* needle, size_t needleLength) { // detect invalid input if (!haystack || !needle || haystackLength < needleLength) return NULL; // empty needle matches everything if (needleLength == 0) return haystack; // find right-most position of each character // and store its distance to the end of needle // default value: when a character in haystack isn't in needle, then // we can jump forward needleLength bytes const size_t NumChar = 1 << (8 * sizeof(char)); size_t skip[NumChar]; size_t i; for (i = 0; i < NumChar; i++) skip[i] = needleLength; // figure out for each character of the needle how much we can skip // (if a character appears multiple times in needle, later occurrences // overwrite previous ones, i.e. the value of skip[x] decreases) const size_t lastPos = needleLength - 1; size_t pos; for (pos = 0; pos < lastPos; pos++) skip[(unsigned char)needle[pos]] = lastPos - pos; // now walk through the haystack while (haystackLength >= needleLength) { // all characters match ? for (i = lastPos; haystack[i] == needle[i]; i--) if (i == 0) return haystack; // no match, jump ahead unsigned char marker = (unsigned char) haystack[lastPos]; haystackLength -= skip[marker]; haystack += skip[marker]; } // needle not found in haystack return NULL; } // ////////////////////////////////////////////////////////// /// Bitap algorithm / Baeza-Yates-Gonnet algorithm (for C strings) const char* searchBitapString(const char* haystack, const char* needle) { // detect invalid input if (!haystack || !needle) return NULL; // empty needle matches everything size_t needleLength = strlen(needle); if (needleLength == 0) return haystack; // create bit masks for each possible byte / ASCII character // each mask is as wide as needleLength const size_t MaxBitWidth = 8 * sizeof(int) - 1; // only if needleLength bits fit into an integer (minus 1), the algorithm will be fast if (needleLength > MaxBitWidth) return searchSimpleString(haystack, needle); // one mask per allowed character (1 byte => 2^8 => 256) // where all bits are set except those where the character is found in needle const size_t AlphabetSize = 256; unsigned int masks[AlphabetSize]; size_t i; for (i = 0; i < AlphabetSize; i++) masks[i] = ~0; for (i = 0; i < needleLength; i++) masks[(unsigned char)needle[i]] &= ~(1 << i); // initial state mask has all bits set except the lowest one unsigned int state = ~1; const unsigned int FullMatch = 1 << needleLength; while (*haystack) { // update the bit array state |= masks[(unsigned char)*haystack]; state <<= 1; // if an unset bit "bubbled up" we have a match if ((state & FullMatch) == 0) return (haystack - needleLength) + 1; haystack++; } // needle not found in haystack return NULL; } /// Bitap algorithm / Baeza-Yates-Gonnet algorithm (for C strings) const char* searchBitap(const char* haystack, size_t haystackLength, const char* needle, size_t needleLength) { // detect invalid input if (!haystack || !needle || haystackLength < needleLength) return NULL; // empty needle matches everything if (needleLength == 0) return haystack; // create bit masks for each possible byte / ASCII character // each mask is as wide as needleLength const size_t MaxBitWidth = 8 * sizeof(int) - 1; // only if needleLength bits fit into an integer (minus 1), the algorithm will be fast if (needleLength > MaxBitWidth) return searchNative(haystack, haystackLength, needle, needleLength); // one mask per allowed character (1 byte => 2^8 => 256) // where all bits are set except those where the character is found in needle const size_t AlphabetSize = 256; unsigned int masks[AlphabetSize]; size_t i; for (i = 0; i < AlphabetSize; i++) masks[i] = ~0; for (i = 0; i < needleLength; i++) masks[(unsigned char)needle[i]] &= ~(1 << i); // points beyond last considered byte const char* haystackEnd = haystack + haystackLength; // initial state mask has all bits set except the lowest one unsigned int state = ~1; const unsigned int FullMatch = 1 << needleLength; while (haystack != haystackEnd) { // update the bit array state |= masks[(unsigned char)*haystack]; state <<= 1; // if an unset bit "bubbled up" we have a match if ((state & FullMatch) == 0) return (haystack - needleLength) + 1; haystack++; } // needle not found in haystack return NULL; } // ////////////////////////////////////////////////////////// /// Rabin-Karp algorithm /** based on simple hash proposed by <NAME> **/ const char* searchRabinKarpString(const char* haystack, const char* needle) { // detect invalid input if (!haystack || !needle) return NULL; // empty needle matches everything if (!*needle) return haystack; // find first match of the first letter haystack = strchr(haystack, *needle); if (!haystack) return NULL; // now first letter of haystack and needle is identical // let's compute the sum of all characters of needle unsigned int hashNeedle = *needle; unsigned int hashHaystack = *haystack; const char* scanNeedle = needle + 1; const char* scanHaystack = haystack + 1; while (*scanNeedle && *scanHaystack) { hashNeedle += *scanNeedle++; hashHaystack += *scanHaystack++; } // if scanNeedle doesn't point to zero, then we have too little haystack if (*scanNeedle) return NULL; // length of needle const size_t needleLength = scanNeedle - needle; // walk through haystack and roll the hash for (;;) { // identical hash ? if (hashHaystack == hashNeedle) { // can be a false positive, therefore must check all characters again if (memcmp(haystack, needle, needleLength) == 0) return haystack; } // no more bytes left ? if (!*scanHaystack) break; // update hash hashHaystack -= *haystack++; hashHaystack += *scanHaystack++; } // needle not found in haystack return NULL; } /// Rabin-Karp algorithm /** based on simple hash proposed by <NAME> **/ const char* searchRabinKarp(const char* haystack, size_t haystackLength, const char* needle, size_t needleLength) { // detect invalid input if (!haystack || !needle || haystackLength < needleLength) return NULL; // empty needle matches everything if (needleLength == 0) return haystack; // one byte beyond last position where a match can begin const char* haystackEnd = haystack + haystackLength - needleLength + 1; // find first match of the first letter haystack = (const char*)memchr(haystack, *needle, haystackLength); if (!haystack) return NULL; // now first letter of haystack and needle is identical // let's compute the sum of all characters of needle unsigned int hashNeedle = 0; unsigned int hashHaystack = 0; size_t i; for (i = 0; i < needleLength; i++) { // not enough haystack left ? if (!haystack[i]) return NULL; hashNeedle += needle [i]; hashHaystack += haystack[i]; } // walk through haystack and roll the hash computation while (haystack != haystackEnd) { // identical hash ? if (hashHaystack == hashNeedle) { // can be a false positive, therefore must check all characters again if (memcmp(haystack, needle, needleLength) == 0) return haystack; } // update hash hashHaystack += *(haystack + needleLength); hashHaystack -= *haystack++; } // needle not found in haystack return NULL; } // ////////////////////////////////////////////////////////// /// super-fast for short strings (less than about 8 bytes), else use searchSimple or searchBoyerMooreHorspool const char* searchNative(const char* haystack, size_t haystackLength, const char* needle, size_t needleLength) { // uses memchr() for the first byte, then memcmp to verify it's a valid match // detect invalid input if (!haystack || !needle || haystackLength < needleLength) return NULL; // empty needle matches everything if (needleLength == 0) return haystack; // shorter code for just one character if (needleLength == 1) return (const char*)memchr(haystack, *needle, haystackLength); haystackLength -= needleLength - 1; // points beyond last considered byte const char* haystackEnd = haystack + haystackLength; // look for first byte while ((haystack = (const char*)memchr(haystack, *needle, haystackLength)) != NULL) { // does last byte match, too ? if (haystack[needleLength - 1] == needle[needleLength - 1]) // okay, perform full comparison, skip first and last byte (if just 2 bytes => already finished) if (needleLength == 2 || memcmp(haystack + 1, needle + 1, needleLength - 2) == 0) return haystack; // compute number of remaining bytes haystackLength = haystackEnd - haystack; if (haystackLength == 0) return NULL; // keep going haystack++; haystackLength--; } // needle not found in haystack return NULL; }
stbrumme/practical-string-searching
search.h
// ////////////////////////////////////////////////////////// // search.h // Copyright (c) 2014,2019 <NAME>. All rights reserved. // see http://create.stephan-brumme.com/disclaimer.html // #pragma once #include <stddef.h> // size_t // all functions are declared similar to strstr /// naive approach (for C strings) const char* searchSimpleString (const char* haystack, const char* needle); /// naive approach (for non-text data) const char* searchSimple (const char* haystack, size_t haystackLength, const char* needle, size_t needleLength); /// Knuth-Morris-Pratt algorithm (for C strings) const char* searchKnuthMorrisPrattString (const char* haystack, const char* needle); /// Knuth-Morris-Pratt algorithm (for non-text data) const char* searchKnuthMorrisPratt (const char* haystack, size_t haystackLength, const char* needle, size_t needleLength); /// Boyer-Moore-Horspool algorithm (for C strings) const char* searchBoyerMooreHorspoolString(const char* haystack, const char* needle); /// Boyer-Moore-Horspool algorithm (for non-text data) const char* searchBoyerMooreHorspool (const char* haystack, size_t haystackLength, const char* needle, size_t needleLength); /// Bitap algorithm / Baeza-Yates-Gonnet algorithm (for C strings) const char* searchBitapString (const char* haystack, const char* needle); /// Bitap algorithm / Baeza-Yates-Gonnet algorithm (for non-text data) const char* searchBitap (const char* haystack, size_t haystackLength, const char* needle, size_t needleLength); /// Rabin-Karp algorithm (for C strings) const char* searchRabinKarpString (const char *haystack, const char *needle); /// Rabin-Karp algorithm (for non-text strings) const char* searchRabinKarp (const char* haystack, size_t haystackLength, const char* needle, size_t needleLength); /// super-fast for short strings (less than about 8 bytes), else use searchSimple or searchBoyerMooreHorspool const char* searchNative (const char* haystack, size_t haystackLength, const char* needle, size_t needleLength);
stbrumme/practical-string-searching
mygrep.c
<gh_stars>1-10 // ////////////////////////////////////////////////////////// // mygrep.c // Copyright (c) 2014,2019 <NAME>. All rights reserved. // see http://create.stephan-brumme.com/disclaimer.html // // gcc -O3 -std=c99 -Wall -pedantic search.c mygrep.c -o mygrep // file size limited to available memory size because whole file is loaded into RAM // enable GNU extensions, such as memmem() #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #ifdef _MSC_VER /// GNU C++ has a super-optimized version of memmem() which Visual C++ lacks, here is a simple replacement using a function reference #define memmem searchNative #define _CRT_SECURE_NO_WARNINGS #endif #include "search.h" #include <string.h> // memmem() #include <stdio.h> // printf() #include <stdlib.h> // malloc() enum Algorithm { UseBest , UseStrStr , UseMemMem , UseSimple , UseNative , UseKnuthMorrisPratt , UseBoyerMooreHorspool , UseBitap , UseRabinKarp } algorithm; enum { ShowLines = 0, ShowCountOnly = 1 } display; int main(int argc, char* argv[]) { const char* syntax = "Syntax: ./mygrep searchphrase filename [--native|--memmem|--strstr|--simple|--knuthmorrispratt|--boyermoorehorspool|--bitap|--rabinkarp] [-c]\n"; if (argc < 3 || argc > 5) { printf("%s", syntax); return -1; } // don't show lines, just count them display = ShowLines; if (argc == 5 && strcmp(argv[4], "-c") == 0) display = ShowCountOnly; // use safer memmem() by default algorithm = UseBest; if (argc >= 4) { if (strcmp(argv[3], "--native") == 0) algorithm = UseNative; else if (strcmp(argv[3], "--memmem") == 0) algorithm = UseMemMem; else if (strcmp(argv[3], "--strstr") == 0) // be careful: buffer overruns possible !!! algorithm = UseStrStr; else if (strcmp(argv[3], "--simple") == 0) algorithm = UseSimple; else if (strcmp(argv[3], "--knuthmorrispratt") == 0 || strcmp(argv[3], "--kmp") == 0) algorithm = UseKnuthMorrisPratt; else if (strcmp(argv[3], "--boyermoorehorspool") == 0 || strcmp(argv[3], "--bmh") == 0) algorithm = UseBoyerMooreHorspool; else if (strcmp(argv[3], "--bitap") == 0) algorithm = UseBitap; else if (strcmp(argv[3], "--rabinkarp") == 0) algorithm = UseRabinKarp; else if (strcmp(argv[3], "-c") == 0) display = ShowCountOnly; else { printf("%s", syntax); return -2; } } // open file FILE* file = fopen(argv[2], "rb"); if (!file) { printf("Failed to open file\n"); return -3; } // determine its filesize fseek(file, 0, SEEK_END); long filesize = ftell(file); fseek(file, 0, SEEK_SET); if (filesize == 0) { printf("Empty file\n"); return -4; } // allocate memory and read the whole file at once char* data = (char*) malloc(filesize + 2); if (!data) { printf("Out of memory\n"); return -5; } fread(data, filesize, 1, file); fclose(file); // pad data to avoid buffer overruns data[filesize ] = '\n'; data[filesize + 1] = 0; // what we look for const char* needle = argv[1]; const size_t needleLength = strlen(needle); // where we look for const char* haystack = data; const size_t haystackLength = filesize; // fence const char* haystackEnd = haystack + haystackLength; // "native" and "Boyer-Moore-Horspool" are in almost all cases the best choice if (algorithm == UseBest) { // when needle is longer than about 16 bytes, Boyer-Moore-Horspool is faster if (needleLength <= 16) algorithm = UseNative; else algorithm = UseBoyerMooreHorspool; } // search until done ... unsigned int numHits = 0; const char* current = haystack; for (;;) { // offset of current hit from the beginning of the haystack size_t bytesDone = current - haystack; size_t bytesLeft = haystackLength - bytesDone; switch (algorithm) { case UseMemMem: // correctly handled zeros, unfortunately much slower { const char* before = current; current = (const char*)memmem (current, bytesLeft, needle, needleLength); // workaround for strange GCC behavior, else I get a memory access violation if (current) { int diff = current - before; current = before + diff; } } break; case UseStrStr: // much faster but has problems when bytes in haystack are zero, // requires both to be properly zero-terminated current = strstr (current, needle); break; case UseSimple: // brute-force current = searchSimple (current, bytesLeft, needle, needleLength); break; case UseNative: // brute-force for short needles, based on compiler-optimized functions current = searchNative (current, bytesLeft, needle, needleLength); break; case UseKnuthMorrisPratt: // Knuth-Morris-Pratt current = searchKnuthMorrisPratt (current, bytesLeft, needle, needleLength); break; case UseBoyerMooreHorspool: // Boyer-Moore-Horspool current = searchBoyerMooreHorspool(current, bytesLeft, needle, needleLength); break; case UseBitap: // Bitap / Baeza-Yates-Gonnet algorithm current = searchBitap (current, bytesLeft, needle, needleLength); break; case UseRabinKarp: // Rabin-Karp algorithm current = searchRabinKarp (current, bytesLeft, needle, needleLength); break; default: printf("Unknown search algorithm\n"); return -6; } // needle not found in the remaining haystack if (!current) break; numHits++; // find end of line const char* right = current; while (right != haystackEnd && *right != '\n') right++; if (display == ShowCountOnly) { current = right; continue; } // find beginning of line const char* left = current; while (left != haystack && *left != '\n') left--; if (*left == '\n' && left != haystackEnd) left++; // send line to standard output size_t lineLength = right - left; fwrite(left, lineLength, 1, stdout); // and append a newline putchar('\n'); // don't search this line anymore current = right; } if (display == ShowCountOnly) printf("%d\n", numHits); // exit with error code 1 if nothing found return numHits == 0 ? 1 : 0; }
Johan-Mi/C64DvdLogo
main.c
#include <stdlib.h> #include <peekpoke.h> #include <string.h> #include <conio.h> char spriteData[] = { 31,255,248,31,255,252,0,15,252,62,7,252,62,3,254,124, 3,222,124,7,158,124,15,159,124,63,15,127,252,15,255,240, 15,0,0,7,0,0,6,0,0,4,3,255,255,63,255,255, 255,255,224,255,255,224,63,255,255,3,255,255,0,0,0,6, 7,255,248,15,255,252,31,0,126,62,0,63,60,248,31,120, 248,31,240,240,62,241,240,62,225,240,252,193,255,240,129,255, 192,0,0,0,0,0,0,0,0,0,255,255,128,255,255,252, 7,255,255,7,255,255,255,255,252,255,255,128,0,0,0,6 }; char possibleColors[] = { 6, 3, 4, 5, 2, 7, 8, 10, 13, 14 }; int main() { const unsigned v = 53248L; // VIC-II base address unsigned x = 160; char y = 140; unsigned xDir; char yDir; unsigned timer = 0; char colorIndex = 0; _randomize(); xDir = (rand() % 2) ? 1L : -1L; yDir = (rand() % 2) ? 1 : -1; x = rand() % 270L + 25L; y = rand() % 178 + 51; clrscr(); POKE(53281L, 0); POKE(v + 21, 3); // Enable sprites 0 and 1 POKE(2040L, 192); // Set pointer for sprite 0 POKE(2041L, 193); // Set pointer for sprite 1 POKE(v + 39, 6); // Set colour for sprite 0 POKE(v + 40, 6); // Set colour for sprite 1 memcpy((char*)12288L, spriteData, sizeof(spriteData)); for(;;) { timer++; timer %= 30; if(!timer) { x += xDir; y += yDir; if(y == 50 || y == 230) { yDir = -yDir; if(x < 27L || x > 293L) { colorIndex++; colorIndex %= sizeof(possibleColors); POKE(v + 39, possibleColors[colorIndex]); POKE(v + 40, possibleColors[colorIndex]); } } if(x == 24L || x == 296L) { xDir = -xDir; if(y < 53 || y > 227) { colorIndex++; colorIndex %= sizeof(possibleColors); POKE(v + 39, possibleColors[colorIndex]); POKE(v + 40, possibleColors[colorIndex]); } } POKE(v + 0, x & 255); // Sprite 0 X POKE(v + 1, y); // Sprite 0 Y POKE(v + 2, (x + 24) & 255); // Sprite 1 X POKE(v + 3, y); // Sprite 1 Y POKE(v + 16, (x > 255) | ((x > 231) << 1)); // X msb } } return EXIT_SUCCESS; }
nikramakrishnan/freetype2
include/freetype/internal/services/svgxval.h
<filename>include/freetype/internal/services/svgxval.h /**************************************************************************** * * svgxval.h * * FreeType API for validating TrueTypeGX/AAT tables (specification). * * Copyright 2004-2018 by * <NAME>, Red Hat K.K., * <NAME>, <NAME>, and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /**************************************************************************** * * gxvalid is derived from both gxlayout module and otvalid module. * Development of gxlayout is supported by the Information-technology * Promotion Agency(IPA), Japan. * */ #ifndef SVGXVAL_H_ #define SVGXVAL_H_ #include FT_GX_VALIDATE_H #include FT_INTERNAL_VALIDATE_H FT_BEGIN_HEADER #define FT_SERVICE_ID_GX_VALIDATE "truetypegx-validate" #define FT_SERVICE_ID_CLASSICKERN_VALIDATE "classickern-validate" typedef FT_Error (*gxv_validate_func)( FT_Face face, FT_UInt gx_flags, FT_Bytes tables[FT_VALIDATE_GX_LENGTH], FT_UInt table_length ); typedef FT_Error (*ckern_validate_func)( FT_Face face, FT_UInt ckern_flags, FT_Bytes *ckern_table ); FT_DEFINE_SERVICE( GXvalidate ) { gxv_validate_func validate; }; FT_DEFINE_SERVICE( CKERNvalidate ) { ckern_validate_func validate; }; /* */ FT_END_HEADER #endif /* SVGXVAL_H_ */ /* END */
nikramakrishnan/freetype2
include/freetype/t1tables.h
/**************************************************************************** * * t1tables.h * * Basic Type 1/Type 2 tables definitions and interface (specification * only). * * Copyright 1996-2018 by * <NAME>, <NAME>, and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T1TABLES_H_ #define T1TABLES_H_ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /************************************************************************** * * @section: * type1_tables * * @title: * Type 1 Tables * * @abstract: * Type~1-specific font tables. * * @description: * This section contains the definition of Type~1-specific tables, * including structures related to other PostScript font formats. * * @order: * PS_FontInfoRec * PS_FontInfo * PS_PrivateRec * PS_Private * * CID_FaceDictRec * CID_FaceDict * CID_FaceInfoRec * CID_FaceInfo * * FT_Has_PS_Glyph_Names * FT_Get_PS_Font_Info * FT_Get_PS_Font_Private * FT_Get_PS_Font_Value * * T1_Blend_Flags * T1_EncodingType * PS_Dict_Keys * */ /* Note that we separate font data in PS_FontInfoRec and PS_PrivateRec */ /* structures in order to support Multiple Master fonts. */ /************************************************************************** * * @struct: * PS_FontInfoRec * * @description: * A structure used to model a Type~1 or Type~2 FontInfo dictionary. * Note that for Multiple Master fonts, each instance has its own * FontInfo dictionary. */ typedef struct PS_FontInfoRec_ { FT_String* version; FT_String* notice; FT_String* full_name; FT_String* family_name; FT_String* weight; FT_Long italic_angle; FT_Bool is_fixed_pitch; FT_Short underline_position; FT_UShort underline_thickness; } PS_FontInfoRec; /************************************************************************** * * @struct: * PS_FontInfo * * @description: * A handle to a @PS_FontInfoRec structure. */ typedef struct PS_FontInfoRec_* PS_FontInfo; /************************************************************************** * * @struct: * T1_FontInfo * * @description: * This type is equivalent to @PS_FontInfoRec. It is deprecated but * kept to maintain source compatibility between various versions of * FreeType. */ typedef PS_FontInfoRec T1_FontInfo; /************************************************************************** * * @struct: * PS_PrivateRec * * @description: * A structure used to model a Type~1 or Type~2 private dictionary. * Note that for Multiple Master fonts, each instance has its own * Private dictionary. */ typedef struct PS_PrivateRec_ { FT_Int unique_id; FT_Int lenIV; FT_Byte num_blue_values; FT_Byte num_other_blues; FT_Byte num_family_blues; FT_Byte num_family_other_blues; FT_Short blue_values[14]; FT_Short other_blues[10]; FT_Short family_blues [14]; FT_Short family_other_blues[10]; FT_Fixed blue_scale; FT_Int blue_shift; FT_Int blue_fuzz; FT_UShort standard_width[1]; FT_UShort standard_height[1]; FT_Byte num_snap_widths; FT_Byte num_snap_heights; FT_Bool force_bold; FT_Bool round_stem_up; FT_Short snap_widths [13]; /* including std width */ FT_Short snap_heights[13]; /* including std height */ FT_Fixed expansion_factor; FT_Long language_group; FT_Long password; FT_Short min_feature[2]; } PS_PrivateRec; /************************************************************************** * * @struct: * PS_Private * * @description: * A handle to a @PS_PrivateRec structure. */ typedef struct PS_PrivateRec_* PS_Private; /************************************************************************** * * @struct: * T1_Private * * @description: * This type is equivalent to @PS_PrivateRec. It is deprecated but * kept to maintain source compatibility between various versions of * FreeType. */ typedef PS_PrivateRec T1_Private; /************************************************************************** * * @enum: * T1_Blend_Flags * * @description: * A set of flags used to indicate which fields are present in a * given blend dictionary (font info or private). Used to support * Multiple Masters fonts. * * @values: * T1_BLEND_UNDERLINE_POSITION :: * T1_BLEND_UNDERLINE_THICKNESS :: * T1_BLEND_ITALIC_ANGLE :: * T1_BLEND_BLUE_VALUES :: * T1_BLEND_OTHER_BLUES :: * T1_BLEND_STANDARD_WIDTH :: * T1_BLEND_STANDARD_HEIGHT :: * T1_BLEND_STEM_SNAP_WIDTHS :: * T1_BLEND_STEM_SNAP_HEIGHTS :: * T1_BLEND_BLUE_SCALE :: * T1_BLEND_BLUE_SHIFT :: * T1_BLEND_FAMILY_BLUES :: * T1_BLEND_FAMILY_OTHER_BLUES :: * T1_BLEND_FORCE_BOLD :: */ typedef enum T1_Blend_Flags_ { /* required fields in a FontInfo blend dictionary */ T1_BLEND_UNDERLINE_POSITION = 0, T1_BLEND_UNDERLINE_THICKNESS, T1_BLEND_ITALIC_ANGLE, /* required fields in a Private blend dictionary */ T1_BLEND_BLUE_VALUES, T1_BLEND_OTHER_BLUES, T1_BLEND_STANDARD_WIDTH, T1_BLEND_STANDARD_HEIGHT, T1_BLEND_STEM_SNAP_WIDTHS, T1_BLEND_STEM_SNAP_HEIGHTS, T1_BLEND_BLUE_SCALE, T1_BLEND_BLUE_SHIFT, T1_BLEND_FAMILY_BLUES, T1_BLEND_FAMILY_OTHER_BLUES, T1_BLEND_FORCE_BOLD, T1_BLEND_MAX /* do not remove */ } T1_Blend_Flags; /* these constants are deprecated; use the corresponding */ /* `T1_Blend_Flags' values instead */ #define t1_blend_underline_position T1_BLEND_UNDERLINE_POSITION #define t1_blend_underline_thickness T1_BLEND_UNDERLINE_THICKNESS #define t1_blend_italic_angle T1_BLEND_ITALIC_ANGLE #define t1_blend_blue_values T1_BLEND_BLUE_VALUES #define t1_blend_other_blues T1_BLEND_OTHER_BLUES #define t1_blend_standard_widths T1_BLEND_STANDARD_WIDTH #define t1_blend_standard_height T1_BLEND_STANDARD_HEIGHT #define t1_blend_stem_snap_widths T1_BLEND_STEM_SNAP_WIDTHS #define t1_blend_stem_snap_heights T1_BLEND_STEM_SNAP_HEIGHTS #define t1_blend_blue_scale T1_BLEND_BLUE_SCALE #define t1_blend_blue_shift T1_BLEND_BLUE_SHIFT #define t1_blend_family_blues T1_BLEND_FAMILY_BLUES #define t1_blend_family_other_blues T1_BLEND_FAMILY_OTHER_BLUES #define t1_blend_force_bold T1_BLEND_FORCE_BOLD #define t1_blend_max T1_BLEND_MAX /* */ /* maximum number of Multiple Masters designs, as defined in the spec */ #define T1_MAX_MM_DESIGNS 16 /* maximum number of Multiple Masters axes, as defined in the spec */ #define T1_MAX_MM_AXIS 4 /* maximum number of elements in a design map */ #define T1_MAX_MM_MAP_POINTS 20 /* this structure is used to store the BlendDesignMap entry for an axis */ typedef struct PS_DesignMap_ { FT_Byte num_points; FT_Long* design_points; FT_Fixed* blend_points; } PS_DesignMapRec, *PS_DesignMap; /* backward compatible definition */ typedef PS_DesignMapRec T1_DesignMap; typedef struct PS_BlendRec_ { FT_UInt num_designs; FT_UInt num_axis; FT_String* axis_names[T1_MAX_MM_AXIS]; FT_Fixed* design_pos[T1_MAX_MM_DESIGNS]; PS_DesignMapRec design_map[T1_MAX_MM_AXIS]; FT_Fixed* weight_vector; FT_Fixed* default_weight_vector; PS_FontInfo font_infos[T1_MAX_MM_DESIGNS + 1]; PS_Private privates [T1_MAX_MM_DESIGNS + 1]; FT_ULong blend_bitflags; FT_BBox* bboxes [T1_MAX_MM_DESIGNS + 1]; /* since 2.3.0 */ /* undocumented, optional: the default design instance; */ /* corresponds to default_weight_vector -- */ /* num_default_design_vector == 0 means it is not present */ /* in the font and associated metrics files */ FT_UInt default_design_vector[T1_MAX_MM_DESIGNS]; FT_UInt num_default_design_vector; } PS_BlendRec, *PS_Blend; /* backward compatible definition */ typedef PS_BlendRec T1_Blend; /************************************************************************** * * @struct: * CID_FaceDictRec * * @description: * A structure used to represent data in a CID top-level dictionary. */ typedef struct CID_FaceDictRec_ { PS_PrivateRec private_dict; FT_UInt len_buildchar; FT_Fixed forcebold_threshold; FT_Pos stroke_width; FT_Fixed expansion_factor; FT_Byte paint_type; FT_Byte font_type; FT_Matrix font_matrix; FT_Vector font_offset; FT_UInt num_subrs; FT_ULong subrmap_offset; FT_Int sd_bytes; } CID_FaceDictRec; /************************************************************************** * * @struct: * CID_FaceDict * * @description: * A handle to a @CID_FaceDictRec structure. */ typedef struct CID_FaceDictRec_* CID_FaceDict; /************************************************************************** * * @struct: * CID_FontDict * * @description: * This type is equivalent to @CID_FaceDictRec. It is deprecated but * kept to maintain source compatibility between various versions of * FreeType. */ typedef CID_FaceDictRec CID_FontDict; /************************************************************************** * * @struct: * CID_FaceInfoRec * * @description: * A structure used to represent CID Face information. */ typedef struct CID_FaceInfoRec_ { FT_String* cid_font_name; FT_Fixed cid_version; FT_Int cid_font_type; FT_String* registry; FT_String* ordering; FT_Int supplement; PS_FontInfoRec font_info; FT_BBox font_bbox; FT_ULong uid_base; FT_Int num_xuid; FT_ULong xuid[16]; FT_ULong cidmap_offset; FT_Int fd_bytes; FT_Int gd_bytes; FT_ULong cid_count; FT_Int num_dicts; CID_FaceDict font_dicts; FT_ULong data_offset; } CID_FaceInfoRec; /************************************************************************** * * @struct: * CID_FaceInfo * * @description: * A handle to a @CID_FaceInfoRec structure. */ typedef struct CID_FaceInfoRec_* CID_FaceInfo; /************************************************************************** * * @struct: * CID_Info * * @description: * This type is equivalent to @CID_FaceInfoRec. It is deprecated but * kept to maintain source compatibility between various versions of * FreeType. */ typedef CID_FaceInfoRec CID_Info; /************************************************************************ * * @function: * FT_Has_PS_Glyph_Names * * @description: * Return true if a given face provides reliable PostScript glyph * names. This is similar to using the @FT_HAS_GLYPH_NAMES macro, * except that certain fonts (mostly TrueType) contain incorrect * glyph name tables. * * When this function returns true, the caller is sure that the glyph * names returned by @FT_Get_Glyph_Name are reliable. * * @input: * face :: * face handle * * @return: * Boolean. True if glyph names are reliable. * */ FT_EXPORT( FT_Int ) FT_Has_PS_Glyph_Names( FT_Face face ); /************************************************************************ * * @function: * FT_Get_PS_Font_Info * * @description: * Retrieve the @PS_FontInfoRec structure corresponding to a given * PostScript font. * * @input: * face :: * PostScript face handle. * * @output: * afont_info :: * Output font info structure pointer. * * @return: * FreeType error code. 0~means success. * * @note: * String pointers within the @PS_FontInfoRec structure are owned by * the face and don't need to be freed by the caller. Missing entries * in the font's FontInfo dictionary are represented by NULL pointers. * * If the font's format is not PostScript-based, this function will * return the `FT_Err_Invalid_Argument' error code. * */ FT_EXPORT( FT_Error ) FT_Get_PS_Font_Info( FT_Face face, PS_FontInfo afont_info ); /************************************************************************ * * @function: * FT_Get_PS_Font_Private * * @description: * Retrieve the @PS_PrivateRec structure corresponding to a given * PostScript font. * * @input: * face :: * PostScript face handle. * * @output: * afont_private :: * Output private dictionary structure pointer. * * @return: * FreeType error code. 0~means success. * * @note: * The string pointers within the @PS_PrivateRec structure are owned by * the face and don't need to be freed by the caller. * * If the font's format is not PostScript-based, this function returns * the `FT_Err_Invalid_Argument' error code. * */ FT_EXPORT( FT_Error ) FT_Get_PS_Font_Private( FT_Face face, PS_Private afont_private ); /************************************************************************** * * @enum: * T1_EncodingType * * @description: * An enumeration describing the `Encoding' entry in a Type 1 * dictionary. * * @values: * T1_ENCODING_TYPE_NONE :: * T1_ENCODING_TYPE_ARRAY :: * T1_ENCODING_TYPE_STANDARD :: * T1_ENCODING_TYPE_ISOLATIN1 :: * T1_ENCODING_TYPE_EXPERT :: * * @since: * 2.4.8 */ typedef enum T1_EncodingType_ { T1_ENCODING_TYPE_NONE = 0, T1_ENCODING_TYPE_ARRAY, T1_ENCODING_TYPE_STANDARD, T1_ENCODING_TYPE_ISOLATIN1, T1_ENCODING_TYPE_EXPERT } T1_EncodingType; /************************************************************************** * * @enum: * PS_Dict_Keys * * @description: * An enumeration used in calls to @FT_Get_PS_Font_Value to identify * the Type~1 dictionary entry to retrieve. * * @values: * PS_DICT_FONT_TYPE :: * PS_DICT_FONT_MATRIX :: * PS_DICT_FONT_BBOX :: * PS_DICT_PAINT_TYPE :: * PS_DICT_FONT_NAME :: * PS_DICT_UNIQUE_ID :: * PS_DICT_NUM_CHAR_STRINGS :: * PS_DICT_CHAR_STRING_KEY :: * PS_DICT_CHAR_STRING :: * PS_DICT_ENCODING_TYPE :: * PS_DICT_ENCODING_ENTRY :: * PS_DICT_NUM_SUBRS :: * PS_DICT_SUBR :: * PS_DICT_STD_HW :: * PS_DICT_STD_VW :: * PS_DICT_NUM_BLUE_VALUES :: * PS_DICT_BLUE_VALUE :: * PS_DICT_BLUE_FUZZ :: * PS_DICT_NUM_OTHER_BLUES :: * PS_DICT_OTHER_BLUE :: * PS_DICT_NUM_FAMILY_BLUES :: * PS_DICT_FAMILY_BLUE :: * PS_DICT_NUM_FAMILY_OTHER_BLUES :: * PS_DICT_FAMILY_OTHER_BLUE :: * PS_DICT_BLUE_SCALE :: * PS_DICT_BLUE_SHIFT :: * PS_DICT_NUM_STEM_SNAP_H :: * PS_DICT_STEM_SNAP_H :: * PS_DICT_NUM_STEM_SNAP_V :: * PS_DICT_STEM_SNAP_V :: * PS_DICT_FORCE_BOLD :: * PS_DICT_RND_STEM_UP :: * PS_DICT_MIN_FEATURE :: * PS_DICT_LEN_IV :: * PS_DICT_PASSWORD :: * PS_DICT_LANGUAGE_GROUP :: * PS_DICT_VERSION :: * PS_DICT_NOTICE :: * PS_DICT_FULL_NAME :: * PS_DICT_FAMILY_NAME :: * PS_DICT_WEIGHT :: * PS_DICT_IS_FIXED_PITCH :: * PS_DICT_UNDERLINE_POSITION :: * PS_DICT_UNDERLINE_THICKNESS :: * PS_DICT_FS_TYPE :: * PS_DICT_ITALIC_ANGLE :: * * @since: * 2.4.8 */ typedef enum PS_Dict_Keys_ { /* conventionally in the font dictionary */ PS_DICT_FONT_TYPE, /* FT_Byte */ PS_DICT_FONT_MATRIX, /* FT_Fixed */ PS_DICT_FONT_BBOX, /* FT_Fixed */ PS_DICT_PAINT_TYPE, /* FT_Byte */ PS_DICT_FONT_NAME, /* FT_String* */ PS_DICT_UNIQUE_ID, /* FT_Int */ PS_DICT_NUM_CHAR_STRINGS, /* FT_Int */ PS_DICT_CHAR_STRING_KEY, /* FT_String* */ PS_DICT_CHAR_STRING, /* FT_String* */ PS_DICT_ENCODING_TYPE, /* T1_EncodingType */ PS_DICT_ENCODING_ENTRY, /* FT_String* */ /* conventionally in the font Private dictionary */ PS_DICT_NUM_SUBRS, /* FT_Int */ PS_DICT_SUBR, /* FT_String* */ PS_DICT_STD_HW, /* FT_UShort */ PS_DICT_STD_VW, /* FT_UShort */ PS_DICT_NUM_BLUE_VALUES, /* FT_Byte */ PS_DICT_BLUE_VALUE, /* FT_Short */ PS_DICT_BLUE_FUZZ, /* FT_Int */ PS_DICT_NUM_OTHER_BLUES, /* FT_Byte */ PS_DICT_OTHER_BLUE, /* FT_Short */ PS_DICT_NUM_FAMILY_BLUES, /* FT_Byte */ PS_DICT_FAMILY_BLUE, /* FT_Short */ PS_DICT_NUM_FAMILY_OTHER_BLUES, /* FT_Byte */ PS_DICT_FAMILY_OTHER_BLUE, /* FT_Short */ PS_DICT_BLUE_SCALE, /* FT_Fixed */ PS_DICT_BLUE_SHIFT, /* FT_Int */ PS_DICT_NUM_STEM_SNAP_H, /* FT_Byte */ PS_DICT_STEM_SNAP_H, /* FT_Short */ PS_DICT_NUM_STEM_SNAP_V, /* FT_Byte */ PS_DICT_STEM_SNAP_V, /* FT_Short */ PS_DICT_FORCE_BOLD, /* FT_Bool */ PS_DICT_RND_STEM_UP, /* FT_Bool */ PS_DICT_MIN_FEATURE, /* FT_Short */ PS_DICT_LEN_IV, /* FT_Int */ PS_DICT_PASSWORD, /* FT_Long */ PS_DICT_LANGUAGE_GROUP, /* FT_Long */ /* conventionally in the font FontInfo dictionary */ PS_DICT_VERSION, /* FT_String* */ PS_DICT_NOTICE, /* FT_String* */ PS_DICT_FULL_NAME, /* FT_String* */ PS_DICT_FAMILY_NAME, /* FT_String* */ PS_DICT_WEIGHT, /* FT_String* */ PS_DICT_IS_FIXED_PITCH, /* FT_Bool */ PS_DICT_UNDERLINE_POSITION, /* FT_Short */ PS_DICT_UNDERLINE_THICKNESS, /* FT_UShort */ PS_DICT_FS_TYPE, /* FT_UShort */ PS_DICT_ITALIC_ANGLE, /* FT_Long */ PS_DICT_MAX = PS_DICT_ITALIC_ANGLE } PS_Dict_Keys; /************************************************************************ * * @function: * FT_Get_PS_Font_Value * * @description: * Retrieve the value for the supplied key from a PostScript font. * * @input: * face :: * PostScript face handle. * * key :: * An enumeration value representing the dictionary key to retrieve. * * idx :: * For array values, this specifies the index to be returned. * * value :: * A pointer to memory into which to write the value. * * valen_len :: * The size, in bytes, of the memory supplied for the value. * * @output: * value :: * The value matching the above key, if it exists. * * @return: * The amount of memory (in bytes) required to hold the requested * value (if it exists, -1 otherwise). * * @note: * The values returned are not pointers into the internal structures of * the face, but are `fresh' copies, so that the memory containing them * belongs to the calling application. This also enforces the * `read-only' nature of these values, i.e., this function cannot be * used to manipulate the face. * * `value' is a void pointer because the values returned can be of * various types. * * If either `value' is NULL or `value_len' is too small, just the * required memory size for the requested entry is returned. * * The `idx' parameter is used, not only to retrieve elements of, for * example, the FontMatrix or FontBBox, but also to retrieve name keys * from the CharStrings dictionary, and the charstrings themselves. It * is ignored for atomic values. * * PS_DICT_BLUE_SCALE returns a value that is scaled up by 1000. To * get the value as in the font stream, you need to divide by * 65536000.0 (to remove the FT_Fixed scale, and the x1000 scale). * * IMPORTANT: Only key/value pairs read by the FreeType interpreter can * be retrieved. So, for example, PostScript procedures such as NP, * ND, and RD are not available. Arbitrary keys are, obviously, not be * available either. * * If the font's format is not PostScript-based, this function returns * the `FT_Err_Invalid_Argument' error code. * * @since: * 2.4.8 * */ FT_EXPORT( FT_Long ) FT_Get_PS_Font_Value( FT_Face face, PS_Dict_Keys key, FT_UInt idx, void *value, FT_Long value_len ); /* */ FT_END_HEADER #endif /* T1TABLES_H_ */ /* END */
nikramakrishnan/freetype2
include/freetype/internal/services/svcid.h
/**************************************************************************** * * svcid.h * * The FreeType CID font services (specification). * * Copyright 2007-2018 by * <NAME> and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef SVCID_H_ #define SVCID_H_ #include FT_INTERNAL_SERVICE_H FT_BEGIN_HEADER #define FT_SERVICE_ID_CID "CID" typedef FT_Error (*FT_CID_GetRegistryOrderingSupplementFunc)( FT_Face face, const char* *registry, const char* *ordering, FT_Int *supplement ); typedef FT_Error (*FT_CID_GetIsInternallyCIDKeyedFunc)( FT_Face face, FT_Bool *is_cid ); typedef FT_Error (*FT_CID_GetCIDFromGlyphIndexFunc)( FT_Face face, FT_UInt glyph_index, FT_UInt *cid ); FT_DEFINE_SERVICE( CID ) { FT_CID_GetRegistryOrderingSupplementFunc get_ros; FT_CID_GetIsInternallyCIDKeyedFunc get_is_cid; FT_CID_GetCIDFromGlyphIndexFunc get_cid_from_glyph_index; }; #define FT_DEFINE_SERVICE_CIDREC( class_, \ get_ros_, \ get_is_cid_, \ get_cid_from_glyph_index_ ) \ static const FT_Service_CIDRec class_ = \ { \ get_ros_, get_is_cid_, get_cid_from_glyph_index_ \ }; /* */ FT_END_HEADER #endif /* SVCID_H_ */ /* END */
nikramakrishnan/freetype2
src/autofit/afglobal.c
/**************************************************************************** * * afglobal.c * * Auto-fitter routines to compute global hinting values (body). * * Copyright 2003-2018 by * <NAME>, <NAME>, and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include "afglobal.h" #include "afranges.h" #include "afshaper.h" #include FT_INTERNAL_DEBUG_H /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT trace_afglobal /* get writing system specific header files */ #undef WRITING_SYSTEM #define WRITING_SYSTEM( ws, WS ) /* empty */ #include "afwrtsys.h" #include "aferrors.h" #undef SCRIPT #define SCRIPT( s, S, d, h, H, ss ) \ AF_DEFINE_SCRIPT_CLASS( \ af_ ## s ## _script_class, \ AF_SCRIPT_ ## S, \ af_ ## s ## _uniranges, \ af_ ## s ## _nonbase_uniranges, \ AF_ ## H, \ ss ) #include "afscript.h" #undef STYLE #define STYLE( s, S, d, ws, sc, ss, c ) \ AF_DEFINE_STYLE_CLASS( \ af_ ## s ## _style_class, \ AF_STYLE_ ## S, \ ws, \ sc, \ ss, \ c ) #include "afstyles.h" #undef WRITING_SYSTEM #define WRITING_SYSTEM( ws, WS ) \ &af_ ## ws ## _writing_system_class, FT_LOCAL_ARRAY_DEF( AF_WritingSystemClass ) af_writing_system_classes[] = { #include "afwrtsys.h" NULL /* do not remove */ }; #undef SCRIPT #define SCRIPT( s, S, d, h, H, ss ) \ &af_ ## s ## _script_class, FT_LOCAL_ARRAY_DEF( AF_ScriptClass ) af_script_classes[] = { #include "afscript.h" NULL /* do not remove */ }; #undef STYLE #define STYLE( s, S, d, ws, sc, ss, c ) \ &af_ ## s ## _style_class, FT_LOCAL_ARRAY_DEF( AF_StyleClass ) af_style_classes[] = { #include "afstyles.h" NULL /* do not remove */ }; #ifdef FT_DEBUG_LEVEL_TRACE #undef STYLE #define STYLE( s, S, d, ws, sc, ss, c ) #s, FT_LOCAL_ARRAY_DEF( char* ) af_style_names[] = { #include "afstyles.h" }; #endif /* FT_DEBUG_LEVEL_TRACE */ /* Compute the style index of each glyph within a given face. */ static FT_Error af_face_globals_compute_style_coverage( AF_FaceGlobals globals ) { FT_Error error; FT_Face face = globals->face; FT_CharMap old_charmap = face->charmap; FT_UShort* gstyles = globals->glyph_styles; FT_UInt ss; FT_UInt i; FT_UInt dflt = ~0U; /* a non-valid value */ /* the value AF_STYLE_UNASSIGNED means `uncovered glyph' */ for ( i = 0; i < (FT_UInt)globals->glyph_count; i++ ) gstyles[i] = AF_STYLE_UNASSIGNED; error = FT_Select_Charmap( face, FT_ENCODING_UNICODE ); if ( error ) { /* * Ignore this error; we simply use the fallback style. * XXX: Shouldn't we rather disable hinting? */ error = FT_Err_Ok; goto Exit; } /* scan each style in a Unicode charmap */ for ( ss = 0; af_style_classes[ss]; ss++ ) { AF_StyleClass style_class = af_style_classes[ss]; AF_ScriptClass script_class = af_script_classes[style_class->script]; AF_Script_UniRange range; if ( !script_class->script_uni_ranges ) continue; /* * Scan all Unicode points in the range and set the corresponding * glyph style index. */ if ( style_class->coverage == AF_COVERAGE_DEFAULT ) { if ( (FT_UInt)style_class->script == globals->module->default_script ) dflt = ss; for ( range = script_class->script_uni_ranges; range->first != 0; range++ ) { FT_ULong charcode = range->first; FT_UInt gindex; gindex = FT_Get_Char_Index( face, charcode ); if ( gindex != 0 && gindex < (FT_ULong)globals->glyph_count && ( gstyles[gindex] & AF_STYLE_MASK ) == AF_STYLE_UNASSIGNED ) gstyles[gindex] = (FT_UShort)ss; for (;;) { charcode = FT_Get_Next_Char( face, charcode, &gindex ); if ( gindex == 0 || charcode > range->last ) break; if ( gindex < (FT_ULong)globals->glyph_count && ( gstyles[gindex] & AF_STYLE_MASK ) == AF_STYLE_UNASSIGNED ) gstyles[gindex] = (FT_UShort)ss; } } /* do the same for the script's non-base characters */ for ( range = script_class->script_uni_nonbase_ranges; range->first != 0; range++ ) { FT_ULong charcode = range->first; FT_UInt gindex; gindex = FT_Get_Char_Index( face, charcode ); if ( gindex != 0 && gindex < (FT_ULong)globals->glyph_count && ( gstyles[gindex] & AF_STYLE_MASK ) == (FT_UShort)ss ) gstyles[gindex] |= AF_NONBASE; for (;;) { charcode = FT_Get_Next_Char( face, charcode, &gindex ); if ( gindex == 0 || charcode > range->last ) break; if ( gindex < (FT_ULong)globals->glyph_count && ( gstyles[gindex] & AF_STYLE_MASK ) == (FT_UShort)ss ) gstyles[gindex] |= AF_NONBASE; } } } else { /* get glyphs not directly addressable by cmap */ af_shaper_get_coverage( globals, style_class, gstyles, 0 ); } } /* handle the remaining default OpenType features ... */ for ( ss = 0; af_style_classes[ss]; ss++ ) { AF_StyleClass style_class = af_style_classes[ss]; if ( style_class->coverage == AF_COVERAGE_DEFAULT ) af_shaper_get_coverage( globals, style_class, gstyles, 0 ); } /* ... and finally the default OpenType features of the default script */ af_shaper_get_coverage( globals, af_style_classes[dflt], gstyles, 1 ); /* mark ASCII digits */ for ( i = 0x30; i <= 0x39; i++ ) { FT_UInt gindex = FT_Get_Char_Index( face, i ); if ( gindex != 0 && gindex < (FT_ULong)globals->glyph_count ) gstyles[gindex] |= AF_DIGIT; } Exit: /* * By default, all uncovered glyphs are set to the fallback style. * XXX: Shouldn't we disable hinting or do something similar? */ if ( globals->module->fallback_style != AF_STYLE_UNASSIGNED ) { FT_Long nn; for ( nn = 0; nn < globals->glyph_count; nn++ ) { if ( ( gstyles[nn] & AF_STYLE_MASK ) == AF_STYLE_UNASSIGNED ) { gstyles[nn] &= ~AF_STYLE_MASK; gstyles[nn] |= globals->module->fallback_style; } } } #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( "\n" "style coverage\n" "==============\n" "\n" )); for ( ss = 0; af_style_classes[ss]; ss++ ) { AF_StyleClass style_class = af_style_classes[ss]; FT_UInt count = 0; FT_Long idx; FT_TRACE4(( "%s:\n", af_style_names[style_class->style] )); for ( idx = 0; idx < globals->glyph_count; idx++ ) { if ( ( gstyles[idx] & AF_STYLE_MASK ) == style_class->style ) { if ( !( count % 10 ) ) FT_TRACE4(( " " )); FT_TRACE4(( " %d", idx )); count++; if ( !( count % 10 ) ) FT_TRACE4(( "\n" )); } } if ( !count ) FT_TRACE4(( " (none)\n" )); if ( count % 10 ) FT_TRACE4(( "\n" )); } #endif /* FT_DEBUG_LEVEL_TRACE */ FT_Set_Charmap( face, old_charmap ); return error; } FT_LOCAL_DEF( FT_Error ) af_face_globals_new( FT_Face face, AF_FaceGlobals *aglobals, AF_Module module ) { FT_Error error; FT_Memory memory; AF_FaceGlobals globals = NULL; memory = face->memory; /* we allocate an AF_FaceGlobals structure together */ /* with the glyph_styles array */ if ( FT_ALLOC( globals, sizeof ( *globals ) + (FT_ULong)face->num_glyphs * sizeof ( FT_UShort ) ) ) goto Exit; globals->face = face; globals->glyph_count = face->num_glyphs; /* right after the globals structure come the glyph styles */ globals->glyph_styles = (FT_UShort*)( globals + 1 ); globals->module = module; globals->stem_darkening_for_ppem = 0; globals->darken_x = 0; globals->darken_y = 0; globals->standard_vertical_width = 0; globals->standard_horizontal_width = 0; globals->scale_down_factor = 0; #ifdef FT_CONFIG_OPTION_USE_HARFBUZZ globals->hb_font = hb_ft_font_create( face, NULL ); globals->hb_buf = hb_buffer_create(); #endif error = af_face_globals_compute_style_coverage( globals ); if ( error ) { af_face_globals_free( globals ); globals = NULL; } else globals->increase_x_height = AF_PROP_INCREASE_X_HEIGHT_MAX; Exit: *aglobals = globals; return error; } FT_LOCAL_DEF( void ) af_face_globals_free( AF_FaceGlobals globals ) { if ( globals ) { FT_Memory memory = globals->face->memory; FT_UInt nn; for ( nn = 0; nn < AF_STYLE_MAX; nn++ ) { if ( globals->metrics[nn] ) { AF_StyleClass style_class = af_style_classes[nn]; AF_WritingSystemClass writing_system_class = af_writing_system_classes[style_class->writing_system]; if ( writing_system_class->style_metrics_done ) writing_system_class->style_metrics_done( globals->metrics[nn] ); FT_FREE( globals->metrics[nn] ); } } #ifdef FT_CONFIG_OPTION_USE_HARFBUZZ hb_font_destroy( globals->hb_font ); hb_buffer_destroy( globals->hb_buf ); #endif /* no need to free `globals->glyph_styles'; */ /* it is part of the `globals' array */ FT_FREE( globals ); } } FT_LOCAL_DEF( FT_Error ) af_face_globals_get_metrics( AF_FaceGlobals globals, FT_UInt gindex, FT_UInt options, AF_StyleMetrics *ametrics ) { AF_StyleMetrics metrics = NULL; AF_Style style = (AF_Style)options; AF_WritingSystemClass writing_system_class; AF_StyleClass style_class; FT_Error error = FT_Err_Ok; if ( gindex >= (FT_ULong)globals->glyph_count ) { error = FT_THROW( Invalid_Argument ); goto Exit; } /* if we have a forced style (via `options'), use it, */ /* otherwise look into `glyph_styles' array */ if ( style == AF_STYLE_NONE_DFLT || style + 1 >= AF_STYLE_MAX ) style = (AF_Style)( globals->glyph_styles[gindex] & AF_STYLE_UNASSIGNED ); style_class = af_style_classes[style]; writing_system_class = af_writing_system_classes [style_class->writing_system]; metrics = globals->metrics[style]; if ( !metrics ) { /* create the global metrics object if necessary */ FT_Memory memory = globals->face->memory; if ( FT_ALLOC( metrics, writing_system_class->style_metrics_size ) ) goto Exit; metrics->style_class = style_class; metrics->globals = globals; if ( writing_system_class->style_metrics_init ) { error = writing_system_class->style_metrics_init( metrics, globals->face ); if ( error ) { if ( writing_system_class->style_metrics_done ) writing_system_class->style_metrics_done( metrics ); FT_FREE( metrics ); goto Exit; } } globals->metrics[style] = metrics; } Exit: *ametrics = metrics; return error; } FT_LOCAL_DEF( FT_Bool ) af_face_globals_is_digit( AF_FaceGlobals globals, FT_UInt gindex ) { if ( gindex < (FT_ULong)globals->glyph_count ) return (FT_Bool)( globals->glyph_styles[gindex] & AF_DIGIT ); return (FT_Bool)0; } /* END */
nikramakrishnan/freetype2
src/autofit/afmodule.c
<filename>src/autofit/afmodule.c /**************************************************************************** * * afmodule.c * * Auto-fitter module implementation (body). * * Copyright 2003-2018 by * <NAME>, <NAME>, and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include "afglobal.h" #include "afmodule.h" #include "afloader.h" #include "aferrors.h" #ifdef FT_DEBUG_AUTOFIT #ifndef FT_MAKE_OPTION_SINGLE_OBJECT #ifdef __cplusplus extern "C" { #endif extern void af_glyph_hints_dump_segments( AF_GlyphHints hints, FT_Bool to_stdout ); extern void af_glyph_hints_dump_points( AF_GlyphHints hints, FT_Bool to_stdout ); extern void af_glyph_hints_dump_edges( AF_GlyphHints hints, FT_Bool to_stdout ); #ifdef __cplusplus } #endif #endif int _af_debug_disable_horz_hints; int _af_debug_disable_vert_hints; int _af_debug_disable_blue_hints; /* we use a global object instead of a local one for debugging */ AF_GlyphHintsRec _af_debug_hints_rec[1]; void* _af_debug_hints = _af_debug_hints_rec; #endif #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_DEBUG_H #include FT_DRIVER_H #include FT_SERVICE_PROPERTIES_H /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT trace_afmodule static FT_Error af_property_get_face_globals( FT_Face face, AF_FaceGlobals* aglobals, AF_Module module ) { FT_Error error = FT_Err_Ok; AF_FaceGlobals globals; if ( !face ) return FT_THROW( Invalid_Face_Handle ); globals = (AF_FaceGlobals)face->autohint.data; if ( !globals ) { /* trigger computation of the global style data */ /* in case it hasn't been done yet */ error = af_face_globals_new( face, &globals, module ); if ( !error ) { face->autohint.data = (FT_Pointer)globals; face->autohint.finalizer = (FT_Generic_Finalizer)af_face_globals_free; } } if ( !error ) *aglobals = globals; return error; } static FT_Error af_property_set( FT_Module ft_module, const char* property_name, const void* value, FT_Bool value_is_string ) { FT_Error error = FT_Err_Ok; AF_Module module = (AF_Module)ft_module; #ifndef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES FT_UNUSED( value_is_string ); #endif if ( !ft_strcmp( property_name, "fallback-script" ) ) { FT_UInt* fallback_script; FT_UInt ss; #ifdef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES if ( value_is_string ) return FT_THROW( Invalid_Argument ); #endif fallback_script = (FT_UInt*)value; /* We translate the fallback script to a fallback style that uses */ /* `fallback-script' as its script and `AF_COVERAGE_NONE' as its */ /* coverage value. */ for ( ss = 0; af_style_classes[ss]; ss++ ) { AF_StyleClass style_class = af_style_classes[ss]; if ( (FT_UInt)style_class->script == *fallback_script && style_class->coverage == AF_COVERAGE_DEFAULT ) { module->fallback_style = ss; break; } } if ( !af_style_classes[ss] ) { FT_TRACE0(( "af_property_set: Invalid value %d for property `%s'\n", fallback_script, property_name )); return FT_THROW( Invalid_Argument ); } return error; } else if ( !ft_strcmp( property_name, "default-script" ) ) { FT_UInt* default_script; #ifdef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES if ( value_is_string ) return FT_THROW( Invalid_Argument ); #endif default_script = (FT_UInt*)value; module->default_script = *default_script; return error; } else if ( !ft_strcmp( property_name, "increase-x-height" ) ) { FT_Prop_IncreaseXHeight* prop; AF_FaceGlobals globals; #ifdef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES if ( value_is_string ) return FT_THROW( Invalid_Argument ); #endif prop = (FT_Prop_IncreaseXHeight*)value; error = af_property_get_face_globals( prop->face, &globals, module ); if ( !error ) globals->increase_x_height = prop->limit; return error; } #ifdef AF_CONFIG_OPTION_USE_WARPER else if ( !ft_strcmp( property_name, "warping" ) ) { #ifdef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES if ( value_is_string ) { const char* s = (const char*)value; long w = ft_strtol( s, NULL, 10 ); if ( w == 0 ) module->warping = 0; else if ( w == 1 ) module->warping = 1; else return FT_THROW( Invalid_Argument ); } else #endif { FT_Bool* warping = (FT_Bool*)value; module->warping = *warping; } return error; } #endif /* AF_CONFIG_OPTION_USE_WARPER */ else if ( !ft_strcmp( property_name, "darkening-parameters" ) ) { FT_Int* darken_params; FT_Int x1, y1, x2, y2, x3, y3, x4, y4; #ifdef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES FT_Int dp[8]; if ( value_is_string ) { const char* s = (const char*)value; char* ep; int i; /* eight comma-separated numbers */ for ( i = 0; i < 7; i++ ) { dp[i] = (FT_Int)ft_strtol( s, &ep, 10 ); if ( *ep != ',' || s == ep ) return FT_THROW( Invalid_Argument ); s = ep + 1; } dp[7] = (FT_Int)ft_strtol( s, &ep, 10 ); if ( !( *ep == '\0' || *ep == ' ' ) || s == ep ) return FT_THROW( Invalid_Argument ); darken_params = dp; } else #endif darken_params = (FT_Int*)value; x1 = darken_params[0]; y1 = darken_params[1]; x2 = darken_params[2]; y2 = darken_params[3]; x3 = darken_params[4]; y3 = darken_params[5]; x4 = darken_params[6]; y4 = darken_params[7]; if ( x1 < 0 || x2 < 0 || x3 < 0 || x4 < 0 || y1 < 0 || y2 < 0 || y3 < 0 || y4 < 0 || x1 > x2 || x2 > x3 || x3 > x4 || y1 > 500 || y2 > 500 || y3 > 500 || y4 > 500 ) return FT_THROW( Invalid_Argument ); module->darken_params[0] = x1; module->darken_params[1] = y1; module->darken_params[2] = x2; module->darken_params[3] = y2; module->darken_params[4] = x3; module->darken_params[5] = y3; module->darken_params[6] = x4; module->darken_params[7] = y4; return error; } else if ( !ft_strcmp( property_name, "no-stem-darkening" ) ) { #ifdef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES if ( value_is_string ) { const char* s = (const char*)value; long nsd = ft_strtol( s, NULL, 10 ); if ( !nsd ) module->no_stem_darkening = FALSE; else module->no_stem_darkening = TRUE; } else #endif { FT_Bool* no_stem_darkening = (FT_Bool*)value; module->no_stem_darkening = *no_stem_darkening; } return error; } FT_TRACE0(( "af_property_set: missing property `%s'\n", property_name )); return FT_THROW( Missing_Property ); } static FT_Error af_property_get( FT_Module ft_module, const char* property_name, void* value ) { FT_Error error = FT_Err_Ok; AF_Module module = (AF_Module)ft_module; FT_UInt fallback_style = module->fallback_style; FT_UInt default_script = module->default_script; #ifdef AF_CONFIG_OPTION_USE_WARPER FT_Bool warping = module->warping; #endif if ( !ft_strcmp( property_name, "glyph-to-script-map" ) ) { FT_Prop_GlyphToScriptMap* prop = (FT_Prop_GlyphToScriptMap*)value; AF_FaceGlobals globals; error = af_property_get_face_globals( prop->face, &globals, module ); if ( !error ) prop->map = globals->glyph_styles; return error; } else if ( !ft_strcmp( property_name, "fallback-script" ) ) { FT_UInt* val = (FT_UInt*)value; AF_StyleClass style_class = af_style_classes[fallback_style]; *val = style_class->script; return error; } else if ( !ft_strcmp( property_name, "default-script" ) ) { FT_UInt* val = (FT_UInt*)value; *val = default_script; return error; } else if ( !ft_strcmp( property_name, "increase-x-height" ) ) { FT_Prop_IncreaseXHeight* prop = (FT_Prop_IncreaseXHeight*)value; AF_FaceGlobals globals; error = af_property_get_face_globals( prop->face, &globals, module ); if ( !error ) prop->limit = globals->increase_x_height; return error; } #ifdef AF_CONFIG_OPTION_USE_WARPER else if ( !ft_strcmp( property_name, "warping" ) ) { FT_Bool* val = (FT_Bool*)value; *val = warping; return error; } #endif /* AF_CONFIG_OPTION_USE_WARPER */ else if ( !ft_strcmp( property_name, "darkening-parameters" ) ) { FT_Int* darken_params = module->darken_params; FT_Int* val = (FT_Int*)value; val[0] = darken_params[0]; val[1] = darken_params[1]; val[2] = darken_params[2]; val[3] = darken_params[3]; val[4] = darken_params[4]; val[5] = darken_params[5]; val[6] = darken_params[6]; val[7] = darken_params[7]; return error; } else if ( !ft_strcmp( property_name, "no-stem-darkening" ) ) { FT_Bool no_stem_darkening = module->no_stem_darkening; FT_Bool* val = (FT_Bool*)value; *val = no_stem_darkening; return error; } FT_TRACE0(( "af_property_get: missing property `%s'\n", property_name )); return FT_THROW( Missing_Property ); } FT_DEFINE_SERVICE_PROPERTIESREC( af_service_properties, (FT_Properties_SetFunc)af_property_set, /* set_property */ (FT_Properties_GetFunc)af_property_get ) /* get_property */ FT_DEFINE_SERVICEDESCREC1( af_services, FT_SERVICE_ID_PROPERTIES, &af_service_properties ) FT_CALLBACK_DEF( FT_Module_Interface ) af_get_interface( FT_Module module, const char* module_interface ) { FT_UNUSED( module ); return ft_service_list_lookup( af_services, module_interface ); } FT_CALLBACK_DEF( FT_Error ) af_autofitter_init( FT_Module ft_module ) /* AF_Module */ { AF_Module module = (AF_Module)ft_module; module->fallback_style = AF_STYLE_FALLBACK; module->default_script = AF_SCRIPT_DEFAULT; #ifdef AF_CONFIG_OPTION_USE_WARPER module->warping = 0; #endif module->no_stem_darkening = TRUE; module->darken_params[0] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1; module->darken_params[1] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1; module->darken_params[2] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2; module->darken_params[3] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2; module->darken_params[4] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3; module->darken_params[5] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3; module->darken_params[6] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4; module->darken_params[7] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4; return FT_Err_Ok; } FT_CALLBACK_DEF( void ) af_autofitter_done( FT_Module ft_module ) /* AF_Module */ { FT_UNUSED( ft_module ); #ifdef FT_DEBUG_AUTOFIT if ( _af_debug_hints_rec->memory ) af_glyph_hints_done( _af_debug_hints_rec ); #endif } FT_CALLBACK_DEF( FT_Error ) af_autofitter_load_glyph( AF_Module module, FT_GlyphSlot slot, FT_Size size, FT_UInt glyph_index, FT_Int32 load_flags ) { FT_Error error = FT_Err_Ok; FT_Memory memory = module->root.library->memory; #ifdef FT_DEBUG_AUTOFIT /* in debug mode, we use a global object that survives this routine */ AF_GlyphHints hints = _af_debug_hints_rec; AF_LoaderRec loader[1]; FT_UNUSED( size ); if ( hints->memory ) af_glyph_hints_done( hints ); af_glyph_hints_init( hints, memory ); af_loader_init( loader, hints ); error = af_loader_load_glyph( loader, module, slot->face, glyph_index, load_flags ); #ifdef FT_DEBUG_LEVEL_TRACE if ( ft_trace_levels[FT_COMPONENT] ) { #endif af_glyph_hints_dump_points( hints, 0 ); af_glyph_hints_dump_segments( hints, 0 ); af_glyph_hints_dump_edges( hints, 0 ); #ifdef FT_DEBUG_LEVEL_TRACE } #endif af_loader_done( loader ); return error; #else /* !FT_DEBUG_AUTOFIT */ AF_GlyphHintsRec hints[1]; AF_LoaderRec loader[1]; FT_UNUSED( size ); af_glyph_hints_init( hints, memory ); af_loader_init( loader, hints ); error = af_loader_load_glyph( loader, module, slot->face, glyph_index, load_flags ); af_loader_done( loader ); af_glyph_hints_done( hints ); return error; #endif /* !FT_DEBUG_AUTOFIT */ } FT_DEFINE_AUTOHINTER_INTERFACE( af_autofitter_interface, NULL, /* reset_face */ NULL, /* get_global_hints */ NULL, /* done_global_hints */ (FT_AutoHinter_GlyphLoadFunc)af_autofitter_load_glyph ) /* load_glyph */ FT_DEFINE_MODULE( autofit_module_class, FT_MODULE_HINTER, sizeof ( AF_ModuleRec ), "autofitter", 0x10000L, /* version 1.0 of the autofitter */ 0x20000L, /* requires FreeType 2.0 or above */ (const void*)&af_autofitter_interface, (FT_Module_Constructor)af_autofitter_init, /* module_init */ (FT_Module_Destructor) af_autofitter_done, /* module_done */ (FT_Module_Requester) af_get_interface /* get_interface */ ) /* END */
nikramakrishnan/freetype2
src/gxvalid/gxvmorx2.c
/**************************************************************************** * * gxvmorx2.c * * TrueTypeGX/AAT morx table validation * body for type2 (Ligature Substitution) subtable. * * Copyright 2005-2018 by * <NAME>, <NAME>, Red Hat K.K., * <NAME>, <NAME>, and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /**************************************************************************** * * gxvalid is derived from both gxlayout module and otvalid module. * Development of gxlayout is supported by the Information-technology * Promotion Agency(IPA), Japan. * */ #include "gxvmorx.h" /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmorx typedef struct GXV_morx_subtable_type2_StateOptRec_ { FT_ULong ligActionTable; FT_ULong componentTable; FT_ULong ligatureTable; FT_ULong ligActionTable_length; FT_ULong componentTable_length; FT_ULong ligatureTable_length; } GXV_morx_subtable_type2_StateOptRec, *GXV_morx_subtable_type2_StateOptRecData; #define GXV_MORX_SUBTABLE_TYPE2_HEADER_SIZE \ ( GXV_XSTATETABLE_HEADER_SIZE + 4 + 4 + 4 ) static void gxv_morx_subtable_type2_opttable_load( FT_Bytes table, FT_Bytes limit, GXV_Validator gxvalid ) { FT_Bytes p = table; GXV_morx_subtable_type2_StateOptRecData optdata = (GXV_morx_subtable_type2_StateOptRecData)gxvalid->xstatetable.optdata; GXV_LIMIT_CHECK( 4 + 4 + 4 ); optdata->ligActionTable = FT_NEXT_ULONG( p ); optdata->componentTable = FT_NEXT_ULONG( p ); optdata->ligatureTable = FT_NEXT_ULONG( p ); GXV_TRACE(( "offset to ligActionTable=0x%08x\n", optdata->ligActionTable )); GXV_TRACE(( "offset to componentTable=0x%08x\n", optdata->componentTable )); GXV_TRACE(( "offset to ligatureTable=0x%08x\n", optdata->ligatureTable )); } static void gxv_morx_subtable_type2_subtable_setup( FT_ULong table_size, FT_ULong classTable, FT_ULong stateArray, FT_ULong entryTable, FT_ULong* classTable_length_p, FT_ULong* stateArray_length_p, FT_ULong* entryTable_length_p, GXV_Validator gxvalid ) { FT_ULong o[6]; FT_ULong* l[6]; FT_ULong buff[7]; GXV_morx_subtable_type2_StateOptRecData optdata = (GXV_morx_subtable_type2_StateOptRecData)gxvalid->xstatetable.optdata; GXV_NAME_ENTER( "subtable boundaries setup" ); o[0] = classTable; o[1] = stateArray; o[2] = entryTable; o[3] = optdata->ligActionTable; o[4] = optdata->componentTable; o[5] = optdata->ligatureTable; l[0] = classTable_length_p; l[1] = stateArray_length_p; l[2] = entryTable_length_p; l[3] = &(optdata->ligActionTable_length); l[4] = &(optdata->componentTable_length); l[5] = &(optdata->ligatureTable_length); gxv_set_length_by_ulong_offset( o, l, buff, 6, table_size, gxvalid ); GXV_TRACE(( "classTable: offset=0x%08x length=0x%08x\n", classTable, *classTable_length_p )); GXV_TRACE(( "stateArray: offset=0x%08x length=0x%08x\n", stateArray, *stateArray_length_p )); GXV_TRACE(( "entryTable: offset=0x%08x length=0x%08x\n", entryTable, *entryTable_length_p )); GXV_TRACE(( "ligActionTable: offset=0x%08x length=0x%08x\n", optdata->ligActionTable, optdata->ligActionTable_length )); GXV_TRACE(( "componentTable: offset=0x%08x length=0x%08x\n", optdata->componentTable, optdata->componentTable_length )); GXV_TRACE(( "ligatureTable: offset=0x%08x length=0x%08x\n", optdata->ligatureTable, optdata->ligatureTable_length )); GXV_EXIT; } #define GXV_MORX_LIGACTION_ENTRY_SIZE 4 static void gxv_morx_subtable_type2_ligActionIndex_validate( FT_Bytes table, FT_UShort ligActionIndex, GXV_Validator gxvalid ) { /* access ligActionTable */ GXV_morx_subtable_type2_StateOptRecData optdata = (GXV_morx_subtable_type2_StateOptRecData)gxvalid->xstatetable.optdata; FT_Bytes lat_base = table + optdata->ligActionTable; FT_Bytes p = lat_base + ligActionIndex * GXV_MORX_LIGACTION_ENTRY_SIZE; FT_Bytes lat_limit = lat_base + optdata->ligActionTable; if ( p < lat_base ) { GXV_TRACE(( "p < lat_base (%d byte rewind)\n", lat_base - p )); FT_INVALID_OFFSET; } else if ( lat_limit < p ) { GXV_TRACE(( "lat_limit < p (%d byte overrun)\n", p - lat_limit )); FT_INVALID_OFFSET; } { /* validate entry in ligActionTable */ FT_ULong lig_action; #ifdef GXV_LOAD_UNUSED_VARS FT_UShort last; FT_UShort store; #endif FT_ULong offset; FT_Long gid_limit; lig_action = FT_NEXT_ULONG( p ); #ifdef GXV_LOAD_UNUSED_VARS last = (FT_UShort)( ( lig_action >> 31 ) & 1 ); store = (FT_UShort)( ( lig_action >> 30 ) & 1 ); #endif offset = lig_action & 0x3FFFFFFFUL; /* this offset is 30-bit signed value to add to GID */ /* it is different from the location offset in mort */ if ( ( offset & 0x3FFF0000UL ) == 0x3FFF0000UL ) { /* negative offset */ gid_limit = gxvalid->face->num_glyphs - (FT_Long)( offset & 0x0000FFFFUL ); if ( gid_limit > 0 ) return; GXV_TRACE(( "ligature action table includes" " too negative offset moving all GID" " below defined range: 0x%04x\n", offset & 0xFFFFU )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); } else if ( ( offset & 0x3FFF0000UL ) == 0x00000000UL ) { /* positive offset */ if ( (FT_Long)offset < gxvalid->face->num_glyphs ) return; GXV_TRACE(( "ligature action table includes" " too large offset moving all GID" " over defined range: 0x%04x\n", offset & 0xFFFFU )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); } GXV_TRACE(( "ligature action table includes" " invalid offset to add to 16-bit GID:" " 0x%08x\n", offset )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); } } static void gxv_morx_subtable_type2_entry_validate( FT_UShort state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator gxvalid ) { #ifdef GXV_LOAD_UNUSED_VARS FT_UShort setComponent; FT_UShort dontAdvance; FT_UShort performAction; #endif FT_UShort reserved; FT_UShort ligActionIndex; FT_UNUSED( state ); FT_UNUSED( limit ); #ifdef GXV_LOAD_UNUSED_VARS setComponent = (FT_UShort)( ( flags >> 15 ) & 1 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); performAction = (FT_UShort)( ( flags >> 13 ) & 1 ); #endif reserved = (FT_UShort)( flags & 0x1FFF ); ligActionIndex = glyphOffset_p->u; if ( reserved > 0 ) GXV_TRACE(( " reserved 14bit is non-zero\n" )); if ( 0 < ligActionIndex ) gxv_morx_subtable_type2_ligActionIndex_validate( table, ligActionIndex, gxvalid ); } static void gxv_morx_subtable_type2_ligatureTable_validate( FT_Bytes table, GXV_Validator gxvalid ) { GXV_morx_subtable_type2_StateOptRecData optdata = (GXV_morx_subtable_type2_StateOptRecData)gxvalid->xstatetable.optdata; FT_Bytes p = table + optdata->ligatureTable; FT_Bytes limit = table + optdata->ligatureTable + optdata->ligatureTable_length; GXV_NAME_ENTER( "morx chain subtable type2 - substitutionTable" ); if ( 0 != optdata->ligatureTable ) { /* Apple does not give specification of ligatureTable format */ while ( p < limit ) { FT_UShort lig_gid; GXV_LIMIT_CHECK( 2 ); lig_gid = FT_NEXT_USHORT( p ); if ( lig_gid < gxvalid->face->num_glyphs ) GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } } GXV_EXIT; } FT_LOCAL_DEF( void ) gxv_morx_subtable_type2_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator gxvalid ) { FT_Bytes p = table; GXV_morx_subtable_type2_StateOptRec lig_rec; GXV_NAME_ENTER( "morx chain subtable type2 (Ligature Substitution)" ); GXV_LIMIT_CHECK( GXV_MORX_SUBTABLE_TYPE2_HEADER_SIZE ); gxvalid->xstatetable.optdata = &lig_rec; gxvalid->xstatetable.optdata_load_func = gxv_morx_subtable_type2_opttable_load; gxvalid->xstatetable.subtable_setup_func = gxv_morx_subtable_type2_subtable_setup; gxvalid->xstatetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_USHORT; gxvalid->xstatetable.entry_validate_func = gxv_morx_subtable_type2_entry_validate; gxv_XStateTable_validate( p, limit, gxvalid ); #if 0 p += gxvalid->subtable_length; #endif gxv_morx_subtable_type2_ligatureTable_validate( table, gxvalid ); GXV_EXIT; } /* END */
nikramakrishnan/freetype2
src/gxvalid/gxvtrak.c
<reponame>nikramakrishnan/freetype2<filename>src/gxvalid/gxvtrak.c /**************************************************************************** * * gxvtrak.c * * TrueTypeGX/AAT trak table validation (body). * * Copyright 2004-2018 by * <NAME>, <NAME>, Red Hat K.K., * <NAME>, <NAME>, and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /**************************************************************************** * * gxvalid is derived from both gxlayout module and otvalid module. * Development of gxlayout is supported by the Information-technology * Promotion Agency(IPA), Japan. * */ #include "gxvalid.h" #include "gxvcommn.h" /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvtrak /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Data and Types *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* * referred track table format specification: * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6trak.html * last update was 1996. * ---------------------------------------------- * [MINIMUM HEADER]: GXV_TRAK_SIZE_MIN * version (fixed: 32bit) = 0x00010000 * format (uint16: 16bit) = 0 is only defined (1996) * horizOffset (uint16: 16bit) * vertOffset (uint16: 16bit) * reserved (uint16: 16bit) = 0 * ---------------------------------------------- * [VARIABLE BODY]: * horizData * header ( 2 + 2 + 4 * trackTable + nTracks * ( 4 + 2 + 2 ) * sizeTable + nSizes * 4 ) * ---------------------------------------------- * vertData * header ( 2 + 2 + 4 * trackTable + nTracks * ( 4 + 2 + 2 ) * sizeTable + nSizes * 4 ) * ---------------------------------------------- */ typedef struct GXV_trak_DataRec_ { FT_UShort trackValueOffset_min; FT_UShort trackValueOffset_max; } GXV_trak_DataRec, *GXV_trak_Data; #define GXV_TRAK_DATA( FIELD ) GXV_TABLE_DATA( trak, FIELD ) /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** UTILITY FUNCTIONS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static void gxv_trak_trackTable_validate( FT_Bytes table, FT_Bytes limit, FT_UShort nTracks, GXV_Validator gxvalid ) { FT_Bytes p = table; FT_Fixed track, t; FT_UShort nameIndex; FT_UShort offset; FT_UShort i, j; GXV_NAME_ENTER( "trackTable" ); GXV_TRAK_DATA( trackValueOffset_min ) = 0xFFFFU; GXV_TRAK_DATA( trackValueOffset_max ) = 0x0000; GXV_LIMIT_CHECK( nTracks * ( 4 + 2 + 2 ) ); for ( i = 0; i < nTracks; i++ ) { p = table + i * ( 4 + 2 + 2 ); track = FT_NEXT_LONG( p ); nameIndex = FT_NEXT_USHORT( p ); offset = FT_NEXT_USHORT( p ); if ( offset < GXV_TRAK_DATA( trackValueOffset_min ) ) GXV_TRAK_DATA( trackValueOffset_min ) = offset; if ( offset > GXV_TRAK_DATA( trackValueOffset_max ) ) GXV_TRAK_DATA( trackValueOffset_max ) = offset; gxv_sfntName_validate( nameIndex, 256, 32767, gxvalid ); for ( j = i; j < nTracks; j++ ) { p = table + j * ( 4 + 2 + 2 ); t = FT_NEXT_LONG( p ); if ( t == track ) GXV_TRACE(( "duplicated entries found for track value 0x%x\n", track )); } } gxvalid->subtable_length = (FT_ULong)( p - table ); GXV_EXIT; } static void gxv_trak_trackData_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator gxvalid ) { FT_Bytes p = table; FT_UShort nTracks; FT_UShort nSizes; FT_ULong sizeTableOffset; GXV_ODTECT( 4, odtect ); GXV_ODTECT_INIT( odtect ); GXV_NAME_ENTER( "trackData" ); /* read the header of trackData */ GXV_LIMIT_CHECK( 2 + 2 + 4 ); nTracks = FT_NEXT_USHORT( p ); nSizes = FT_NEXT_USHORT( p ); sizeTableOffset = FT_NEXT_ULONG( p ); gxv_odtect_add_range( table, (FT_ULong)( p - table ), "trackData header", odtect ); /* validate trackTable */ gxv_trak_trackTable_validate( p, limit, nTracks, gxvalid ); gxv_odtect_add_range( p, gxvalid->subtable_length, "trackTable", odtect ); /* sizeTable is array of FT_Fixed, don't check contents */ p = gxvalid->root->base + sizeTableOffset; GXV_LIMIT_CHECK( nSizes * 4 ); gxv_odtect_add_range( p, nSizes * 4, "sizeTable", odtect ); /* validate trackValueOffet */ p = gxvalid->root->base + GXV_TRAK_DATA( trackValueOffset_min ); if ( limit - p < nTracks * nSizes * 2 ) GXV_TRACE(( "too short trackValue array\n" )); p = gxvalid->root->base + GXV_TRAK_DATA( trackValueOffset_max ); GXV_LIMIT_CHECK( nSizes * 2 ); gxv_odtect_add_range( gxvalid->root->base + GXV_TRAK_DATA( trackValueOffset_min ), GXV_TRAK_DATA( trackValueOffset_max ) - GXV_TRAK_DATA( trackValueOffset_min ) + nSizes * 2, "trackValue array", odtect ); gxv_odtect_validate( odtect, gxvalid ); GXV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** trak TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) gxv_trak_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { FT_Bytes p = table; FT_Bytes limit = 0; GXV_ValidatorRec gxvalidrec; GXV_Validator gxvalid = &gxvalidrec; GXV_trak_DataRec trakrec; GXV_trak_Data trak = &trakrec; FT_ULong version; FT_UShort format; FT_UShort horizOffset; FT_UShort vertOffset; FT_UShort reserved; GXV_ODTECT( 3, odtect ); GXV_ODTECT_INIT( odtect ); gxvalid->root = ftvalid; gxvalid->table_data = trak; gxvalid->face = face; limit = gxvalid->root->limit; FT_TRACE3(( "validating `trak' table\n" )); GXV_INIT; GXV_LIMIT_CHECK( 4 + 2 + 2 + 2 + 2 ); version = FT_NEXT_ULONG( p ); format = FT_NEXT_USHORT( p ); horizOffset = FT_NEXT_USHORT( p ); vertOffset = FT_NEXT_USHORT( p ); reserved = FT_NEXT_USHORT( p ); GXV_TRACE(( " (version = 0x%08x)\n", version )); GXV_TRACE(( " (format = 0x%04x)\n", format )); GXV_TRACE(( " (horizOffset = 0x%04x)\n", horizOffset )); GXV_TRACE(( " (vertOffset = 0x%04x)\n", vertOffset )); GXV_TRACE(( " (reserved = 0x%04x)\n", reserved )); /* Version 1.0 (always:1996) */ if ( version != 0x00010000UL ) FT_INVALID_FORMAT; /* format 0 (always:1996) */ if ( format != 0x0000 ) FT_INVALID_FORMAT; GXV_32BIT_ALIGNMENT_VALIDATE( horizOffset ); GXV_32BIT_ALIGNMENT_VALIDATE( vertOffset ); /* Reserved Fixed Value (always) */ if ( reserved != 0x0000 ) FT_INVALID_DATA; /* validate trackData */ if ( 0 < horizOffset ) { gxv_trak_trackData_validate( table + horizOffset, limit, gxvalid ); gxv_odtect_add_range( table + horizOffset, gxvalid->subtable_length, "horizJustData", odtect ); } if ( 0 < vertOffset ) { gxv_trak_trackData_validate( table + vertOffset, limit, gxvalid ); gxv_odtect_add_range( table + vertOffset, gxvalid->subtable_length, "vertJustData", odtect ); } gxv_odtect_validate( odtect, gxvalid ); FT_TRACE4(( "\n" )); } /* END */
nikramakrishnan/freetype2
include/freetype/ftmm.h
/**************************************************************************** * * ftmm.h * * FreeType Multiple Master font interface (specification). * * Copyright 1996-2018 by * <NAME>, <NAME>, and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef FTMM_H_ #define FTMM_H_ #include <ft2build.h> #include FT_TYPE1_TABLES_H FT_BEGIN_HEADER /************************************************************************** * * @section: * multiple_masters * * @title: * Multiple Masters * * @abstract: * How to manage Multiple Masters fonts. * * @description: * The following types and functions are used to manage Multiple * Master fonts, i.e., the selection of specific design instances by * setting design axis coordinates. * * Besides Adobe MM fonts, the interface supports Apple's TrueType GX * and OpenType variation fonts. Some of the routines only work with * Adobe MM fonts, others will work with all three types. They are * similar enough that a consistent interface makes sense. * */ /************************************************************************** * * @struct: * FT_MM_Axis * * @description: * A structure to model a given axis in design space for Multiple * Masters fonts. * * This structure can't be used for TrueType GX or OpenType variation * fonts. * * @fields: * name :: * The axis's name. * * minimum :: * The axis's minimum design coordinate. * * maximum :: * The axis's maximum design coordinate. */ typedef struct FT_MM_Axis_ { FT_String* name; FT_Long minimum; FT_Long maximum; } FT_MM_Axis; /************************************************************************** * * @struct: * FT_Multi_Master * * @description: * A structure to model the axes and space of a Multiple Masters * font. * * This structure can't be used for TrueType GX or OpenType variation * fonts. * * @fields: * num_axis :: * Number of axes. Cannot exceed~4. * * num_designs :: * Number of designs; should be normally 2^num_axis * even though the Type~1 specification strangely * allows for intermediate designs to be present. * This number cannot exceed~16. * * axis :: * A table of axis descriptors. */ typedef struct FT_Multi_Master_ { FT_UInt num_axis; FT_UInt num_designs; FT_MM_Axis axis[T1_MAX_MM_AXIS]; } FT_Multi_Master; /************************************************************************** * * @struct: * FT_Var_Axis * * @description: * A structure to model a given axis in design space for Multiple * Masters, TrueType GX, and OpenType variation fonts. * * @fields: * name :: * The axis's name. * Not always meaningful for TrueType GX or OpenType * variation fonts. * * minimum :: * The axis's minimum design coordinate. * * def :: * The axis's default design coordinate. * FreeType computes meaningful default values for Adobe * MM fonts. * * maximum :: * The axis's maximum design coordinate. * * tag :: * The axis's tag (the equivalent to `name' for TrueType * GX and OpenType variation fonts). FreeType provides * default values for Adobe MM fonts if possible. * * strid :: * The axis name entry in the font's `name' table. This * is another (and often better) version of the `name' * field for TrueType GX or OpenType variation fonts. Not * meaningful for Adobe MM fonts. * * @note: * The fields `minimum', `def', and `maximum' are 16.16 fractional * values for TrueType GX and OpenType variation fonts. For Adobe MM * fonts, the values are integers. */ typedef struct FT_Var_Axis_ { FT_String* name; FT_Fixed minimum; FT_Fixed def; FT_Fixed maximum; FT_ULong tag; FT_UInt strid; } FT_Var_Axis; /************************************************************************** * * @struct: * FT_Var_Named_Style * * @description: * A structure to model a named instance in a TrueType GX or OpenType * variation font. * * This structure can't be used for Adobe MM fonts. * * @fields: * coords :: * The design coordinates for this instance. * This is an array with one entry for each axis. * * strid :: * The entry in `name' table identifying this instance. * * psid :: * The entry in `name' table identifying a PostScript name * for this instance. Value 0xFFFF indicates a missing * entry. */ typedef struct FT_Var_Named_Style_ { FT_Fixed* coords; FT_UInt strid; FT_UInt psid; /* since 2.7.1 */ } FT_Var_Named_Style; /************************************************************************** * * @struct: * FT_MM_Var * * @description: * A structure to model the axes and space of an Adobe MM, TrueType * GX, or OpenType variation font. * * Some fields are specific to one format and not to the others. * * @fields: * num_axis :: * The number of axes. The maximum value is~4 for * Adobe MM fonts; no limit in TrueType GX or * OpenType variation fonts. * * num_designs :: * The number of designs; should be normally * 2^num_axis for Adobe MM fonts. Not meaningful * for TrueType GX or OpenType variation fonts * (where every glyph could have a different * number of designs). * * num_namedstyles :: * The number of named styles; a `named style' is * a tuple of design coordinates that has a string * ID (in the `name' table) associated with it. * The font can tell the user that, for example, * [Weight=1.5,Width=1.1] is `Bold'. Another name * for `named style' is `named instance'. * * For Adobe Multiple Masters fonts, this value is * always zero because the format does not support * named styles. * * axis :: * An axis descriptor table. * TrueType GX and OpenType variation fonts * contain slightly more data than Adobe MM fonts. * Memory management of this pointer is done * internally by FreeType. * * namedstyle :: * A named style (instance) table. * Only meaningful for TrueType GX and OpenType * variation fonts. Memory management of this * pointer is done internally by FreeType. */ typedef struct FT_MM_Var_ { FT_UInt num_axis; FT_UInt num_designs; FT_UInt num_namedstyles; FT_Var_Axis* axis; FT_Var_Named_Style* namedstyle; } FT_MM_Var; /************************************************************************** * * @function: * FT_Get_Multi_Master * * @description: * Retrieve a variation descriptor of a given Adobe MM font. * * This function can't be used with TrueType GX or OpenType variation * fonts. * * @input: * face :: * A handle to the source face. * * @output: * amaster :: * The Multiple Masters descriptor. * * @return: * FreeType error code. 0~means success. */ FT_EXPORT( FT_Error ) FT_Get_Multi_Master( FT_Face face, FT_Multi_Master *amaster ); /************************************************************************** * * @function: * FT_Get_MM_Var * * @description: * Retrieve a variation descriptor for a given font. * * This function works with all supported variation formats. * * @input: * face :: * A handle to the source face. * * @output: * amaster :: * The variation descriptor. * Allocates a data structure, which the user must * deallocate with a call to @FT_Done_MM_Var after use. * * @return: * FreeType error code. 0~means success. */ FT_EXPORT( FT_Error ) FT_Get_MM_Var( FT_Face face, FT_MM_Var* *amaster ); /************************************************************************** * * @function: * FT_Done_MM_Var * * @description: * Free the memory allocated by @FT_Get_MM_Var. * * @input: * library :: * A handle of the face's parent library object that was * used in the call to @FT_Get_MM_Var to create `amaster'. * * @return: * FreeType error code. 0~means success. */ FT_EXPORT( FT_Error ) FT_Done_MM_Var( FT_Library library, FT_MM_Var *amaster ); /************************************************************************** * * @function: * FT_Set_MM_Design_Coordinates * * @description: * For Adobe MM fonts, choose an interpolated font design through * design coordinates. * * This function can't be used with TrueType GX or OpenType variation * fonts. * * @inout: * face :: * A handle to the source face. * * @input: * num_coords :: * The number of available design coordinates. If it * is larger than the number of axes, ignore the excess * values. If it is smaller than the number of axes, * use default values for the remaining axes. * * coords :: * An array of design coordinates. * * @return: * FreeType error code. 0~means success. * * @note: * [Since 2.8.1] To reset all axes to the default values, call the * function with `num_coords' set to zero and `coords' set to NULL. * * [Since 2.9] If `num_coords' is larger than zero, this function * sets the @FT_FACE_FLAG_VARIATION bit in @FT_Face's `face_flags' * field (i.e., @FT_IS_VARIATION will return true). If `num_coords' * is zero, this bit flag gets unset. */ FT_EXPORT( FT_Error ) FT_Set_MM_Design_Coordinates( FT_Face face, FT_UInt num_coords, FT_Long* coords ); /************************************************************************** * * @function: * FT_Set_Var_Design_Coordinates * * @description: * Choose an interpolated font design through design coordinates. * * This function works with all supported variation formats. * * @inout: * face :: * A handle to the source face. * * @input: * num_coords :: * The number of available design coordinates. If it * is larger than the number of axes, ignore the excess * values. If it is smaller than the number of axes, * use default values for the remaining axes. * * coords :: * An array of design coordinates. * * @return: * FreeType error code. 0~means success. * * @note: * [Since 2.8.1] To reset all axes to the default values, call the * function with `num_coords' set to zero and `coords' set to NULL. * [Since 2.9] `Default values' means the currently selected named * instance (or the base font if no named instance is selected). * * [Since 2.9] If `num_coords' is larger than zero, this function * sets the @FT_FACE_FLAG_VARIATION bit in @FT_Face's `face_flags' * field (i.e., @FT_IS_VARIATION will return true). If `num_coords' * is zero, this bit flag gets unset. */ FT_EXPORT( FT_Error ) FT_Set_Var_Design_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /************************************************************************** * * @function: * FT_Get_Var_Design_Coordinates * * @description: * Get the design coordinates of the currently selected interpolated * font. * * This function works with all supported variation formats. * * @input: * face :: * A handle to the source face. * * num_coords :: * The number of design coordinates to retrieve. If it * is larger than the number of axes, set the excess * values to~0. * * @output: * coords :: * The design coordinates array. * * @return: * FreeType error code. 0~means success. * * @since: * 2.7.1 */ FT_EXPORT( FT_Error ) FT_Get_Var_Design_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /************************************************************************** * * @function: * FT_Set_MM_Blend_Coordinates * * @description: * Choose an interpolated font design through normalized blend * coordinates. * * This function works with all supported variation formats. * * @inout: * face :: * A handle to the source face. * * @input: * num_coords :: * The number of available design coordinates. If it * is larger than the number of axes, ignore the excess * values. If it is smaller than the number of axes, * use default values for the remaining axes. * * coords :: * The design coordinates array (each element must be * between 0 and 1.0 for Adobe MM fonts, and between * -1.0 and 1.0 for TrueType GX and OpenType variation * fonts). * * @return: * FreeType error code. 0~means success. * * @note: * [Since 2.8.1] To reset all axes to the default values, call the * function with `num_coords' set to zero and `coords' set to NULL. * [Since 2.9] `Default values' means the currently selected named * instance (or the base font if no named instance is selected). * * [Since 2.9] If `num_coords' is larger than zero, this function * sets the @FT_FACE_FLAG_VARIATION bit in @FT_Face's `face_flags' * field (i.e., @FT_IS_VARIATION will return true). If `num_coords' * is zero, this bit flag gets unset. */ FT_EXPORT( FT_Error ) FT_Set_MM_Blend_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /************************************************************************** * * @function: * FT_Get_MM_Blend_Coordinates * * @description: * Get the normalized blend coordinates of the currently selected * interpolated font. * * This function works with all supported variation formats. * * @input: * face :: * A handle to the source face. * * num_coords :: * The number of normalized blend coordinates to * retrieve. If it is larger than the number of axes, * set the excess values to~0.5 for Adobe MM fonts, and * to~0 for TrueType GX and OpenType variation fonts. * * @output: * coords :: * The normalized blend coordinates array. * * @return: * FreeType error code. 0~means success. * * @since: * 2.7.1 */ FT_EXPORT( FT_Error ) FT_Get_MM_Blend_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /************************************************************************** * * @function: * FT_Set_Var_Blend_Coordinates * * @description: * This is another name of @FT_Set_MM_Blend_Coordinates. */ FT_EXPORT( FT_Error ) FT_Set_Var_Blend_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /************************************************************************** * * @function: * FT_Get_Var_Blend_Coordinates * * @description: * This is another name of @FT_Get_MM_Blend_Coordinates. * * @since: * 2.7.1 */ FT_EXPORT( FT_Error ) FT_Get_Var_Blend_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /************************************************************************** * * @enum: * FT_VAR_AXIS_FLAG_XXX * * @description: * A list of bit flags used in the return value of * @FT_Get_Var_Axis_Flags. * * @values: * FT_VAR_AXIS_FLAG_HIDDEN :: * The variation axis should not be exposed to user interfaces. * * @since: * 2.8.1 */ #define FT_VAR_AXIS_FLAG_HIDDEN 1 /************************************************************************** * * @function: * FT_Get_Var_Axis_Flags * * @description: * Get the `flags' field of an OpenType Variation Axis Record. * * Not meaningful for Adobe MM fonts (`*flags' is always zero). * * @input: * master :: * The variation descriptor. * * axis_index :: * The index of the requested variation axis. * * @output: * flags :: * The `flags' field. See @FT_VAR_AXIS_FLAG_XXX for * possible values. * * @return: * FreeType error code. 0~means success. * * @since: * 2.8.1 */ FT_EXPORT( FT_Error ) FT_Get_Var_Axis_Flags( FT_MM_Var* master, FT_UInt axis_index, FT_UInt* flags ); /************************************************************************** * * @function: * FT_Set_Named_Instance * * @description: * Set or change the current named instance. * * @input: * face :: * A handle to the source face. * * instance_index :: * The index of the requested instance, starting * with value 1. If set to value 0, FreeType * switches to font access without a named * instance. * * @return: * FreeType error code. 0~means success. * * @note: * The function uses the value of `instance_index' to set bits 16-30 * of the face's `face_index' field. It also resets any variation * applied to the font, and the @FT_FACE_FLAG_VARIATION bit of the * face's `face_flags' field gets reset to zero (i.e., * @FT_IS_VARIATION will return false). * * For Adobe MM fonts (which don't have named instances) this * function simply resets the current face to the default instance. * * @since: * 2.9 */ FT_EXPORT( FT_Error ) FT_Set_Named_Instance( FT_Face face, FT_UInt instance_index ); /* */ FT_END_HEADER #endif /* FTMM_H_ */ /* END */
nikramakrishnan/freetype2
include/freetype/internal/services/svcfftl.h
/**************************************************************************** * * svcfftl.h * * The FreeType CFF tables loader service (specification). * * Copyright 2017-2018 by * <NAME>, <NAME>, and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef SVCFFTL_H_ #define SVCFFTL_H_ #include FT_INTERNAL_SERVICE_H #include FT_INTERNAL_CFF_TYPES_H FT_BEGIN_HEADER #define FT_SERVICE_ID_CFF_LOAD "cff-load" typedef FT_UShort (*FT_Get_Standard_Encoding_Func)( FT_UInt charcode ); typedef FT_Error (*FT_Load_Private_Dict_Func)( CFF_Font font, CFF_SubFont subfont, FT_UInt lenNDV, FT_Fixed* NDV ); typedef FT_Byte (*FT_FD_Select_Get_Func)( CFF_FDSelect fdselect, FT_UInt glyph_index ); typedef FT_Bool (*FT_Blend_Check_Vector_Func)( CFF_Blend blend, FT_UInt vsindex, FT_UInt lenNDV, FT_Fixed* NDV ); typedef FT_Error (*FT_Blend_Build_Vector_Func)( CFF_Blend blend, FT_UInt vsindex, FT_UInt lenNDV, FT_Fixed* NDV ); FT_DEFINE_SERVICE( CFFLoad ) { FT_Get_Standard_Encoding_Func get_standard_encoding; FT_Load_Private_Dict_Func load_private_dict; FT_FD_Select_Get_Func fd_select_get; FT_Blend_Check_Vector_Func blend_check_vector; FT_Blend_Build_Vector_Func blend_build_vector; }; #define FT_DEFINE_SERVICE_CFFLOADREC( class_, \ get_standard_encoding_, \ load_private_dict_, \ fd_select_get_, \ blend_check_vector_, \ blend_build_vector_ ) \ static const FT_Service_CFFLoadRec class_ = \ { \ get_standard_encoding_, \ load_private_dict_, \ fd_select_get_, \ blend_check_vector_, \ blend_build_vector_ \ }; FT_END_HEADER #endif /* END */
helix-datasets/blind-helix
evaluation/data/manual-labels/semantic/gcj-2020-00000000003775e9/MicGor.c
#include <bits/stdc++.h> using namespace std; typedef long long LL; typedef pair<int, int> PII; #define sz(x) (int)(x).size() #define all(x) (x).begin(), (x).end() void solve() { LL n, d; cin >> n >> d; LL x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; LL k1 = abs(x1 + y1 - (x2 + y2)), k2 = abs(x1 - y1 - (x2 - y2)); LL l1 = 2 * d - k1, l2 = 2 * d - k2; cerr << k1 << " " << l1 << "\n"; cerr << k2 << " " << l2 << "\n"; LL k = abs(x1 - x2) + abs(y1 - y2); if(k >= 2 * d) { cout << 0 << " " << 1 << "\n"; return; } if(k >= d) { LL a = 3 * l1 * l2; LL b = 2 * (2 * d) * (2 * d) - l1 * l2; LL g = __gcd(a, b); cout << a / g << " " << b / g << "\n"; return; } LL b = 2 * (2 * d) * (2 * d) - l1 * l2; LL a = b - 4 * k1 * k2; LL g = __gcd(a, b); cout << a / g << " " << b / g << "\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(int i = 1; i <= t; i++) { cout << "Case #" << i << ": "; solve(); } return 0; }
helix-datasets/blind-helix
evaluation/data/manual-labels/semantic/gcj-2020-00000000003775e9/minQZ.c
#include <bits/stdc++.h> using namespace std; #define pb push_back #define X first #define Y second #define mp make_pair typedef long long ll; int n; ll d; ll ans; ll myabs(ll a) { return a > 0 ? a : -a; } ll mygcd(ll a, ll b) { return a % b ? mygcd(b, a%b) : b; } void init() { } void solve() { scanf("%d %d", &n, &d); if (n != 2) { puts("0 1"); return; } ll a = d * d * 4 * 2, b, c; ll x1, y1, x2, y2; scanf("%d %d %d %d", &x1, &y1, &x2, &y2); ll a1 = d * 2 - myabs(x1 + y1 - x2 - y2); ll a2 = d * 2 - myabs(x1 - y1 - x2 + y2); if (a1 <= 0 || a2 <= 0) { puts("0 1"); return; } if (a1 > 0 && a2 > 0) b = a - a1 * a2; c = a1 * a2 * 3; if (a1 > d && a2 > d) c -= (a1 - d)*(a2 - d) * 2; ll g = mygcd(c, b); c /= g; b /= g; printf("%lld %lld\n", c, b); } int main() { int t; scanf("%d", &t); for (int tn = 1; tn <= t; tn++) { printf("Case #%d: ", tn); init(); solve(); } }
helix-datasets/blind-helix
evaluation/data/manual-labels/semantic/gcj-2012-1475486/iPeter.c
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<iostream> #include<algorithm> using namespace std; int n,s[2000],p[2000],q[2000]; int cmp(int a, int b){ if(p[a] == p[b]){ if(s[a] == s[b]) return a < b; return s[a] > s[b]; } return p[a] > p[b]; } int main(void){ int t; scanf("%d",&t); for(int tt=1;tt<=t;tt++){ scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&s[i]); for(int i=0;i<n;i++) scanf("%d",&p[i]); for(int i=0;i<n;i++) q[i]=i; sort(q,q+n,cmp); printf("Case #%d:", tt); for(int i=0;i<n;i++) printf(" %d", q[i]); puts(""); } return 0; }