repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
LandonMorrison/BlackJackRepo
BlackJack/BlackJack/VingtEtUnDeck.h
<gh_stars>0 /************************************************* * Author: <NAME> * File Name: VingtEtUnDeck.h * Date Created: 3/6/2020 * Modifications: 3/8/2020 - changed from Deck to VingtEtUnDeck * *************************************************/ #ifndef DECK_H #define DECK_H #include "VingtEtUnCard.h" /*********************************** * Class: Deck * * Purpose: This class creates a standard deck of 52 playing cards specifically for VingtEtUn. * * Manager Functions: * Deck() * Default CTor that makes a standard card deck. * Deck(const Deck& copy) * Copy CTor called when passed by value, returned by value, or instantiated with an object of the same type. * Deck(Deck&& temp) noexcept * Move CTor called to create an object using values from a temporary object. * Deck& operator = (const Deck& rhs) * Copy Assignment Operator used to define how the "=" operator should function when both the lhs and rhs string objects have * been initialized prior to assignment. * Deck& operator = (Deck&& temp) noexcept * Move Assignement Operator used when the rhs is a temporary object such as a function return that will go out of scope * when the line finishes. * ~Deck() * DTor for releasing any memory allocated by Deck. * * Deck Functions: * void RecombineDeck() * Puts the discards back into the deck. * void ShuffleDeck() * Recombines and then Shuffles the card deck. * Card DealCard(bool FaceUp) * Deals the top card, if no arg provided, will deal card face up. * void Discard(Card CardToDiscard) * Puts the passed in card into the discard pile. * * Utility Functions: * void Display() const * Displays the whole deck from top to bottom. * ***********************************/ class Deck { public: // Manager Functions Deck(); Deck(const Deck& copy); Deck(Deck&& temp) noexcept; Deck& operator= (const Deck& rhs); Deck& operator= (Deck&& temprhs) noexcept; ~Deck(); // Deck Functions void RecombineDeck(); void ShuffleDeck(); Card DealCard(bool FaceUp = true); void Discard(Card CardToDiscard); // Getters and Setters const int GetTopCardIndex() const; const int GetDeckSize() const; const int GetDiscardsSize() const; // Utilities void Display() const; private: // Data Members Card* m_cards = nullptr; Card* m_discards = nullptr; int m_topCardIndex = 0; int m_deckSize = 0; int m_discardsSize = 0; // Internal Utilities void Swap(Card* a, Card* b); }; #endif
LandonMorrison/BlackJackRepo
BlackJack/BlackJack/VingtEtUnDealer.h
<gh_stars>0 /************************************************* * Author: <NAME> * File Name: VingtEtUnDealer.h * Date Created: 3/6/2020 * Modifications: * *************************************************/ #ifndef DEALER_H #define DEALER_H #include "VingtEtUnPlayer.h" /*********************************** * Class: Dealer * * Purpose: This is the default player class for Vingt Et Un otherwise known as 21 or Blackjack * * Manager Functions: * Player() * Default CTor * ~Player() * DTor for releasing any memory allocated by Player. * ***********************************/ class Dealer : public Player { public: // Manager Functions Dealer(); ~Dealer(); private: friend class VingtEtUn; }; #endif
LandonMorrison/BlackJackRepo
BlackJack/BlackJack/VingtEtUnPlayer.h
/************************************************* * Author: <NAME> * File Name: VingtEtUnPlayer.h * Date Created: 3/6/2020 * Modifications: 3/8/2020 Adjusted to match the new Card, Deck, and Hand * *************************************************/ #ifndef PLAYER_H #define PLAYER_H #include <string> #include "VingtEtUnHand.h" using std::string; /*********************************** * Class: Player * * Purpose: This is the default player class for Vingt Et Un otherwise known as 21 or Blackjack * * Manager Functions: * Player() * Default CTor * ~Player() * DTor for releasing any memory allocated by Player. * ***********************************/ class Player { public: // Manager Functions Player(); Player(const Player& copy); Player(Player&& temp) noexcept; Player& operator=(const Player& rhs); Player& operator=(Player&& temprhs) noexcept; ~Player(); // Player Functions void Bet(); bool BuyIn(); void Split(Card CardForHand, Card CardForSplitHand); // This function currently has no safety checks and is only set up for 2 hands so be careful with it void AddToPurse(int AmountToAdd); // Utilities void AddHand(); void RemoveHand(int handOffset); void Display() const; void CheckForInsurance(); void ResetAmountBet(); void ResetSplitBet(); void ResetInsuranceBet(); // Getters and Setters const string GetName() const; const int GetPurse() const; const bool GetNumHands() const; const int GetAmountBet() const; const int GetSplitBet() const; const int GetInsuranceBet() const; const bool GetOutOfGame() const; void SetName(string NameIn); private: friend class VingtEtUn; // Can't have the game without players and vice versa // Data Members string m_name = ""; int m_purse = 500; int m_numHands = 0; bool PlayAgain = true; protected: Hand* m_hands = nullptr; private: // Currency int AmountBet = 0; int InsuranceBet = 0; int SplitBet = 0; bool hasCurrency = true; }; #endif
zuoyou1314/zuoyouDemo
JM_ActionSheet/UIView+JMExtension.h
<reponame>zuoyou1314/zuoyouDemo<filename>JM_ActionSheet/UIView+JMExtension.h // // UIView+JMExtension.h // ymt // // Created by zhujiamin on 16/11/14. // Copyright © 2016年 <EMAIL>. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (JMExtension) #pragma mark properties @property (nonatomic, assign) CGFloat x; @property (nonatomic, assign) CGFloat y; @property (nonatomic, assign) CGFloat centerX; @property (nonatomic, assign) CGFloat centerY; @property (nonatomic, assign) CGFloat width; @property (nonatomic, assign) CGFloat height; @property (nonatomic, assign) CGSize size; @property (nonatomic, assign) CGPoint origin; @end
zuoyou1314/zuoyouDemo
JM_ActionSheet/JM_ActionSheet.h
// // JM_ActionSheet.h // CustomActionSheet // // Created by zhujiamin on 2016/12/9. // Copyright © 2016年 zhujiamin. All rights reserved. // #import <UIKit/UIKit.h> //每一行的样式Model(字体颜色、字号、行高有默认值,也可以自定义) @interface M_SheetItem : NSObject @property(nonatomic, strong) NSString *title; //标题 @property(nonatomic, strong) UIColor *textColor; //字体颜色 default is blackColor; @property(nonatomic, strong) UIFont *textFont; //字号 default is 15; @property(nonatomic) CGFloat height; //行高 defaule is 44; @property(nonatomic) BOOL isTitle; //标题无法点击 defaule is NO; - (instancetype)initWithTitle:(NSString *)title; @end @protocol JM_ActionSheetDelegate; @interface JM_ActionSheet : UIView<UITableViewDelegate, UITableViewDataSource> @property (nonatomic, strong) NSArray<NSArray *> *dataSource; //数据源, 外层数组为组数,内层数组为每组行数 ex:@[@[@"xx",@"zz", ...],@[@"yy",...],...] @property(nonatomic,weak) id<JM_ActionSheetDelegate> delegate; //调用方,需要实现协议方法 - (instancetype)initWithDelegate:(id<JM_ActionSheetDelegate>)delegate; - (void)show; - (void)cancel; @end @protocol JM_ActionSheetDelegate <NSObject> - (void)jm_actionSheet:(JM_ActionSheet *)jm_actionSheet clickedItem:(M_SheetItem *)item atIndex:(NSIndexPath *)indexPath; //item点击事件 //- (void)jm_actionSheetCancel:(JM_ActionSheet *)jm_actionSheet; //暂时用不到退出时的代理方法 @end
liskin/dotfiles
src/pango-force-subpixel-positioning/pango.c
#include <stddef.h> #include <stdbool.h> #include <dlfcn.h> #include <pango/pango.h> typedef typeof(pango_context_new) pango_context_new_t; static pango_context_new_t *orig_pango_context_new = NULL; PangoContext *pango_context_new (void) { if (!orig_pango_context_new) { orig_pango_context_new = dlsym(RTLD_NEXT, "pango_context_new"); if (!orig_pango_context_new) abort(); } PangoContext *ctx = orig_pango_context_new(); pango_context_set_round_glyph_positions(ctx, false); return ctx; } typedef typeof(pango_font_map_create_context) pango_font_map_create_context_t; static pango_font_map_create_context_t *orig_pango_font_map_create_context = NULL; PangoContext *pango_font_map_create_context (PangoFontMap *fontmap) { if (!orig_pango_font_map_create_context) { orig_pango_font_map_create_context = dlsym(RTLD_NEXT, "pango_font_map_create_context"); if (!orig_pango_font_map_create_context) abort(); } PangoContext *ctx = orig_pango_font_map_create_context(fontmap); pango_context_set_round_glyph_positions(ctx, false); return ctx; }
bp2008/-turbojpegCLI
turbojpegCLI/turbojpegCLI/TJ.h
#pragma once #pragma warning( disable : 4635 ) #include "turbojpeg.h" #pragma warning( default : 4635 ) #include "TJScalingFactor.h" #include "TJException.h" #include "stringconvert.h" using namespace System; namespace turbojpegCLI { public enum class SubsamplingOption { /// <summary> /// 4:4:4 chrominance subsampling (no chrominance subsampling). The JPEG /// or YUV image will contain one chrominance component for every pixel in the /// source image. /// </summary> SAMP_444 = 0, /// <summary> /// 4:2:2 chrominance subsampling. The JPEG or YUV image will contain one /// chrominance component for every 2x1 block of pixels in the source image. /// </summary> SAMP_422 = 1, /// <summary> /// 4:2:0 chrominance subsampling. The JPEG or YUV image will contain one /// chrominance component for every 2x2 block of pixels in the source image. /// </summary> SAMP_420 = 2, /// <summary> /// Grayscale. The JPEG or YUV image will contain no chrominance components. /// </summary> SAMP_GRAY = 3, /// <summary> /// 4:4:0 chrominance subsampling. The JPEG or YUV image will contain one /// chrominance component for every 1x2 block of pixels in the source image. /// Note that 4:4:0 subsampling is not fully accelerated in libjpeg-turbo. /// </summary> SAMP_440 = 4, /// <summary> /// 4:1:1 chrominance subsampling. The JPEG or YUV image will contain one /// chrominance component for every 4x1 block of pixels in the source image. /// JPEG images compressed with 4:1:1 subsampling will be almost exactly the /// same size as those compressed with 4:2:0 subsampling, and in the /// aggregate, both subsampling methods produce approximately the same /// perceptual quality. However, 4:1:1 is better able to reproduce sharp /// horizontal features. Note that 4:1:1 subsampling is not fully accelerated /// in libjpeg-turbo. /// </summary> SAMP_411 = 5 }; public enum class PixelFormat { /// <summary> /// RGB pixel format. The red, green, and blue components in the image are /// stored in 3-byte pixels in the order R, G, B from lowest to highest byte /// address within each pixel. /// </summary> RGB = 0, /// <summary> /// BGR pixel format. The red, green, and blue components in the image are /// stored in 3-byte pixels in the order B, G, R from lowest to highest byte /// address within each pixel. /// </summary> BGR = 1, /// <summary> /// RGBX pixel format. The red, green, and blue components in the image are /// stored in 4-byte pixels in the order R, G, B from lowest to highest byte /// address within each pixel. The X component is ignored when compressing /// and undefined when decompressing. /// </summary> RGBX = 2, /// <summary> /// BGRX pixel format. The red, green, and blue components in the image are /// stored in 4-byte pixels in the order B, G, R from lowest to highest byte /// address within each pixel. The X component is ignored when compressing /// and undefined when decompressing. /// </summary> BGRX = 3, /// <summary> /// XBGR pixel format. The red, green, and blue components in the image are /// stored in 4-byte pixels in the order R, G, B from highest to lowest byte /// address within each pixel. The X component is ignored when compressing /// and undefined when decompressing. /// </summary> XBGR = 4, /// <summary> /// XRGB pixel format. The red, green, and blue components in the image are /// stored in 4-byte pixels in the order B, G, R from highest to lowest byte /// address within each pixel. The X component is ignored when compressing /// and undefined when decompressing. /// </summary> XRGB = 5, /// <summary> /// Grayscale pixel format. Each 1-byte pixel represents a luminance /// (brightness) level from 0 to 255. /// </summary> GRAY = 6, /// <summary> /// RGBA pixel format. This is the same as {@link #PF_RGBX}, except that when /// decompressing, the X byte is guaranteed to be 0xFF, which can be /// interpreted as an opaque alpha channel. /// </summary> RGBA = 7, /// <summary> /// BGRA pixel format. This is the same as {@link #PF_BGRX}, except that when /// decompressing, the X byte is guaranteed to be 0xFF, which can be /// interpreted as an opaque alpha channel. /// </summary> BGRA = 8, /// <summary> /// ABGR pixel format. This is the same as {@link #PF_XBGR}, except that when /// decompressing, the X byte is guaranteed to be 0xFF, which can be /// interpreted as an opaque alpha channel. /// </summary> ABGR = 9, /// <summary> /// ARGB pixel format. This is the same as {@link #PF_XRGB}, except that when /// decompressing, the X byte is guaranteed to be 0xFF, which can be /// interpreted as an opaque alpha channel. /// </summary> ARGB = 10, /// <summary> /// CMYK pixel format. Unlike RGB, which is an additive color model used /// primarily for display, CMYK (Cyan/Magenta/Yellow/Key) is a subtractive /// color model used primarily for printing. In the CMYK color model, the /// value of each color component typically corresponds to an amount of cyan, /// magenta, yellow, or black ink that is applied to a white background. In /// order to convert between CMYK and RGB, it is necessary to use a color /// management system (CMS.) A CMS will attempt to map colors within the /// printer's gamut to perceptually similar colors in the display's gamut and /// vice versa, but the mapping is typically not 1:1 or reversible, nor can it /// be defined with a simple formula. Thus, such a conversion is out of scope /// for a codec library. However, the TurboJPEG API allows for compressing /// CMYK pixels into a YCCK JPEG image (see {@link #CS_YCCK}) and /// decompressing YCCK JPEG images into CMYK pixels. /// </summary> CMYK = 11 }; public enum class Colorspace { /// <summary> /// RGB colorspace. When compressing the JPEG image, the R, G, and B /// components in the source image are reordered into image planes, but no /// colorspace conversion or subsampling is performed. RGB JPEG images can be /// decompressed to any of the extended RGB pixel formats or grayscale, but /// they cannot be decompressed to YUV images. /// </summary> RGB = 0, /// <summary> /// YCbCr colorspace. YCbCr is not an absolute colorspace but rather a /// mathematical transformation of RGB designed solely for storage and /// transmission. YCbCr images must be converted to RGB before they can /// actually be displayed. In the YCbCr colorspace, the Y (luminance) /// component represents the black &amp; white portion of the original image, and /// the Cb and Cr (chrominance) components represent the color portion of the /// original image. Originally, the analog equivalent of this transformation /// allowed the same signal to drive both black &amp; white and color televisions, /// but JPEG images use YCbCr primarily because it allows the color data to be /// optionally subsampled for the purposes of reducing bandwidth or disk /// space. YCbCr is the most common JPEG colorspace, and YCbCr JPEG images /// can be compressed from and decompressed to any of the extended RGB pixel /// formats or grayscale, or they can be decompressed to YUV planar images. /// </summary> YCbCr = 1, /// <summary> /// Grayscale colorspace. The JPEG image retains only the luminance data (Y /// component), and any color data from the source image is discarded. /// Grayscale JPEG images can be compressed from and decompressed to any of /// the extended RGB pixel formats or grayscale, or they can be decompressed /// to YUV planar images. /// </summary> GRAY = 2, /// <summary> /// CMYK colorspace. When compressing the JPEG image, the C, M, Y, and K /// components in the source image are reordered into image planes, but no /// colorspace conversion or subsampling is performed. CMYK JPEG images can /// only be decompressed to CMYK pixels. /// </summary> CMYK = 3, /// <summary> /// YCCK colorspace. YCCK (AKA "YCbCrK") is not an absolute colorspace but /// rather a mathematical transformation of CMYK designed solely for storage /// and transmission. It is to CMYK as YCbCr is to RGB. CMYK pixels can be /// reversibly transformed into YCCK, and as with YCbCr, the chrominance /// components in the YCCK pixels can be subsampled without incurring major /// perceptual loss. YCCK JPEG images can only be compressed from and /// decompressed to CMYK pixels. /// </summary> YCCK = 4 }; public enum class Flag { /// <summary> /// A flag specifying no flags are to be used. This is equivalent to the integer 0. /// </summary> NONE = 0, /// <summary> /// The uncompressed source/destination image is stored in bottom-up (Windows, /// OpenGL) order, not top-down (X11) order. /// </summary> BOTTOMUP = 2, /// <summary> /// When decompressing an image that was compressed using chrominance /// subsampling, use the fastest chrominance upsampling algorithm available in /// the underlying codec. The default is to use smooth upsampling, which /// creates a smooth transition between neighboring chrominance components in /// order to reduce upsampling artifacts in the decompressed image. /// </summary> FASTUPSAMPLE = 256, /// <summary> /// Use the fastest DCT/IDCT algorithm available in the underlying codec. The /// default if this flag is not specified is implementation-specific. For /// example, the implementation of TurboJPEG for libjpeg[-turbo] uses the fast /// algorithm by default when compressing, because this has been shown to have /// only a very slight effect on accuracy, but it uses the accurate algorithm /// when decompressing, because this has been shown to have a larger effect. /// </summary> FASTDCT = 2048, /// <summary> /// Use the most accurate DCT/IDCT algorithm available in the underlying /// codec. The default if this flag is not specified is /// implementation-specific. For example, the implementation of TurboJPEG for /// libjpeg[-turbo] uses the fast algorithm by default when compressing, /// because this has been shown to have only a very slight effect on accuracy, /// but it uses the accurate algorithm when decompressing, because this has /// been shown to have a larger effect. /// </summary> ACCURATEDCT = 4096 }; public ref class TJ { public: /// <summary> /// The number of chrominance subsampling options /// </summary> static const int NUMSAMP = 6; /// <summary> /// The number of JPEG colorspaces /// </summary> static const int NUMCS = 5; /// <summary> /// The number of pixel formats /// </summary> static const int NUMPF = 12; /// <summary> /// Throws an exception if the specified SubsamplingOption is invalid. /// </summary> static void checkSubsampling(SubsamplingOption subsamp) { if (!isValidSubsampling(subsamp)) throw gcnew ArgumentException("Invalid subsampling type"); } /// <summary> /// Throws an exception if the specified PixelFormat is invalid. /// </summary> static void checkPixelFormat(PixelFormat pixelFormat) { if (!isValidPixelFormat(pixelFormat)) throw gcnew ArgumentException("Invalid pixel format"); } /// <summary> /// Returns false if the specified SubsamplingOption is invalid. /// </summary> static bool isValidSubsampling(SubsamplingOption subsamp) { if (NUMSAMP != TJ_NUMSAMP) throw gcnew Exception("Mismatch between .NET and C API"); if ((int)subsamp < 0 || (int)subsamp >= NUMSAMP) return false; return true; } /// <summary> /// Returns false if the specified PixelFormat is invalid. /// </summary> static bool isValidPixelFormat(PixelFormat pixelFormat) { if (NUMPF != TJ_NUMPF) throw gcnew Exception("Mismatch between .NET and C API"); if ((int)pixelFormat < 0 || (int)pixelFormat >= NUMPF) return false; return true; } /// <summary> /// Returns the MCU block width for the given level of chrominance /// subsampling. /// </summary> /// /// <param name="subsamp">the level of chrominance subsampling (one of /// <code>SubsamplingOption</code> enum values)</param> /// /// <returns>the MCU block width for the given level of chrominance /// subsampling.</returns> static int getMCUWidth(SubsamplingOption subsamp) { checkSubsampling(subsamp); return tjMCUWidth[(int)subsamp]; } /// <summary> /// Returns the MCU block height for the given level of chrominance /// subsampling. /// </summary> /// /// <param name="subsamp">the level of chrominance subsampling (one of /// <code>SAMP_*</code>)</param> /// /// <returns>the MCU block height for the given level of chrominance /// subsampling.</returns> static int getMCUHeight(SubsamplingOption subsamp) { checkSubsampling(subsamp); return tjMCUHeight[(int)subsamp]; } /// <summary> /// Returns the pixel size (in bytes) for the given pixel format. /// </summary> /// /// <param name="pixelFormat">the pixel format (one of <code>PixelFormat</code> enum values)</param> /// /// <returns>the pixel size (in bytes) for the given pixel format.</returns> static int getPixelSize(PixelFormat pixelFormat) { checkPixelFormat(pixelFormat); return tjPixelSize[(int)pixelFormat]; } /// <summary> /// For the given pixel format, returns the number of bytes that the red /// component is offset from the start of the pixel. For instance, if a pixel /// of format <code>TJ.PF_BGRX</code> is stored in <code>char pixel[]</code>, /// then the red component will be /// <code>pixel[TJ.getRedOffset(TJ.PF_BGRX)]</code>. /// </summary> /// /// <param name="pixelFormat">the pixel format (one of <code>PixelFormat</code> enum values)</param> /// /// <returns>the red offset for the given pixel format.</returns> static int getRedOffset(PixelFormat pixelFormat) { checkPixelFormat(pixelFormat); return tjRedOffset[(int)pixelFormat]; } /// <summary> /// For the given pixel format, returns the number of bytes that the green /// component is offset from the start of the pixel. For instance, if a pixel /// of format <code>TJ.PF_BGRX</code> is stored in <code>char pixel[]</code>, /// then the green component will be /// <code>pixel[TJ.getGreenOffset(TJ.PF_BGRX)]</code>. /// </summary> /// /// <param name="pixelFormat">the pixel format (one of <code>PixelFormat</code> enum values)</param> /// /// <returns>the green offset for the given pixel format.</returns> static int getGreenOffset(PixelFormat pixelFormat) { checkPixelFormat(pixelFormat); return tjGreenOffset[(int)pixelFormat]; } /// <summary> /// For the given pixel format, returns the number of bytes that the blue /// component is offset from the start of the pixel. For instance, if a pixel /// of format <code>TJ.PF_BGRX</code> is stored in <code>char pixel[]</code>, /// then the blue component will be /// <code>pixel[TJ.getBlueOffset(TJ.PF_BGRX)]</code>. /// </summary> /// /// <param name="pixelFormat">the pixel format (one of <code>PixelFormat</code> enum values)</param> /// /// <returns>the blue offset for the given pixel format.</returns> static int getBlueOffset(PixelFormat pixelFormat) { checkPixelFormat(pixelFormat); return tjBlueOffset[(int)pixelFormat]; } /// <summary> /// Returns the maximum size of the buffer (in bytes) required to hold a JPEG /// image with the given width, height, and level of chrominance subsampling. /// </summary> /// /// <param name="width">the width (in pixels) of the JPEG image</param> /// /// <param name="height">the height (in pixels) of the JPEG image</param> /// /// <param name="jpegSubsamp">the level of chrominance subsampling to be used when /// generating the JPEG image (one of SubsamplingOption enum values)</param> /// /// <returns>the maximum size of the buffer (in bytes) required to hold a JPEG /// image with the given width, height, and level of chrominance subsampling.</returns> static int bufSize(int width, int height, SubsamplingOption jpegSubsamp) { unsigned long retval = tjBufSize(width, height, (int)jpegSubsamp); if (retval == -1) throw gcnew TJException(getSystemString(tjGetErrorStr())); return retval; } /// <summary> /// Returns a list of fractional scaling factors that the JPEG decompressor in /// this implementation of TurboJPEG supports. /// </summary> /// /// <returns>a list of fractional scaling factors that the JPEG decompressor in /// this implementation of TurboJPEG supports.</returns> static array<TJScalingFactor^>^ getScalingFactors() { int n = 0; tjscalingfactor *sf; sf = tjGetScalingFactors(&n); if (sf == nullptr || n == 0) throw gcnew TJException(getSystemString(tjGetErrorStr())); array<TJScalingFactor^>^ sfManaged = gcnew array<TJScalingFactor^>(n); for (int i = 0; i < n; i++) sfManaged[i] = gcnew TJScalingFactor(sf[i].num, sf[i].denom); return sfManaged; } }; }
bp2008/-turbojpegCLI
turbojpegCLI/turbojpegCLI/TJException.h
#pragma once using namespace System; namespace turbojpegCLI { public ref class TJException : public Exception { public: TJException() : Exception() { } TJException(String^ msg) : Exception(msg) { } }; }
bp2008/-turbojpegCLI
turbojpegCLI/turbojpegCLI/TJScalingFactor.h
<reponame>bp2008/-turbojpegCLI<filename>turbojpegCLI/turbojpegCLI/TJScalingFactor.h #pragma once using namespace System; namespace turbojpegCLI { public ref class TJScalingFactor { /// <summary> /// Numerator /// </summary> int num; /// <summary> /// Denominator /// </summary> int denom; public: TJScalingFactor(int num, int denom) { if (num < 1 || denom < 1) throw gcnew ArgumentException("Numerator and denominator must be >= 1"); this->num = num; this->denom = denom; } /// <summary> /// Returns numerator /// </summary> int getNum() { return num; } /// <summary> /// Returns denominator /// </summary> int getDenom() { return denom; } /// <summary> /// Returns the scaled value of <code>dimension</code>. This function /// performs the integer equivalent of /// <code>ceil(dimension * scalingFactor)</code>. /// </summary> /// /// <returns>the scaled value of <code>dimension</code>.</returns> int getScaled(int dimension) { return (dimension * num + denom - 1) / denom; } /// <summary> /// Returns true or false, depending on whether this instance and /// <code>other</code> have the same numerator and denominator. /// </summary> /// /// <returns>true or false, depending on whether this instance and /// <code>other</code> have the same numerator and denominator.</returns> bool equals(TJScalingFactor other) { return this->num == other.num && this->denom == other.denom; } /// <summary> /// Returns true or false, depending on whether this instance is equal to /// 1/1. /// </summary> /// /// <returns>true or false, depending on whether this instance is equal to /// 1/1.</returns> bool isOne() { return num == 1 && denom == 1; } }; }
bp2008/-turbojpegCLI
turbojpegCLI/turbojpegCLI/TJDecompressor.h
<reponame>bp2008/-turbojpegCLI<filename>turbojpegCLI/turbojpegCLI/TJDecompressor.h #pragma once #pragma warning( disable : 4635 ) #include "turbojpeg.h" #pragma warning( default : 4635 ) #include "TJ.h" using namespace System; namespace turbojpegCLI { /// <summary> /// TurboJPEG decompressor /// </summary> public ref class TJDecompressor { private: String^ NO_ASSOC_ERROR; tjhandle handle; array<Byte>^ jpegBuf; int jpegBufSize; int jpegWidth; int jpegHeight; SubsamplingOption jpegSubsamp; Colorspace jpegColorspace; bool isDisposed; !TJDecompressor(); void Initialize() { NO_ASSOC_ERROR = "No JPEG image is associated with this instance"; handle = 0; jpegBufSize = 0; jpegWidth = 0; jpegHeight = 0; jpegSubsamp = (SubsamplingOption)-1; jpegColorspace = (Colorspace)-1; isDisposed = false; } public: TJDecompressor(); TJDecompressor(array<Byte>^ jpegImage); TJDecompressor(array<Byte>^ jpegImage, int imageSize); ~TJDecompressor(); void setSourceImage(array<Byte>^ jpegImage, int imageSize); int getWidth(); int getHeight(); SubsamplingOption getSubsamp(); Colorspace getColorspace(); array<Byte>^ getJPEGBuf(); int getJPEGSize(); int getScaledWidth(int desiredWidth, int desiredHeight); int getScaledHeight(int desiredWidth, int desiredHeight); void decompress(array<Byte>^ dstBuf, int x, int y, int desiredWidth, int pitch, int desiredHeight, PixelFormat pixelFormat, Flag flags); void decompress(array<Byte>^ dstBuf, PixelFormat pixelFormat, Flag flags); void decompress(array<Byte>^ dstBuf); array<Byte>^ decompress(int desiredWidth, int pitch, int desiredHeight, PixelFormat pixelFormat, Flag flags); array<Byte>^ decompress(PixelFormat pixelFormat, Flag flags); array<Byte>^ decompress(); }; }
bp2008/-turbojpegCLI
turbojpegCLI/turbojpegCLI/stringconvert.h
<reponame>bp2008/-turbojpegCLI #pragma once #pragma managed( push, off ) #include <string> #pragma managed( pop ) System::String^ getSystemString(std::string const& source); std::string getStdString(System::String^ source);
bp2008/-turbojpegCLI
turbojpegCLI/turbojpegCLI/TJCompressor.h
<filename>turbojpegCLI/turbojpegCLI/TJCompressor.h #pragma once #pragma warning( disable : 4635 ) #include "turbojpeg.h" #pragma warning( default : 4635 ) #include "TJ.h" using namespace System; namespace turbojpegCLI { /// <summary> /// TurboJPEG compressor /// </summary> public ref class TJCompressor { private: String^ NO_ASSOC_ERROR; tjhandle handle; array<Byte>^ srcBuf; int srcWidth; int srcHeight; int srcX; int srcY; int srcPitch; int srcStride; PixelFormat srcPixelFormat; SubsamplingOption subsamp; int jpegQuality; int compressedSize; bool isDisposed; !TJCompressor(); void Initialize() { NO_ASSOC_ERROR = "No source image is associated with this instance"; handle = 0; srcWidth = 0; srcHeight = 0; srcX = -1; srcY = -1; srcPitch = 0; srcStride = 0; srcPixelFormat = (PixelFormat)-1; subsamp = SubsamplingOption::SAMP_420; jpegQuality = 80; compressedSize = 0; isDisposed = false; } void checkSourceImage(); public: TJCompressor(); TJCompressor(array<Byte>^ srcImage, int width, int height); TJCompressor(array<Byte>^ srcImage, int width, int height, PixelFormat pixelFormat); TJCompressor(array<Byte>^ srcImage, int x, int y, int width, int pitch, int height, PixelFormat pixelFormat); ~TJCompressor(); void setSourceImage(array<Byte>^ srcImage, int width, int height); void setSourceImage(array<Byte>^ srcImage, int width, int height, PixelFormat pixelFormat); void setSourceImage(array<Byte>^ srcImage, int x, int y, int width, int pitch, int height, PixelFormat pixelFormat); void setSubsamp(SubsamplingOption newSubsamp); SubsamplingOption getSubsamp(); void setJPEGQuality(int quality); int getJPEGQuality(); void compress(array<Byte>^ %dstBuf, Flag flags); array<Byte>^ compress(Flag flags); array<Byte>^ compressToExactSize(Flag flags); array<Byte>^ compress(); array<Byte>^ compressToExactSize(); int getCompressedSize(); }; }
resin-io/node-ext2fs
src/glue.c
<filename>src/glue.c #include <emscripten.h> #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "ext2fs.h" #include "glue.h" #define O_WRONLY 00000001 #define O_RDWR 00000002 #define O_CREAT 00000100 #define O_EXCL 00000200 #define O_TRUNC 00001000 #define O_APPEND 00002000 #define O_DIRECTORY 00200000 #define O_NOATIME 01000000 // Access js stuff from C EM_JS(void, array_push_buffer, (int array_id, char* value, int len), { const heapBuffer = Module.getBuffer(value, len); const buffer = Buffer.alloc(len); heapBuffer.copy(buffer); Module.getObject(array_id).push(buffer); }); EM_JS(errcode_t, blk_read, (int disk_id, short block_size, unsigned long block, unsigned long count, void *data), { return Asyncify.handleAsync(async () => { const offset = block * block_size; const size = count < 0 ? -count : count * block_size; const buffer = Module.getBuffer(data, size); const disk = Module.getObject(disk_id); try { await disk.read(buffer, 0, buffer.length, offset); return 0; } catch (error) { return Module.EIO; } }); }); EM_JS(errcode_t, blk_write, (int disk_id, short block_size, unsigned long block, unsigned long count, const void *data), { return Asyncify.handleAsync(async () => { const offset = block * block_size; const size = count < 0 ? -count : count * block_size; const buffer = Module.getBuffer(data, size); const disk = Module.getObject(disk_id); try { await disk.write(buffer, 0, buffer.length, offset); return 0; } catch (error) { return Module.EIO; } }); }); EM_JS(errcode_t, discard, (int disk_id, short block_size, unsigned long block, unsigned long count), { return Asyncify.handleAsync(async () => { const disk = Module.getObject(disk_id); const offset = block * block_size; const size = count < 0 ? -count : count * block_size; try { await disk.discard(offset, size); return 0; } catch (error) { return Module.EIO; } }); }); EM_JS(errcode_t, flush, (int disk_id), { return Asyncify.handleAsync(async () => { const disk = Module.getObject(disk_id); try { await disk.flush(); return 0; } catch (error) { return Module.EIO; } }); }); // ------------------------ // Utils ------------------ ext2_ino_t string_to_inode(ext2_filsys fs, const char *str) { ext2_ino_t ino; int retval; retval = ext2fs_namei(fs, EXT2_ROOT_INO, EXT2_ROOT_INO, str, &ino); if (retval) { return 0; } return ino; } int copy_filename_to_result( struct ext2_dir_entry *dirent, int offset, int blocksize, char *buf, void *priv_data // this is the js array_id ) { size_t len = ext2fs_dirent_name_len(dirent); if ( (strncmp(dirent->name, ".", len) != 0) && (strncmp(dirent->name, "..", len) != 0) ) { array_push_buffer((int)priv_data, dirent->name, len); } return 0; } ext2_ino_t get_parent_dir_ino(ext2_filsys fs, const char* path) { char* last_slash = strrchr(path, '/'); if (last_slash == NULL) { return 0; } unsigned int parent_len = last_slash - path + 1; char* parent_path = strndup(path, parent_len); ext2_ino_t parent_ino = string_to_inode(fs, parent_path); free(parent_path); return parent_ino; } char* get_filename(const char* path) { char* last_slash = strrchr((char*)path, (int)'/'); if (last_slash == NULL) { return NULL; } char* filename = last_slash + 1; if (strlen(filename) == 0) { return NULL; } return filename; } unsigned int translate_open_flags(unsigned int js_flags) { unsigned int result = 0; if (js_flags & (O_WRONLY | O_RDWR)) { result |= EXT2_FILE_WRITE; } if (js_flags & O_CREAT) { result |= EXT2_FILE_CREATE; } // JS flags: // O_RDONLY // O_WRONLY EXT2_FILE_WRITE // O_RDWR // O_CREAT EXT2_FILE_CREATE // O_EXCL // O_NOCTTY // O_TRUNC // O_APPEND // O_DIRECTORY // O_NOATIME // O_NOFOLLOW // O_SYNC // O_SYMLINK // O_DIRECT // O_NONBLOCK return result; } errcode_t create_file(ext2_filsys fs, const char* path, unsigned int mode, ext2_ino_t* ino) { // Returns a >= 0 error code errcode_t ret = 0; ext2_ino_t parent_ino = get_parent_dir_ino(fs, path); if (parent_ino == 0) { return ENOTDIR; } ret = ext2fs_new_inode(fs, parent_ino, mode, 0, ino); if (ret) return ret; char* filename = get_filename(path); if (filename == NULL) { // This should never happen. return EISDIR; } ret = ext2fs_link(fs, parent_ino, filename, *ino, EXT2_FT_REG_FILE); if (ret == EXT2_ET_DIR_NO_SPACE) { ret = ext2fs_expand_dir(fs, parent_ino); if (ret) return ret; ret = ext2fs_link(fs, parent_ino, filename, *ino, EXT2_FT_REG_FILE); } if (ret) return ret; if (ext2fs_test_inode_bitmap2(fs->inode_map, *ino)) { printf("Warning: inode already set\n"); } ext2fs_inode_alloc_stats2(fs, *ino, +1, 0); struct ext2_inode inode; memset(&inode, 0, sizeof(inode)); inode.i_mode = (mode & ~LINUX_S_IFMT) | LINUX_S_IFREG; inode.i_atime = inode.i_ctime = inode.i_mtime = time(0); inode.i_links_count = 1; ret = ext2fs_inode_size_set(fs, &inode, 0); // TODO: update size? also on write? if (ret) return ret; if (ext2fs_has_feature_inline_data(fs->super)) { inode.i_flags |= EXT4_INLINE_DATA_FL; } else if (ext2fs_has_feature_extents(fs->super)) { ext2_extent_handle_t handle; inode.i_flags &= ~EXT4_EXTENTS_FL; ret = ext2fs_extent_open2(fs, *ino, &inode, &handle); if (ret) return ret; ext2fs_extent_free(handle); } ret = ext2fs_write_new_inode(fs, *ino, &inode); if (ret) return ret; if (inode.i_flags & EXT4_INLINE_DATA_FL) { ret = ext2fs_inline_data_init(fs, *ino); if (ret) return ret; } return 0; } errcode_t update_xtime(ext2_file_t file, bool a, bool c, bool m) { errcode_t err = 0; err = ext2fs_read_inode(file->fs, file->ino, &(file->inode)); if (err) return err; struct timespec now; clock_gettime(CLOCK_REALTIME, &now); if (a) { file->inode.i_atime = now.tv_sec; } if (c) { file->inode.i_ctime = now.tv_sec; } if (m) { file->inode.i_mtime = now.tv_sec; } increment_version(&(file->inode)); err = ext2fs_write_inode(file->fs, file->ino, &(file->inode)); return err; } unsigned long getUInt64Number(unsigned long long hi, unsigned long long lo) { return lo | (hi << 32); } // ------------------------ // Call these from js ----- // We can read and write C memory from js but we can't read & write js Buffer data from C so we need a way to allocate & free C memory from js. // That way we can allocate C memory from js, pass it to a C function to be written to and read it in js. char* malloc_from_js(int length) { return malloc(length); } void free_from_js(char *data) { free(data); } errcode_t node_ext2fs_mount(int disk_id) { ext2_filsys fs; char hex_ptr[sizeof(void*) * 2 + 3]; sprintf(hex_ptr, "%d", disk_id); errcode_t ret = ext2fs_open( hex_ptr, // name EXT2_FLAG_RW, // flags 0, // superblock 0, // block_size get_js_io_manager(), // manager &fs // ret_fs ); if (ret) { return -ret; } ret = ext2fs_read_bitmaps(fs); if (ret) { return -ret; } return (long)fs; } errcode_t node_ext2fs_trim(ext2_filsys fs) { unsigned int start, blk, count; errcode_t ret; if (!fs->block_map) { if ((ret = ext2fs_read_block_bitmap(fs))) { return -ret; } } start = fs->super->s_first_data_block; count = fs->super->s_blocks_count; for (blk = start; blk <= count; blk++) { // Check for either the last iteration or a used block if (blk == count || ext2fs_test_block_bitmap(fs->block_map, blk)) { if (start < blk) { if ((ret = io_channel_discard(fs->io, start, blk - start))) { return -ret; } } start = blk + 1; } } return 0; } errcode_t node_ext2fs_readdir(ext2_filsys fs, char* path, int array_id) { ext2_ino_t ino = string_to_inode(fs, path); if (ino == 0) { return -ENOENT; } ext2_file_t file; errcode_t ret = ext2fs_file_open( fs, ino, // inode, 0, // flags TODO &file ); if (ret) return -ret; ret = ext2fs_check_directory(fs, ino); if (ret) return -ret; char* block_buf = malloc(fs->blocksize); ret = ext2fs_dir_iterate( fs, ino, 0, // flags block_buf, copy_filename_to_result, (void*)array_id ); free(block_buf); return -ret; } long node_ext2fs_open(ext2_filsys fs, char* path, unsigned int flags, unsigned int mode) { // TODO: O_NOFOLLOW, O_SYMLINK ext2_ino_t ino = string_to_inode(fs, path); errcode_t ret; if (ino == 0) { if (!(flags & O_CREAT)) { return -ENOENT; } ret = create_file(fs, path, mode, &ino); if (ret) return -ret; } else if (flags & O_EXCL) { return -EEXIST; } if ((flags & O_DIRECTORY) && ext2fs_check_directory(fs, ino)) { return -ENOTDIR; } ext2_file_t file; ret = ext2fs_file_open(fs, ino, translate_open_flags(flags), &file); if (ret) return -ret; if (flags & O_TRUNC) { ret = ext2fs_file_set_size2(file, 0); if (ret) return -ret; } return (long)file; } long node_ext2fs_read( ext2_file_t file, int flags, char *buffer, unsigned long length, // requested length unsigned long position // position in file, -1 for current position ) { errcode_t ret = 0; if ((flags & O_WRONLY) != 0) { // Don't try to read write only files. return -EBADF; } if (position != -1) { ret = ext2fs_file_llseek(file, position, EXT2_SEEK_SET, NULL); if (ret) return -ret; } unsigned int got; ret = ext2fs_file_read(file, buffer, length, &got); if (ret) return -ret; if ((flags & O_NOATIME) == 0) { ret = update_xtime(file, true, false, false); if (ret) return -ret; } return got; } long node_ext2fs_write( ext2_file_t file, int flags, char *buffer, unsigned long length, // requested length unsigned long position // position in file, -1 for current position ) { if ((flags & (O_WRONLY | O_RDWR)) == 0) { // Don't try to write to readonly files. return -EBADF; } errcode_t ret = 0; if ((flags & O_APPEND) != 0) { // append mode: seek to the end before each write ret = ext2fs_file_llseek(file, 0, EXT2_SEEK_END, NULL); } else if (position != -1) { ret = ext2fs_file_llseek(file, position, EXT2_SEEK_SET, NULL); } if (ret) return -ret; unsigned int written; ret = ext2fs_file_write(file, buffer, length, &written); if (ret) return -ret; if ((flags & O_CREAT) != 0) { ret = update_xtime(file, false, true, true); if (ret) return -ret; } return written; } errcode_t node_ext2fs_mkdir( ext2_filsys fs, const char *path, int mode ) { ext2_ino_t parent_ino = get_parent_dir_ino(fs, path); if (parent_ino == 0) { return -ENOTDIR; } char* filename = get_filename(path); if (filename == NULL) { // This should never happen. return -EISDIR; } ext2_ino_t newdir; errcode_t ret; ret = ext2fs_new_inode( fs, parent_ino, LINUX_S_IFDIR, NULL, &newdir ); if (ret) return -ret; ret = ext2fs_mkdir(fs, parent_ino, newdir, filename); if (ret) return -ret; struct ext2_inode inode; ret = ext2fs_read_inode(fs, newdir, &inode); if (ret) return -ret; inode.i_mode = (mode & ~LINUX_S_IFMT) | LINUX_S_IFDIR; ret = ext2fs_write_inode(fs, newdir, &inode); return -ret; } errcode_t node_ext2fs_unlink( ext2_filsys fs, const char *path, bool rmdir ) { if (strlen(path) == 0) { return -ENOENT; } ext2_ino_t ino = string_to_inode(fs, path); if (ino == 0) { return -ENOENT; } errcode_t ret; ret = ext2fs_check_directory(fs, ino); bool is_dir = (ret == 0); if (rmdir) { if (!is_dir) { return -ENOTDIR; } } else { if (is_dir) { return -EISDIR; } } ext2_ino_t parent_ino = get_parent_dir_ino(fs, path); if (parent_ino == 0) { return -ENOENT; } ret = ext2fs_unlink(fs, parent_ino, NULL, ino, 0); return -ret; } errcode_t node_ext2fs_chmod( ext2_file_t file, int mode ) { errcode_t ret = ext2fs_read_inode(file->fs, file->ino, &(file->inode)); if (ret) return -ret; // keep only fmt (file or directory) file->inode.i_mode &= LINUX_S_IFMT; // apply new mode file->inode.i_mode |= (mode & ~LINUX_S_IFMT); increment_version(&(file->inode)); ret = ext2fs_write_inode(file->fs, file->ino, &(file->inode)); return -ret; } errcode_t node_ext2fs_chown( ext2_file_t file, int uid, int gid ) { // TODO handle 32 bit {u,g}ids errcode_t ret = ext2fs_read_inode(file->fs, file->ino, &(file->inode)); if (ret) return -ret; // keep only the lower 16 bits file->inode.i_uid = uid & 0xFFFF; file->inode.i_gid = gid & 0xFFFF; increment_version(&(file->inode)); ret = ext2fs_write_inode(file->fs, file->ino, &(file->inode)); return -ret; } errcode_t node_ext2fs_close(ext2_file_t file) { return -ext2fs_file_close(file); } int node_ext2fs_stat_i_mode(ext2_file_t file) { return file->inode.i_mode; } int node_ext2fs_stat_i_links_count(ext2_file_t file) { return file->inode.i_links_count; } int node_ext2fs_stat_i_uid(ext2_file_t file) { return file->inode.i_uid; } int node_ext2fs_stat_i_gid(ext2_file_t file) { return file->inode.i_gid; } int node_ext2fs_stat_blocksize(ext2_file_t file) { return file->fs->blocksize; } unsigned long node_ext2fs_stat_i_size(ext2_file_t file) { return getUInt64Number(file->inode.i_size_high, file->inode.i_size); } int node_ext2fs_stat_ino(ext2_file_t file) { return file->ino; } int node_ext2fs_stat_i_blocks(ext2_file_t file) { return file->inode.i_blocks; } int node_ext2fs_stat_i_atime(ext2_file_t file) { return file->inode.i_atime; } int node_ext2fs_stat_i_mtime(ext2_file_t file) { return file->inode.i_mtime; } int node_ext2fs_stat_i_ctime(ext2_file_t file) { return file->inode.i_ctime; } errcode_t node_ext2fs_umount(ext2_filsys fs) { return -ext2fs_close(fs); } //------------------------------------------- int get_disk_id(io_channel channel) { return (int)channel->private_data; } static errcode_t js_open_entry(const char *disk_id_str, int flags, io_channel *channel) { io_channel io = NULL; errcode_t ret = ext2fs_get_mem(sizeof(struct struct_io_channel), &io); if (ret) { return ret; } memset(io, 0, sizeof(struct struct_io_channel)); io->magic = EXT2_ET_MAGIC_IO_CHANNEL; io->manager = get_js_io_manager(); sscanf(disk_id_str, "%d", (int*)&io->private_data); *channel = io; return 0; } static errcode_t js_close_entry(io_channel channel) { return ext2fs_free_mem(&channel); } static errcode_t set_blksize(io_channel channel, int blksize) { channel->block_size = blksize; return 0; } static errcode_t js_read_blk_entry(io_channel channel, unsigned long block, int count, void *data) { int disk_id = get_disk_id(channel); return blk_read(disk_id, channel->block_size, block, count, data); } static errcode_t js_write_blk_entry(io_channel channel, unsigned long block, int count, const void *data) { int disk_id = get_disk_id(channel); return blk_write(disk_id, channel->block_size, block, count, data); } static errcode_t js_flush_entry(io_channel channel) { int disk_id = get_disk_id(channel); return flush(disk_id); } static errcode_t js_read_blk64_entry(io_channel channel, unsigned long long block, int count, void *data) { return js_read_blk_entry(channel, block, count, data); } static errcode_t js_write_blk64_entry(io_channel channel, unsigned long long block, int count, const void *data) { return js_write_blk_entry(channel, block, count, data); } static errcode_t js_discard_entry(io_channel channel, unsigned long long block, unsigned long long count) { int disk_id = get_disk_id(channel); return discard(disk_id, channel->block_size, block, count); } static errcode_t js_cache_readahead_entry(io_channel channel, unsigned long long block, unsigned long long count) { return 0; } static errcode_t js_zeroout_entry(io_channel channel, unsigned long long block, unsigned long long count) { int disk_id = get_disk_id(channel); unsigned long long size = (count < 0) ? -count : count * channel->block_size; char *data = malloc(size); memset(data, 0, size); errcode_t ret = blk_write(disk_id, channel->block_size, block, count, data); if (ret) return ret; return discard(disk_id, channel->block_size, block, count); } struct struct_io_manager js_io_manager; io_manager get_js_io_manager() { js_io_manager.magic = EXT2_ET_MAGIC_IO_MANAGER; js_io_manager.name = "JavaScript IO Manager"; js_io_manager.open = js_open_entry; js_io_manager.close = js_close_entry; js_io_manager.set_blksize = set_blksize; js_io_manager.read_blk = js_read_blk_entry; js_io_manager.write_blk = js_write_blk_entry; js_io_manager.flush = js_flush_entry; js_io_manager.read_blk64 = js_read_blk64_entry; js_io_manager.write_blk64 = js_write_blk64_entry; js_io_manager.discard = js_discard_entry; js_io_manager.cache_readahead = js_cache_readahead_entry; js_io_manager.zeroout = js_zeroout_entry; return &js_io_manager; };
MattBBaker/threaded-ssca1
util.c
/* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #include <stdlib.h> #include <util.h> #include <pairwise_align.h> #include <string.h> #include <unistd.h> #include <stdio.h> extern unsigned int random_seed; extern int num_nods; extern int rank; #ifdef USE_MPI3 MPI_Comm world; MPI_Win window; void *window_base; size_t window_size; void *next_window_address; MPI_Request request; #endif #ifdef USE_SHMEM long seed_psync[_SHMEM_BCAST_SYNC_SIZE]; #endif void distribute_rng_seed(unsigned int new_seed){ #ifdef USE_SHMEM for(int idx=0; idx < _SHMEM_BCAST_SYNC_SIZE; idx++){ seed_psync[idx] = _SHMEM_SYNC_VALUE; } shmem_barrier_all(); shmem_broadcast32(&random_seed,&new_seed,1,0,0,0,num_nodes,seed_psync); #endif } void seed_rng(int adjustment){ srand(random_seed + adjustment); } void extend_seq(seq_t *extended, index_t extend_size){ codon_t *realloc_temp = (codon_t*)realloc(extended->sequence, sizeof(codon_t) * (extended->backing_memory + extend_size)); if(realloc_temp == NULL) { printf("Realloc error\n"); abort(); } extended->sequence = realloc_temp; extended->backing_memory += extend_size; } seq_t *alloc_global_seq(index_t size){ seq_t *new = malloc(sizeof(seq_t)); new->local_size = size / num_nodes; new->length = new->local_size * num_nodes; new->backing_memory = new->local_size; malloc_all(sizeof(codon_t)*new->local_size, (void **)&new->sequence); if(new->sequence == NULL){ printf("Shmalloc error\n"); abort(); } return new; } void free_global_seq(seq_t *doomed){ if(doomed == NULL)return; FREE_ALL(doomed->sequence); free(doomed); } seq_t *alloc_local_seq(index_t size){ seq_t *new = (seq_t*)malloc(sizeof(seq_t)); new->local_size = size; new->length = size; new->backing_memory = size; new->sequence = (codon_t*)malloc(sizeof(codon_t)*new->local_size); if(new->sequence == NULL){ printf("malloc error\n"); abort(); } return new; } void free_local_seq(seq_t *doomed){ if(doomed == NULL)return; free(doomed->sequence); free(doomed); } void touch_memory(void *mem, size_t size) { index_t page_size = sysconf(_SC_PAGESIZE); index_t *this_memory = (index_t *)mem; index_t size_increment = page_size / sizeof(index_t); index_t size_max = size / sizeof(index_t); for(index_t idx=0; idx < size_max; idx+=size_increment) { this_memory[idx] = 0; } this_memory[size_max-1] = 0; } /* Fix up a sequence to remove the gaps Input- good_match_t *A - the match struct for the sequence. Used for the hyphen member int *dest - destination array. Needs to be allocated before it is passed in int *source - sequence to be scrubbed int length - length of the source. Dest should be the same size Output- int *dest - will be full of a gapless sequence int (return value) - size of dest */ index_t scrub_hyphens(good_match_t *A, seq_t *dest, seq_t *source, index_t length) { index_t source_index=0, dest_index=0; while(source_index < length) { while(source_index < length && source->sequence[source_index] == A->simMatrix->hyphen) source_index++; dest->sequence[dest_index] = source->sequence[source_index]; source_index++; dest_index++; } dest->length = dest_index-1; return dest_index-1; } /* Helper function for displaying acid chains. This function will take a chain and make an ascii representation of the acids as defined in A Input- good_match_t *A - the match struct for the sequence. char *result - the resulting chain as a sequnce of acids int *chain - the sequence to convert into ascii int length - size of the chain */ void assemble_acid_chain(good_match_t *A, char *result, seq_t *chain, index_t length) { memset(result, '\0', length); if(length > chain->length) length = chain->length; for(int idx=0; idx < length; idx++) { result[idx] = (char)A->simMatrix->aminoAcid[chain->sequence[idx]]; } result[length] = '\0'; } /* Helper function for displaying codon chains. This function will take a chain and make an ascii representation of the codon sequence out of it Input- good_match_t *A - the match struct for the sequence. char *result - the resulting chain as a sequnce of codons int *chain - the sequence to convert into ascii int length - size of the chain */ void assemble_codon_chain(good_match_t *A, char *result, seq_t *chain, index_t length) { memset(result, '\0', length); if(length > chain->length) length = chain->length; for(int idx=0; idx < length; idx++) { if(chain->sequence[idx] == HYPHEN) { result[idx*3] = '-'; result[idx*3+1] = '-'; result[idx*3+2] = '-'; } else { result[idx*3] = (char)A->simMatrix->codon[chain->sequence[idx]][0]; result[idx*3+1] = (char)A->simMatrix->codon[chain->sequence[idx]][1]; result[idx*3+2] = (char)A->simMatrix->codon[chain->sequence[idx]][2]; } } result[length*3] = '\0'; } /* Very simple scoring routine. Compares main to match. Both must be at least length long. Input- goot_match_t *A - the match structure used to generate main and match int main[] - the main sequences int match[] - the sequence to compare to main int length - the size of smallest of main or match Output- int - the score of the match */ score_t simple_score(good_match_t *A, seq_t *main, seq_t *match) { score_t score = 0; int mainMatch = 1; int matchMatch = 1; index_t length = main->length; if(match->length < length){ length = match->length; } // recompute score by a brain dead simple method for(int i=0; i < length; i++) { if(main->sequence[i] == A->simMatrix->hyphen) { if(mainMatch == 1) { mainMatch = 0; score = score - A->simMatrix->gapStart; } score = score - A->simMatrix->gapExtend; continue; } if(match->sequence[i] == A->simMatrix->hyphen) { if(matchMatch == 1) { matchMatch = 0; score = score - A->simMatrix->gapStart; } score = score - A->simMatrix->gapExtend; continue; } mainMatch = 1; matchMatch = 1; score = score + A->simMatrix->similarity[main->sequence[i]][match->sequence[i]]; } return score; }
MattBBaker/threaded-ssca1
gen_scal_data.h
/* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #include <gen_sim_matrix.h> #include <types.h> #ifndef _GEN_SCAL_DATA #define _GEN_SCAL_DATA /* * seqData - [structure] holds the generated sequences. * main - [1D uint8 array] generated main codon sequence (1-64). * match - [1D uint8 array] generated match codon sequence (1-64). * maxValidation - [Integer] longest matching validation string. */ /* typedef struct _seq_data { codon_t *main; codon_t *match; index_t mainLen; index_t node_main; index_t matchLen; index_t node_match; int maxValidation; } seq_data_t; */ seq_data_t *gen_scal_data( sim_matrix_t *simMatrix, index_t mainLen, index_t matchLen, int constant_rng); void release_scal_data(seq_data_t *doomed_scal_data); void verifyData(sim_matrix_t *simMatrix, seq_data_t *seqData); #endif
MattBBaker/threaded-ssca1
gen_sim_matrix.h
<reponame>MattBBaker/threaded-ssca1<filename>gen_sim_matrix.h /* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #ifndef _SIM_MATRIX_H #define _SIM_MATRIX_H #include <types.h> #define STAR ((int)48) #define HYPHEN ((int)64) typedef struct _sim_matrix_t { score_t similarity[64][64]; /* - [2D array int] 1-based codon/codon similarity table */ char aminoAcid[65]; /* - [1D char vector] 1-based codon to aminoAcid table */ char bases[5]; /* - [1D char vector] 1-based encoding to base letter table */ char codon[65][4]; /* - [64 x 3 char array] 1-based codon to base letters table */ int encode[128]; /* - [int vector] aminoAcid character to last codon number */ int hyphen; /* - [int] encoding representing a hyphen (gap or space) */ int star; /* - [int] encoding representing a star */ int exact; /* - [integer] value for exactly matching codons */ int similar; /* - [integer] value for similar codons (same amino acid) */ int dissimilar; /* - [integer] value for all other codons */ int gapStart; /* - [integer] penalty to start gap (>=0) */ int gapExtend; /* - [integer] penalty to for each codon in the gap (>0) */ int matchLimit; /* - [integer] longest match including hyphens */ } sim_matrix_t; sim_matrix_t *gen_sim_matrix(int exact, int similar, int dissimilar, int gapStart, int gapExtend, int matchLimit); void release_sim_matrix(sim_matrix_t *doomed_matrix); #endif
MattBBaker/threaded-ssca1
pairwise_align.h
<filename>pairwise_align.h<gh_stars>0 /* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #ifndef _PAIRWISE_ALIGN_H #define _PAIRWISE_ALIGN_H #include <types.h> #include <gen_sim_matrix.h> #include <gen_scal_data.h> #define index2d(x,y,stride) ((y) + ((x) * (stride))) /* typedef struct _seq_t { codon_t *main; codon_t *match; index_t length; index_t backing_memory; //NOTE: right now this is only used in multipleAlign, before that backing memory is the same as length } seq_t; */ // all pointers of of length numReports typedef struct _good_match_t { sim_matrix_t *simMatrix; // simMatrixed used to generate the matches seq_data_t *seqData; // sequences used to generate the matches index_t *goodEnds[2]; // end point for good sequences score_t *goodScores; // scores for the good sequences int numReports; // number of reports given back. index_t *bestStarts[2]; // location of the best starting points index_t *bestEnds[2]; // location of the best end points score_t *bestScores; // location of the best scores seq_data_t *bestSeqs; // list of the best sequences index_t bestLength; } good_match_t; good_match_t *pairwise_align(seq_data_t *seq_data, sim_matrix_t *sim_matrix, int K1_MIN_SCORE, int K1_MAX_REPORTS, int K1_MIN_SEPARATION); void release_good_match(good_match_t *); #endif
MattBBaker/threaded-ssca1
parameters.c
/* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <parameters.h> void init_parameters(parameters_t *parameters) { double scale; static const char *scale_name = "SCALE"; char *result = getenv(scale_name); if(result == NULL) { scale = 22.0; } else { scale = atof(result); } parameters->ENABLE_PAUSE = 0; parameters->ENABLE_VERIF = 1; parameters->ENABLE_DEBUG = 0; parameters->CONSTANT_RNG = 1; /* * Scalable Data Generator parameters. */ parameters->MAIN_SEQ_LENGTH = ceil(pow(2.0, (scale/2.0))); /* Total main codon sequence length. */ parameters->MATCH_SEQ_LENGTH = ceil(pow(2.0, (scale/2.0))); /* Total match codon sequence length. */ /* * Kernel parameters. */ /* Kernel 1/2/3 codon sequence similarity scoring function */ parameters->SIM_EXACT = 5; /* >0 Exact codon match */ parameters->SIM_SIMILAR = 4; /* Amino acid (or Stop) match */ parameters->SIM_DISSIMILAR = -3; /* <0 Different amino acids */ parameters->GAP_START = 5; /* >=0 Gap-start penalty */ parameters->GAP_EXTEND = 2; /* >0 Gap-extension penalty */ parameters->MATCH_LIMIT = 3*(int)scale; /* Longest interesting match */ /* Kernel 4/5 base sequence difference scoring function */ parameters->MISMATCH_PENALTY = 20; /* >0 Mismatch penalty */ parameters->SPACE_PENALTY = 30; /* >0 Penalty for each space in a gap */ /* Kernel 1 */ parameters->K1_MIN_SCORE = 20; /* >0 Minimum end-point score */ parameters->K1_MIN_SEPARATION = 5; /* >=0 Minimum end-point separation */ parameters->K1_MAX_REPORTS = 200; /* >0 Maximum end-points reported to K2 */ /* Kernel 2 */ parameters->K2_MIN_SEPARATION = parameters->K1_MIN_SEPARATION; /* >=0 Minimum start-point separation */ parameters->K2_MAX_REPORTS = ceil(parameters->K1_MAX_REPORTS/2);/* >0 Maximum sequences reported to K3 */ parameters->K2_DISPLAY = 10; /* >=0 Number of reports to display */ /* Kernel 3 */ parameters->K3_MIN_SCORE = 10; /* >0 Minimum end-point score */ parameters->K3_MIN_SEPARATION = parameters->K1_MIN_SEPARATION; /* >=0 Minimum end-point separation */ parameters->K3_MAX_REPORTS = 100; /* >0 Maximum sequences reported to K4 */ parameters->K3_MAX_MATCH = 2.0; /* match_limit = MAX_MATCH * seq_len */ parameters->K3_DISPLAY = 10; /* >=0 Number of reports to display */ /* Kernel 4 */ parameters->K4_DISPLAY = 10; /* >=0 Number of reports to display */ /* Kernel 5 */ parameters->K5_DISPLAY = 100; /* >=0 Number of reports to display */ /* sanity tests */ if(parameters->SIM_EXACT <= 0 || parameters->SIM_DISSIMILAR >= 0 || parameters->GAP_START < 0 || parameters->GAP_EXTEND <= 0) { fprintf(stderr, "Similarity parameters set in getUserParameters are invalid\n"); abort(); } if(parameters->MISMATCH_PENALTY <= 0 || parameters->SPACE_PENALTY <= 0) { fprintf(stderr, "Difference parameters set in getUserParameters are invalid\n"); abort(); } if(parameters->K1_MAX_REPORTS <= 0) { fprintf(stderr, "Kernel 1 parameters set in getUserParameters are invalid\n"); abort(); } if(parameters->K2_MAX_REPORTS <= 0) { fprintf(stderr, "Kernel 2 parameters set in getUserParameters are invalid\n"); abort(); } if(parameters->K3_MAX_REPORTS <= 0) { fprintf(stderr, "Kernel 3 parameters set in getUserParameters are invalid\n"); abort(); } }
MattBBaker/threaded-ssca1
scan_backwards.h
/* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #ifndef _SCAN_BACKWARDS_H #define _SCAN_BACKWARDS_H #include <pairwise_align.h> #include <types.h> void scanBackward(good_match_t *A, int maxReports, int minSeparation); int verify_alignment(good_match_t *A, int maxDisplay); #endif
MattBBaker/threaded-ssca1
parameters.h
<gh_stars>0 /* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #ifndef _PARAMETERS_H #define _PARAMETERS_H typedef struct _params { int ENABLE_PAUSE; int ENABLE_VERIF; int ENABLE_DEBUG; int CONSTANT_RNG; double MAIN_SEQ_LENGTH; double MATCH_SEQ_LENGTH; int SIM_EXACT; int SIM_SIMILAR; int SIM_DISSIMILAR; int GAP_START; int GAP_EXTEND; int MATCH_LIMIT; int MISMATCH_PENALTY; int SPACE_PENALTY; int K1_MIN_SCORE; int K1_MIN_SEPARATION; int K1_MAX_REPORTS; int K2_MIN_SEPARATION; int K2_MAX_REPORTS; int K2_DISPLAY; int K3_MIN_SCORE; int K3_MIN_SEPARATION; int K3_MAX_REPORTS; int K3_MAX_MATCH; int K3_DISPLAY; int K4_DISPLAY; int K5_DISPLAY; int threads; } parameters_t; void init_parameters(parameters_t *parameters); #endif
MattBBaker/threaded-ssca1
main.c
<gh_stars>0 /* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <parameters.h> #include <gen_sim_matrix.h> #include <sys/time.h> #include <time.h> #include <gen_scal_data.h> #include <pairwise_align.h> #include <scan_backwards.h> #include <limits.h> #include <util.h> unsigned int random_seed; int num_nodes; int rank; /* unsigned int get_dev_rand() - routine to get an unsigned int from /dev/random. Intput- None Output- unsigned int- value from /dev/random */ unsigned int get_dev_rand() { int rand_file = open("/dev/urandom", O_RDONLY); unsigned int value; ssize_t read_value = read(rand_file, &value, sizeof(unsigned int)); close(rand_file); if(read_value != sizeof(unsigned int)) { fprintf(stderr, "Error reading random values, aborting\n"); abort(); } return value; } /* void display_elapsed(struct timeval *start_time) Given a start time, display how much time has elapsed since thing Input- struct timeval *start_time- pointer to the struct with the starting time Output- None */ void display_elapsed(struct timeval *start_time) { struct timeval now; gettimeofday(&now, NULL); long hours_elapsed = 0; long minutes_elapsed = 0; time_t seconds_elapsed = now.tv_sec - start_time->tv_sec; long miliseconds_elapsed = 0; long u_elapsed = now.tv_usec - start_time->tv_usec; if(u_elapsed < 0) { seconds_elapsed--; u_elapsed = 1000000 + u_elapsed; } if(seconds_elapsed > 60) { minutes_elapsed = seconds_elapsed / 60; seconds_elapsed = seconds_elapsed % 60; } if(minutes_elapsed > 60) { hours_elapsed = minutes_elapsed / 60; minutes_elapsed = minutes_elapsed % 60; } if(u_elapsed > 1000) { miliseconds_elapsed = u_elapsed / 1000; u_elapsed = u_elapsed % 1000; } printf("\n\tElapsed time: %li hour(s), %li minute(s), %li second(s), %li milliseconds, %li micro second(s).\n", hours_elapsed, minutes_elapsed, seconds_elapsed, miliseconds_elapsed, u_elapsed); } /* int main(int argc, char **argv) Entry routine. Calls each kernel once, displaying elapsed time */ int main(int argc, char **argv) { parameters_t global_parameters; sim_matrix_t *sim_matrix; seq_data_t *seq_data; struct timeval start_time; good_match_t *A; #ifdef USE_MPI3 MPI_Info winfo; #endif #ifdef _OPENMP printf("Running with OpenMP\n"); #endif #ifdef USE_MPI3 MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_nodes); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Info_create(&winfo); MPI_Info_set(winfo, "same_size", "true"); MPI_Info_set(winfo, "alloc_shm", "false"); window_size = 1000000; window_base = malloc(window_size); MPI_Win_create(window_base, window_size, 1, winfo, MPI_COMM_WORLD, &window); MPI_Win_lock_all(0, window); next_window_address = window_base; MPI_Info_free(&winfo); printf("Running with MPI-3, world size is %d\n", num_nodes); #else #ifdef USE_SHMEM start_pes(0); num_nodes=shmem_n_pes(); rank=shmem_my_pe(); if(rank == 0) printf("Running with OpenSHMEM, npes = %i\n", num_nodes); #else num_nodes=1; rank=0; #endif #endif #ifdef USE_PREFETCH if(rank == 0) printf("Using OpenSHMEM prefetching\n"); #else if(rank == 0) printf("Disabling OpenSHMEM prefetching\n"); #endif init_parameters(&global_parameters); if(argc > 1 && !strcmp(argv[1],"--threads")) { global_parameters.threads = atoi(argv[2]); } else { global_parameters.threads = 1; } good_match_t *S[global_parameters.K2_MAX_REPORTS]; memset(S, 0, sizeof(good_match_t *)*global_parameters.K2_MAX_REPORTS); if(global_parameters.ENABLE_VERIF || global_parameters.CONSTANT_RNG) { //printf("\n\tVerification run, using constant seed for RNG\n"); // interesting values that have uncovered bugs in the past, // 2613174141 -- segfault caused by insert_validation producting two identical values // -550696422 -- segfault caused by the RNG producing 0. random_seed = (unsigned int)2613174141; } else { random_seed = (unsigned int)time(NULL); /* casting from time_t to unsigned int we can lose precision... no big deal here */ random_seed += get_dev_rand(); distribute_rng_seed(random_seed); } if(rank == 0){ printf("HPCS SSCA #1 Bioinformatics Sequence Alignment Executable Specification:\nRunning...\n"); printf("Using seed %u\n", random_seed); printf("\nScalable Data Generator - genScalData() beginning execution...\n"); } /* int gogogo=0; printf("Ready to debug on pid=%i\n", getpid()); while(gogogo == 0){ } shmem_barrier_all(); */ gettimeofday(&start_time, NULL); sim_matrix = gen_sim_matrix(global_parameters.SIM_EXACT, global_parameters.SIM_SIMILAR, global_parameters.SIM_DISSIMILAR, global_parameters.GAP_START, global_parameters.GAP_EXTEND, global_parameters.MATCH_LIMIT); seq_data = gen_scal_data(sim_matrix, global_parameters.MAIN_SEQ_LENGTH, global_parameters.MATCH_SEQ_LENGTH, global_parameters.CONSTANT_RNG); if(rank == 0){ display_elapsed(&start_time); if(global_parameters.ENABLE_VERIF) { verifyData(sim_matrix, seq_data); } } /* Kernel 1 run */ if(rank == 0){ printf("\nBegining Kernel 1 execution.\n"); gettimeofday(&start_time, NULL); } #ifdef USE_MPI3 QUIET(); #endif A=pairwise_align(seq_data, sim_matrix, global_parameters.K1_MIN_SCORE, global_parameters.K1_MAX_REPORTS, global_parameters.K1_MIN_SEPARATION); if(rank == 0){ display_elapsed(&start_time); } /* Kernel 2 run */ if(rank == 0){ printf("\nBegining Kernel 2 execution.\n"); gettimeofday(&start_time, NULL); scanBackward(A, global_parameters.K2_MAX_REPORTS, global_parameters.K2_MIN_SEPARATION); display_elapsed(&start_time); if(global_parameters.ENABLE_VERIF) { verify_alignment(A, global_parameters.K2_DISPLAY); } } //release_good_match(A); release_sim_matrix(sim_matrix); release_scal_data(seq_data); BARRIER_ALL(); #ifdef USE_MPI3 MPI_Win_unlock_all(window); #endif return 0; }
MattBBaker/threaded-ssca1
scan_backwards.c
<filename>scan_backwards.c /* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #include <pairwise_align.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <util.h> int verify_alignment(good_match_t *A, int maxDisplay) { int score; int retval = 0; if(A->bestLength == 0) { printf("\nFound no acceptable alignments.\n"); return retval; // returning sucess here because the alignment didn't actually fail... } else { printf("\nFound %lu acceptable alignments with scores from %i to %i.\n", A->bestLength, (int)A->bestScores[0], (int)A->bestScores[A->bestLength-1]); if(maxDisplay > 0) { printf("\nStarting Amino Codon Ending"); printf("\nposition acids bases position\n"); } } for(int m=0; m < A->bestLength; m++) { score = simple_score(A, A->bestSeqs[m].main, A->bestSeqs[m].match); if(score != A->bestScores[m]) { retval = 1; printf("\nverifyAlignment %i failed; Kernel 1 reported %i versus Kernel 2 reported %i:\n---------------------------\n", m, (int)A->bestScores[m], (int)score); } else if(m < maxDisplay) { printf("\nverifyAlignment %i, succeeded; score %i:\n", m, (int)A->bestScores[m]); } if(m < maxDisplay) { char main_acid_chain[A->bestSeqs[m].main->length+1]; char match_acid_chain[A->bestSeqs[m].match->length+1]; char main_codon_chain[A->bestSeqs[m].main->length*3+1]; char match_codon_chain[A->bestSeqs[m].match->length*3+1]; memset(main_acid_chain, '\0', A->bestSeqs[m].main->length+1); memset(match_acid_chain, '\0', A->bestSeqs[m].match->length+1); memset(main_codon_chain, '\0', A->bestSeqs[m].main->length*3+1); memset(match_codon_chain, '\0', A->bestSeqs[m].match->length*3+1); assemble_acid_chain(A, main_acid_chain, A->bestSeqs[m].main, A->bestSeqs[m].main->length); assemble_acid_chain(A, match_acid_chain, A->bestSeqs[m].match, A->bestSeqs[m].match->length); assemble_codon_chain(A, main_codon_chain, A->bestSeqs[m].main, A->bestSeqs[m].main->length); assemble_codon_chain(A, match_codon_chain, A->bestSeqs[m].match, A->bestSeqs[m].match->length); printf("%7ld %s %s %7ld\n%7ld %s %s %7ld\n", A->bestStarts[0][m], main_acid_chain, main_codon_chain, A->bestEnds[0][m], A->bestStarts[1][m], match_acid_chain, match_codon_chain, A->bestEnds[1][m]); } } return retval; } /* * Generate a typical matching pair. * * With a small change this recursive approach can be used to generate all * possible matches. We only need to identify a single match. C implementation * is limited in recursion only by memory. * * INPUTS * A [good_match_t] used to extract the hyphen * sizeT [int] size of the matrix T * T [int[][]] matrix used to navigate with * ei,ej [int] base position for codons in the sequence * i,j [int] subsequence end coordinates, used recursively * dir [int] 1 when extending a gap in main (down), * 2 when extending a gap in match (right), else 0 * depth [int] used to decide how big the outputs will be and for debugging * OUTPUT * rs [i, j] coordinates of end of path or -1 if there is no path * ri [int[M]] main sequence * rj [uint8 row vector] match sequence */ /* Matlab allows for a = [1 2] and b = [0 a] and b will be [0 1 2]. Obviously we can't have that in C. */ void tracepath(good_match_t *A, int sizeT, int *T, int ei, int ej, int i, int j, int dir, int rs[2], seq_data_t *sequence, int depth) { codon_t Ci, Cj; /* debug code */ /* if(depth > sizeT) { printf("Recursion went to an insane depth, aborting."); abort(); } */ if(i == -1 || j == -1) /* Done */ { rs[0] = i + 1; rs[1] = j + 1; sequence->main = alloc_local_seq(depth); sequence->match = alloc_local_seq(depth); return; } if(dir == 0 || (dir & T[index2d(i,j,sizeT)])) // if we aren't skipping and it isn't part of a gap { // then we fan out from here dir = T[index2d(i,j,sizeT)] >> 2; } if(dir == 0) // if we didn't find a sequence { rs[0] = -1; // Using -1 to mean 'does not exist' rs[1] = -1; } fetch_from_seq(A->seqData->main,ei-i,&Ci); fetch_from_seq(A->seqData->match,ej-j,&Cj); if(dir & 4) { tracepath(A, sizeT, T, ei, ej, i-1, j-1, 0, rs, sequence, depth+1); if(rs[0]!=-1) { sequence->main->sequence[depth] = Ci; sequence->match->sequence[depth] = Cj; return; } } if(dir & 2) { tracepath(A, sizeT, T, ei, ej,i-1, j, 2, rs, sequence, depth+1); if(rs[0]!=-1) { sequence->main->sequence[depth] = Ci; sequence->match->sequence[depth] = A->simMatrix->hyphen; return; } } if(dir & 1) { tracepath(A, sizeT, T, ei, ej, i, j-1, 1, rs, sequence, depth+1); if(rs[0]!=-1) { sequence->main->sequence[depth] = A->simMatrix->hyphen; sequence->match->sequence[depth] = Cj; return; } } } /* * Scan from the current end point -- return if expected match is found. * * This variant of the Smith-Waterman algorithm starts at an end-point pair and * proceeds diagonally up and to the left, searching for the matching * start-point pair. The outer loop goes right to left horizontally across the * matchSeq dimension. The inner loop goes diagonally up and right, working * backward through the main sequence and simultaneously forward through the * match sequence. The loops terminate at the edges of the square of possible * matches; the algorithm terminates at the first match with the specified * score. * * This variant differs from the Kernel 1 variant in that its initial point * is fixed (the end-point pair), and that its goal is known. To find this * goal it may be necessary for intermediate values of the score to go * negative, which is impossible for Kernel 1. However such matches are * rejected during traceback and may cause the end-point pair to be rejected. * For example the match * ABCDEF------G * ABCDEFXXXXXXG * might be found by Kernel 1 since its score stays positive scanning right to * left and its end-point pair is distinct from the F/F end-point pair. But * scaning left to right the G/G match is not enough to prevent the gap from * taking the score negative. (In this case, this match would also be rejected * since its start-point pair A/A matches the better ABCDEF/ABCDEF match.) */ void doScan(good_match_t *A, int *bestR, int minSeparation, int report) { score_t goal = A->goodScores[report]; index_t ei = A->goodEnds[0][report]; index_t ej = A->goodEnds[1][report]; //codon_t *mainSeq = A->seqData->main->sequence; //codon_t *matchSeq = A->seqData->match->sequence; seq_t *main_seq = A->seqData->main; seq_t *match_seq = A->seqData->match; int gapExtend = A->simMatrix->gapExtend; int gapFirst = A->simMatrix->gapStart + A->simMatrix->gapExtend; // total penalty for first codon in gap int m = ei > ej ? ei : ej; int *V[2]; int *E; int *F; int s, fj, fi, lj, v, dj, di, e, f, G; int compare_a, compare_b; int rs[2]; codon_t main_codon, match_codon; int sizeT = 2 * (A->simMatrix->matchLimit > A->seqData->max_validation ? A->simMatrix->matchLimit : A->seqData->max_validation); int *T = malloc(sizeof(int) * sizeT * sizeT); memset(T, '\0', sizeof(int) * sizeT * sizeT); V[0] = malloc(sizeof(int) * (m+1)); V[1] = malloc(sizeof(int) * (m+1)); E = malloc(sizeof(int) * m); F = malloc(sizeof(int) * m); //initialize the V, E, and F arrays. We use the smallest possible value that won't be underflowed by the algorithm. for(int idx=0; idx < m; idx++) { V[0][idx] = INT_MIN + gapFirst; V[1][idx] = INT_MIN + gapFirst; E[idx] = INT_MIN + gapFirst; F[idx] = INT_MIN + gapFirst; } V[0][m] = INT_MIN + gapFirst; V[1][m] = INT_MIN + gapFirst; fetch_from_seq(main_seq,ei,&main_codon); fetch_from_seq(match_seq,ej,&match_codon); s = A->simMatrix->similarity[main_codon][match_codon]; //special case for the first point if(s==goal) return; V[0][1] = s; E[0] = s - gapFirst; F[0] = s - gapFirst; T[0] = 19; fj = ej - 1; // final point on the diagnal fi = ei; lj = ej; // first point on the diagnal v = 1; seq_data_t test_seq; while(fi > 0) // loop over diagnal starting positions { dj=fj; di=fi; e=ei-di; f=ej-dj; while(dj <= lj && di > 0 && e < sizeT && f < sizeT) { fetch_from_seq(main_seq,di,&main_codon); fetch_from_seq(match_seq,dj,&match_codon); G = A->simMatrix->similarity[main_codon][match_codon] + V[v][f]; // find the very best weight ending with this pair compare_a = E[e] > F[f] ? E[e] : F[f]; s = G > compare_a ? G : compare_a; V[v][f+1] = s; if(s>0) // if score is okay, track this path { T[index2d(e,f,sizeT)] = 4*(s == E[e]) + 8*(s == F[f]) + 16*(s == G); } else // eliminate this path { T[index2d(e,f,sizeT)] = 0; } if(s == goal) { //discard if start is too close to a better sequence for(int r = 0; r < *bestR; r++) { compare_a = abs(di - A->bestStarts[0][r]); compare_b = abs(dj - A->bestStarts[1][r]); if((compare_a > compare_b ? compare_a : compare_b) < minSeparation) { //printf("Start too close to %i: report %i discarded\n", r, report); goto out; } } tracepath(A, sizeT, T, ei, ej, e, f, 0, rs, &test_seq, 0); if(rs[0] == -1 && rs[1] == -1) // tracepath returns -1 in rs if there is no path { //printf("No path: report %d discarded\n", report); goto out; } // record the result and return A->bestStarts[0][*bestR] = di; A->bestStarts[1][*bestR] = dj; A->bestEnds[0][*bestR] = ei; A->bestEnds[1][*bestR] = ej; A->bestScores[*bestR] = goal; memcpy(&(A->bestSeqs[*bestR]), &test_seq, sizeof(seq_t)); (*bestR) = (*bestR)+1; goto out; // sucess } s = s - gapFirst; // find the best weight assuming a gap in matchSeq E[e] = ((E[e]-gapExtend > s) ? E[e]-gapExtend : s ); // find the weight assuming a gap in mainSeq F[f] = ((F[f]-gapExtend > s) ? F[f]-gapExtend : s ); T[index2d(e,f,sizeT)] = T[index2d(e,f,sizeT)] + (E[e] == s) + 2*(F[f] == s); dj++; di--; e++; f--; } v = 1 - v; if(fj != 0) { fj--; } else { fi--; } } // see the note in the function header regarding sequences that could not be found printf("Could not find sequence %i.\n", report); out: free(F); free(E); free(V[0]); free(V[1]); free(T); } /* * This function uses a variant of the Smith-Waterman dynamic programming * algorithm to locate each actual aligned sequence from its end points and * score as reported by Kernel 1. Some of end-points pairs may be rejected, * primarily because their matching start-points fall within a specified * interval of a better match. Only the best maxReports matches are reported. * * While the start-points are being located, a record is kept of the * alternatives at each point. Then the recursive tracepath function is * used to locate the match to report; there may be one or more equally * valid matches and if so the first one found is reported. * * For a detailed description of the SSCA #1 Optimal Pattern Matching problem, * please see the SSCA #1 Written Specification. * * INPUT * A - [good_match_t] results from pairwiseAlign * seqData - [seq_data_t] data sequences created by genScalData() * main - [char pointer] first codon sequence * match - [char pointer] second codon sequence * maxValidation- [int] longest matching validation string. * simMatrix - [sim_matrix_t] codon similarity created by genSimMatrix() * similarity - [int [64][64]] 1-based codon/codon similarity table * aminoAcid - [char[65]] 1-based codon to aminoAcid table * bases - [char [4]] 1-based encoding to base letter table * codon - [char [64][3]] 1-based codon to base letters table * encode - [int [128]] aminoAcid character to last codon number * hyphen - [char] encoding representing a hyphen (gap or space) * exact - [int] value for exactly matching codons * similar - [int] value for similar codons (same amino acid) * dissimilar - [int] value for all other codons * gapStart - [int] penalty to start gap (>=0) * gapExtend - [int] penalty to for each codon in the gap (>0) * matchLimit - [int] longest match including hyphens * goodEnds - [int[M][2]] M matches; main/match endpoints * goodScores - [int[M]] the scores for the goodEnds * maxReports - [int] maximum number of endpoints reported * minSeparation - [int] minimum startpoint separation in codons * * OUTPUT * A * bestStarts - [int[M][2]] main/match startpoints * bestEnds - [int[M][2]] main/match endpoints * bestSeqs - [seq_t[M]] main/match sequences * main - [int[M]] codon sequence from main sequence * match - [int[M]] codon sequence from match sequence * length - length of the codons, including gaps * bestScores - [int[M]] the scores for the bestSeqs * bestLength - [int] value of M. */ /* * This function really just sets up memory and invokes the main loop until we have the required number of reports. * The real meat is in doScan. */ void scanBackward(good_match_t *A, int maxReports, int minSeparation) { // Preallocate working storage, thinking of cleaning up large chunks of this. A->bestStarts[0] = (index_t *)malloc(maxReports*sizeof(index_t)*2); A->bestStarts[1] = (index_t *)malloc(maxReports*sizeof(index_t)*2); A->bestEnds[0] = (index_t *)malloc(maxReports*sizeof(index_t)*2); A->bestEnds[1] = (index_t *)malloc(maxReports*sizeof(index_t)*2); A->bestScores = (score_t *)malloc(maxReports*sizeof(score_t)*2); A->bestSeqs = (seq_data_t *)malloc(maxReports * sizeof(seq_data_t)*2); memset(A->bestStarts[0], '\0', sizeof(index_t) * maxReports); memset(A->bestStarts[1], '\0', sizeof(index_t) * maxReports); memset(A->bestEnds[0], '\0', sizeof(index_t) * maxReports); memset(A->bestEnds[1], '\0', sizeof(index_t) * maxReports); memset(A->bestScores, '\0', sizeof(score_t) * maxReports); memset(A->bestSeqs, '\0', sizeof(seq_data_t) * maxReports); int bestR = 0; for(int report=0; report < A->numReports; report++) { doScan(A, &bestR, minSeparation, report); if(bestR==maxReports) break; } A->bestLength=bestR; }
MattBBaker/threaded-ssca1
gen_sim_matrix.c
/* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #include <gen_sim_matrix.h> #include <string.h> #include <stdio.h> #include <stdlib.h> // constant data, should remain the same. static const char *a_similarity[] = {"A", "gct", "gcc", "gca", "gcg"}; static const char *c_similarity[] = {"C", "tgt", "tgc"}; static const char *d_similarity[] = {"D", "gat", "gac"}; static const char *e_similarity[] = {"E", "gaa", "gag"}; static const char *f_similarity[] = {"F", "ttt", "ttc"}; static const char *g_similarity[] = {"G", "ggt", "ggc", "gga", "ggg"}; static const char *h_similarity[] = {"H", "cat", "cac"}; static const char *i_similarity[] = {"I", "att", "atc", "ata"}; static const char *k_similarity[] = {"K", "aaa", "aag"}; static const char *l_similarity[] = {"L", "ttg", "tta", "ctt", "ctc", "cta", "ctg"}; static const char *m_similarity[] = {"M", "atg"}; static const char *n_similarity[] = {"N", "aat", "aac"}; static const char *p_similarity[] = {"P", "cct", "ccc", "cca", "ccg"}; static const char *q_similarity[] = {"Q", "caa", "cag"}; static const char *r_similarity[] = {"R", "cgt", "cgc", "cga", "cgg", "aga", "agg"}; static const char *s_similarity[] = {"S", "tct", "tcc", "tca", "tcg", "agt", "agc"}; static const char *t_similarity[] = {"T", "act", "acc", "aca", "acg"}; static const char *v_similarity[] = {"V", "gtt", "gtc", "gta", "gtg"}; static const char *w_similarity[] = {"W", "tgg"}; static const char *y_similarity[] = {"Y", "tat", "tac"}; static const char *star_similarity[] = {"*", "taa", "tag", "tga"}; static const char **similarity[] = {a_similarity, c_similarity, d_similarity, e_similarity, f_similarity, g_similarity, h_similarity, i_similarity, k_similarity, l_similarity, m_similarity, n_similarity, p_similarity, q_similarity, r_similarity, s_similarity, t_similarity, v_similarity,w_similarity, y_similarity, star_similarity}; /* lengths for the similarity matrix above, */ static const int similarity_length[] = {5, 3, 3, 3, 3, 5, 3, 4, 3, 7, 2, 3, 5, 3, 7, 7, 5, 5, 2, 3, 4}; int x_encode_array[128] = {[0 ... 127] = STAR}; /* gen_sim_matrix */ /* generates a similarity matrix. It defines codon similarity values. */ /* Input: * int exact - value of an exact codon match * int similar - value of a similar codon * int dissimilar - value for codons that are not similar at all * int gapStart - penelty to start gap * int gapExtend - penelty for each codon in the gap * int matchLimit - limit to the largest match. * * Output: * sim_matrix_t * - similarity matrix * ->similarity - int [64][64] a matrix of codon/codon similarity values * ->aminoAcid - char [64] an array of codon to aminoAcid ararys * ->bases - char [5] 1-base encoding to 1 base letter * ->codon - char [64][3] 1-based codon to base letters table * ->encode - int [128] aminoAcid to the last codon number * ->hyphen - int encoding to represent the hyphen * ->star - int encoding to represent the star * ->exact - int value for exactly matching codons * ->similar - int value for similarly matching codons * ->dissimilar - int value for codons that don't match at all * ->gapStart - int penelty to start gap * ->gapExtend - int penelty for each codon in the gap * ->matchLimit - int longest match including hyphens */ sim_matrix_t *gen_sim_matrix(int exact, int similar, int dissimilar, int gapStart, int gapExtend, int matchLimit) { char process_acid; int ccode = 0; sim_matrix_t *the_similarity_matrix = (sim_matrix_t*)malloc(sizeof(sim_matrix_t)); the_similarity_matrix->star = STAR; the_similarity_matrix->hyphen = HYPHEN; //strcpy(the_similarity_matrix->codon[64], {(char)HYPHEN,(char)HYPHEN,(char)HYPHEN}); the_similarity_matrix->codon[64][0] = (char)HYPHEN; the_similarity_matrix->codon[64][1] = (char)HYPHEN; the_similarity_matrix->codon[64][2] = (char)HYPHEN; the_similarity_matrix->aminoAcid[HYPHEN] = '-'; strcpy(the_similarity_matrix->bases, "agct"); for(int encode_index = 0; encode_index < 128; encode_index++) the_similarity_matrix->encode[encode_index] = STAR; /* 21 rows in similiarity matrix */ for(int similarity_matrix_index = 0; similarity_matrix_index < 21; similarity_matrix_index++) { process_acid = similarity[similarity_matrix_index][0][0]; for(int codon_index = 1; codon_index < similarity_length[similarity_matrix_index]; codon_index++) { ccode = 0; for(int base_index = 0; base_index < 3; base_index++) { switch(similarity[similarity_matrix_index][codon_index][base_index]) { case 'a': ccode = 0 + 4 * ccode; break; case 'g': ccode = 1 + 4 * ccode; break; case 'c': ccode = 2 + 4 * ccode; break; case 't': ccode = 3 + 4 * ccode; break; default: fprintf(stderr, "Wandered into territory I wasn't supposed to, aborting.\n"); abort(); break; } } strcpy(the_similarity_matrix->codon[ccode],similarity[similarity_matrix_index][codon_index]); the_similarity_matrix->aminoAcid[ccode] = process_acid; } the_similarity_matrix->encode[(int)process_acid] = ccode; } /* We don't get fancy vector notation like in matlab, so let's do all the work in one big loop */ for(int i=0; i<64; i++) { for(int j=0; j<64; j++) { if(i == j) { the_similarity_matrix->similarity[i][j]=exact; } else if(the_similarity_matrix->aminoAcid[i] == the_similarity_matrix->aminoAcid[j]) { the_similarity_matrix->similarity[i][j]=similar; } else { the_similarity_matrix->similarity[i][j]=dissimilar; } } } the_similarity_matrix->exact = exact; the_similarity_matrix->similar = similar; the_similarity_matrix->dissimilar = dissimilar; the_similarity_matrix->gapStart = gapStart; the_similarity_matrix->gapExtend = gapExtend; the_similarity_matrix->matchLimit = matchLimit; return the_similarity_matrix; } /* release_sim_matrix * frees the sim_matrix, returning the memory to the OS. * Input: * sim_matrix_t *doomed_matrix - the matrix to be freed * Output: * None */ void release_sim_matrix(sim_matrix_t *doomed_matrix) { free(doomed_matrix); }
MattBBaker/threaded-ssca1
glibc_sort.c
/* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #include <sort.h> #include <stdlib.h> /* function to be passed to to glibc's qsort function */ int sort_cmp(const void *first, const void *second) { index_t *number_a = (index_t *)first; index_t *number_b = (index_t *)second; return (int)(((score_t)*number_a) - ((score_t)*number_b)); } int ends_cmp(const void *first, const void *second){ sort_ends_t *end_a = (sort_ends_t *)first; sort_ends_t *end_b = (sort_ends_t *)second; return (int)(end_b->score - end_a->score); } /* A wrapper around glibc's qsort. Input- int *numbers - values to be sorted int array_size - size of the numbers array Output- int *numbers - sorted values */ void sort(index_t numbers[], index_t array_size) { qsort(numbers, array_size, sizeof(index_t), sort_cmp); } /* Sort the values and return a list of indexes of the sorted values Input- int *numbers - values to be sorted int *indexes - an int array size of array_size int array_size - size of the numbers array Output- int *numbers - sorted values int *indexes - the index where the value used to be before sorting */ void index_sort(score_t numbers[], index_t indexes[], index_t array_size) { index_t big_index[array_size][2]; for(index_t idx=0; idx < array_size; idx++) { big_index[idx][0] = (index_t)numbers[idx]; big_index[idx][1] = idx; } qsort(big_index, array_size, sizeof(index_t)*2, sort_cmp); for(int idx=0; idx < array_size; idx++) { numbers[idx] = (score_t)big_index[idx][0]; indexes[idx] = big_index[idx][1]; } } void ends_sort(sort_ends_t *ends, index_t array_size){ qsort(ends, array_size, sizeof(sort_ends_t), ends_cmp); }
MattBBaker/threaded-ssca1
gen_scal_data.c
/* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sort.h> #include <gen_scal_data.h> #include <types.h> #include <util.h> #ifdef _OPENMP #include <omp.h> #endif extern unsigned int random_seed; extern int rank; extern int num_nodes; char validations[2][3][32] = { {"ACDEFG*IDENTICAL*HIKLMN", "ACDEFG*MISQRMATCHES*HIKLMN", "ACDEFG*STARTGAPMIDSTEND*HIKLMN"}, {"MNLKIH*IDENTICAL*GFEDCA", "MNLKIH*MISRQMATCHES*GFEDCA", "MNLKIH*STARTMIDSTGAPEND*GFEDCA"} }; /* print the output */ void verifyData(sim_matrix_t *simMatrix, seq_data_t *seqData) { printf("\n"); printf(" Length of main sequence in codons: %lu\n", seqData->main->length); printf(" Length of match sequence in codons: %lu\n", seqData->match->length); printf(" Weight for exactly matching codons: %i\n", simMatrix->exact); printf(" Weight for similar codons: %i\n", simMatrix->similar); printf(" Weight for dissimilar codons: %i\n", simMatrix->dissimilar); printf(" Penalty to start a gap: %i\n", simMatrix->gapStart); printf(" Penalty for each codon in a gap: %i\n", simMatrix->gapExtend); } index_t *gen_indexes(int num_indexes, index_t rand_max, index_t min_seperation) { int not_done; index_t *indexes = (index_t*)malloc(sizeof(index_t) * num_indexes); do{ not_done = 0; for(int idx=0; idx < num_indexes; idx++) { indexes[idx] = rand()%rand_max; } for(int idx=0; idx < num_indexes; idx++) { for(int jdx=idx+1; jdx < num_indexes; jdx++) { if(indexes[idx] - indexes[jdx] < min_seperation) not_done = 1; } } } while(not_done); return indexes; } void create_sequence(seq_t *sequence, char validations[][32], int num_validations, sim_matrix_t *simMatrix){ index_t total_length = sequence->length; index_t end; index_t *indexes = gen_indexes(num_validations, total_length-32, 32); for(index_t idx=0; idx < sequence->local_size; idx++) { sequence->sequence[idx] = rand()%64; } if(rank == 0){ for(int idx=0; idx < num_validations; idx++) { end = strlen(validations[idx]); printf("Inserting sequence %s in location %lu\n", validations[idx], indexes[idx]); for(int jdx=0; jdx < end; jdx++){ write_to_seq(sequence, indexes[idx]+jdx, simMatrix->encode[(int)validations[idx][jdx]]); } } } free(indexes); } seq_data_t *gen_scal_data( sim_matrix_t *simMatrix, index_t mainLen, index_t matchLen, int constant_rng) { seq_data_t *new_scal_data = (seq_data_t *)malloc(sizeof(seq_data_t)); int validation_length, validation_size=0; memset(new_scal_data, '\0', sizeof(seq_data_t)); for(int jdx=0; jdx < 3; jdx++){ validation_length = strlen(validations[0][jdx]); validation_size += validation_length; if(validation_length > new_scal_data->max_validation) new_scal_data->max_validation = validation_length; } new_scal_data->max_validation -= 12; index_t main_size_with_validation = mainLen + validation_size; index_t match_size_with_validation = mainLen + validation_size; new_scal_data->main = alloc_global_seq(main_size_with_validation); new_scal_data->match = alloc_global_seq(match_size_with_validation); seq_t *gen_sequences[2] = {new_scal_data->main, new_scal_data->match}; seed_rng(rank + 1); #ifdef _OPENMP int thread_number = 2; if(constant_rng==1){ thread_number = 1; } #pragma omp parallel for num_threads(thread_number) #endif for(int idx=0; idx < 2; idx++){ touch_memory(gen_sequences[idx]->sequence, sizeof(codon_t)*gen_sequences[idx]->backing_memory); create_sequence(gen_sequences[idx], validations[idx], 3, simMatrix); } return new_scal_data; } void release_scal_data(seq_data_t *doomed_seq) { free_global_seq(doomed_seq->main); free_global_seq(doomed_seq->match); free((void *)doomed_seq); }
MattBBaker/threaded-ssca1
types.h
/* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #ifndef _TYPES_H #define _TYPES_H #include <stdint.h> typedef uint64_t index_t; extern int num_nodes; extern int rank; #if defined(USE_SHMEM) || defined(USE_MPI3) typedef uint16_t codon_t; typedef int16_t score_t; #else typedef int_fast8_t codon_t; typedef int_fast16_t score_t; #endif typedef struct _sequence_t { codon_t *sequence; index_t length; index_t backing_memory; index_t local_size; } seq_t; typedef struct _seq_data_t { seq_t *main; seq_t *match; index_t max_validation; } seq_data_t; #endif
MattBBaker/threaded-ssca1
pairwise_align.c
<filename>pairwise_align.c /* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #define _BSD_SOURCE #include <stdio.h> #include <stdlib.h> #include <sort.h> #include <pairwise_align.h> #include <string.h> #include <util.h> #include <assert.h> #include <unistd.h> #include <sys/time.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_max_threads() 1 #define omp_get_thread_num() 0 #endif typedef struct { index_t *goodEnds[2]; score_t *goodScores; int report; int size; score_t min_score; } current_ends_t; static index_t unsigned_abs_diff(index_t A, index_t B) { return (A > B) ? (A - B) : (B - A); } void print_back_20(good_match_t *A, seq_t *in_seq, index_t end_index){ index_t start = end_index - 20; char main_acid_chain[21]; char main_codon_chain[61]; seq_t this_seq; this_seq.sequence = in_seq->sequence+start; this_seq.length = 20; memset(main_acid_chain, '\0', 21); memset(main_codon_chain, '\0', 21); assemble_acid_chain(A, main_acid_chain, &this_seq, 20); assemble_codon_chain(A, main_codon_chain, &this_seq, 20); printf("%7ld %s %s %7ld\n", start, main_acid_chain, main_codon_chain, end_index); } static void considerAdding(score_t score, int minSeparation, index_t main_index, index_t match_index, int maxReports, current_ends_t *score_ends) { //first scan the list to see if there is a match already that is closer for(int idx=0; idx < score_ends->report; idx++){ if(unsigned_abs_diff(score_ends->goodEnds[0][idx], main_index) < minSeparation || unsigned_abs_diff(score_ends->goodEnds[1][idx], match_index) < minSeparation) { if(score_ends->goodScores[idx] < score) { score_ends->goodEnds[0][idx] = main_index; score_ends->goodEnds[1][idx] = match_index; score_ends->goodScores[idx] = score; return; } else { return; } } } //enlarge if needed if(score_ends->report == score_ends->size) { index_t worst_keeper, new_best_index=0; index_t *index_array = NULL; score_t *sorted_array = NULL; index_t *best_index = NULL; if(index_array == NULL) index_array = (index_t *)malloc(score_ends->size*sizeof(index_t)); if(sorted_array == NULL) sorted_array = (score_t *)malloc(score_ends->size*sizeof(score_t)); if(best_index == NULL) best_index = (index_t *)malloc(score_ends->size*sizeof(index_t)); memcpy(sorted_array, score_ends->goodScores, sizeof(score_t)*score_ends->report); index_sort(sorted_array, index_array, score_ends->report); worst_keeper = score_ends->size - maxReports; score_ends->min_score = score_ends->goodScores[best_index[worst_keeper]]; for(int index_for_index=worst_keeper; index_for_index < score_ends->size; index_for_index++) { best_index[new_best_index] = index_array[index_for_index]; new_best_index++; } sort(best_index, new_best_index); for(int idx=0; idx < new_best_index; idx++) { score_ends->goodScores[idx] =score_ends->goodScores[best_index[idx]]; score_ends->goodEnds[0][idx]=score_ends->goodEnds[0][best_index[idx]]; score_ends->goodEnds[1][idx]=score_ends->goodEnds[1][best_index[idx]]; } score_ends->report = maxReports; free(index_array); free(sorted_array); free(best_index); } score_ends->goodEnds[0][score_ends->report] = main_index; score_ends->goodEnds[1][score_ends->report] = match_index; score_ends->goodScores[score_ends->report] = score; score_ends->report++; } /* release_good_match: * Free the goot_match_t structure generated by Kernel 1 and Kernel 2 * Note: You can still release a matrix that has not been through Kernel 2, * there are not ill side effects. * Input: * good_match_t *doomed - the structure to be freed * Output: * None */ void release_good_match(good_match_t *doomed) { if(doomed==NULL) return; free(doomed->goodScores); free(doomed->goodEnds[1]); free(doomed->goodEnds[0]); free(doomed->bestStarts[0]); free(doomed->bestStarts[1]); free(doomed->bestEnds[0]); free(doomed->bestEnds[1]); free(doomed->bestScores); for(int idx=0; idx<doomed->bestLength; idx++) { free_local_seq(doomed->bestSeqs[idx].main); free_local_seq(doomed->bestSeqs[idx].match); } free(doomed->bestSeqs); free(doomed); } //typedef score_t score_matrix_t; typedef struct { score_t *scores; index_t length; index_t local_length; } score_matrix_t; typedef score_matrix_t gap_matrix_t; static score_matrix_t *alloc_score_matrix(index_t matrix_length){ score_matrix_t *new_alloc = (score_matrix_t *)malloc(sizeof(score_matrix_t)); assert(new_alloc != NULL); new_alloc->length = matrix_length; new_alloc->local_length = (matrix_length / num_nodes); malloc_all(sizeof(score_t)*3*new_alloc->local_length, (void **)&new_alloc->scores); assert(new_alloc->scores != NULL); touch_memory(new_alloc->scores, sizeof(score_t)*3*new_alloc->local_length); return new_alloc; } static gap_matrix_t *alloc_gap_matrix(index_t matrix_length){ gap_matrix_t *new_alloc = (gap_matrix_t *)malloc(sizeof(score_matrix_t)); assert(new_alloc != NULL); new_alloc->length = matrix_length; new_alloc->local_length = (matrix_length / num_nodes); malloc_all(sizeof(score_t)*2*new_alloc->local_length, (void **)&new_alloc->scores); assert(new_alloc->scores != NULL); touch_memory(new_alloc->scores, sizeof(score_t)*2*new_alloc->local_length); return new_alloc; } static void free_score_matrix(score_matrix_t *doomed){ FREE_ALL(doomed->scores); free(doomed); } static void free_gap_matrix(gap_matrix_t *doomed){ FREE_ALL(doomed->scores); free(doomed); } #define index2d(x,y,stride) ((y) + ((x) * (stride))) static void fetch_score(score_matrix_t *A, index_t m, index_t n, score_t *in){ int target_ep = n / A->local_length; int local_index = n % A->local_length; SHORT_GET(in, &(A->scores[index2d(m%3,local_index,A->local_length)]), 1, target_ep); } static void fetch_gap(gap_matrix_t *A, index_t m, index_t n, score_t *in){ int target_ep = n / A->local_length; int local_index = n %A->local_length; SHORT_GET(in, &(A->scores[index2d(m%2,local_index,A->local_length)]), 1, target_ep); } /* maybe useful for going to further extremes. Commented out because GCC complains of unused functions */ #if 0 static void fetch_score_nb(score_matrix_t *A, index_t m, index_t n, score_t *in){ int target_ep = n / A->local_length; int local_index = n % A->local_length; SHORT_GET_NB((short*)in, &(A->scores[index2d(m%3,local_index,A->local_length)]), 1, target_ep); } static void fetch_gap_nb(gap_matrix_t *A, index_t m, index_t n, score_t *in){ int target_ep = n / A->local_length; int local_index = n %A->local_length; SHORT_GET_NB((short*)in, &(A->scores[index2d(m%2,local_index,A->local_length)]), 1, target_ep); } #endif static void assign_score(score_matrix_t *A, index_t m, index_t n, score_t new_value){ int target_ep = n / A->local_length; int local_index = n %A->local_length; SHORT_PUT(&(A->scores[index2d(m%3,local_index,A->local_length)]), &new_value, 1, target_ep); } static void assign_gap(score_matrix_t *A, index_t m, index_t n, score_t new_value){ int target_ep = n / A->local_length; int local_index = n % A->local_length; SHORT_PUT(&(A->scores[index2d(m%2,local_index,A->local_length)]), &new_value, 1, target_ep); } #ifdef USE_SHMEM long collect_pSync[_SHMEM_REDUCE_SYNC_SIZE]; int collect_pWrk[_SHMEM_REDUCE_MIN_WRKDATA_SIZE]; #endif static void collect_best_results(current_ends_t **good_ends, int max_reports, int max_threads, good_match_t *answer){ index_t copied=0; int max_values=0; current_ends_t collected_ends, current_end; if(rank != 0) return; memset(answer->goodEnds[0], 0, sizeof(index_t)*max_reports); memset(answer->goodEnds[1], 0, sizeof(index_t)*max_reports); memset(answer->goodScores, 0, sizeof(score_t)*max_reports); collected_ends.goodScores = malloc(sizeof(score_t)*good_ends[0]->size*num_nodes); collected_ends.goodEnds[0] = malloc(sizeof(index_t)*good_ends[0]->size*num_nodes); collected_ends.goodEnds[1] = malloc(sizeof(index_t)*good_ends[0]->size*num_nodes); for(int idx=0; idx < num_nodes; idx++){ GETMEM(&current_end, good_ends[0], sizeof(current_ends_t), idx); SHORT_GET(&(collected_ends.goodScores[copied]), good_ends[0]->goodScores, current_end.report, idx); LONG_GET(&(collected_ends.goodEnds[0][copied]), good_ends[0]->goodEnds[0], current_end.report, idx); LONG_GET(&(collected_ends.goodEnds[1][copied]), good_ends[0]->goodEnds[1], current_end.report, idx); copied += current_end.report; } sort_ends_t *sorted_list = malloc(sizeof(sort_ends_t)*copied); for(int idx=0; idx < copied; idx++){ sorted_list[idx].score = collected_ends.goodScores[idx]; sorted_list[idx].main_end = collected_ends.goodEnds[0][idx]; sorted_list[idx].match_end = collected_ends.goodEnds[1][idx]; } ends_sort(sorted_list, copied); if(copied > max_reports){ max_values = max_reports; } else { max_values = copied; } for(int idx=0; idx < max_values; idx++){ answer->goodScores[idx] = sorted_list[idx].score; answer->goodEnds[0][idx] = sorted_list[idx].main_end; answer->goodEnds[1][idx] = sorted_list[idx].match_end; } free(sorted_list); answer->numReports = max_values; } /* pairwise_align * real meat of the program, this function finds codon similarities in seq_data using the matrix sim_matrix * Input: * seq_data_t *seq_data - Sequence data generated by genScalData() * sim_matrix_t *sim_matrix - Codon similarity matrix generated by genSimMatrix() * int minScore - Minimum end point score, from the init_parameters() function * int maxReports - Maximum number of reports to keep, from the init_parameters() function * int minSeparation - Minimum end point seperation in codons, from the init_parameters() function * * Output: * good_matrix_t * - a matrix of good matches * ->simMatrix - a pointer to the sim_matrix_t used * ->seqData - a pointer to the seq_data_t used * ->goodEnds - a [2][maxReports] matrix with main/match endpoints * ->goodScores - a [maxReports] good scores for upto maxReports endpoints * ->numReports - an integer, the number of reports represented */ good_match_t *pairwise_align(seq_data_t *seq_data, sim_matrix_t *sim_matrix, const int minScore, const int maxReports, const int minSeparation) { const int sortReports = maxReports * 10; const seq_t *main_seq = seq_data->main; const seq_t *match_seq = seq_data->match; const score_t gapExtend = sim_matrix->gapExtend; const score_t gapFirst = sim_matrix->gapStart + gapExtend; const index_t main_len = seq_data->main->length; codon_t current_main, current_match; codon_t next_main, next_match; const int max_threads = omp_get_max_threads(); current_ends_t **good_ends = (current_ends_t **)malloc(sizeof(current_ends_t *)*max_threads); #ifdef _OPENMP #pragma omp parallel for #endif for(int jdx=0; jdx < max_threads; jdx++) { int idx = omp_get_thread_num(); malloc_all(sizeof(current_ends_t), (void **)&good_ends[idx]); good_ends[idx]->size = sortReports; good_ends[idx]->report = 0; malloc_all(sizeof(score_t)*sortReports, (void **)&good_ends[idx]->goodScores); malloc_all(sizeof(index_t)*sortReports, (void **)&good_ends[idx]->goodEnds[0]); malloc_all(sizeof(index_t)*sortReports, (void **)&good_ends[idx]->goodEnds[1]); good_ends[idx]->min_score = minScore; } score_matrix_t *restrict score_matrix = alloc_score_matrix(seq_data->match->length); gap_matrix_t *restrict main_gap_matrix = alloc_gap_matrix(seq_data->match->length); gap_matrix_t *restrict match_gap_matrix = alloc_gap_matrix(seq_data->match->length); index_t score_start, score_end; score_t G, W, E, F, cmp_a, cmp_b, cmp_c, new_score, next_G, next_F, next_E; index_t m, n; good_match_t *answer; codon_t main_codon; codon_t match_codon; index_t local_main_start = seq_data->main->local_size * rank; index_t local_main_end = seq_data->main->local_size * (rank+1) - 1; /* if(rank == 0){ printf("Ready to debug on PID=%i\n", getpid()); int gogogo=0; while(gogogo==0){} } */ //First iteration, done by hand. Basically idx=0 in the big loop if(rank == 0){ fetch_from_seq(main_seq,0,&main_codon); fetch_from_seq(match_seq,0,&match_codon); W = sim_matrix->similarity[main_codon][match_codon]; assign_score(score_matrix,0,0,0 > W ? 0 : W); assign_gap(main_gap_matrix,0,0,-gapFirst + W); assign_gap(match_gap_matrix,0,0,-gapFirst + W); //idx=1 m=0,1 n =1,0 fetch_from_seq(main_seq,0,&main_codon); fetch_from_seq(match_seq,1, &match_codon); W = sim_matrix->similarity[main_codon][match_codon]; G = W; fetch_gap(main_gap_matrix,0,0,&E); cmp_a = 0 > E ? 0 : E; cmp_a = cmp_a > G ? cmp_a : G; assign_score(score_matrix,1,1,cmp_a); cmp_a = E - gapExtend; cmp_b = G - gapFirst; assign_gap(main_gap_matrix,1,0,cmp_a > cmp_b ? cmp_a : cmp_b); assign_gap(match_gap_matrix,1,0,-gapFirst > cmp_b ? -gapFirst : cmp_b); fetch_from_seq(main_seq,1,&main_codon); fetch_from_seq(match_seq,0,&match_codon); W = sim_matrix->similarity[main_codon][match_codon]; G = W; fetch_gap(match_gap_matrix,0,0, &F); cmp_a = 0 > F ? 0 : F; cmp_a = cmp_a > G ? cmp_a : G; assign_score(score_matrix,1,0,cmp_a); cmp_a = F - gapExtend; cmp_b = G - gapFirst; assign_gap(main_gap_matrix,1,1,-gapFirst > cmp_b ? -gapFirst : cmp_b); assign_gap(match_gap_matrix,1,1,cmp_a > cmp_b ? cmp_a : cmp_b); } for(index_t idx=2; idx < seq_data->match->length * 2 - 1; idx++) { BARRIER_ALL(); score_start = idx > (seq_data->match->length - 1) ? (idx-(seq_data->match->length-1)) : 0; score_end = idx < (seq_data->match->length-1) ? (idx) : (seq_data->match->length-1); if(idx < seq_data->match->length) { if(rank == 0){ m = 0; n = idx; fetch_from_seq(main_seq,m,&main_codon); fetch_from_seq(match_seq,n,&match_codon); W = sim_matrix->similarity[main_codon][match_codon]; G = W; fetch_gap(match_gap_matrix,idx-1,n-1,&F); cmp_a = F > 0 ? F : 0; cmp_a = cmp_a > G ? cmp_a : G; assign_score(score_matrix,idx,m,cmp_a); new_score= cmp_a; if((new_score > good_ends[omp_get_thread_num()]->min_score && W > 0 && new_score == G)){ if (m+1 == seq_data->main->length || n == 0) { considerAdding(new_score, minSeparation, m, n, maxReports, good_ends[omp_get_thread_num()]); } else { fetch_from_seq(main_seq, m+1, &next_main); fetch_from_seq(match_seq, n-1, &next_match); if((m == main_len - 1) || (n == 0) || sim_matrix->similarity[next_main][next_match] <= 0){ considerAdding(new_score, minSeparation, m, n, maxReports, good_ends[omp_get_thread_num()]); } } } cmp_a = F - gapExtend; cmp_b = G - gapFirst; assign_gap(match_gap_matrix,idx,n,cmp_a > cmp_b ? cmp_a : cmp_b); m = idx; n = 0; fetch_from_seq(main_seq,m,&main_codon); fetch_from_seq(match_seq,n,&match_codon); W = sim_matrix->similarity[main_codon][match_codon]; G = W; fetch_gap(main_gap_matrix, idx-1, m-1, &E); cmp_a = E > 0 ? E : 0; cmp_a = cmp_a > G ? cmp_a : G; assign_score(score_matrix,idx,m,cmp_a); new_score = cmp_a; if((new_score > good_ends[omp_get_thread_num()]->min_score && W > 0 && new_score == G)){ if (m+1 == seq_data->main->length || n == 0) { considerAdding(new_score, minSeparation, m, n, maxReports, good_ends[omp_get_thread_num()]); } else { fetch_from_seq(main_seq, m+1, &next_main); fetch_from_seq(match_seq, n-1, &next_match); if((m == main_len - 1) || (n == 0) || sim_matrix->similarity[next_main][next_match] <= 0){ considerAdding(new_score, minSeparation, m, n, maxReports, good_ends[omp_get_thread_num()]); } } } cmp_a = E - gapExtend; cmp_b = G - gapFirst; assign_gap(main_gap_matrix, idx, m, cmp_a > cmp_b ? cmp_a : cmp_b); } score_start++; score_end = score_end - 1; } index_t local_start, local_end; if(score_end < local_main_start && score_start > local_main_end){ local_start = 1; local_end = 0; } else { if(local_main_start > score_start){ local_start = local_main_start; } else { local_start = score_start; } if(score_end > local_main_end){ local_end = local_main_end; } else { local_end = score_end; } fetch_from_seq(main_seq,local_start,&next_main); fetch_from_seq(match_seq,idx - score_start,&next_match); fetch_score(score_matrix, (idx-2)%3, local_start-1, &next_G); fetch_gap(match_gap_matrix, idx-1, idx - (score_start+1), &next_F); fetch_gap(main_gap_matrix, idx-1, local_start-1, &next_E); } //As a note, this loop is the program execution time. If you're looking to optimize this benchmark, this is all that counts. for(index_t antidiagonal = local_start; antidiagonal <= local_end; antidiagonal++) { m = antidiagonal; n = idx - m; #ifdef USE_PREFETCH current_main = next_main; current_match = next_match; G = next_G; F = next_F; E = next_E; if (m < (seq_data->main->length-1)) fetch_from_seq_nb(main_seq, m+1, &next_main); if (n > 0) fetch_from_seq_nb(match_seq, n-1, &next_match); if (n > 1) fetch_gap(match_gap_matrix, idx-1, n-2, &next_F); fetch_gap(main_gap_matrix, idx-1, m, &next_E); fetch_score(score_matrix, (idx-2)%3, m, &next_G); #else fetch_from_seq(main_seq, m, &current_main); fetch_from_seq(match_seq, n, &current_match); fetch_gap(match_gap_matrix, idx-1, n-1, &F); fetch_gap(main_gap_matrix, idx-1, m-1, &E); fetch_score(score_matrix, (idx-2)%3, m-1, &G); #endif cmp_a = 0; cmp_a = cmp_a > E ? cmp_a : E; cmp_a = cmp_a > F ? cmp_a : F; W = sim_matrix->similarity[current_main][current_match]; G += W; new_score = cmp_a > G ? cmp_a : G; if((new_score > good_ends[omp_get_thread_num()]->min_score && W > 0 && new_score == G)){ #ifdef USE_PREFETCH if (m+1 == seq_data->main->length || n == 0) { considerAdding(new_score, minSeparation, m, n, maxReports, good_ends[omp_get_thread_num()]); } else { WAIT_NB(); if((m == main_len - 1) || (n == 0) || sim_matrix->similarity[next_main][next_match] <= 0){ considerAdding(new_score, minSeparation, m, n, maxReports, good_ends[omp_get_thread_num()]); } } #else if (m+1 == seq_data->main->length || n == 0) { considerAdding(new_score, minSeparation, m, n, maxReports, good_ends[omp_get_thread_num()]); } else { fetch_from_seq(main_seq, m+1, &next_main); fetch_from_seq(match_seq, n-1, &next_match); if((m == main_len - 1) || (n == 0) || sim_matrix->similarity[next_main][next_match] <= 0){ considerAdding(new_score, minSeparation, m, n, maxReports, good_ends[omp_get_thread_num()]); } } #endif } cmp_a = E - gapExtend; cmp_b = G - gapFirst; cmp_c = F - gapExtend; #ifdef USE_PREFETCH WAIT_NB(); #endif assign_score(score_matrix,idx,m,new_score); assign_gap(main_gap_matrix, idx, m, cmp_a > cmp_b ? cmp_a : cmp_b); assign_gap(match_gap_matrix, idx, n, cmp_c > cmp_b ? cmp_c : cmp_b); } } answer = (good_match_t*)malloc(sizeof(good_match_t)); answer->simMatrix = sim_matrix; answer->seqData = seq_data; answer->goodEnds[0] = (index_t*)malloc(sizeof(index_t)*maxReports); answer->goodEnds[1] = (index_t*)malloc(sizeof(index_t)*maxReports); answer->goodScores = (score_t*)malloc(sizeof(score_t)*maxReports); answer->bestEnds[0] = NULL; answer->bestStarts[0] = NULL; answer->bestEnds[1] = NULL; answer->bestStarts[1] = NULL; answer->bestSeqs = NULL; answer->bestScores = NULL; BARRIER_ALL(); collect_best_results(good_ends, maxReports, max_threads, answer); free_score_matrix(score_matrix); free_gap_matrix(main_gap_matrix); free_gap_matrix(match_gap_matrix); for(int idx=0; idx < max_threads; idx++) { FREE_ALL(good_ends[idx]->goodScores); FREE_ALL(good_ends[idx]->goodEnds[0]); FREE_ALL(good_ends[idx]->goodEnds[1]); FREE_ALL(good_ends[idx]); } free(good_ends); return answer; }
MattBBaker/threaded-ssca1
util.h
<reponame>MattBBaker/threaded-ssca1<gh_stars>0 /* This file is part of SSCA1. Copyright (C) 2008-2015, UT-Battelle, LLC. This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the SSCA1 developers at: <EMAIL> */ #ifndef __UTIL_H #define __UTIL_H #include <pairwise_align.h> #include <types.h> #include <stdio.h> #ifdef USE_MPI3 #include <mpi.h> extern MPI_Comm world; extern MPI_Win window; extern void *window_base; extern size_t window_size; extern void *next_window_address; extern MPI_Request request; #else #ifdef SGI_SHMEM #include <mpp/shmem.h> #else #include <shmem.h> #endif #endif #ifdef USE_MPI3 #define SHORT_GET(target, source, num_elems, rank) MPI_Get(target, num_elems, MPI_SHORT, rank, (void *)source - window_base, num_elems, MPI_SHORT, window); QUIET() #else #define SHORT_GET(target, source, num_elems, pe) shmem_short_get(target, source, num_elems, pe) #endif #ifdef USE_MPI3 #define SHORT_GET_NB(target, source, num_elems, rank) MPI_Get(target, num_elems, MPI_SHORT, rank, (void *)source - window_base, num_elems, MPI_SHORT, window) #else #define SHORT_GET_NB(target, source, num_elems, pe) shmem_short_get_nb(target, source, num_elems, pe, NULL) #endif #ifdef USE_MPI3 #define LONG_GET(target, source, num_elems, rank) MPI_Get(target, num_elems, MPI_LONG, rank, (void *)source - window_base, num_elems, MPI_LONG, window); QUIET() #else #define LONG_GET(target, source, num_elems, pe) shmem_long_get((long*)target, (long*)source, num_elems, pe) #endif #ifdef USE_MPI3 #define GETMEM(target, source, length, rank) MPI_Get(target, length, MPI_BYTE, rank, (void *)source - window_base, length, MPI_BYTE, window); QUIET() #else #define GETMEM(target, source, length, pe) shmem_getmem(target, source, length, pe) #endif #ifdef USE_MPI3 #define SHORT_PUT(target, source, num_elems, rank) MPI_Put(source, num_elems, MPI_SHORT, rank, (void *)target - window_base, num_elems, MPI_SHORT, window); QUIET() #else #define SHORT_PUT(target, source, num_elems, pe) shmem_short_put(target, source, num_elems, pe) #endif #ifdef USE_MPI3 #define QUIET() MPI_Win_flush_all(window) #else #define QUIET() shmem_quiet() #endif #ifdef USE_MPI3 #define BARRIER_ALL() QUIET(); MPI_Barrier(MPI_COMM_WORLD) #else #define BARRIER_ALL() shmem_barrier_all() #endif #ifdef USE_MPI3 static inline int malloc_all(size_t size, void **address) { *address = next_window_address; next_window_address += size; MPI_Barrier(MPI_COMM_WORLD); if (next_window_address - window_base > window_size) { printf("ran out of memory!\n"); return -1; } else return 0; } #else static inline int malloc_all(size_t size, void **address) { *address = shmalloc(size); if (*address == NULL) return -1; else return 0; } #endif #ifdef USE_MPI3 #define FREE_ALL(address) /* unable to free memory like this */ #else #define FREE_ALL(address) shfree(address) #endif static inline int global_index_to_rank(const seq_t *in, const index_t codon_index){ return codon_index / in->local_size; } static inline int global_index_to_local_index(const seq_t *in, const index_t codon_index){ return codon_index % in->local_size; } static inline void fetch_from_seq(const seq_t *in, index_t const codon_index, codon_t *out){ int target_ep = global_index_to_rank(in,codon_index); int local_index = global_index_to_local_index(in,codon_index); short *typed_seq = (short *)in->sequence; SHORT_GET((short *)out, &(typed_seq[local_index]), 1, target_ep); } static inline void fetch_from_seq_nb(const seq_t *in, index_t const codon_index, codon_t *out){ int target_ep = global_index_to_rank(in,codon_index); int local_index = global_index_to_local_index(in,codon_index); short *typed_seq = (short *)in->sequence; SHORT_GET_NB((short *)out, &(typed_seq[local_index]), 1, target_ep); } static inline void write_to_seq(const seq_t *in, const index_t codon_index, codon_t data){ int target_ep = global_index_to_rank(in,codon_index); int local_index = global_index_to_local_index(in,codon_index); short *typed_seq = (short *)in->sequence; short typed_data = (short)data; SHORT_PUT(&(typed_seq[local_index]), &typed_data, 1, target_ep); } #ifdef USE_MPI3 #define WAIT_NB() QUIET() #else #define WAIT_NB() QUIET() #endif void distribute_rng_seed(unsigned int new_seed); void seed_rng(int adjustment); void touch_memory(void *mem, index_t size); index_t scrub_hyphens(good_match_t *A, seq_t *dest, seq_t *source, index_t length); void assemble_acid_chain(good_match_t *A, char *result, seq_t *chain, index_t length); void assemble_codon_chain(good_match_t *A, char *result, seq_t *chain, index_t length); score_t simple_score(good_match_t *A, seq_t *main, seq_t *match); seq_t *alloc_global_seq(index_t seq_size); seq_t *alloc_local_seq(index_t seq_size); void free_global_seq(seq_t *doomed); void free_local_seq(seq_t *doomed); #endif
gwamoniak/Cpp
Point_equalityOperator/point.h
<reponame>gwamoniak/Cpp<filename>Point_equalityOperator/point.h<gh_stars>0 #pragma once #ifndef POINT_H #define POINT_H #include <iostream> class Point { friend std::ostream& operator << (std::ostream& out, const Point& p); public: Point() = default; Point(double x, double y) :mX{x},mY{y}{} Point(double x_y) : Point{ mX,mY } {} ~Point() = default; bool operator==(const Point& other) const; private: double mX{}; double mY{}; double length() const; }; inline std::ostream& operator << (std::ostream& out, const Point& p) { out << "Point [ x: " << p.mX << ", y :" << p.mY << "length: " <<p.length() << " ]"; } #endif
Andries-Smit/nativecontacts
ios/AppDelegate.h
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder<UIApplicationDelegate> @property (nonatomic, strong) UIWindow *window; @property BOOL shouldOpenInLastApp; @end
Andries-Smit/nativecontacts
ios/MendixNative/AppPreferences.h
<filename>ios/MendixNative/AppPreferences.h<gh_stars>10-100 // // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> @interface AppPreferences : NSObject + (NSString *) getAppUrl; + (void) setAppUrl:(NSString *)url; + (BOOL) devModeEnabled; + (void) devMode:(BOOL)enable; + (BOOL) remoteDebuggingEnabled; + (void) remoteDebugging:(BOOL)enable; + (void) setRemoteDebuggingPackagerPort:(NSInteger)port; + (int) getRemoteDebuggingPackagerPort; + (BOOL) isElementInspectorEnabled; + (void) setElementInspector:(BOOL)enable; @end
Andries-Smit/nativecontacts
ios/MendixNative/MendixBackwardsCompatUtility.h
<gh_stars>10-100 // // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> #import "UnsupportedFeatures.h" extern const UnsupportedFeatures *DEFAULT_UNSUPPORTED_FEATURES; @interface MendixBackwardsCompatUtility: NSObject + (NSDictionary<NSString *, UnsupportedFeatures *> *) versionDictionary; + (UnsupportedFeatures *) unsupportedFeatures; + (void) update:(NSString *)forVersion; @end
Andries-Smit/nativecontacts
ios/MendixNative/RuntimeInfo.h
// // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> @interface RuntimeInfo: NSObject @property (nonatomic, copy, readonly) NSString *cacheburst; @property (nonatomic, readonly) long nativeBinaryVersion; @property (nonatomic, readonly) long packagerPort; @property (nonatomic, copy, readonly) NSString *version; - (instancetype) initWithVersion:(NSString *)version cacheburst:(NSString *)cacheburst nativeBinaryVersion:(long)nativeBinaryVersion packagerPort:(long)packagerPort; @end
Andries-Smit/nativecontacts
ios/MendixNative/WarningsFilter.h
// // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> typedef NS_ENUM(NSInteger, WarningsFilter) { all, partial, none }; extern NSString * const WarningsFilter_toString[];
Andries-Smit/nativecontacts
ios/MendixNative/UnsupportedFeatures.h
<reponame>Andries-Smit/nativecontacts<filename>ios/MendixNative/UnsupportedFeatures.h // // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> @interface UnsupportedFeatures: NSObject @property BOOL reloadInClient; @property BOOL hideSplashScreenInClient; - (id _Nonnull)init:(BOOL)reloadInClient; - (id _Nonnull)init:(BOOL)reloadInClient hideSplashScreenInClient:(BOOL)hideSplashScreenInClient; @end
Andries-Smit/nativecontacts
ios/MendixNative/MendixApp.h
<gh_stars>10-100 // // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "AppMenuProtocol.h" #import "SplashScreenPresenterProtocol.h" #import "WarningsFilter.h" @interface MendixApp : NSObject @property NSURL * _Nonnull bundleUrl; @property NSURL * _Nonnull runtimeUrl; @property WarningsFilter warningsFilter; @property NSString * _Nullable identifier; @property BOOL isDeveloperApp; @property BOOL clearDataAtLaunch; @property id<AppMenuProtocol> _Nullable appMenu; @property id<SplashScreenPresenterProtocol> _Nullable splashScreenPresenter; @property UIStoryboard * _Nullable reactLoading; @property BOOL enableThreeFingerGestures; -(id _Nonnull)init:(NSString * _Nullable)identifier bundleUrl:(NSURL * _Nonnull)bundleUrl runtimeUrl:(NSURL * _Nonnull)runtimeUrl warningsFilter:(WarningsFilter)warningsFilter isDeveloperApp:(BOOL)enableGestures clearDataAtLaunch:(BOOL)clearDataAtLaunch splashScreenPresenter:(id<SplashScreenPresenterProtocol> _Nonnull)splashScreenPresenter; -(id _Nonnull)init:(NSString * _Nullable)identifier bundleUrl:(NSURL * _Nonnull)bundleUrl runtimeUrl:(NSURL * _Nonnull)runtimeUrl warningsFilter:(WarningsFilter)warningsFilter isDeveloperApp:(BOOL)enableGestures clearDataAtLaunch:(BOOL)clearDataAtLaunch reactLoading:(UIStoryboard * _Nonnull)reactLoading; -(id _Nonnull)init:(NSString * _Nullable)identifier bundleUrl:(NSURL * _Nonnull)bundleUrl runtimeUrl:(NSURL * _Nonnull)runtimeUrl warningsFilter:(WarningsFilter)warningsFilter isDeveloperApp:(BOOL)enableGestures clearDataAtLaunch:(BOOL)clearDataAtLaunch splashScreenPresenter:(id<SplashScreenPresenterProtocol> _Nonnull)splashScreenPresenter enableThreeFingerGestures:(BOOL)enableThreeFingerGestures ; -(id _Nonnull)init:(NSString * _Nullable)identifier bundleUrl:(NSURL * _Nonnull)bundleUrl runtimeUrl:(NSURL * _Nonnull)runtimeUrl warningsFilter:(WarningsFilter)warningsFilter isDeveloperApp:(BOOL)enableGestures clearDataAtLaunch:(BOOL)clearDataAtLaunch reactLoading:(UIStoryboard * _Nonnull)reactLoading enableThreeFingerGestures:(BOOL)enableThreeFingerGestures; -(id _Nonnull)init:(NSString * _Nullable)identifier bundleUrl:(NSURL * _Nonnull)bundleUrl runtimeUrl:(NSURL * _Nonnull)runtimeUrl warningsFilter:(WarningsFilter)warningsFilter isDeveloperApp:(BOOL)enableGestures clearDataAtLaunch:(BOOL)clearDataAtLaunch; @end
Andries-Smit/nativecontacts
ios/MendixNative/SplashScreenPresenterProtocol.h
// // Copyright (c) Mendix, Inc. All rights reserved. // #import <UIKit/UIKit.h> @protocol SplashScreenPresenterProtocol - (void) show:(UIView * _Nullable)rootView; - (void) hide; @end
Andries-Smit/nativecontacts
ios/MendixNative/AppMenuProtocol.h
<filename>ios/MendixNative/AppMenuProtocol.h<gh_stars>1-10 #import <Foundation/Foundation.h> @protocol AppMenuProtocol @required -(void) show:(BOOL)devMode; @end
Andries-Smit/nativecontacts
ios/MendixNative/MxConfiguration.h
<filename>ios/MendixNative/MxConfiguration.h<gh_stars>1-10 // // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> #import <React/RCTBridgeModule.h> #import "WarningsFilter.h" @interface MxConfiguration : NSObject <RCTBridgeModule> + (NSString *) defaultDatabaseName; + (NSString *) defaultFilesDirectoryName; + (NSURL *) runtimeUrl; + (NSString *) databaseName; + (NSString *) filesDirectoryName; + (NSString *) codePushKey; + (WarningsFilter) warningsFilter; + (void) setRuntimeUrl:(NSURL*)value; + (void) setDatabaseName:(NSString*)value; + (void) setFilesDirectoryName:(NSString*)value; + (void) setWarningsFilter:(WarningsFilter)value; + (void) setCodePushKey:(NSString*)value; @end
Andries-Smit/nativecontacts
ios/MendixNative/MendixReactWindow.h
// // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> #import "UIKit/UIKit.h" @interface MendixReactWindow : UIWindow @end
Andries-Smit/nativecontacts
ios/MendixAppDelegate.h
#import <UIKit/UIKit.h> @interface MendixAppDelegate : NSObject + (void) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions; + (void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification; + (void) application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler; + (void) application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings; + (void) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation; @end
Andries-Smit/nativecontacts
ios/MendixNative/RuntimeInfoResponse.h
<reponame>Andries-Smit/nativecontacts // // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> #import "RuntimeInfo.h" @interface RuntimeInfoResponse : NSObject @property (nonatomic, copy, readonly) NSString *status; @property (nonatomic, copy, readonly) RuntimeInfo *runtimeInfo; - (instancetype) initWithStatus:(NSString *)status runtimeInfo:(RuntimeInfo *)runtimeInfo; @end
Andries-Smit/nativecontacts
ios/RNSplashScreen+StoryBoardSplash.h
#import <Foundation/Foundation.h> #import "RNSplashScreen.h" @interface RNSplashScreen (StoryBoardSplash) + (void)showStoryBoard:(NSString *)name inRootView:(UIView *)rootView; + (void)hideStoryBoard; @end
Andries-Smit/nativecontacts
ios/SplashScreenPresenter.h
#import <Foundation/Foundation.h> #import "SplashScreenPresenterProtocol.h" @interface SplashScreenPresenter : NSObject<SplashScreenPresenterProtocol> @end
Andries-Smit/nativecontacts
ios/MendixNative/RuntimeInfoProvider.h
// // Copyright (c) Mendix, Inc. All rights reserved. // #import <Foundation/Foundation.h> #import "RuntimeInfoResponse.h" @interface RuntimeInfoProvider: NSObject + (void) getRuntimeInfo:(NSURL*) runtimeURL completionHandler:(void (^)(RuntimeInfoResponse *response))completionHandler; @end
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WRContent/ContentViewController.h
// // ContentViewController.h // Weather-Report // // Created by 沈君瑶 on 2019/8/10. // Copyright © 2019 沈君瑶. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface ContentViewController : UIViewController @property NSMutableArray *contentMutableArray; @property NSMutableArray *futureHourMutableArray; @property NSMutableArray *futureDayMutableArray; @property NSMutableArray *nowMutableArray; @property NSMutableArray *nowWeatherMutableArray; @property (nonatomic, assign) NSInteger contentNumber; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WRSearch/SearchViewController.h
<reponame>yaoayaoyyao/Weather-Report // // SearchViewController.h // Weather-Report // // Created by 沈君瑶 on 2019/8/8. // Copyright © 2019 沈君瑶. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @protocol SearchViewControllerDelegate <NSObject> - (void)passNSString:(NSString *)str; @end @interface SearchViewController : UIViewController @property NSMutableArray *searchMutableArray; @property id<SearchViewControllerDelegate> delegate; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WRContent/NowTableViewCell.h
// // NowTableViewCell.h // Weather-Report // // Created by 沈君瑶 on 2019/8/10. // Copyright © 2019 沈君瑶. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface NowTableViewCell : UITableViewCell @property (nonatomic, strong) UILabel *titleLabel; @property (nonatomic, strong) UILabel *conLabel; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WRContent/WeekTableViewCell.h
<reponame>yaoayaoyyao/Weather-Report<filename>Weather-Report/Weather-Report/WRContent/WeekTableViewCell.h // // WeekTableViewCell.h // Weather-Report // // Created by 沈君瑶 on 2019/8/10. // Copyright © 2019 沈君瑶. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface WeekTableViewCell : UITableViewCell @property (nonatomic, strong) UILabel *weekLabel; @property (nonatomic, strong) UIImageView *weatherImageView; @property (nonatomic, strong) UILabel *temNowLabel; @property (nonatomic, strong) UILabel *temAllLabel; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WRContent/ContentHeadView.h
// // ContentHeadView.h // Weather-Report // // Created by 沈君瑶 on 2019/8/9. // Copyright © 2019 沈君瑶. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface ContentHeadView : UIView @property (nonatomic, strong) UILabel *locationLabel; @property (nonatomic, strong) UILabel *temperatureLabel; @property (nonatomic, strong) UILabel *weatherLabel; @property (nonatomic, strong) UILabel *timeLabel; @property (nonatomic, strong) UILabel *todayLabel; @property (nonatomic, strong) UILabel *tmpMax; @property (nonatomic, strong) UILabel *tmpMin; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WeatherData/FutureDay.h
// // FutureDay.h // Weather-Report // // Created by 沈君瑶 on 2019/8/13. // Copyright © 2019 沈君瑶. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface FutureDay : NSObject @property NSString *futureDayLocationString; @property NSString *weekString; @property NSString *wtIconString; @property NSString *wtTempMaxString; @property NSString *wtTempMinString; - (instancetype)initWithweekString:(NSString *)weekString andwtIconString:(NSString *)wtIconString andwtTempMaxString:(NSString *)wtTempMaxString andwtTempMinString:(NSString *)wtTempMinString andfutureDayLocationString:(NSString *)futureDayLocationString; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WRMain/MainTableViewCell.h
// // MainTableViewCell.h // Weather-Report // // Created by 沈君瑶 on 2019/8/9. // Copyright © 2019 沈君瑶. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface MainTableViewCell : UITableViewCell @property (nonatomic, strong) UILabel *timeLabel; @property (nonatomic, strong) UILabel *locationLabel; @property (nonatomic, strong) UILabel *temperatureLabel; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WRContent/HoursView.h
<gh_stars>0 // // HoursView.h // Weather-Report // // Created by 沈君瑶 on 2019/8/10. // Copyright © 2019 沈君瑶. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface HoursView : UIView @property (nonatomic, strong) UILabel *timeLabel; @property (nonatomic, strong) UIImageView *weatherImageView; @property (nonatomic, strong) UILabel *temLabel; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WeatherData/FutureHour.h
<filename>Weather-Report/Weather-Report/WeatherData/FutureHour.h // // FutureHour.h // Weather-Report // // Created by 沈君瑶 on 2019/8/14. // Copyright © 2019 沈君瑶. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface FutureHour : NSObject @property NSString *futureHourLocationString; @property NSString *dateYmdh; @property NSString *wtIconString; @property NSString *wtTempString; - (instancetype)initWithdateYmdh:(NSString *)dateYmdh andwtIconString:(NSString *)wtIconString andwtTempString:(NSString *)wtTempString andfutureHourLocationString:(NSString *)futureHourLocationString; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WeatherData/Weather.h
<gh_stars>0 // // Weather.h // Weather-Report // // Created by 沈君瑶 on 2019/8/12. // Copyright © 2019 沈君瑶. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface Weather : NSObject @property NSString *location; @property NSString *cond; @property NSString *tmpNow; @property NSString *tmpMax; @property NSString *tmpMin; @property NSString *comf; - (instancetype)initWithcond:(NSString *)newcond andtmpNow:(NSString *)newtmpNow andtmpMax:(NSString *)newtmpMax andtmpMin:(NSString *)newtmpMin andcomf:(NSString *)newcomf andlocation:(NSString *)location; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WRContent/ContentView.h
<filename>Weather-Report/Weather-Report/WRContent/ContentView.h // // ContentView.h // Weather-Report // // Created by 沈君瑶 on 2019/8/10. // Copyright © 2019 沈君瑶. All rights reserved. // #import <UIKit/UIKit.h> #import "ContentHeadView.h" #import "Weather.h" NS_ASSUME_NONNULL_BEGIN @interface ContentView : UIView<UITableViewDelegate,UITableViewDataSource> @property (nonatomic, strong) UITableView *contentTableView; @property (nonatomic, strong) UIScrollView *hoursScrollView; @property (nonatomic, strong) ContentHeadView *contentHeadView; @property NSMutableArray *futureHourMutableArray; @property NSMutableArray *futureDayMutableArray; @property NSMutableArray *nowMutableArray; @property Weather *nowWeather; @property NSMutableArray *nowNameMutableArray; - (instancetype)initWithFrame:(CGRect)frame andLocation:(NSString *)location andnowMutableArray:(NSMutableArray *)nowMutableArray andnowWeather:(Weather *)nowWeather andfutureDayMutableArray:(NSMutableArray *)futureDayMutableArray andfutureHourMutableArray:(NSMutableArray *)futureHourMutableArray; @end NS_ASSUME_NONNULL_END
yaoayaoyyao/Weather-Report
Weather-Report/Weather-Report/WRMain/MainViewController.h
<filename>Weather-Report/Weather-Report/WRMain/MainViewController.h // // MainViewController.h // Weather-Report // // Created by 沈君瑶 on 2019/8/9. // Copyright © 2019 沈君瑶. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface MainViewController : UIViewController @property (nonatomic, copy)NSMutableArray *mainMutableArray; @property NSMutableArray *nowMutableArray; @property NSMutableArray *nowWeatherMutableArray; @property NSMutableArray *futureDayMutableArray; @property NSMutableArray *futureHourMutableArray; @end NS_ASSUME_NONNULL_END
twinaphex/OpenLara
src/network.h
<filename>src/network.h<gh_stars>10-100 #ifndef H_NET #define H_NET #include "core.h" #include "utils.h" #include "format.h" #include "controller.h" #include "ui.h" #define NET_PROTOCOL 1 #define NET_PORT 21468 #define NET_PING_TIMEOUT ( 1000 * 10 ) #define NET_PING_PERIOD ( 1000 * 3 ) #define NET_SYMC_INPUT_PERIOD ( 1000 / 25 ) #define NET_SYMC_STATE_PERIOD ( 1000 / 1000 ) namespace Network { struct Packet { enum Type { HELLO, INFO, PING, PONG, JOIN, ACCEPT, REJECT, INPUT, STATE, }; uint16 type; uint16 id; union { struct { uint8 protocol; uint8 game; } hello; struct { str16 name; uint8 level; uint8 players; struct { uint16 secure:1; } flags; } info; struct { str16 nick; str16 pass; } join; struct { uint16 id; uint8 level; uint8 roomIndex; int16 posX; int16 posY; int16 posZ; int16 angle; } accept; struct { uint16 reason; } reject; struct { uint16 mask; } input; struct { uint8 roomIndex; uint8 reserved; int16 pos[3]; int16 angle[2]; uint8 frame; uint8 stand; uint16 animIndex; } state; }; int getSize() const { const int sizes[] = { sizeof(hello), sizeof(info), 0, 0, sizeof(join), sizeof(accept), sizeof(reject), sizeof(input), sizeof(state), }; if (type >= 0 && type < COUNT(sizes)) return 2 + 2 + sizes[type]; ASSERT(false); return 0; } }; IGame *game; struct Player { NAPI::Peer peer; int pingTime; int pingIndex; Controller *controller; }; Array<Player> players; int syncInputTime; int syncStateTime; void start(IGame *game) { Network::game = game; NAPI::listen(NET_PORT); syncInputTime = syncStateTime = osGetTime(); } void stop() { players.clear(); } bool sendPacket(const NAPI::Peer &to, const Packet &packet) { return NAPI::send(to, &packet, packet.getSize()) > 0; } bool recvPacket(NAPI::Peer &from, Packet &packet) { int count = NAPI::recv(from, &packet, sizeof(packet)); if (count > 0) { if (count != packet.getSize()) { ASSERT(false); return false; } return true; } return false; } void sayHello() { Packet packet; packet.type = Packet::HELLO; packet.hello.protocol = NET_PROTOCOL; packet.hello.game = game->getLevel()->version & TR::VER_VERSION; NAPI::broadcast(&packet, packet.getSize()); } void joinGame(const NAPI::Peer &peer) { Packet packet; packet.type = Packet::JOIN; packet.join.nick = "Player_2"; packet.join.pass = ""; LOG("join game\n"); sendPacket(peer, packet); } void pingPlayers(int time) { int i = 0; while (i < players.length) { int delta = time - players[i].pingTime; if (delta > NET_PING_TIMEOUT) { players.removeFast(i); continue; } if (delta > NET_PING_PERIOD) { Packet packet; packet.type = Packet::PING; sendPacket(players[i].peer, packet); } i++; } } void syncInput(int time) { Lara *lara = (Lara*)game->getLara(); if (!lara) return; if ((time - syncInputTime) < NET_SYMC_INPUT_PERIOD) return; Packet packet; packet.type = Packet::INPUT; packet.input.mask = lara->getInput(); for (int i = 0; i < players.length; i++) sendPacket(players[i].peer, packet); syncInputTime = time; } void syncState(int time) { if ((time - syncStateTime) < NET_SYMC_STATE_PERIOD) return; // TODO syncStateTime = time; } Player* getPlayerByPeer(const NAPI::Peer &peer) { for (int i = 0; i < players.length; i++) if (players[i].peer == peer) { return &players[i]; } return NULL; } void getSpawnPoint(uint8 &roomIndex, vec3 &pos, float &angle) { Controller *lara = game->getLara(); roomIndex = lara->getRoomIndex(); pos = lara->getPos(); angle = normalizeAngle(lara->angle.y); // 0..2PI } void update() { int count; NAPI::Peer from; Packet packet, response; int time = osGetTime(); while ( (count = recvPacket(from, packet)) > 0 ) { Player *player = getPlayerByPeer(from); if (player) player->pingTime = time; switch (packet.type) { case Packet::HELLO : if (game->getLevel()->isTitle()) break; LOG("recv HELLO\n"); if (packet.hello.game != (game->getLevel()->version & TR::VER_VERSION)) break; if (packet.hello.protocol != NET_PROTOCOL) break; LOG("send INFO\n"); response.type = Packet::INFO; response.info.name = "MultiOpenLara"; response.info.level = game->getLevel()->id; response.info.players = players.length + 1; response.info.flags.secure = false; sendPacket(from, response); break; case Packet::INFO : { LOG("recv INFO\n"); char buf[sizeof(packet.info.name) + 1]; packet.info.name.get(buf); LOG("name: %s\n", buf); joinGame(from); break; } case Packet::PING : if (player) { response.type = Packet::PONG; sendPacket(from, response); } break; case Packet::PONG : break; case Packet::JOIN : if (!player) { uint8 roomIndex; vec3 pos; float angle; getSpawnPoint(roomIndex, pos, angle); Player newPlayer; newPlayer.peer = from; newPlayer.pingIndex = 0; newPlayer.pingTime = time; newPlayer.controller = game->addEntity(TR::Entity::LARA, roomIndex, pos, angle); players.push(newPlayer); ((Lara*)newPlayer.controller)->networkInput = 0; char buf[32]; packet.join.nick.get(buf); LOG("Player %s joined\n", buf); ASSERT(newPlayer.controller); TR::Room &room = game->getLevel()->rooms[roomIndex]; vec3 offset = pos - room.getOffset(); response.type = Packet::ACCEPT; response.accept.id = 0; response.accept.level = game->getLevel()->id; response.accept.roomIndex = roomIndex; response.accept.posX = int16(offset.x); response.accept.posY = int16(offset.y); response.accept.posZ = int16(offset.z); response.accept.angle = int16(angle * RAD2DEG); sendPacket(from, response); } break; case Packet::ACCEPT : { LOG("accept!\n"); game->loadLevel(TR::LevelID(packet.accept.level)); inventory->toggle(); break; } case Packet::REJECT : break; case Packet::INPUT : if (game->getLevel()->isTitle()) break; if (!player) { uint8 roomIndex; vec3 pos; float angle; getSpawnPoint(roomIndex, pos, angle); Player newPlayer; newPlayer.peer = from; newPlayer.pingIndex = 0; newPlayer.pingTime = time; newPlayer.controller = game->addEntity(TR::Entity::LARA, roomIndex, pos, angle); players.push(newPlayer); ((Lara*)newPlayer.controller)->networkInput = 0; player = getPlayerByPeer(from); } if (player) { ((Lara*)player->controller)->networkInput = packet.input.mask; } break; case Packet::STATE : break; } } pingPlayers(time); syncInput(time); syncState(time); } } #endif
twinaphex/OpenLara
src/platform/libretro/libretro_core_options.h
<filename>src/platform/libretro/libretro_core_options.h #ifndef LIBRETRO_CORE_OPTIONS_H__ #define LIBRETRO_CORE_OPTIONS_H__ #include <stdlib.h> #include <string.h> #include <libretro.h> #include <retro_inline.h> #ifdef __cplusplus extern "C" { #endif /* ******************************** * Core Option Definitions ******************************** */ /* RETRO_LANGUAGE_ENGLISH */ /* Default language: * - All other languages must include the same keys and values * - Will be used as a fallback in the event that frontend language * is not available * - Will be used as a fallback for any missing entries in * frontend language definition */ struct retro_core_option_definition option_defs_us[] = { { "openlara_resolution", "Internal resolution (restart)", "Configure the resolution. Requires a restart.", { { "320x240", NULL }, { "360x480", NULL }, { "480x272", NULL }, { "512x384", NULL }, { "512x512", NULL }, { "640x224", NULL }, { "640x448", NULL }, { "640x480", NULL }, { "720x576", NULL }, { "800x600", NULL }, { "960x720", NULL }, { "1024x768", NULL }, { "1280x720", NULL }, { "1280x960", NULL }, { "1600x1200", NULL }, { "1920x1080", NULL }, { "1920x1440", NULL }, { "1920x1600", NULL }, { "2048x2048", NULL }, { "2560x1440", NULL }, { "3840x2160", NULL }, { "7680x4320", NULL }, { "15360x8640", NULL }, { "16000x9000", NULL }, { NULL, NULL }, }, "320x240" }, { "openlara_framerate", "Framerate (restart)", "Modify framerate. Requires a restart.", { { "30fps", NULL}, { "60fps", NULL}, { "70fps", NULL}, { "72fps", NULL}, { "75fps", NULL}, { "90fps", NULL}, { "100fps", NULL}, { "119fps", NULL}, { "120fps", NULL}, { "144fps", NULL}, { "240fps", NULL}, { "244fps", NULL}, { NULL, NULL }, }, "60fps" }, { NULL, NULL, NULL, {{0}}, NULL }, }; /* RETRO_LANGUAGE_JAPANESE */ /* RETRO_LANGUAGE_FRENCH */ /* RETRO_LANGUAGE_SPANISH */ /* RETRO_LANGUAGE_GERMAN */ /* RETRO_LANGUAGE_ITALIAN */ /* RETRO_LANGUAGE_DUTCH */ /* RETRO_LANGUAGE_PORTUGUESE_BRAZIL */ /* RETRO_LANGUAGE_PORTUGUESE_PORTUGAL */ /* RETRO_LANGUAGE_RUSSIAN */ /* RETRO_LANGUAGE_KOREAN */ /* RETRO_LANGUAGE_CHINESE_TRADITIONAL */ /* RETRO_LANGUAGE_CHINESE_SIMPLIFIED */ /* RETRO_LANGUAGE_ESPERANTO */ /* RETRO_LANGUAGE_POLISH */ /* RETRO_LANGUAGE_VIETNAMESE */ /* RETRO_LANGUAGE_ARABIC */ /* RETRO_LANGUAGE_GREEK */ /* RETRO_LANGUAGE_TURKISH */ /* ******************************** * Language Mapping ******************************** */ struct retro_core_option_definition *option_defs_intl[RETRO_LANGUAGE_LAST] = { option_defs_us, /* RETRO_LANGUAGE_ENGLISH */ NULL, /* RETRO_LANGUAGE_JAPANESE */ NULL, /* RETRO_LANGUAGE_FRENCH */ NULL, /* RETRO_LANGUAGE_SPANISH */ NULL, /* RETRO_LANGUAGE_GERMAN */ NULL, /* RETRO_LANGUAGE_ITALIAN */ NULL, /* RETRO_LANGUAGE_DUTCH */ NULL, /* RETRO_LANGUAGE_PORTUGUESE_BRAZIL */ NULL, /* RETRO_LANGUAGE_PORTUGUESE_PORTUGAL */ NULL, /* RETRO_LANGUAGE_RUSSIAN */ NULL, /* RETRO_LANGUAGE_KOREAN */ NULL, /* RETRO_LANGUAGE_CHINESE_TRADITIONAL */ NULL, /* RETRO_LANGUAGE_CHINESE_SIMPLIFIED */ NULL, /* RETRO_LANGUAGE_ESPERANTO */ NULL, /* RETRO_LANGUAGE_POLISH */ NULL, /* RETRO_LANGUAGE_VIETNAMESE */ NULL, /* RETRO_LANGUAGE_ARABIC */ NULL, /* RETRO_LANGUAGE_GREEK */ NULL, /* RETRO_LANGUAGE_TURKISH */ }; /* ******************************** * Functions ******************************** */ /* Handles configuration/setting of core options. * Should only be called inside retro_set_environment(). * > We place the function body in the header to avoid the * necessity of adding more .c files (i.e. want this to * be as painless as possible for core devs) */ static INLINE void libretro_set_core_options(retro_environment_t environ_cb) { unsigned version = 0; if (!environ_cb) return; if (environ_cb(RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION, &version) && (version == 1)) { struct retro_core_options_intl core_options_intl; unsigned language = 0; core_options_intl.us = option_defs_us; core_options_intl.local = NULL; if (environ_cb(RETRO_ENVIRONMENT_GET_LANGUAGE, &language) && (language < RETRO_LANGUAGE_LAST) && (language != RETRO_LANGUAGE_ENGLISH)) core_options_intl.local = option_defs_intl[language]; environ_cb(RETRO_ENVIRONMENT_SET_CORE_OPTIONS_INTL, &core_options_intl); } else { size_t i; size_t num_options = 0; struct retro_variable *variables = NULL; char **values_buf = NULL; /* Determine number of options */ while (true) { if (option_defs_us[num_options].key) num_options++; else break; } /* Allocate arrays */ variables = (struct retro_variable *)calloc(num_options + 1, sizeof(struct retro_variable)); values_buf = (char **)calloc(num_options, sizeof(char *)); if (!variables || !values_buf) goto error; /* Copy parameters from option_defs_us array */ for (i = 0; i < num_options; i++) { const char *key = option_defs_us[i].key; const char *desc = option_defs_us[i].desc; const char *default_value = option_defs_us[i].default_value; struct retro_core_option_value *values = option_defs_us[i].values; size_t buf_len = 3; size_t default_index = 0; values_buf[i] = NULL; if (desc) { size_t num_values = 0; /* Determine number of values */ while (true) { if (values[num_values].value) { /* Check if this is the default value */ if (default_value) if (strcmp(values[num_values].value, default_value) == 0) default_index = num_values; buf_len += strlen(values[num_values].value); num_values++; } else break; } /* Build values string */ if (num_values > 1) { size_t j; buf_len += num_values - 1; buf_len += strlen(desc); values_buf[i] = (char *)calloc(buf_len, sizeof(char)); if (!values_buf[i]) goto error; strcpy(values_buf[i], desc); strcat(values_buf[i], "; "); /* Default value goes first */ strcat(values_buf[i], values[default_index].value); /* Add remaining values */ for (j = 0; j < num_values; j++) { if (j != default_index) { strcat(values_buf[i], "|"); strcat(values_buf[i], values[j].value); } } } } variables[i].key = key; variables[i].value = values_buf[i]; } /* Set variables */ environ_cb(RETRO_ENVIRONMENT_SET_VARIABLES, variables); error: /* Clean up */ if (values_buf) { for (i = 0; i < num_options; i++) { if (values_buf[i]) { free(values_buf[i]); values_buf[i] = NULL; } } free(values_buf); values_buf = NULL; } if (variables) { free(variables); variables = NULL; } } } #ifdef __cplusplus } #endif #endif
twinaphex/OpenLara
src/libs/minimp3/libc.h
<gh_stars>10-100 // a libc replacement (more or less) for the Microsoft Visual C compiler // this file is public domain -- do with it whatever you want! #ifndef __LIBC_H_INCLUDED__ #define __LIBC_H_INCLUDED__ #ifdef _MSC_VER #define INLINE __forceinline #define FASTCALL __fastcall #ifdef NOLIBC #ifdef MAIN_PROGRAM int _fltused=0; #endif #endif #else #define INLINE inline #define FASTCALL __attribute__((fastcall)) #include <stdint.h> #endif #ifdef _WIN32 #ifndef WIN32 #define WIN32 #endif #endif #ifdef WIN32 #include <windows.h> #endif #if !NEED_MINILIBC #include <stdio.h> #include <stdlib.h> #include <string.h> #endif #include <math.h> #include <stdint.h> #if !defined(__int8_t_defined) && !defined(__LIBRETRO__) #define __int8_t_defined typedef unsigned char uint8_t; typedef signed char int8_t; typedef unsigned short uint16_t; typedef signed short int16_t; typedef unsigned int uint32_t; typedef signed int int32_t; #ifdef _MSC_VER typedef unsigned __int64 uint64_t; typedef signed __int64 int64_t; #elif defined(__x86_64__) && defined(__linux__) #include <sys/types.h> #else typedef unsigned long long uint64_t; typedef signed long long int64_t; #endif #endif #ifndef NULL #define NULL 0 #endif #ifndef M_PI #define M_PI 3.14159265358979 #endif #define libc_malloc malloc #define libc_calloc calloc #define libc_realloc realloc #define libc_free free #define libc_memset memset #define libc_memcpy memcpy #define libc_memmove memmove #if defined(_MSC_VER) && !defined(_DEBUG) static INLINE double libc_frexp(double x, int *e) { double res = -9999.999; unsigned __int64 i = *(unsigned __int64*)(&x); if (!(i & 0x7F00000000000000UL)) { *e = 0; return x; } *e = ((i << 1) >> 53) - 1022; i &= 0x800FFFFFFFFFFFFFUL; i |= 0x3FF0000000000000UL; return *(double*)(&i) * 0.5; } #else #define libc_frexp frexp #endif #define libc_exp exp #define libc_pow pow #endif//__LIBC_H_INCLUDED__
twinaphex/OpenLara
src/glyph_cyr.h
#ifndef __GLYPH_CYR__ #define __GLYPH_CYR__ static unsigned int size_GLYPH_CYR = 3088; static unsigned char GLYPH_CYR[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x30, 0x08, 0x03, 0x00, 0x00, 0x00, 0xc9, 0xa1, 0x54, 0x4d, 0x00, 0x00, 0x00, 0x19, 0x74, 0x45, 0x58, 0x74, 0x53, 0x6f, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x00, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x20, 0x49, 0x6d, 0x61, 0x67, 0x65, 0x52, 0x65, 0x61, 0x64, 0x79, 0x71, 0xc9, 0x65, 0x3c, 0x00, 0x00, 0x03, 0x66, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x3f, 0x78, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x62, 0x65, 0x67, 0x69, 0x6e, 0x3d, 0x22, 0xef, 0xbb, 0xbf, 0x22, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x57, 0x35, 0x4d, 0x30, 0x4d, 0x70, 0x43, 0x65, 0x68, 0x69, 0x48, 0x7a, 0x72, 0x65, 0x53, 0x7a, 0x4e, 0x54, 0x63, 0x7a, 0x6b, 0x63, 0x39, 0x64, 0x22, 0x3f, 0x3e, 0x20, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x20, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x33, 0x2d, 0x63, 0x30, 0x31, 0x31, 0x20, 0x36, 0x36, 0x2e, 0x31, 0x34, 0x35, 0x36, 0x36, 0x31, 0x2c, 0x20, 0x32, 0x30, 0x31, 0x32, 0x2f, 0x30, 0x32, 0x2f, 0x30, 0x36, 0x2d, 0x31, 0x34, 0x3a, 0x35, 0x36, 0x3a, 0x32, 0x37, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x3e, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x6d, 0x6d, 0x2f, 0x22, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x73, 0x74, 0x52, 0x65, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x73, 0x54, 0x79, 0x70, 0x65, 0x2f, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x65, 0x66, 0x23, 0x22, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x20, 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3a, 0x4f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x44, 0x3d, 0x22, 0x78, 0x6d, 0x70, 0x2e, 0x64, 0x69, 0x64, 0x3a, 0x42, 0x42, 0x34, 0x35, 0x44, 0x30, 0x32, 0x41, 0x33, 0x38, 0x33, 0x36, 0x45, 0x39, 0x31, 0x31, 0x41, 0x46, 0x41, 0x46, 0x45, 0x31, 0x39, 0x34, 0x30, 0x32, 0x31, 0x32, 0x32, 0x37, 0x37, 0x46, 0x22, 0x20, 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3a, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x44, 0x3d, 0x22, 0x78, 0x6d, 0x70, 0x2e, 0x64, 0x69, 0x64, 0x3a, 0x44, 0x44, 0x39, 0x37, 0x30, 0x39, 0x39, 0x41, 0x33, 0x37, 0x32, 0x42, 0x31, 0x31, 0x45, 0x39, 0x42, 0x39, 0x35, 0x37, 0x46, 0x32, 0x33, 0x45, 0x42, 0x36, 0x41, 0x32, 0x42, 0x43, 0x34, 0x42, 0x22, 0x20, 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3a, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x49, 0x44, 0x3d, 0x22, 0x78, 0x6d, 0x70, 0x2e, 0x69, 0x69, 0x64, 0x3a, 0x44, 0x44, 0x39, 0x37, 0x30, 0x39, 0x39, 0x39, 0x33, 0x37, 0x32, 0x42, 0x31, 0x31, 0x45, 0x39, 0x42, 0x39, 0x35, 0x37, 0x46, 0x32, 0x33, 0x45, 0x42, 0x36, 0x41, 0x32, 0x42, 0x43, 0x34, 0x42, 0x22, 0x20, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3d, 0x22, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x20, 0x50, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x20, 0x43, 0x53, 0x36, 0x20, 0x28, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x73, 0x29, 0x22, 0x3e, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3a, 0x44, 0x65, 0x72, 0x69, 0x76, 0x65, 0x64, 0x46, 0x72, 0x6f, 0x6d, 0x20, 0x73, 0x74, 0x52, 0x65, 0x66, 0x3a, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x49, 0x44, 0x3d, 0x22, 0x78, 0x6d, 0x70, 0x2e, 0x69, 0x69, 0x64, 0x3a, 0x42, 0x38, 0x35, 0x32, 0x39, 0x45, 0x42, 0x39, 0x32, 0x34, 0x33, 0x37, 0x45, 0x39, 0x31, 0x31, 0x39, 0x31, 0x38, 0x41, 0x43, 0x39, 0x36, 0x38, 0x35, 0x41, 0x34, 0x38, 0x41, 0x42, 0x36, 0x38, 0x22, 0x20, 0x73, 0x74, 0x52, 0x65, 0x66, 0x3a, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x44, 0x3d, 0x22, 0x78, 0x6d, 0x70, 0x2e, 0x64, 0x69, 0x64, 0x3a, 0x42, 0x42, 0x34, 0x35, 0x44, 0x30, 0x32, 0x41, 0x33, 0x38, 0x33, 0x36, 0x45, 0x39, 0x31, 0x31, 0x41, 0x46, 0x41, 0x46, 0x45, 0x31, 0x39, 0x34, 0x30, 0x32, 0x31, 0x32, 0x32, 0x37, 0x37, 0x46, 0x22, 0x2f, 0x3e, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x20, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x20, 0x3c, 0x3f, 0x78, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x65, 0x6e, 0x64, 0x3d, 0x22, 0x72, 0x22, 0x3f, 0x3e, 0xb8, 0x39, 0x80, 0x02, 0x00, 0x00, 0x00, 0x3f, 0x50, 0x4c, 0x54, 0x45, 0xce, 0x94, 0x5a, 0xff, 0xef, 0x8c, 0xa5, 0x6b, 0x39, 0xff, 0xff, 0x9c, 0xa5, 0x7b, 0x4a, 0xdc, 0xa0, 0x64, 0x70, 0x5c, 0x2c, 0x30, 0x0c, 0x04, 0xe8, 0xc0, 0x70, 0xff, 0xd6, 0x7b, 0x58, 0x44, 0x00, 0xc8, 0x90, 0x58, 0xb0, 0x80, 0x50, 0x73, 0x5a, 0x29, 0xb5, 0x84, 0x52, 0x8c, 0x5a, 0x29, 0xef, 0xc6, 0x73, 0xde, 0xa5, 0x63, 0x31, 0x08, 0x00, 0x5a, 0x42, 0x00, 0xff, 0xff, 0xff, 0x41, 0x45, 0xe3, 0xb4, 0x00, 0x00, 0x00, 0x15, 0x74, 0x52, 0x4e, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x2b, 0xd9, 0x7d, 0xea, 0x00, 0x00, 0x07, 0xd4, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0xec, 0x9a, 0x89, 0x72, 0xdb, 0x38, 0x0c, 0x86, 0x29, 0x3a, 0x76, 0x9c, 0x74, 0x79, 0x42, 0xef, 0xff, 0xac, 0x0b, 0x80, 0x07, 0x00, 0xca, 0x6e, 0xe3, 0x99, 0xad, 0x9b, 0xd9, 0x5a, 0x53, 0xbb, 0xe1, 0x4d, 0x7c, 0x02, 0x29, 0xfe, 0xb0, 0xdc, 0xfe, 0x97, 0x5f, 0xee, 0x05, 0xe0, 0x9b, 0x5f, 0x89, 0x2e, 0xe0, 0xaf, 0xaf, 0xd7, 0x1f, 0xd7, 0x57, 0x00, 0x84, 0x79, 0xb5, 0x8c, 0xb0, 0x66, 0xcc, 0x2c, 0x49, 0xec, 0xfd, 0xd3, 0xb2, 0xc0, 0x4c, 0x6e, 0x8c, 0xac, 0x26, 0x60, 0xa6, 0xb3, 0x4e, 0x4f, 0xd7, 0xba, 0x51, 0x7d, 0x4f, 0xdb, 0x96, 0x23, 0xf0, 0x97, 0x19, 0x3f, 0xdc, 0x31, 0x98, 0xea, 0xc3, 0x96, 0x37, 0xfc, 0x94, 0x34, 0x26, 0x7f, 0x00, 0x34, 0xa7, 0x89, 0x00, 0xca, 0x86, 0x4d, 0xf0, 0xea, 0x03, 0x72, 0x5a, 0x67, 0xec, 0x81, 0x32, 0xb6, 0x32, 0x00, 0xd0, 0x5f, 0x09, 0x0b, 0xc3, 0x96, 0x39, 0x2b, 0x65, 0xac, 0x5d, 0x26, 0x01, 0x4f, 0x95, 0x3d, 0x65, 0xe7, 0x98, 0x86, 0x09, 0xd4, 0x5f, 0xf4, 0x52, 0x4e, 0xdd, 0x4b, 0x29, 0xe8, 0xff, 0xf7, 0x54, 0xa8, 0x1c, 0x07, 0x1c, 0x80, 0xc8, 0x74, 0xfa, 0xea, 0x00, 0x4e, 0x27, 0xd8, 0xe1, 0x74, 0x9a, 0x00, 0x16, 0x83, 0x77, 0xc8, 0x1e, 0x20, 0x03, 0x6c, 0x9e, 0x1b, 0x04, 0xec, 0xca, 0x00, 0x68, 0xf3, 0x4b, 0x63, 0x06, 0x0e, 0x6b, 0x60, 0xdf, 0x00, 0x65, 0xd8, 0xeb, 0x5b, 0x7a, 0x66, 0x84, 0x8d, 0xd2, 0x39, 0x8e, 0x5e, 0x62, 0x06, 0x06, 0x90, 0x1a, 0x21, 0xb4, 0xbf, 0x40, 0xd1, 0x04, 0xda, 0xbd, 0x4a, 0x45, 0x59, 0x48, 0xed, 0x6d, 0xff, 0x33, 0x0d, 0xa5, 0x03, 0xe8, 0x5d, 0xf8, 0x82, 0x06, 0x65, 0x07, 0x08, 0xb5, 0x11, 0x9b, 0x00, 0x7a, 0x7d, 0xaa, 0x87, 0xa5, 0x73, 0xbc, 0xc5, 0xe0, 0x99, 0xce, 0x3d, 0x1d, 0xe6, 0xbd, 0x33, 0xf3, 0xf3, 0x7d, 0x06, 0x0d, 0x00, 0x3b, 0xf2, 0x40, 0xd4, 0xc7, 0x1a, 0x19, 0x80, 0x00, 0x76, 0x05, 0x00, 0x90, 0x00, 0x1a, 0x3f, 0xaa, 0xa5, 0x42, 0x13, 0x57, 0x00, 0x5a, 0x01, 0xda, 0xd3, 0xa7, 0xcc, 0x69, 0x98, 0x06, 0x1c, 0xd3, 0x4c, 0x20, 0xa1, 0xcd, 0xfb, 0xec, 0x2f, 0xbb, 0x66, 0xe8, 0x9c, 0xf0, 0x0a, 0xa0, 0x1c, 0x01, 0xe4, 0x09, 0x20, 0xb6, 0x74, 0x6f, 0x81, 0xf3, 0x37, 0x00, 0x7a, 0x57, 0xa3, 0x47, 0x06, 0x60, 0xf6, 0x0b, 0x35, 0x37, 0x03, 0x40, 0x46, 0x8c, 0x19, 0x01, 0x9c, 0x47, 0xff, 0x00, 0xbb, 0x9a, 0x5f, 0x6f, 0x8f, 0xf6, 0x0f, 0x00, 0xf0, 0x0b, 0x00, 0x68, 0x21, 0xf7, 0xe0, 0xf7, 0xdb, 0x00, 0x9a, 0x07, 0x14, 0x01, 0xe0, 0x08, 0x40, 0x31, 0xe3, 0x19, 0x83, 0x6f, 0x00, 0xd0, 0xdb, 0xc0, 0x01, 0x00, 0x64, 0xb5, 0x22, 0xbf, 0x02, 0x80, 0x08, 0xe4, 0xb3, 0xae, 0x94, 0x94, 0x47, 0x72, 0x55, 0xf2, 0xe7, 0x7b, 0x00, 0xd6, 0x34, 0x1a, 0x47, 0xd3, 0xed, 0x0e, 0x40, 0x00, 0x12, 0x01, 0x48, 0xf7, 0x00, 0x38, 0x02, 0xe0, 0x1e, 0x02, 0x40, 0xbb, 0x8e, 0xae, 0xcf, 0xbb, 0xa0, 0x02, 0xc0, 0x6b, 0x72, 0xee, 0x01, 0x73, 0xe6, 0x77, 0x01, 0x90, 0xc1, 0x67, 0x5d, 0x07, 0x3d, 0xd2, 0x78, 0x00, 0x4d, 0xfe, 0x3e, 0x00, 0x2a, 0x30, 0x83, 0xf8, 0xec, 0xdc, 0x70, 0x00, 0x02, 0x80, 0x0e, 0xe6, 0xc8, 0x85, 0xee, 0x01, 0xf0, 0xde, 0x3f, 0x02, 0xa0, 0xb0, 0x7d, 0x59, 0xc6, 0xc7, 0x11, 0x70, 0x83, 0x12, 0x00, 0xa5, 0xad, 0xd9, 0xb1, 0x52, 0x7e, 0x0d, 0x80, 0xec, 0x3f, 0x9f, 0xd3, 0x1d, 0x02, 0x58, 0xb5, 0x2d, 0x53, 0x35, 0x01, 0xdd, 0xe9, 0x11, 0x00, 0xba, 0xc0, 0x74, 0x00, 0x26, 0x50, 0xb2, 0x43, 0xf3, 0x61, 0xbf, 0x05, 0x80, 0x08, 0xd0, 0xf5, 0x10, 0x00, 0x6c, 0xa4, 0x00, 0xa0, 0x07, 0xe0, 0x02, 0x2d, 0x8f, 0x00, 0x00, 0xe3, 0xb2, 0x71, 0x4b, 0x67, 0xdc, 0x03, 0xf4, 0x73, 0xdc, 0xb8, 0x38, 0x3b, 0xef, 0x03, 0x00, 0x68, 0x07, 0xf4, 0xe6, 0x49, 0x8d, 0x3c, 0x40, 0x36, 0x49, 0x0b, 0x80, 0x76, 0x1d, 0x70, 0x6f, 0x92, 0xa4, 0x3b, 0xac, 0x3c, 0x2e, 0x2d, 0x69, 0x28, 0xbc, 0x66, 0x9c, 0x19, 0x9f, 0x28, 0x0b, 0x00, 0xbf, 0x00, 0xf0, 0xc6, 0xbd, 0x73, 0xbf, 0xc6, 0x0c, 0x12, 0xee, 0x81, 0x08, 0x60, 0x10, 0x68, 0xfb, 0x91, 0x71, 0x71, 0x76, 0x4f, 0x35, 0x01, 0x0f, 0xba, 0xd3, 0x03, 0x10, 0x90, 0x47, 0x80, 0x00, 0xd1, 0xfe, 0x41, 0x6b, 0xb6, 0x44, 0x50, 0x55, 0x34, 0x80, 0xd5, 0x60, 0x5f, 0x62, 0xc4, 0xdb, 0x1b, 0x47, 0x0b, 0x7e, 0x62, 0x18, 0x00, 0xfe, 0x00, 0x00, 0x07, 0xc0, 0xfa, 0xf5, 0x0e, 0x80, 0x52, 0xe9, 0x9a, 0x33, 0x8e, 0xfd, 0x0c, 0x90, 0xb6, 0x48, 0xc9, 0x1a, 0xc9, 0xe5, 0x70, 0x09, 0x54, 0x35, 0x80, 0xf2, 0x00, 0x6c, 0xff, 0x73, 0x00, 0xd5, 0xc1, 0x62, 0xff, 0x0a, 0xa0, 0x5d, 0xda, 0x65, 0xe0, 0x4d, 0x00, 0x88, 0xc1, 0xed, 0x86, 0xc4, 0x52, 0x4c, 0x0b, 0x5a, 0xfe, 0xda, 0x65, 0xd8, 0x5e, 0xe7, 0x86, 0x4f, 0x39, 0x18, 0xb5, 0x87, 0xfd, 0xd4, 0x81, 0x1e, 0xab, 0x1f, 0x13, 0xc6, 0x04, 0x02, 0xed, 0x7f, 0x04, 0x00, 0x3b, 0x0e, 0x9d, 0x40, 0x96, 0xe6, 0xa3, 0x3d, 0x8c, 0x09, 0x74, 0x07, 0x90, 0xa7, 0x62, 0xa4, 0x3f, 0xa3, 0x18, 0x54, 0xf5, 0x82, 0x1e, 0xcc, 0xd5, 0x14, 0x18, 0x7f, 0xc5, 0x16, 0xe9, 0x26, 0x80, 0xd5, 0xe0, 0x3a, 0xae, 0xde, 0x02, 0xde, 0x78, 0xcb, 0x78, 0xab, 0x6a, 0x0f, 0x74, 0x64, 0x7f, 0xaf, 0xef, 0x5a, 0x65, 0xfc, 0xe8, 0xf1, 0xd4, 0x84, 0x6a, 0x2b, 0xaa, 0xa3, 0x46, 0xa0, 0x3f, 0xfa, 0x27, 0xa8, 0x19, 0xee, 0xb6, 0x3d, 0x1f, 0x26, 0xfb, 0x84, 0x4c, 0xa7, 0x55, 0x66, 0x28, 0x2d, 0xac, 0x3e, 0xb1, 0x1d, 0x9a, 0x69, 0x0c, 0x2b, 0xec, 0x7c, 0x61, 0x74, 0x69, 0x30, 0x02, 0x1f, 0xe5, 0xd6, 0xa2, 0x5a, 0xed, 0x0c, 0x5e, 0x72, 0xf8, 0x05, 0xe0, 0x3f, 0x93, 0xed, 0x0f, 0x08, 0xfc, 0xef, 0x04, 0x60, 0x91, 0xcb, 0x4a, 0xd1, 0xab, 0x94, 0xb5, 0x6f, 0x8d, 0x37, 0xd0, 0x53, 0x44, 0xd4, 0xf3, 0xaf, 0xec, 0x27, 0xb1, 0x9b, 0xfc, 0x37, 0x02, 0x20, 0xd2, 0x7a, 0x3c, 0x83, 0x48, 0xae, 0xcf, 0x3d, 0x97, 0xf4, 0x73, 0x62, 0xcd, 0x6b, 0x4c, 0x50, 0xf2, 0x81, 0x1b, 0x00, 0x7c, 0x2d, 0x60, 0xb3, 0xf3, 0x21, 0x6d, 0xcb, 0xe9, 0xfb, 0x00, 0xc8, 0x65, 0x51, 0x8b, 0x1b, 0x3e, 0xf8, 0x95, 0xc0, 0xa7, 0xa3, 0x28, 0xe6, 0x4d, 0x24, 0x69, 0x23, 0x6b, 0x41, 0xdb, 0x1f, 0xbf, 0x6a, 0x7d, 0x3b, 0xf7, 0xe0, 0xa3, 0xeb, 0x8f, 0x12, 0x30, 0x4e, 0x7f, 0x03, 0x00, 0x59, 0xaa, 0x04, 0x37, 0x03, 0x28, 0x92, 0x91, 0x38, 0x80, 0x21, 0x47, 0xbf, 0xb4, 0x45, 0x78, 0x74, 0x0a, 0x48, 0xe0, 0xcf, 0x01, 0x08, 0x14, 0x4f, 0x0a, 0x06, 0x80, 0x91, 0xcb, 0x29, 0xe9, 0x00, 0x0d, 0x03, 0xe0, 0x93, 0xcd, 0x70, 0x81, 0x94, 0x0d, 0x00, 0xd2, 0xef, 0xa0, 0x16, 0xc0, 0x12, 0x4f, 0xdc, 0xd7, 0x00, 0x63, 0x3b, 0xcb, 0xc3, 0x88, 0x17, 0x71, 0x78, 0xf1, 0x72, 0xb9, 0xf0, 0x47, 0xb5, 0x58, 0x6e, 0x97, 0xd7, 0xa7, 0x53, 0xca, 0x92, 0x11, 0x7b, 0xdd, 0x19, 0xb3, 0x44, 0xad, 0xd8, 0xbe, 0xfa, 0x68, 0x6d, 0x78, 0xa9, 0x0f, 0x1b, 0x9e, 0x83, 0x4e, 0xf3, 0xfe, 0x22, 0x80, 0x7c, 0x3a, 0x9d, 0x32, 0xac, 0xdb, 0xe0, 0x04, 0x00, 0x1d, 0x40, 0x99, 0x00, 0x32, 0x85, 0x41, 0x35, 0x80, 0xa2, 0xc4, 0x20, 0xee, 0x29, 0xa6, 0x3f, 0xec, 0x9f, 0x06, 0x08, 0x4a, 0x5c, 0x91, 0xd2, 0x9d, 0x00, 0xde, 0xb7, 0xeb, 0xe5, 0x82, 0xff, 0xb6, 0xeb, 0xfb, 0x28, 0xc7, 0xeb, 0x43, 0xda, 0x9f, 0xd0, 0xe3, 0xfc, 0x49, 0x1d, 0x4e, 0xc3, 0xb6, 0x95, 0x8f, 0x8f, 0x31, 0x42, 0x68, 0x21, 0xbf, 0x30, 0xe2, 0x3e, 0x1c, 0x33, 0xe4, 0x2f, 0xd5, 0x5d, 0x29, 0xb3, 0x3e, 0xe0, 0x0a, 0x77, 0xbe, 0x4e, 0x79, 0xec, 0x82, 0x73, 0x46, 0x2e, 0x77, 0x1b, 0xb3, 0x02, 0x30, 0xce, 0xb6, 0xa0, 0x4a, 0xb3, 0xa8, 0xcd, 0x42, 0x7b, 0xc6, 0x3c, 0xd9, 0x06, 0x8a, 0x05, 0x80, 0x9f, 0xfd, 0x85, 0x52, 0xde, 0x42, 0x7d, 0x0b, 0x62, 0xbf, 0xad, 0xbf, 0xbf, 0x9f, 0xaf, 0x08, 0xe0, 0x7a, 0x9e, 0xf6, 0x67, 0x3c, 0xa3, 0x89, 0xde, 0xa7, 0xa9, 0x19, 0xfb, 0xd1, 0x56, 0x92, 0x26, 0x13, 0x40, 0xa6, 0x23, 0x79, 0xd8, 0x3e, 0x72, 0x98, 0xf5, 0x69, 0x50, 0x25, 0x3d, 0xaa, 0xae, 0x0f, 0xd8, 0xbd, 0xf7, 0x15, 0xff, 0x53, 0x00, 0xb4, 0x5c, 0x66, 0x13, 0x39, 0x42, 0x72, 0xf0, 0x00, 0x11, 0xa8, 0x58, 0xa8, 0x00, 0xd0, 0x59, 0x57, 0x00, 0x60, 0x7f, 0xd5, 0x02, 0xe0, 0xb3, 0xb0, 0x02, 0xc0, 0xf5, 0xcb, 0xcc, 0x41, 0x02, 0xd7, 0x69, 0x3f, 0x9d, 0x72, 0x71, 0x91, 0x28, 0xf1, 0x96, 0x4b, 0x36, 0xf6, 0xe3, 0x06, 0x52, 0xa9, 0xbd, 0x84, 0xc8, 0x62, 0xc6, 0xfb, 0x2f, 0x00, 0x8a, 0xf7, 0x0b, 0x80, 0xdd, 0xd4, 0x47, 0x00, 0x51, 0x03, 0x58, 0xe4, 0x72, 0xdf, 0x03, 0xc4, 0x5e, 0xec, 0x61, 0x01, 0x40, 0x70, 0x26, 0x80, 0x6a, 0xd5, 0xff, 0x4e, 0xfd, 0x79, 0xb5, 0x64, 0x31, 0x5d, 0x17, 0xa5, 0x03, 0x63, 0x5a, 0xed, 0xfa, 0xbc, 0x9e, 0xaf, 0xe7, 0xf3, 0xa7, 0x0e, 0xaf, 0xe8, 0x78, 0x47, 0x71, 0x3e, 0x67, 0x7d, 0x6e, 0x00, 0xb7, 0x00, 0x00, 0x12, 0xa4, 0x1f, 0x7d, 0x2f, 0xa7, 0xf5, 0x78, 0x3a, 0x69, 0x00, 0xce, 0x02, 0xf0, 0xae, 0x46, 0x47, 0xab, 0xa0, 0x03, 0x60, 0xc3, 0x34, 0x80, 0xd2, 0x9e, 0x02, 0xaa, 0x87, 0xd4, 0xd6, 0xb9, 0x64, 0x64, 0x1d, 0x22, 0x82, 0x56, 0x5f, 0xd4, 0x74, 0x41, 0x0f, 0x10, 0x8f, 0x42, 0x8f, 0xb8, 0x01, 0x20, 0xc9, 0x3d, 0xfd, 0xbc, 0xfe, 0xc0, 0x25, 0x30, 0x09, 0xd0, 0x9e, 0x87, 0x4b, 0x40, 0xc9, 0x77, 0x5c, 0xa2, 0xa5, 0x78, 0xd9, 0xc3, 0x19, 0xc0, 0x94, 0xb7, 0x08, 0x00, 0x85, 0x1f, 0xd4, 0xe1, 0xb1, 0xa8, 0xfe, 0xc8, 0xe3, 0xd5, 0x6c, 0xd9, 0xe3, 0x44, 0x0e, 0x57, 0x4f, 0xea, 0x70, 0xd8, 0x8f, 0x00, 0x22, 0xed, 0x01, 0x4e, 0xe4, 0x7a, 0xe4, 0x80, 0x9e, 0x8d, 0xe1, 0x61, 0x9e, 0x32, 0x98, 0xec, 0x17, 0x00, 0x15, 0x09, 0x50, 0xde, 0x94, 0xd3, 0xb6, 0xbf, 0x03, 0x00, 0x22, 0x80, 0xf6, 0x8f, 0xcc, 0xcf, 0xed, 0xc7, 0xe5, 0x72, 0xc6, 0x7f, 0xdb, 0x67, 0x6f, 0x4f, 0x01, 0xa8, 0xa8, 0xc2, 0x05, 0xed, 0x86, 0xfb, 0xd9, 0x1f, 0x79, 0xaf, 0x18, 0x54, 0x11, 0xc0, 0x0e, 0x72, 0x8b, 0x51, 0x29, 0x53, 0xb1, 0x9a, 0x7e, 0xb6, 0x00, 0x68, 0xc2, 0x51, 0x96, 0xa4, 0xc3, 0x05, 0x41, 0x40, 0x64, 0x91, 0xa1, 0xbe, 0x2f, 0x8b, 0xbe, 0x07, 0x8a, 0x7a, 0xcc, 0x3b, 0xdc, 0x7f, 0x99, 0x50, 0x04, 0x68, 0x5b, 0x9f, 0xf2, 0x74, 0xe9, 0x0f, 0xf7, 0x33, 0xab, 0x6c, 0x2b, 0x39, 0x29, 0xc8, 0x02, 0xf8, 0x07, 0x1f, 0x81, 0x67, 0xfa, 0x7c, 0xce, 0x06, 0x3a, 0xfa, 0x41, 0xfe, 0x4a, 0x2e, 0x3c, 0x30, 0x52, 0x48, 0x10, 0x2d, 0x9c, 0x01, 0x81, 0x1a, 0x79, 0x66, 0x75, 0x20, 0xe3, 0x50, 0x01, 0x44, 0x99, 0x3f, 0xdf, 0x80, 0xaa, 0x22, 0x28, 0x66, 0xfd, 0xf5, 0x78, 0x80, 0x51, 0xd2, 0x37, 0xf4, 0xf3, 0xbe, 0xc4, 0x0b, 0xf6, 0x55, 0xd0, 0x1f, 0xf4, 0xf6, 0x1d, 0x21, 0x7f, 0xa8, 0xbe, 0xbf, 0xbf, 0xbf, 0xcf, 0xcf, 0xad, 0x72, 0x89, 0x47, 0xe8, 0x74, 0x5d, 0xd2, 0x92, 0x31, 0xa7, 0xb7, 0xdf, 0xae, 0x6f, 0xa3, 0x09, 0x2f, 0x39, 0xfc, 0x02, 0xf0, 0x02, 0xf0, 0x02, 0xf0, 0x02, 0xf0, 0x97, 0x03, 0x58, 0x5f, 0x39, 0xf9, 0x42, 0x34, 0x61, 0x7e, 0xfe, 0x17, 0x00, 0xfa, 0x8f, 0xb7, 0x79, 0x98, 0xb3, 0xea, 0xe9, 0xd5, 0xe0, 0xf0, 0x11, 0x6b, 0xd8, 0xf0, 0xe8, 0x39, 0xe4, 0xe7, 0x02, 0xaf, 0x27, 0x67, 0xee, 0x91, 0xed, 0x2d, 0xbd, 0xaf, 0xf3, 0xd6, 0xf8, 0xc1, 0xef, 0x06, 0x40, 0x01, 0x9d, 0x2a, 0x11, 0xb0, 0x55, 0x4f, 0xaf, 0x06, 0x63, 0xfd, 0x1a, 0x8a, 0x02, 0x70, 0xb2, 0x41, 0xc5, 0x1e, 0x63, 0x9c, 0x3d, 0x1c, 0x62, 0x8e, 0x7e, 0xd5, 0xfb, 0x34, 0x5e, 0xc6, 0xbc, 0x2e, 0x99, 0xb9, 0x7c, 0x09, 0x50, 0x3c, 0xc1, 0x03, 0x9c, 0xd6, 0xdf, 0x46, 0x4f, 0x2f, 0x06, 0x1f, 0x00, 0x00, 0x87, 0x94, 0xb4, 0xd8, 0x61, 0x87, 0x99, 0xe2, 0xc4, 0x16, 0x1f, 0xf4, 0x3e, 0x55, 0x0c, 0x8e, 0xc2, 0x8c, 0x99, 0x4f, 0xab, 0x58, 0x1e, 0xb4, 0x18, 0x7a, 0x02, 0x00, 0xb7, 0x00, 0x58, 0xf4, 0xf4, 0x5d, 0x00, 0xf2, 0xc6, 0x82, 0x8e, 0x00, 0xf5, 0xe4, 0xec, 0x61, 0x29, 0x3e, 0xe8, 0x7d, 0xaa, 0xd8, 0xde, 0xfa, 0x68, 0x73, 0xa0, 0xd5, 0xf8, 0x5c, 0x00, 0x24, 0x3c, 0xea, 0x36, 0x25, 0x1b, 0xf8, 0x45, 0x4f, 0x2f, 0x06, 0x8f, 0xb4, 0x8a, 0x80, 0x50, 0x7c, 0x45, 0xc9, 0xdf, 0x96, 0x1c, 0x3d, 0x2c, 0xc5, 0x43, 0xef, 0x3b, 0xfd, 0xc2, 0x46, 0xe1, 0x98, 0x44, 0x6e, 0xaa, 0x09, 0x5c, 0x0c, 0xf0, 0x64, 0x00, 0x24, 0x6e, 0xab, 0xfc, 0x5e, 0x0f, 0x46, 0x4f, 0x2f, 0x06, 0xf3, 0x0b, 0x18, 0xfc, 0x73, 0x7c, 0x9d, 0xbf, 0xff, 0xe3, 0x1d, 0x53, 0x2f, 0x60, 0xb4, 0xe4, 0xf4, 0x00, 0x5b, 0xcc, 0x2f, 0x55, 0x59, 0xbd, 0x4f, 0x9d, 0x35, 0x0f, 0xa8, 0x43, 0xac, 0xc5, 0x45, 0x43, 0xff, 0x4e, 0x00, 0x28, 0x34, 0x51, 0x9e, 0xe6, 0x18, 0x8d, 0x20, 0x74, 0xe6, 0x9d, 0x26, 0xfd, 0xfe, 0x41, 0xcd, 0xfd, 0xb7, 0xe8, 0xd1, 0x02, 0x22, 0xde, 0x62, 0x1d, 0x4f, 0xe0, 0xe4, 0xec, 0x61, 0x29, 0xee, 0xaf, 0xec, 0x44, 0xf5, 0xc6, 0x0b, 0x8a, 0x73, 0x0a, 0x7a, 0x40, 0x69, 0x3f, 0x61, 0x73, 0x50, 0xd1, 0xc5, 0xe7, 0x01, 0x68, 0xca, 0x16, 0xcc, 0x88, 0x4a, 0x4f, 0x8b, 0xc1, 0x55, 0xcb, 0x5d, 0xfa, 0xfd, 0xbd, 0x4a, 0x00, 0xc0, 0x8b, 0x1c, 0x6e, 0xc9, 0xd9, 0xc3, 0x52, 0x7c, 0xd0, 0xfb, 0x5c, 0x91, 0xef, 0xc2, 0xb0, 0x9f, 0x02, 0x1c, 0x31, 0x3e, 0x6d, 0x09, 0x88, 0x6c, 0x5e, 0x24, 0xbb, 0xd5, 0xf7, 0x37, 0x65, 0xfd, 0x8d, 0xf0, 0xc1, 0x48, 0xd6, 0x3b, 0xc5, 0x77, 0xf4, 0x7e, 0xd5, 0xef, 0x1f, 0x50, 0xd0, 0xa4, 0x3e, 0xcb, 0x03, 0xfe, 0x15, 0x60, 0x00, 0x44, 0xbe, 0x69, 0xfa, 0x76, 0xae, 0xa1, 0x59, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, }; #endif
twinaphex/OpenLara
src/platform/libretro/libretro-common/include/file/file_path.h
<filename>src/platform/libretro/libretro-common/include/file/file_path.h /* Copyright (C) 2010-2018 The RetroArch team * * --------------------------------------------------------------------------------------- * The following license statement only applies to this file (file_path.h). * --------------------------------------------------------------------------------------- * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __LIBRETRO_SDK_FILE_PATH_H #define __LIBRETRO_SDK_FILE_PATH_H #include <stdio.h> #include <stdint.h> #include <stddef.h> #include <sys/types.h> #include <retro_common_api.h> #include <boolean.h> RETRO_BEGIN_DECLS /* Order in this enum is equivalent to negative sort order in filelist * (i.e. DIRECTORY is on top of PLAIN_FILE) */ enum { RARCH_FILETYPE_UNSET, RARCH_PLAIN_FILE, RARCH_COMPRESSED_FILE_IN_ARCHIVE, RARCH_COMPRESSED_ARCHIVE, RARCH_DIRECTORY, RARCH_FILE_UNSUPPORTED }; /** * path_is_compressed_file: * @path : path * * Checks if path is a compressed file. * * Returns: true (1) if path is a compressed file, otherwise false (0). **/ bool path_is_compressed_file(const char *path); /** * path_contains_compressed_file: * @path : path * * Checks if path contains a compressed file. * * Currently we only check for hash symbol (#) inside the pathname. * If path is ever expanded to a general URI, we should check for that here. * * Example: Somewhere in the path there might be a compressed file * E.g.: /path/to/file.7z#mygame.img * * Returns: true (1) if path contains compressed file, otherwise false (0). **/ #define path_contains_compressed_file(path) (path_get_archive_delim((path)) != NULL) /** * path_get_archive_delim: * @path : path * * Gets delimiter of an archive file. Only the first '#' * after a compression extension is considered. * * Returns: pointer to the delimiter in the path if it contains * a compressed file, otherwise NULL. */ const char *path_get_archive_delim(const char *path); /** * path_get_extension: * @path : path * * Gets extension of file. Only '.'s * after the last slash are considered. * * Returns: extension part from the path. */ const char *path_get_extension(const char *path); /** * path_remove_extension: * @path : path * * Mutates path by removing its extension. Removes all * text after and including the last '.'. * Only '.'s after the last slash are considered. * * Returns: * 1) If path has an extension, returns path with the * extension removed. * 2) If there is no extension, returns NULL. * 3) If path is empty or NULL, returns NULL */ char *path_remove_extension(char *path); /** * path_basename: * @path : path * * Get basename from @path. * * Returns: basename from path. **/ const char *path_basename(const char *path); /** * path_basedir: * @path : path * * Extracts base directory by mutating path. * Keeps trailing '/'. **/ void path_basedir(char *path); /** * path_parent_dir: * @path : path * * Extracts parent directory by mutating path. * Assumes that path is a directory. Keeps trailing '/'. **/ void path_parent_dir(char *path); /** * path_resolve_realpath: * @buf : buffer for path * @size : size of buffer * * Turns relative paths into absolute path. * If relative, rebases on current working dir. **/ void path_resolve_realpath(char *buf, size_t size); /** * path_is_absolute: * @path : path * * Checks if @path is an absolute path or a relative path. * * Returns: true if path is absolute, false if path is relative. **/ bool path_is_absolute(const char *path); /** * fill_pathname: * @out_path : output path * @in_path : input path * @replace : what to replace * @size : buffer size of output path * * FIXME: Verify * * Replaces filename extension with 'replace' and outputs result to out_path. * The extension here is considered to be the string from the last '.' * to the end. * * Only '.'s after the last slash are considered as extensions. * If no '.' is present, in_path and replace will simply be concatenated. * 'size' is buffer size of 'out_path'. * E.g.: in_path = "/foo/bar/baz/boo.c", replace = ".asm" => * out_path = "/foo/bar/baz/boo.asm" * E.g.: in_path = "/foo/bar/baz/boo.c", replace = "" => * out_path = "/foo/bar/baz/boo" */ void fill_pathname(char *out_path, const char *in_path, const char *replace, size_t size); /** * fill_dated_filename: * @out_filename : output filename * @ext : extension of output filename * @size : buffer size of output filename * * Creates a 'dated' filename prefixed by 'RetroArch', and * concatenates extension (@ext) to it. * * E.g.: * out_filename = "RetroArch-{month}{day}-{Hours}{Minutes}.{@ext}" **/ void fill_dated_filename(char *out_filename, const char *ext, size_t size); /** * fill_str_dated_filename: * @out_filename : output filename * @in_str : input string * @ext : extension of output filename * @size : buffer size of output filename * * Creates a 'dated' filename prefixed by the string @in_str, and * concatenates extension (@ext) to it. * * E.g.: * out_filename = "RetroArch-{year}{month}{day}-{Hour}{Minute}{Second}.{@ext}" **/ void fill_str_dated_filename(char *out_filename, const char *in_str, const char *ext, size_t size); /** * fill_pathname_noext: * @out_path : output path * @in_path : input path * @replace : what to replace * @size : buffer size of output path * * Appends a filename extension 'replace' to 'in_path', and outputs * result in 'out_path'. * * Assumes in_path has no extension. If an extension is still * present in 'in_path', it will be ignored. * */ void fill_pathname_noext(char *out_path, const char *in_path, const char *replace, size_t size); /** * find_last_slash: * @str : input path * * Gets a pointer to the last slash in the input path. * * Returns: a pointer to the last slash in the input path. **/ char *find_last_slash(const char *str); /** * fill_pathname_dir: * @in_dir : input directory path * @in_basename : input basename to be appended to @in_dir * @replace : replacement to be appended to @in_basename * @size : size of buffer * * Appends basename of 'in_basename', to 'in_dir', along with 'replace'. * Basename of in_basename is the string after the last '/' or '\\', * i.e the filename without directories. * * If in_basename has no '/' or '\\', the whole 'in_basename' will be used. * 'size' is buffer size of 'in_dir'. * * E.g..: in_dir = "/tmp/some_dir", in_basename = "/some_content/foo.c", * replace = ".asm" => in_dir = "/tmp/some_dir/foo.c.asm" **/ void fill_pathname_dir(char *in_dir, const char *in_basename, const char *replace, size_t size); /** * fill_pathname_base: * @out : output path * @in_path : input path * @size : size of output path * * Copies basename of @in_path into @out_path. **/ void fill_pathname_base(char *out_path, const char *in_path, size_t size); void fill_pathname_base_noext(char *out_dir, const char *in_path, size_t size); void fill_pathname_base_ext(char *out, const char *in_path, const char *ext, size_t size); /** * fill_pathname_basedir: * @out_dir : output directory * @in_path : input path * @size : size of output directory * * Copies base directory of @in_path into @out_path. * If in_path is a path without any slashes (relative current directory), * @out_path will get path "./". **/ void fill_pathname_basedir(char *out_path, const char *in_path, size_t size); void fill_pathname_basedir_noext(char *out_dir, const char *in_path, size_t size); /** * fill_pathname_parent_dir_name: * @out_dir : output directory * @in_dir : input directory * @size : size of output directory * * Copies only the parent directory name of @in_dir into @out_dir. * The two buffers must not overlap. Removes trailing '/'. * Returns true on success, false if a slash was not found in the path. **/ bool fill_pathname_parent_dir_name(char *out_dir, const char *in_dir, size_t size); /** * fill_pathname_parent_dir: * @out_dir : output directory * @in_dir : input directory * @size : size of output directory * * Copies parent directory of @in_dir into @out_dir. * Assumes @in_dir is a directory. Keeps trailing '/'. **/ void fill_pathname_parent_dir(char *out_dir, const char *in_dir, size_t size); /** * fill_pathname_resolve_relative: * @out_path : output path * @in_refpath : input reference path * @in_path : input path * @size : size of @out_path * * Joins basedir of @in_refpath together with @in_path. * If @in_path is an absolute path, out_path = in_path. * E.g.: in_refpath = "/foo/bar/baz.a", in_path = "foobar.cg", * out_path = "/foo/bar/foobar.cg". **/ void fill_pathname_resolve_relative(char *out_path, const char *in_refpath, const char *in_path, size_t size); /** * fill_pathname_join: * @out_path : output path * @dir : directory * @path : path * @size : size of output path * * Joins a directory (@dir) and path (@path) together. * Makes sure not to get two consecutive slashes * between directory and path. **/ void fill_pathname_join(char *out_path, const char *dir, const char *path, size_t size); void fill_pathname_join_special_ext(char *out_path, const char *dir, const char *path, const char *last, const char *ext, size_t size); void fill_pathname_join_concat_noext( char *out_path, const char *dir, const char *path, const char *concat, size_t size); void fill_pathname_join_concat(char *out_path, const char *dir, const char *path, const char *concat, size_t size); void fill_pathname_join_noext(char *out_path, const char *dir, const char *path, size_t size); /** * fill_pathname_join_delim: * @out_path : output path * @dir : directory * @path : path * @delim : delimiter * @size : size of output path * * Joins a directory (@dir) and path (@path) together * using the given delimiter (@delim). **/ void fill_pathname_join_delim(char *out_path, const char *dir, const char *path, const char delim, size_t size); void fill_pathname_join_delim_concat(char *out_path, const char *dir, const char *path, const char delim, const char *concat, size_t size); /** * fill_short_pathname_representation: * @out_rep : output representation * @in_path : input path * @size : size of output representation * * Generates a short representation of path. It should only * be used for displaying the result; the output representation is not * binding in any meaningful way (for a normal path, this is the same as basename) * In case of more complex URLs, this should cut everything except for * the main image file. * * E.g.: "/path/to/game.img" -> game.img * "/path/to/myarchive.7z#folder/to/game.img" -> game.img */ void fill_short_pathname_representation(char* out_rep, const char *in_path, size_t size); void fill_short_pathname_representation_noext(char* out_rep, const char *in_path, size_t size); void fill_pathname_expand_special(char *out_path, const char *in_path, size_t size); void fill_pathname_abbreviate_special(char *out_path, const char *in_path, size_t size); /** * path_basedir: * @path : path * * Extracts base directory by mutating path. * Keeps trailing '/'. **/ void path_basedir_wrapper(char *path); /** * path_char_is_slash: * @c : character * * Checks if character (@c) is a slash. * * Returns: true (1) if character is a slash, otherwise false (0). */ #ifdef _WIN32 #define path_char_is_slash(c) (((c) == '/') || ((c) == '\\')) #else #define path_char_is_slash(c) ((c) == '/') #endif /** * path_default_slash and path_default_slash_c: * * Gets the default slash separator. * * Returns: default slash separator. */ #if defined(_WIN32) || defined(_XBOX) #define path_default_slash() "\\" #define path_default_slash_c() '\\' #else #define path_default_slash() "/" #define path_default_slash_c() '/' #endif /** * fill_pathname_slash: * @path : path * @size : size of path * * Assumes path is a directory. Appends a slash * if not already there. **/ void fill_pathname_slash(char *path, size_t size); #if !defined(RARCH_CONSOLE) && defined(RARCH_INTERNAL) void fill_pathname_application_path(char *buf, size_t size); #endif /** * path_mkdir: * @dir : directory * * Create directory on filesystem. * * Returns: true (1) if directory could be created, otherwise false (0). **/ bool path_mkdir(const char *dir); /** * path_is_directory: * @path : path * * Checks if path is a directory. * * Returns: true (1) if path is a directory, otherwise false (0). */ bool path_is_directory(const char *path); bool path_is_character_special(const char *path); bool path_is_valid(const char *path); int32_t path_get_size(const char *path); RETRO_END_DECLS #endif
twinaphex/OpenLara
src/video.h
<reponame>twinaphex/OpenLara<filename>src/video.h<gh_stars>10-100 #ifndef H_VIDEO #define H_VIDEO #include "utils.h" #include "texture.h" #include "sound.h" struct AC_ENTRY { uint8 code; uint8 skip; uint8 ac; uint8 length; }; // ISO 13818-2 table B-14 static const AC_ENTRY STR_AC[] = { // signBit = (8 + shift) - length // AC_LUT_1 (shift = 1) { 0XC0 , 1 , 1 , 4 }, // 11000000 { 0X80 , 0 , 2 , 5 }, // 10000000 { 0XA0 , 2 , 1 , 5 }, // 10100000 { 0X50 , 0 , 3 , 6 }, // 01010000 { 0X60 , 4 , 1 , 6 }, // 01100000 { 0X70 , 3 , 1 , 6 }, // 01110000 { 0X20 , 7 , 1 , 7 }, // 00100000 { 0X28 , 6 , 1 , 7 }, // 00101000 { 0X30 , 1 , 2 , 7 }, // 00110000 { 0X38 , 5 , 1 , 7 }, // 00111000 { 0X10 , 2 , 2 , 8 }, // 00010000 { 0X14 , 9 , 1 , 8 }, // 00010100 { 0X18 , 0 , 4 , 8 }, // 00011000 { 0X1C , 8 , 1 , 8 }, // 00011100 { 0X40 , 13 , 1 , 9 }, // 01000000 { 0X42 , 0 , 6 , 9 }, // 01000010 { 0X44 , 12 , 1 , 9 }, // 01000100 { 0X46 , 11 , 1 , 9 }, // 01000110 { 0X48 , 3 , 2 , 9 }, // 01001000 { 0X4A , 1 , 3 , 9 }, // 01001010 { 0X4C , 0 , 5 , 9 }, // 01001100 { 0X4E , 10 , 1 , 9 }, // 01001110 // AC_LUT_6 (shift = 6) { 0X80 , 16 , 1 , 11 }, // 10000000 { 0X90 , 5 , 2 , 11 }, // 10010000 { 0XA0 , 0 , 7 , 11 }, // 10100000 { 0XB0 , 2 , 3 , 11 }, // 10110000 { 0XC0 , 1 , 4 , 11 }, // 11000000 { 0XD0 , 15 , 1 , 11 }, // 11010000 { 0XE0 , 14 , 1 , 11 }, // 11100000 { 0XF0 , 4 , 2 , 11 }, // 11110000 { 0X40 , 0 , 11 , 13 }, // 01000000 { 0X44 , 8 , 2 , 13 }, // 01000100 { 0X48 , 4 , 3 , 13 }, // 01001000 { 0X4C , 0 , 10 , 13 }, // 01001100 { 0X50 , 2 , 4 , 13 }, // 01010000 { 0X54 , 7 , 2 , 13 }, // 01010100 { 0X58 , 21 , 1 , 13 }, // 01011000 { 0X5C , 20 , 1 , 13 }, // 01011100 { 0X60 , 0 , 9 , 13 }, // 01100000 { 0X64 , 19 , 1 , 13 }, // 01100100 { 0X68 , 18 , 1 , 13 }, // 01101000 { 0X6C , 1 , 5 , 13 }, // 01101100 { 0X70 , 3 , 3 , 13 }, // 01110000 { 0X74 , 0 , 8 , 13 }, // 01110100 { 0X78 , 6 , 2 , 13 }, // 01111000 { 0X7C , 17 , 1 , 13 }, // 01111100 { 0X20 , 10 , 2 , 14 }, // 00100000 { 0X22 , 9 , 2 , 14 }, // 00100010 { 0X24 , 5 , 3 , 14 }, // 00100100 { 0X26 , 3 , 4 , 14 }, // 00100110 { 0X28 , 2 , 5 , 14 }, // 00101000 { 0X2A , 1 , 7 , 14 }, // 00101010 { 0X2C , 1 , 6 , 14 }, // 00101100 { 0X2E , 0 , 15 , 14 }, // 00101110 { 0X30 , 0 , 14 , 14 }, // 00110000 { 0X32 , 0 , 13 , 14 }, // 00110010 { 0X34 , 0 , 12 , 14 }, // 00110100 { 0X36 , 26 , 1 , 14 }, // 00110110 { 0X38 , 25 , 1 , 14 }, // 00111000 { 0X3A , 24 , 1 , 14 }, // 00111010 { 0X3C , 23 , 1 , 14 }, // 00111100 { 0X3E , 22 , 1 , 14 }, // 00111110 // AC_LUT_9 (shift = 9) { 0X80 , 0 , 31 , 15 }, // 10000000 { 0X88 , 0 , 30 , 15 }, // 10001000 { 0X90 , 0 , 29 , 15 }, // 10010000 { 0X98 , 0 , 28 , 15 }, // 10011000 { 0XA0 , 0 , 27 , 15 }, // 10100000 { 0XA8 , 0 , 26 , 15 }, // 10101000 { 0XB0 , 0 , 25 , 15 }, // 10110000 { 0XB8 , 0 , 24 , 15 }, // 10111000 { 0XC0 , 0 , 23 , 15 }, // 11000000 { 0XC8 , 0 , 22 , 15 }, // 11001000 { 0XD0 , 0 , 21 , 15 }, // 11010000 { 0XD8 , 0 , 20 , 15 }, // 11011000 { 0XE0 , 0 , 19 , 15 }, // 11100000 { 0XE8 , 0 , 18 , 15 }, // 11101000 { 0XF0 , 0 , 17 , 15 }, // 11110000 { 0XF8 , 0 , 16 , 15 }, // 11111000 { 0X40 , 0 , 40 , 16 }, // 01000000 { 0X44 , 0 , 39 , 16 }, // 01000100 { 0X48 , 0 , 38 , 16 }, // 01001000 { 0X4C , 0 , 37 , 16 }, // 01001100 { 0X50 , 0 , 36 , 16 }, // 01010000 { 0X54 , 0 , 35 , 16 }, // 01010100 { 0X58 , 0 , 34 , 16 }, // 01011000 { 0X5C , 0 , 33 , 16 }, // 01011100 { 0X60 , 0 , 32 , 16 }, // 01100000 { 0X64 , 1 , 14 , 16 }, // 01100100 { 0X68 , 1 , 13 , 16 }, // 01101000 { 0X6C , 1 , 12 , 16 }, // 01101100 { 0X70 , 1 , 11 , 16 }, // 01110000 { 0X74 , 1 , 10 , 16 }, // 01110100 { 0X78 , 1 , 9 , 16 }, // 01111000 { 0X7C , 1 , 8 , 16 }, // 01111100 { 0X20 , 1 , 18 , 17 }, // 00100000 { 0X22 , 1 , 17 , 17 }, // 00100010 { 0X24 , 1 , 16 , 17 }, // 00100100 { 0X26 , 1 , 15 , 17 }, // 00100110 { 0X28 , 6 , 3 , 17 }, // 00101000 { 0X2A , 16 , 2 , 17 }, // 00101010 { 0X2C , 15 , 2 , 17 }, // 00101100 { 0X2E , 14 , 2 , 17 }, // 00101110 { 0X30 , 13 , 2 , 17 }, // 00110000 { 0X32 , 12 , 2 , 17 }, // 00110010 { 0X34 , 11 , 2 , 17 }, // 00110100 { 0X36 , 31 , 1 , 17 }, // 00110110 { 0X38 , 30 , 1 , 17 }, // 00111000 { 0X3A , 29 , 1 , 17 }, // 00111010 { 0X3C , 28 , 1 , 17 }, // 00111100 { 0X3E , 27 , 1 , 17 }, // 00111110 }; static const uint8 STR_ZIG_ZAG[] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, }; static const uint8 STR_QUANTIZATION[] = { 2, 16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22, 22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26, 27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83 }; static const float STR_IDCT[] = { 0.354f, 0.354f, 0.354f, 0.354f, 0.354f, 0.354f, 0.354f, 0.354f, 0.490f, 0.416f, 0.278f, 0.098f, -0.098f, -0.278f, -0.416f, -0.490f, 0.462f, 0.191f, -0.191f, -0.462f, -0.462f, -0.191f, 0.191f, 0.462f, 0.416f, -0.098f, -0.490f, -0.278f, 0.278f, 0.490f, 0.098f, -0.416f, 0.354f, -0.354f, -0.354f, 0.354f, 0.354f, -0.354f, -0.354f, 0.354f, 0.278f, -0.490f, 0.098f, 0.416f, -0.416f, -0.098f, 0.490f, -0.278f, 0.191f, -0.462f, 0.462f, -0.191f, -0.191f, 0.462f, -0.462f, 0.191f, 0.098f, -0.278f, 0.416f, -0.490f, 0.490f, -0.416f, 0.278f, -0.098f, }; struct Video { struct Decoder : Sound::Decoder { int width, height, fps; Decoder(Stream *stream) : Sound::Decoder(stream, 2, 0) {} virtual ~Decoder() { /* delete stream; */ } virtual bool decodeVideo(Color32 *pixels) { return false; } }; // based on ffmpeg https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/ implementation of escape codecs struct Escape : Decoder { int vfmt, bpp; int sfmt, rate, channels, bps; int framesCount, chunksCount, offset; int curVideoPos, curVideoChunk; int curAudioPos, curAudioChunk; Sound::Decoder *audioDecoder; uint8 *prevFrame, *nextFrame, *lumaFrame; struct Chunk { int32 offset; int32 videoSize; int32 audioSize; uint8 *data; } *chunks; union MacroBlock { uint32 pixels[4]; }; union SuperBlock { uint32 pixels[64]; }; struct Codebook { uint32 size; uint32 depth; MacroBlock *blocks; } codebook[3]; Escape(Stream *stream) : Decoder(stream), audioDecoder(NULL), prevFrame(NULL), nextFrame(NULL), lumaFrame(NULL), chunks(NULL) { for (int i = 0; i < 4; i++) skipLine(); vfmt = readValue(); // video format width = readValue(); // x size in pixels height = readValue(); // y size in pixels bpp = readValue(); // bits per pixel RGB fps = readValue(); // frames per second sfmt = readValue(); // sound format rate = readValue(); // Hz Samples channels = readValue(); // channel bps = readValue(); // bits per sample (LINEAR UNSIGNED) framesCount = readValue(); // frames per chunk chunksCount = readValue() + 1; // number of chunks skipLine(); // even chunk size skipLine(); // odd chunk size offset = readValue(); // offset to chunk cat skipLine(); // offset to sprite skipLine(); // size of sprite skipLine(); // offset to key frames stream->setPos(offset); chunks = new Chunk[chunksCount]; for (int i = 0; i < chunksCount; i++) { chunks[i].offset = readValue(); chunks[i].videoSize = readValue(); chunks[i].audioSize = readValue(); chunks[i].data = NULL; } switch (vfmt) { case 124 : prevFrame = new uint8[width * height * 4]; nextFrame = new uint8[width * height * 4]; memset(prevFrame, 0, width * height * sizeof(uint32)); memset(nextFrame, 0, width * height * sizeof(uint32)); break; case 130 : // Y[w*h], Cb[w*h/4], Cr[w*h/4], F[w*h/4] prevFrame = new uint8[width * height * 7 / 4]; nextFrame = new uint8[width * height * 7 / 4]; lumaFrame = new uint8[width * height / 4]; memset(prevFrame, 0, width * height); memset(prevFrame + width * height, 16, width * height / 2); break; default : LOG("! unsupported Escape codec version (%d)\n", vfmt); ASSERT(false); } codebook[0].blocks = codebook[1].blocks = codebook[2].blocks = NULL; curVideoPos = curAudioPos = 0; curVideoChunk = curAudioChunk = 0; nextChunk(0, 0); if (sfmt == 1) audioDecoder = new Sound::PCM(NULL, channels, rate, 0x7FFFFF, bps); // TR2 else if (sfmt == 101) { if (bps == 8) audioDecoder = new Sound::PCM(NULL, channels, rate, 0x7FFFFF, bps); // TR1 else audioDecoder = new Sound::IMA(NULL, channels, rate); // TR3 } } virtual ~Escape() { { OS_LOCK(Sound::lock); audioDecoder->stream = NULL; delete audioDecoder; } for (int i = 0; i < chunksCount; i++) delete[] chunks[i].data; delete[] chunks; delete[] codebook[0].blocks; delete[] codebook[1].blocks; delete[] codebook[2].blocks; delete[] prevFrame; delete[] nextFrame; delete[] lumaFrame; } void skipLine() { char c; while (stream->read(c) != '\n'); } int readValue() { char buf[255]; for (uint32 i = 0; i < sizeof(buf); i++) { char &c = buf[i]; stream->read(c); if (c == ' ' || c == '.' || c == ',' || c == ';' || c == '\n') { if (c == ' ' || c == '.') skipLine(); c = '\0'; return atoi(buf); } } ASSERT(false); return 0; } int getSkip124(BitStream &bs) { int value; if ((value = bs.readBit()) != 1 || (value += bs.read(3)) != 8 || (value += bs.read(7)) != 135) return value; return value + bs.read(12); } int getSkip130(BitStream &bs) { int value; if ((value = bs.readBit())) return 0; if ((value = bs.read(3))) return value; if ((value = bs.read(8))) return value + 7; if ((value = bs.read(15))) return value + 262; return -1; } void copySuperBlock(uint32 *dst, int dstWidth, uint32 *src, int srcWidth) { for (int i = 0; i < 8; i++) { memcpy(dst, src, 8 * sizeof(uint32)); src += srcWidth; dst += dstWidth; } } void decodeMacroBlock(BitStream &bs, MacroBlock &mb, int &cbIndex, int sbIndex) { int value = bs.readBit(); if (value) { static const int8 trans[3][2] = { {2, 1}, {0, 2}, {1, 0} }; value = bs.readBit(); cbIndex = trans[cbIndex][value]; } Codebook &cb = codebook[cbIndex]; uint32 bIndex = bs.read(cb.depth); if (cbIndex == 1) bIndex += sbIndex << cb.depth; memcpy(&mb, cb.blocks + bIndex, sizeof(mb)); } void insertMacroBlock(SuperBlock &sb, const MacroBlock &mb, int index) { uint32 *dst = sb.pixels + (index + (index & -4)) * 2; dst[0] = mb.pixels[0]; dst[1] = mb.pixels[1]; dst[8] = mb.pixels[2]; dst[9] = mb.pixels[3]; } void nextChunk(int from, int to) { OS_LOCK(Sound::lock); if (from < curVideoChunk && from < curAudioChunk) { delete[] chunks[from].data; chunks[from].data = NULL; } Chunk &chunk = chunks[to]; if (chunk.data) return; chunk.data = new uint8[chunk.videoSize + chunk.audioSize]; stream->setPos(chunk.offset); stream->raw(chunk.data, chunk.videoSize + chunk.audioSize); } virtual bool decodeVideo(Color32 *pixels) { if (curVideoChunk >= chunksCount) return false; if (curVideoPos >= chunks[curVideoChunk].videoSize) { curVideoChunk++; curVideoPos = 0; if (curVideoChunk >= chunksCount) return false; nextChunk(curVideoChunk - 1, curVideoChunk); } uint8 *data = chunks[curVideoChunk].data + curVideoPos; switch (vfmt) { case 124 : return decode124(data, pixels); case 130 : return decode130(data, pixels); default : ASSERT(false); } return false; } bool decode124(uint8 *data, Color32 *pixels) { uint32 flags, size; memcpy(&flags, data + 0, 4); memcpy(&size, data + 4, 4); data += 8; curVideoPos += size; // skip unchanged frame if (!(flags & 0x114) || !(flags & 0x7800000)) return true; int sbCount = (width / 8) * (height / 8); // read data into bit stream size -= (sizeof(flags) + sizeof(size)); BitStream bs(data, size); // read codebook changes for (int i = 0; i < 3; i++) { if (flags & (1 << (17 + i))) { Codebook &cb = codebook[i]; if (i == 2) { cb.size = bs.read(20); cb.depth = log2i(cb.size - 1) + 1; } else { cb.depth = bs.read(4); cb.size = (i == 0 ? 1 : sbCount) << cb.depth; } delete[] cb.blocks; cb.blocks = new MacroBlock[cb.size]; for (uint32 j = 0; j < cb.size; j++) { uint8 mask = bs.read(4); Color32 cA, cB; cA.SetRGB15(bs.read(15)); cB.SetRGB15(bs.read(15)); if (cA.value != cB.value && (mask == 6 || mask == 9) && // check for 0101 or 1010 mask abs(int(cA.r) - int(cB.r)) <= 8 && abs(int(cA.g) - int(cB.g)) <= 8 && abs(int(cA.b) - int(cB.b)) <= 8) { cA.r = (int(cA.r) + int(cB.r)) / 2; cA.g = (int(cA.g) + int(cB.g)) / 2; cA.b = (int(cA.b) + int(cB.b)) / 2; cB = cA; } for (int k = 0; k < 4; k++) cb.blocks[j].pixels[k] = (mask & (1 << k)) ? cB.value : cA.value; } } } static const uint16 maskMatrix[] = { 0x0001, 0x0002, 0x0010, 0x0020, 0x0004, 0x0008, 0x0040, 0x0080, 0x0100, 0x0200, 0x1000, 0x2000, 0x0400, 0x0800, 0x4000, 0x8000}; SuperBlock sb; MacroBlock mb; int cbIndex = 1; int skip = -1; for (int sbIndex = 0; sbIndex < sbCount; sbIndex++) { int sbLine = width / 8; int sbOffset = ((sbIndex / sbLine) * width + (sbIndex % sbLine)) * 8; uint32 *src = (uint32*)prevFrame + sbOffset; uint32 *dst = (uint32*)nextFrame + sbOffset; uint16 multiMask = 0; if (skip == -1) skip = getSkip124(bs); if (skip) { copySuperBlock(dst, width, src, width); } else { copySuperBlock(sb.pixels, 8, src, width); while (!bs.readBit()) { decodeMacroBlock(bs, mb, cbIndex, sbIndex); uint16 mask = bs.read(16); multiMask |= mask; for (int i = 0; i < 16; i++) if (mask & maskMatrix[i]) insertMacroBlock(sb, mb, i); } if (!bs.readBit()) { uint16 invMask = bs.read(4); for (int i = 0; i < 4; i++) multiMask ^= ((invMask & (1 << i)) ? 0x0F : bs.read(4)) << (i * 4); for (int i = 0; i < 16; i++) if (multiMask & maskMatrix[i]) { decodeMacroBlock(bs, mb, cbIndex, sbIndex); insertMacroBlock(sb, mb, i); } } else if (flags & (1 << 16)) while (!bs.readBit()) { decodeMacroBlock(bs, mb, cbIndex, sbIndex); insertMacroBlock(sb, mb, bs.read(4)); } copySuperBlock(dst, width, sb.pixels, 8); } skip--; } memcpy(pixels, nextFrame, width * height * 4); swap(prevFrame, nextFrame); return true; } bool decode130(uint8 *data, Color32 *pixels) { static const uint8 offsetLUT[] = { 2, 4, 10, 20 }; static const int8 signLUT[64][4] = { { 0, 0, 0, 0 }, { -1, 1, 0, 0 }, { 1, -1, 0, 0 }, { -1, 0, 1, 0 }, { -1, 1, 1, 0 }, { 0, -1, 1, 0 }, { 1, -1, 1, 0 }, { -1, -1, 1, 0 }, { 1, 0, -1, 0 }, { 0, 1, -1, 0 }, { 1, 1, -1, 0 }, { -1, 1, -1, 0 }, { 1, -1, -1, 0 }, { -1, 0, 0, 1 }, { -1, 1, 0, 1 }, { 0, -1, 0, 1 }, { 0, 0, 0, 0 }, { 1, -1, 0, 1 }, { -1, -1, 0, 1 }, { -1, 0, 1, 1 }, { -1, 1, 1, 1 }, { 0, -1, 1, 1 }, { 1, -1, 1, 1 }, { -1, -1, 1, 1 }, { 0, 0, -1, 1 }, { 1, 0, -1, 1 }, { -1, 0, -1, 1 }, { 0, 1, -1, 1 }, { 1, 1, -1, 1 }, { -1, 1, -1, 1 }, { 0, -1, -1, 1 }, { 1, -1, -1, 1 }, { 0, 0, 0, 0 }, { -1, -1, -1, 1 }, { 1, 0, 0, -1 }, { 0, 1, 0, -1 }, { 1, 1, 0, -1 }, { -1, 1, 0, -1 }, { 1, -1, 0, -1 }, { 0, 0, 1, -1 }, { 1, 0, 1, -1 }, { -1, 0, 1, -1 }, { 0, 1, 1, -1 }, { 1, 1, 1, -1 }, { -1, 1, 1, -1 }, { 0, -1, 1, -1 }, { 1, -1, 1, -1 }, { -1, -1, 1, -1 }, { 0, 0, 0, 0 }, { 1, 0, -1, -1 }, { 0, 1, -1, -1 }, { 1, 1, -1, -1 }, { -1, 1, -1, -1 }, { 1, -1, -1, -1 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, }; static const int8 lumaLUT[] = { -4, -3, -2, -1, 1, 2, 3, 4 }; static const int8 chromaLUT[2][8] = { { 1, 1, 0, -1, -1, -1, 0, 1 }, { 0, 1, 1, 1, 0, -1, -1, -1 } }; static const uint8 chromaValueLUT[] = { 20, 28, 36, 44, 52, 60, 68, 76, 84, 92, 100, 106, 112, 116, 120, 124, 128, 132, 136, 140, 144, 150, 156, 164, 172, 180, 188, 196, 204, 212, 220, 228 }; Chunk &chunk = chunks[curVideoChunk]; curVideoPos = chunk.videoSize; BitStream bs(data, chunk.videoSize); bs.data += 16; // skip 16 bytes (frame size, version, gamma/linear chroma flags etc.) uint8 *lumaPtr = lumaFrame; int skip = -1; int bCount = width * height / 4; uint32 luma = 0, Y[4] = { 0 }, U = 16, V = 16, F = 0; uint8 *oY = prevFrame, *oU = oY + width * height, *oV = oU + width * height / 4, *oF = oV + width * height / 4; uint8 *nY = nextFrame, *nU = nY + width * height, *nV = nU + width * height / 4, *nF = nV + width * height / 4; for (int bIndex = 0; bIndex < bCount; bIndex++) { if (skip == -1) skip = getSkip130(bs); if (skip) { Y[0] = oY[0]; Y[1] = oY[1]; Y[2] = oY[width]; Y[3] = oY[width + 1]; U = oU[0]; V = oV[0]; F = oF[0]; luma = *lumaPtr; } else { if (bs.readBit()) { uint32 sign = bs.read(6); uint32 diff = bs.read(2); luma = bs.read(5) * 2; for (int i = 0; i < 4; i++) Y[i] = clamp(luma + offsetLUT[diff] * signLUT[sign][i], 0U, 63U); F = 1; } else { if (bs.readBit()) luma = bs.readBit() ? bs.read(6) : ((luma + lumaLUT[bs.read(3)]) & 63); for (int i = 0; i < 4; i++) Y[i] = luma; F = 0; } if (bs.readBit()) { if (bs.readBit()) { U = bs.read(5); V = bs.read(5); } else { uint32 idx = bs.read(3); U = (U + chromaLUT[0][idx]) & 31; V = (V + chromaLUT[1][idx]) & 31; } } } *lumaPtr++ = luma; nY[0] = Y[0]; nY[1] = Y[1]; nY[width] = Y[2]; nY[width + 1] = Y[3]; nU[0] = U; nV[0] = V; nF[0] = F; nY += 2; nU++; nV++; nF++; oY += 2; oU++; oV++; oF++; if (!(((bIndex + 1) * 2) % width)) { nY += width; oY += width; } skip--; } nY = nextFrame; nU = nY + width * height; nV = nU + width * height / 4; nF = nV + width * height / 4; for (int y = 0; y < height / 2; y++) { for (int x = 0; x < width / 2; x++) { int i = (y * width + x) * 2; Color32::YCbCr_T871_420(nY[i] << 2, nY[i + 1] << 2, nY[i + width] << 2, nY[i + width + 1] << 2, chromaValueLUT[*nU] - 128, chromaValueLUT[*nV] - 128, *nF * 4, pixels[i], pixels[i + 1], pixels[i + width], pixels[i + width + 1]); nU++; nV++; nF++; } } swap(prevFrame, nextFrame); return true; } virtual int decode(Sound::Frame *frames, int count) { if (!audioDecoder) return 0; if (bps != 4 && abs(curAudioChunk - curVideoChunk) > 1) { // sync with video chunk, doesn't work for IMA nextChunk(curAudioChunk, curVideoChunk); curAudioChunk = curVideoChunk; curAudioPos = 0; } int i = 0; while (i < count) { if (curAudioChunk >= chunksCount) { memset(&frames[i], 0, sizeof(Sound::Frame) * (count - i)); break; } Chunk *chunk = &chunks[curAudioChunk]; if (curAudioPos >= chunk->audioSize) { curAudioPos = 0; curAudioChunk++; nextChunk(curAudioChunk - 1, curAudioChunk); continue; } int part = min(count - i, (chunk->audioSize - curAudioPos) / (channels * bps / 8)); Stream *memStream = new Stream(NULL, chunk->data + chunk->videoSize + curAudioPos, chunk->audioSize - curAudioPos); audioDecoder->stream = memStream; while (part > 0) { int res = audioDecoder->decode(&frames[i], part); i += res; part -= res; } curAudioPos += memStream->pos; delete memStream; } return count; } }; // based on https://raw.githubusercontent.com/m35/jpsxdec/readme/jpsxdec/PlayStation1_STR_format.txt struct STR : Decoder { enum { MAGIC_STR = 0x80010160, VIDEO_SECTOR_SIZE = 2016, VIDEO_SECTOR_MAX = 16, AUDIO_SECTOR_SIZE = (16 + 112) * 18, // XA ADPCM data block size MAX_CHUNKS = 4, }; struct SyncHeader { uint32 sync[3]; uint8 mins, secs, block, mode; uint8 interleaved; uint8 channel; struct { uint8 isEnd:1, isVideo:1, isAudio:1, isData:1, trigger:1, form:1, realtime:1, eof:1; } submode; struct { uint8 stereo:1, :1, rate:1, :1, bps:1, :3; } coding; uint32 dup; }; struct Sector { uint32 magic; uint16 chunkIndex; uint16 chunksCount; uint32 frameIndex; uint32 chunkSize; uint16 width, height; uint16 blocks; uint16 unk1; uint16 qscale; uint16 version; uint32 unk2; }; struct VideoChunk { int size; uint16 width; uint16 height; uint32 qscale; uint8 data[VIDEO_SECTOR_SIZE * VIDEO_SECTOR_MAX]; }; struct AudioChunk { int size; uint8 data[AUDIO_SECTOR_SIZE]; }; uint8 AC_LUT_1[256]; uint8 AC_LUT_6[256]; uint8 AC_LUT_9[256]; VideoChunk videoChunks[MAX_CHUNKS]; AudioChunk audioChunks[MAX_CHUNKS]; int videoChunksCount; int audioChunksCount; int curVideoChunk; int curAudioChunk; Sound::Decoder *audioDecoder; struct { uint8 code; uint8 length; } vlc[176]; bool hasSyncHeader; STR(Stream *stream) : Decoder(stream), videoChunksCount(0), audioChunksCount(0), curVideoChunk(-1), curAudioChunk(-1), audioDecoder(NULL) { if (stream->pos >= stream->size) { LOG("Can't load STR format \"%s\"\n", stream->name); ASSERT(false); return; } memset(AC_LUT_1, 255, sizeof(AC_LUT_1)); memset(AC_LUT_6, 255, sizeof(AC_LUT_6)); memset(AC_LUT_9, 255, sizeof(AC_LUT_9)); buildLUT(AC_LUT_1, 0, 22, 1); buildLUT(AC_LUT_6, 22, 62, 6); buildLUT(AC_LUT_9, 62, 110, 9); uint32 syncMagic[3]; stream->raw(syncMagic, sizeof(syncMagic)); stream->seek(-(int)sizeof(syncMagic)); hasSyncHeader = syncMagic[0] == 0xFFFFFF00 && syncMagic[1] == 0xFFFFFFFF && syncMagic[2] == 0x00FFFFFF; if (!hasSyncHeader) { LOG("! No sync header found, please use jpsxdec tool to extract FMVs\n"); } for (int i = 0; i < MAX_CHUNKS; i++) { videoChunks[i].size = 0; audioChunks[i].size = 0; } nextChunk(); VideoChunk &chunk = videoChunks[0]; width = (chunk.width + 15) / 16 * 16; height = (chunk.height + 15) / 16 * 16; fps = 150 / (chunk.size / VIDEO_SECTOR_SIZE); fps = (fps < 20) ? 15 : 30; channels = 2; freq = 37800; audioDecoder = new Sound::XA(NULL); } virtual ~STR() { OS_LOCK(Sound::lock); audioDecoder->stream = NULL; delete audioDecoder; } void buildLUT(uint8 *LUT, int start, int end, int shift) { for (int i = start; i < end; i++) { const AC_ENTRY &e = STR_AC[i]; uint8 trash = (1 << (8 + shift - e.length + 1)); // fill the value and all possible endings while (trash--) LUT[e.code | trash] = i; } } bool nextChunk() { OS_LOCK(Sound::lock); if (videoChunks[videoChunksCount % MAX_CHUNKS].size > 0) return false; if (stream->pos >= stream->size) return false; bool readingVideo = false; while (stream->pos < stream->size) { if (hasSyncHeader) stream->seek(24); Sector sector; stream->raw(&sector, sizeof(Sector)); if (sector.magic == MAGIC_STR) { VideoChunk *chunk = videoChunks + (videoChunksCount % MAX_CHUNKS); if (sector.chunkIndex == 0) { readingVideo = true; chunk->size = 0; chunk->width = sector.width; chunk->height = sector.height; chunk->qscale = sector.qscale; } ASSERT(chunk->size + VIDEO_SECTOR_SIZE < sizeof(chunk->data)); stream->raw(chunk->data + chunk->size, VIDEO_SECTOR_SIZE); chunk->size += VIDEO_SECTOR_SIZE; if (hasSyncHeader) stream->seek(280); if (sector.chunkIndex == sector.chunksCount - 1) { videoChunksCount++; return true; } } else { AudioChunk *chunk = audioChunks + (audioChunksCount++ % MAX_CHUNKS); memcpy(chunk->data, &sector, sizeof(sector)); // audio chunk has no sector header (just XA data) stream->raw(chunk->data + sizeof(sector), AUDIO_SECTOR_SIZE - sizeof(sector)); // !!! MUST BE 2304 !!! most of CD image tools copy only 2048 per sector, so "clicks" will be there chunk->size = AUDIO_SECTOR_SIZE; stream->seek(24); if (!hasSyncHeader) stream->seek(2048 - (AUDIO_SECTOR_SIZE + 24)); if (!readingVideo) return true; }; } return false; } // http://jpsxdec.blogspot.com/2011/06/decoding-mpeg-like-bitstreams.html bool readCode(BitStream &bs, int16 &skip, int16 &ac) { if (bs.readU(1)) { if (bs.readU(1)) { skip = 0; ac = bs.readU(1) ? -1 : 1; return true; } return false; // end of block } int nz = 1; while (!bs.readU(1)) nz++; if (nz == 5) { // escape code == 0b1000001 uint16 esc = bs.readU(16); skip = esc >> 10; ac = esc & 0x3FF; if (ac & 0x200) ac -= 0x400; return true; } uint8 *table, shift; if (nz < 6) { table = AC_LUT_1; shift = 1; } else if (nz < 9) { table = AC_LUT_6; shift = 6; } else { table = AC_LUT_9; shift = 9; } BitStream state = bs; uint32 code = (1 << 7) | state.readU(7); code >>= nz - shift; ASSERT(table); int index = table[code]; ASSERT(index != 255); const AC_ENTRY &e = STR_AC[index]; bs.skip(e.length - nz - 1); skip = e.skip; ac = (code & (1 << (8 + shift - e.length))) ? -e.ac : e.ac; return true; } void IDCT(int16 *b) { float t[64]; for (int x = 0; x < 8; x++) for (int y = 0; y < 8; y++) t[x + y * 8] = b[x + 0 * 8] * STR_IDCT[0 * 8 + y] + b[x + 1 * 8] * STR_IDCT[1 * 8 + y] + b[x + 2 * 8] * STR_IDCT[2 * 8 + y] + b[x + 3 * 8] * STR_IDCT[3 * 8 + y] + b[x + 4 * 8] * STR_IDCT[4 * 8 + y] + b[x + 5 * 8] * STR_IDCT[5 * 8 + y] + b[x + 6 * 8] * STR_IDCT[6 * 8 + y] + b[x + 7 * 8] * STR_IDCT[7 * 8 + y]; for (int x = 0; x < 8; x++) for (int y = 0; y < 8; y++) { int i = y * 8; b[x + i] = int16( t[0 + i] * STR_IDCT[x + 0 * 8] + t[1 + i] * STR_IDCT[x + 1 * 8] + t[2 + i] * STR_IDCT[x + 2 * 8] + t[3 + i] * STR_IDCT[x + 3 * 8] + t[4 + i] * STR_IDCT[x + 4 * 8] + t[5 + i] * STR_IDCT[x + 5 * 8] + t[6 + i] * STR_IDCT[x + 6 * 8] + t[7 + i] * STR_IDCT[x + 7 * 8]); } } virtual bool decodeVideo(Color32 *pixels) { curVideoChunk++; while (curVideoChunk >= videoChunksCount) { if (!nextChunk()) { return false; } } VideoChunk *chunk = videoChunks + (curVideoChunk % MAX_CHUNKS); BitStream bs(chunk->data + 8, chunk->size - 8); // make bitstream without frame header int16 block[6][64]; // Cr, Cb, YTL, YTR, YBL, YBR for (int bX = 0; bX < width / 16; bX++) for (int bY = 0; bY < height / 16; bY++) { memset(block, 0, sizeof(block)); for (int i = 0; i < 6; i++) { bool nonZero = false; int16 *channel = block[i]; channel[0] = bs.readU(10); if (channel[0]) { if (channel[0] & 0x200) channel[0] -= 0x400; channel[0] = channel[0] * STR_QUANTIZATION[0]; // DC nonZero = true; } int16 skip, ac; int index = 0; while (readCode(bs, skip, ac)) { index += 1 + skip; ASSERT(index < 64); int zIndex = STR_ZIG_ZAG[index]; channel[zIndex] = (ac * STR_QUANTIZATION[zIndex] * chunk->qscale + 4) >> 3; nonZero = true; } if (nonZero) IDCT(channel); } Color32 *blockPixels = pixels + (width * bY * 16 + bX * 16); for (uint32 i = 0; i < 8 * 8; i++) { int x = (i % 8) * 2; int y = (i / 8) * 2; int j = (x & 7) + (y & 7) * 8; Color32 *c = blockPixels + (width * y + x); int16 *b = block[(x < 8) ? ((y < 8) ? 2 : 4) : ((y < 8) ? 3 : 5)]; Color32::YCbCr_T871_420(b[j] + 128, b[j + 1] + 128, b[j + 8] + 128, b[j + 8 + 1] + 128, block[1][i], block[0][i], 4, c[0], c[1], c[width], c[width + 1]); } } chunk->size = 0; return true; } virtual int decode(Sound::Frame *frames, int count) { if (!audioDecoder) return 0; Sound::XA *xa = (Sound::XA*)audioDecoder; int i = 0; while (i < count) { if (xa->pos >= COUNT(xa->buffer)) { curAudioChunk++; while (curAudioChunk >= audioChunksCount) { if (!nextChunk()) { curAudioChunk--; memset(frames, 0, count * sizeof(Sound::Frame)); return count; } } } AudioChunk *chunk = audioChunks + (curAudioChunk % MAX_CHUNKS); ASSERT(chunk->size > 0); Stream *memStream = new Stream(NULL, chunk->data, AUDIO_SECTOR_SIZE); audioDecoder->stream = memStream; i += audioDecoder->decode(&frames[i], count - i); delete memStream; } return count; } }; // based on https://wiki.multimedia.cx/index.php/Sega_FILM struct Cinepak : Decoder { struct Chunk { int offset; int size; uint32 info[2]; } *chunks; int chunksCount; int audioChunkIndex; int audioChunkPos; Array<Sound::Frame> audioChunkFrames; int videoChunkIndex; int videoChunkPos; Array<uint8> videoChunkData; Cinepak(Stream *stream) : Decoder(stream), chunks(NULL), audioChunkIndex(-1), audioChunkPos(0), videoChunkIndex(-1), videoChunkPos(0) { ASSERTV(stream->readLE32() == FOURCC("FILM")); int sampleOffset = stream->readBE32(); stream->seek(4); // skip version 1.06 stream->seek(4); // skip reserved ASSERTV(stream->readLE32() == FOURCC("FDSC")); ASSERTV(stream->readBE32() == 32); ASSERTV(stream->readLE32() == FOURCC("cvid")); height = stream->readBE32(); width = stream->readBE32(); ASSERTV(stream->read() == 24); channels = stream->read(); ASSERT(channels == 2); ASSERTV(stream->read() == 16); ASSERTV(stream->read() == 0); freq = stream->readBE16(); ASSERT(freq == 22254); stream->seek(6); ASSERTV(stream->readLE32() == FOURCC("STAB")); stream->seek(4); // skip STAB length fps = stream->readBE32() / 2; chunksCount = stream->readBE32(); chunks = new Chunk[chunksCount]; for (int i = 0; i < chunksCount; i++) { Chunk &c = chunks[i]; c.offset = stream->readBE32() + sampleOffset; c.size = stream->readBE32(); c.info[0] = stream->readBE32(); c.info[1] = stream->readBE32(); } } virtual ~Cinepak() { delete[] chunks; } virtual bool decodeVideo(Color32 *pixels) { if (audioChunkIndex >= chunksCount) return false; /* // TODO: sega cinepak film decoder // get next audio chunk if (videoChunkPos >= videoChunkData.length) { videoChunkPos = 0; while (++videoChunkIndex < chunksCount) { if (chunks[videoChunkIndex].info[0] != 0xFFFFFFFF || chunks[videoChunkIndex].info[1] != 1) break; } if (videoChunkIndex >= chunksCount) return true; const Chunk &chunk = chunks[videoChunkIndex]; { OS_LOCK(Sound::lock); stream->setPos(chunk.offset); videoChunkData.resize(chunk.size); stream->raw(videoChunkData.items, videoChunkData.length); } } // TODO: decode Stream data(NULL, videoChunkData.items + videoChunkPos, videoChunkData.length - videoChunkPos); union FrameHeader { struct { uint32 flags:8, size:24; }; uint32 value; } hdr; hdr.value = data.readBE32(); ASSERT(hdr.size <= videoChunkData.length - videoChunkPos); videoChunkPos += hdr.size; */ for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) { Color32 c; c.r = c.g = c.b = x ^ y; c.a = 255; pixels[y * width + x] = c; } return true; } virtual int decode(Sound::Frame *frames, int count) { if (audioChunkIndex >= chunksCount) { memset(frames, 0, count * sizeof(Sound::Frame)); return count; } // get next audio chunk if (audioChunkPos >= audioChunkFrames.length) { audioChunkPos = 0; while (++audioChunkIndex < chunksCount) { if (chunks[audioChunkIndex].info[0] == 0xFFFFFFFF) break; } if (audioChunkIndex >= chunksCount) { memset(frames, 0, count); return count; } const Chunk &chunk = chunks[audioChunkIndex]; audioChunkFrames.resize(chunk.size / sizeof(Sound::Frame)); stream->setPos(chunk.offset); // read LEFT channel samples for (int i = 0; i < audioChunkFrames.length; i++) audioChunkFrames[i].L = stream->readBE16(); // read RIGHT channel samples for (int i = 0; i < audioChunkFrames.length; i++) audioChunkFrames[i].R = stream->readBE16(); } for (int i = 0; i < count; i += 2) { frames[i + 0] = audioChunkFrames[audioChunkPos]; frames[i + 1] = audioChunkFrames[audioChunkPos++]; if (audioChunkPos >= audioChunkFrames.length) return i + 2; } return count; } }; enum Format { PC, PSX, SAT, } format; Decoder *decoder; Texture *frameTex[2]; Color32 *frameData; float step, stepTimer, time; bool isPlaying; bool needUpdate; Sound::Sample *sample; Video(Stream *stream) : decoder(NULL), stepTimer(0.0f), time(0.0f), isPlaying(false) { frameTex[0] = frameTex[1] = NULL; if (!stream) return; uint32 magic = stream->readLE32(); stream->seek(-4); float pitch = 1.0f; if (magic == FOURCC("FILM")) { format = SAT; decoder = new Cinepak(stream); pitch = decoder->freq / 22050.0f; // 22254 / 22050 = 1.00925 } else if (magic == FOURCC("ARMo")) { format = PC; decoder = new Escape(stream); } else { format = PSX; decoder = new STR(stream); } frameData = new Color32[decoder->width * decoder->height]; memset(frameData, 0, decoder->width * decoder->height * sizeof(Color32)); for (int i = 0; i < 2; i++) frameTex[i] = new Texture(decoder->width, decoder->height, 1, FMT_RGBA, 0, frameData); sample = Sound::play(decoder); sample->pitch = pitch; step = 1.0f / decoder->fps; stepTimer = step; time = 0.0f; isPlaying = true; } virtual ~Video() { OS_LOCK(Sound::lock); sample->decoder = NULL; sample->stop(); delete decoder; delete frameTex[0]; delete frameTex[1]; delete[] frameData; } void update() { if (!isPlaying) return; stepTimer += Core::deltaTime; if (stepTimer < step) return; stepTimer -= step; time += step; #ifdef VIDEO_TEST int t = Core::getTime(); while (decoder->decodeVideo(frameData)) {} LOG("time: %d\n", Core::getTime() - t); isPlaying = false; #else isPlaying = needUpdate = decoder->decodeVideo(frameData); #endif } void render() { // just update GPU texture if it's necessary if (!needUpdate) return; frameTex[0]->update(frameData); swap(frameTex[0], frameTex[1]); needUpdate = false; } }; #endif
twinaphex/OpenLara
src/gapi_gx.h
<filename>src/gapi_gx.h #ifndef H_GAPI_GX #define H_GAPI_GX // TODO #endif
twinaphex/OpenLara
src/cache.h
<filename>src/cache.h #ifndef H_CACHE #define H_CACHE #include "core.h" #include "format.h" #include "controller.h" #include "camera.h" #define NO_CLIP_PLANE 1000000.0f #if defined(_OS_IOS) || defined(_GAPI_D3D9) || defined(_GAPI_GXM) #define USE_SCREEN_TEX #endif struct ShaderCache { enum Effect { FX_NONE = 0, FX_UNDERWATER = 1, FX_ALPHA_TEST = 2, FX_CLIP_PLANE = 4 }; Shader *shaders[Core::passMAX][Shader::MAX][(FX_UNDERWATER | FX_ALPHA_TEST | FX_CLIP_PLANE) + 1]; PSO *pso[Core::passMAX][Shader::MAX][(FX_UNDERWATER | FX_ALPHA_TEST | FX_CLIP_PLANE) + 1][bmMAX]; ShaderCache() { memset(shaders, 0, sizeof(shaders)); LOG("shader: cache warm-up...\n"); prepareCompose(FX_NONE); if (Core::settings.detail.water > Core::Settings::LOW && !Core::support.clipDist) prepareCompose(FX_CLIP_PLANE); prepareAmbient(FX_NONE); if (Core::settings.detail.shadows > Core::Settings::LOW) prepareShadows(FX_NONE); prepareSky(FX_NONE); if (Core::settings.detail.water > Core::Settings::LOW) prepareWater(FX_NONE); prepareFilter(FX_NONE); prepareGUI(FX_NONE); Core::resetTime(); LOG("shader: cache is ready\n"); } ~ShaderCache() { for (int pass = 0; pass < Core::passMAX; pass++) for (int type = 0; type < Shader::MAX; type++) for (int fx = 0; fx < COUNT(shaders[pass][Shader::MAX]); fx++) delete shaders[pass][type][fx]; } #define rsBase (RS_COLOR_WRITE | RS_DEPTH_TEST | RS_DEPTH_WRITE | RS_CULL_FRONT) #define rsBlend (RS_BLEND_ALPHA | RS_BLEND_ADD) #define rsFull (rsBase | rsBlend) #define rsShadow (RS_DEPTH_TEST | RS_DEPTH_WRITE | RS_CULL_BACK) void prepareCompose(int fx) { compile(Core::passCompose, Shader::MIRROR, fx, rsBase); compile(Core::passCompose, Shader::ROOM, fx, rsFull); compile(Core::passCompose, Shader::ROOM, fx, rsFull | RS_DISCARD); compile(Core::passCompose, Shader::ROOM, fx | FX_UNDERWATER, rsFull); compile(Core::passCompose, Shader::ROOM, fx | FX_UNDERWATER, rsFull | RS_DISCARD); compile(Core::passCompose, Shader::ENTITY, fx, rsFull); compile(Core::passCompose, Shader::ENTITY, fx, rsFull | RS_DISCARD); compile(Core::passCompose, Shader::ENTITY, fx | FX_UNDERWATER, rsFull); compile(Core::passCompose, Shader::ENTITY, fx | FX_UNDERWATER, rsFull | RS_DISCARD); compile(Core::passCompose, Shader::SPRITE, fx, rsFull | RS_DISCARD); compile(Core::passCompose, Shader::SPRITE, fx | FX_UNDERWATER, rsFull | RS_DISCARD); compile(Core::passCompose, Shader::FLASH, fx, rsFull | RS_BLEND_MULT); // spot shadow } void prepareAmbient(int fx) { compile(Core::passAmbient, Shader::ROOM, fx, rsFull); compile(Core::passAmbient, Shader::ROOM, fx, rsFull | RS_DISCARD); compile(Core::passAmbient, Shader::SPRITE, fx, rsFull | RS_DISCARD); } void prepareShadows(int fx) { compile(Core::passShadow, Shader::MIRROR, fx, rsShadow); compile(Core::passShadow, Shader::ENTITY, fx, rsShadow); compile(Core::passShadow, Shader::ENTITY, fx, rsShadow | RS_DISCARD); } void prepareSky(int fx) { compile(Core::passSky, Shader::DEFAULT, fx, rsBase); if (Core::support.tex3D) { compile(Core::passSky, Shader::SKY_CLOUDS, fx, rsBase); compile(Core::passSky, Shader::SKY_CLOUDS_AZURE, fx, rsBase); } } void prepareWater(int fx) { compile(Core::passWater, Shader::WATER_MASK, fx, RS_COLOR_WRITE_A | RS_DEPTH_TEST); compile(Core::passWater, Shader::WATER_SIMULATE, fx, RS_COLOR_WRITE); compile(Core::passWater, Shader::WATER_DROP, fx, RS_COLOR_WRITE); compile(Core::passWater, Shader::WATER_RAYS, fx, RS_COLOR_WRITE | RS_DEPTH_TEST); compile(Core::passWater, Shader::WATER_CAUSTICS, fx, RS_COLOR_WRITE); compile(Core::passWater, Shader::WATER_COMPOSE, fx, RS_COLOR_WRITE | RS_DEPTH_TEST); } void prepareFilter(int fx) { compile(Core::passFilter, Shader::FILTER_UPSCALE, fx, RS_COLOR_WRITE); compile(Core::passFilter, Shader::FILTER_DOWNSAMPLE, fx, RS_COLOR_WRITE); compile(Core::passFilter, Shader::FILTER_GRAYSCALE, fx, RS_COLOR_WRITE); compile(Core::passFilter, Shader::FILTER_BLUR, fx, RS_COLOR_WRITE); } void prepareGUI(int fx) { compile(Core::passGUI, Shader::DEFAULT, fx, RS_COLOR_WRITE | RS_BLEND_ALPHA); } #undef rsBase #undef rsBlend #undef rsFull #undef rsShadow Shader* compile(Core::Pass pass, Shader::Type type, int fx, uint32 rs) { if (rs & RS_DISCARD) fx |= FX_ALPHA_TEST; #ifndef FFP if (shaders[pass][type][fx]) return shaders[pass][type][fx]; int def[SD_MAX], defCount = 0; #define SD_ADD(x) (def[defCount++] = SD_##x) if (Core::settings.detail.shadows) { if (Core::support.shadowSampler) { SD_ADD(SHADOW_SAMPLER); } else { if (Core::support.depthTexture) SD_ADD(SHADOW_DEPTH); else SD_ADD(SHADOW_COLOR); } } switch (pass) { case Core::passCompose : case Core::passShadow : case Core::passAmbient : { def[defCount++] = SD_TYPE_SPRITE + type; if (fx & FX_UNDERWATER) SD_ADD(UNDERWATER); if (fx & FX_ALPHA_TEST) SD_ADD(ALPHA_TEST); if (pass == Core::passCompose) { if (fx & FX_CLIP_PLANE) SD_ADD(CLIP_PLANE); if (Core::settings.detail.lighting > Core::Settings::MEDIUM && (type == Shader::ENTITY)) SD_ADD(OPT_AMBIENT); if (Core::settings.detail.shadows > Core::Settings::LOW && (type == Shader::ENTITY || type == Shader::ROOM)) SD_ADD(OPT_SHADOW); if (Core::settings.detail.shadows > Core::Settings::MEDIUM && (type == Shader::ROOM)) SD_ADD(OPT_CONTACT); if (Core::settings.detail.water > Core::Settings::MEDIUM && (type == Shader::ENTITY || type == Shader::ROOM) && (fx & FX_UNDERWATER)) SD_ADD(OPT_CAUSTICS); } break; } case Core::passSky : def[defCount++] = SD_SKY_TEXTURE + type; break; case Core::passWater : def[defCount++] = SD_WATER_DROP + type; break; case Core::passFilter : def[defCount++] = SD_FILTER_UPSCALE + type; break; case Core::passGUI : break; default : ASSERT(false); } #undef SD_ADD return shaders[pass][type][fx] = new Shader(pass, type, def, defCount); #else return NULL; #endif } Shader *getShader(Core::Pass pass, Shader::Type type, int fx) { Shader *shader = shaders[pass][type][fx]; #ifndef FFP if (shader == NULL) LOG("! NULL shader: %d %d %d\n", int(pass), int(type), int(fx)); ASSERT(shader != NULL); #endif return shader; } void bind(Core::Pass pass, Shader::Type type, int fx) { Core::pass = pass; if (Core::support.clipDist) fx &= ~ShaderCache::FX_CLIP_PLANE; Shader *shader = getShader(pass, type, fx); if (shader) { shader->setup(); } Core::setAlphaTest((fx & FX_ALPHA_TEST) != 0); } }; struct AmbientCache { IGame *game; TR::Level *level; struct Cube { enum int32 { BLANK, WAIT, READY } status; vec4 colors[6]; // TODO: ubyte4[6] } *items; int *offsets; struct Task { int room; int flip; int sector; Cube *cube; } tasks[32]; int tasksCount; Texture *textures[6 * 4]; // 64, 16, 4, 1 AmbientCache(IGame *game) : game(game), level(game->getLevel()), tasksCount(0) { items = NULL; offsets = new int[level->roomsCount]; int sectors = 0; for (int i = 0; i < level->roomsCount; i++) { TR::Room &r = level->rooms[i]; offsets[i] = sectors; sectors += r.xSectors * r.zSectors * (r.alternateRoom > -1 ? 2 : 1); // x2 for flipped rooms } // init cache buffer items = new Cube[sectors]; memset(items, 0, sizeof(Cube) * sectors); // init downsample textures for (int j = 0; j < 6; j++) for (int i = 0; i < 4; i++) textures[j * 4 + i] = new Texture(64 >> (i << 1), 64 >> (i << 1), 1, FMT_RGBA, OPT_TARGET | OPT_NEAREST); } ~AmbientCache() { delete[] items; delete[] offsets; for (int i = 0; i < 6 * 4; i++) delete textures[i]; } void addTask(int room, int sector) { if (tasksCount >= COUNT(tasks)) return; Task &task = tasks[tasksCount++]; task.room = room; task.flip = level->state.flags.flipped && level->rooms[room].alternateRoom > -1; task.sector = sector; task.cube = &items[offsets[room] + sector]; task.cube->status = Cube::WAIT; } void renderAmbient(int room, int sector, vec4 *colors) { PROFILE_MARKER("PASS_AMBIENT"); TR::Room &r = level->rooms[room]; TR::Room::Sector &s = r.sectors[sector]; vec3 pos = vec3(float((sector / r.zSectors) * 1024 + 512 + r.info.x), float(max((s.floor - 2) * 256, (s.floor + s.ceiling) * 256 / 2)), float((sector % r.zSectors) * 1024 + 512 + r.info.z)); Core::setClearColor(vec4(0, 0, 0, 1)); // first pass - render environment from position (room geometry & static meshes) game->renderEnvironment(room, pos, textures, 4); // second pass - downsample it Core::setDepthTest(false); game->setShader(Core::passFilter, Shader::FILTER_DOWNSAMPLE); for (int i = 1; i < 4; i++) { int size = 64 >> (i << 1); Core::active.shader->setParam(uParam, vec4(1.0f / (size << 2), 0.0f, 0.0f, 0.0f)); for (int j = 0; j < 6; j++) { Texture *src = textures[j * 4 + i - 1]; Texture *dst = textures[j * 4 + i]; Core::setTarget(dst, NULL, RT_STORE_COLOR); src->bind(sDiffuse); game->getMesh()->renderQuad(); } } // get result color from 1x1 textures for (int j = 0; j < 6; j++) { Core::setTarget(textures[j * 4 + 3], NULL, RT_LOAD_COLOR); colors[j] = Core::copyPixel(0, 0); } Core::setDepthTest(true); Core::setClearColor(vec4(0, 0, 0, 0)); } void processQueue() { game->setupBinding(); for (int i = 0; i < tasksCount; i++) { Task &task = tasks[i]; bool needFlip = task.flip != level->state.flags.flipped; if (needFlip) game->flipMap(false); int sector = task.sector; if (task.flip) { TR::Room &r = level->rooms[task.room]; sector -= r.xSectors * r.zSectors; } renderAmbient(task.room, sector, &task.cube->colors[0]); if (needFlip) game->flipMap(false); task.cube->status = Cube::READY; } tasksCount = 0; } Cube* getAmbient(int roomIndex, int x, int z) { TR::Room &r = level->rooms[roomIndex]; int sx = clamp(x / 1024, 0, r.xSectors - 1); int sz = clamp(z / 1024, 0, r.zSectors - 1); int sector = sx * r.zSectors + sz; if (r.sectors[sector].floor == TR::NO_FLOOR) return NULL; if (level->state.flags.flipped && r.alternateRoom > -1) sector += r.xSectors * r.zSectors; Cube *cube = &items[offsets[roomIndex] + sector]; if (cube->status == Cube::BLANK) addTask(roomIndex, sector); return cube->status == Cube::READY ? cube : NULL; } void lerpCubes(Cube &result, const Cube *a, const Cube *b, float t) { ASSERT(a != NULL && b != NULL); result.colors[0] = a->colors[0].lerp(b->colors[0], t); result.colors[1] = a->colors[1].lerp(b->colors[1], t); result.colors[2] = a->colors[2].lerp(b->colors[2], t); result.colors[3] = a->colors[3].lerp(b->colors[3], t); result.colors[4] = a->colors[4].lerp(b->colors[4], t); result.colors[5] = a->colors[5].lerp(b->colors[5], t); } void getAmbient(int room, const vec3 &pos, Cube &value) { TR::Room &r = level->rooms[room]; int x = int(pos.x) - r.info.x; int z = int(pos.z) - r.info.z; // cc cx // cz cd Cube *cc = getAmbient(room, x, z); if (cc && cc->status == Cube::READY) { Cube *cx = NULL, *cz = NULL, *cd = NULL; int sx = (x / 1024) * 1024 + 512; int sz = (z / 1024) * 1024 + 512; int ox = sx + sign(x - sx) * 1024; int oz = sz + sign(z - sz) * 1024; float tx, tz; tx = abs(x - sx) / 1024.0f; tz = abs(z - sz) / 1024.0f; cx = getAmbient(room, ox, sz); cz = getAmbient(room, sx, oz); cd = getAmbient(room, ox, oz); if (cx != NULL && cx->status != Cube::READY) cx = cc; if (cz != NULL && cz->status != Cube::READY) cz = cc; if (cd != NULL && cd->status != Cube::READY) cd = cc; Cube lx, lz; if (cd != NULL && cx != NULL && cz != NULL) { lerpCubes(lx, cc, cx, tx); lerpCubes(lz, cz, cd, tx); lerpCubes(value, &lx, &lz, tz); } else if (cd != NULL && cx != NULL) { lerpCubes(lx, cc, cx, tx); lerpCubes(value, &lx, cd, tz); } else if (cd != NULL && cz != NULL) { lerpCubes(lz, cc, cz, tz); lerpCubes(value, &lz, cd, tx); } else if (cx != NULL && cz != NULL) { lerpCubes(lx, cc, cx, tx); lerpCubes(value, &lx, cz, tz); } else if (cx != NULL) { lerpCubes(value, cc, cx, tx); } else if (cz != NULL) { lerpCubes(value, cc, cz, tz); } else value = *cc; value.status = cc->status; } else value.status = Cube::BLANK; } }; struct WaterCache { #define MAX_SURFACES 16 #define MAX_INVISIBLE_TIME 5.0f #define SIMULATE_TIMESTEP (1.0f / 40.0f) #define WATER_TILE_SIZE 64 #define DETAIL (WATER_TILE_SIZE / 1024.0f) #define MAX_DROPS 32 IGame *game; TR::Level *level; Texture *screen; Texture *refract; Texture *reflect; struct Item { int from, to, caust; float timer; bool flip; bool visible; bool blank; vec3 pos, size; Texture *mask; Texture *caustics; #ifdef BLUR_CAUSTICS Texture *caustics_tmp; #endif Texture *data[2]; Item() { mask = caustics = data[0] = data[1] = NULL; } Item(int from, int to) : from(from), to(to), caust(to), timer(SIMULATE_TIMESTEP), visible(true), blank(true) { mask = caustics = data[0] = data[1] = NULL; } void init(IGame *game) { TR::Level *level = game->getLevel(); TR::Room &r = level->rooms[to]; // underwater room ASSERT(r.flags.water); int minX = r.xSectors, minZ = r.zSectors, maxX = 0, maxZ = 0; int posY = level->rooms[to].waterLevelSurface; if (posY == TR::NO_WATER) posY = level->rooms[from].waterLevelSurface; ASSERT(posY != -1); // underwater room without reaching the surface int caustY = posY; for (int z = 0; z < r.zSectors; z++) for (int x = 0; x < r.xSectors; x++) { TR::Room::Sector &s = r.sectors[x * r.zSectors + z]; if (s.roomAbove != TR::NO_ROOM && !level->rooms[s.roomAbove].flags.water) { minX = min(minX, x); minZ = min(minZ, z); maxX = max(maxX, x); maxZ = max(maxZ, z); if (s.roomBelow != TR::NO_ROOM) { int16 caustRoom = s.roomBelow; int floor = int(level->getFloor(&s, vec3(float(r.info.x + x * 1024), float(posY), float(r.info.z + z * 1024)), &caustRoom)); if (floor > caustY) { caustY = floor; caust = caustRoom; } } } } maxX++; maxZ++; int w = maxX - minX; int h = maxZ - minZ; uint8 *m = new uint8[w * h]; memset(m, 0, w * h * sizeof(m[0])); for (int z = minZ; z < maxZ; z++) for (int x = minX; x < maxX; x++) { TR::Room::Sector &s = r.sectors[x * r.zSectors + z]; bool hasWater = s.roomAbove != TR::NO_ROOM && !level->rooms[s.roomAbove].flags.water; if (hasWater) { TR::Room &rt = level->rooms[s.roomAbove]; int xt = int(r.info.x + x * 1024 - rt.info.x) / 1024; int zt = int(r.info.z + z * 1024 - rt.info.z) / 1024; TR::Room::Sector &st = rt.sectors[xt * rt.zSectors + zt]; hasWater = s.ceiling > st.ceiling; if (s.ceiling == st.ceiling) { vec3 p = vec3(float(r.info.x + x * 1024 + 512), float(posY), float(r.info.z + z * 1024 + 512)); hasWater = (s.ceiling * 256 - level->getCeiling(&st, p)) > 8.0f; } } m[(x - minX) + w * (z - minZ)] = hasWater ? 0xFF : 0x00; // TODO: flow map } mask = new Texture(w, h, 1, FMT_LUMINANCE, OPT_NEAREST, m); delete[] m; size = vec3(float((maxX - minX) * 512), 1.0f, float((maxZ - minZ) * 512)); // half size pos = vec3(r.info.x + minX * 1024 + size.x, float(posY), r.info.z + minZ * 1024 + size.z); int *mf = new int[4 * w * h * SQR(WATER_TILE_SIZE)]; memset(mf, 0, sizeof(int) * 4 * w * h * SQR(WATER_TILE_SIZE)); data[0] = new Texture(w * WATER_TILE_SIZE, h * WATER_TILE_SIZE, 1, FMT_RG_HALF, OPT_TARGET | OPT_VERTEX, mf); data[1] = new Texture(w * WATER_TILE_SIZE, h * WATER_TILE_SIZE, 1, FMT_RG_HALF, OPT_TARGET | OPT_VERTEX); delete[] mf; caustics = Core::settings.detail.water > Core::Settings::MEDIUM ? new Texture(512, 512, 1, FMT_RGBA, OPT_TARGET | OPT_DEPEND) : NULL; #ifdef BLUR_CAUSTICS caustics_tmp = Core::settings.detail.water > Core::Settings::MEDIUM ? new Texture(512, 512, 1, Texture::RGBA) : NULL; #endif blank = false; } void deinit() { delete data[0]; delete data[1]; delete caustics; #ifdef BLUR_CAUSTICS delete caustics_tmp; #endif delete mask; mask = caustics = data[0] = data[1] = NULL; } } items[MAX_SURFACES]; int count, visible; int dropCount; struct Drop { vec3 pos; float radius; float strength; Drop() {} Drop(const vec3 &pos, float radius, float strength) : pos(pos), radius(radius), strength(strength) {} } drops[MAX_DROPS]; WaterCache(IGame *game) : game(game), level(game->getLevel()), screen(NULL), refract(NULL), count(0), dropCount(0) { reflect = new Texture(512, 512, 1, FMT_RGBA, OPT_TARGET); } ~WaterCache() { delete screen; delete refract; delete reflect; for (int i = 0; i < count; i++) items[i].deinit(); } void update() { int i = 0; while (i < count) { Item &item = items[i]; if (item.timer > MAX_INVISIBLE_TIME) { items[i].deinit(); items[i] = items[--count]; continue; } item.timer += Core::deltaTime; i++; } } void reset() { for (int i = 0; i < count; i++) items[i].visible = false; visible = 0; } void flipMap() { for (int i = 0; i < level->roomsCount && count; i++) if (level->rooms[i].alternateRoom > -1) { int j = 0; while (j < count) { if (items[j].from == i || items[j].to == i) { items[j].deinit(); items[j] = items[--count]; } else j++; } } } void setVisible(int roomIndex, int nextRoom = TR::NO_ROOM) { if (nextRoom == TR::NO_ROOM) { // setVisible(underwaterRoom) for caustics update for (int i = 0; i < count; i++) if (items[i].caust == roomIndex) { nextRoom = items[i].from; if (!items[i].visible) { items[i].visible = true; visible++; } break; } return; } int from, to; // from surface room to underwater room if (level->rooms[roomIndex].flags.water) { from = nextRoom; to = roomIndex; } else { from = roomIndex; to = nextRoom; } if (level->rooms[to].waterLevelSurface == TR::NO_WATER && level->rooms[from].waterLevelSurface == TR::NO_WATER) // not have water surface return; for (int i = 0; i < count; i++) { Item &item = items[i]; if (item.from == from && item.to == to) { if (!item.visible) { visible++; item.visible = true; } return; } } if (count == MAX_SURFACES) return; items[count++] = Item(from, to); visible++; } void bindCaustics(int roomIndex) { Item *item = NULL; for (int i = 0; i < count; i++) if (items[i].caust == roomIndex) { item = &items[i]; break; } if (item && item->caustics) { item->caustics->bind(sReflect); Core::active.shader->setParam(uRoomSize, vec4(item->pos.x - item->size.x, item->pos.z - item->size.z, item->size.x * 2.0f, item->size.z * 2.0f)); game->setWaterParams(item->pos.y); } else { Core::active.shader->setParam(uRoomSize, vec4(0, 0, 1, 1)); Core::blackTex->bind(sReflect); } } void addDrop(const vec3 &pos, float radius, float strength) { if (dropCount >= MAX_DROPS) return; drops[dropCount++] = Drop(pos, radius, strength); } void drop(Item &item) { if (!dropCount) return; vec2 s(item.size.x * DETAIL * 2.0f, item.size.z * DETAIL * 2.0f); game->setShader(Core::passWater, Shader::WATER_DROP); vec4 rPosScale[2] = { vec4(0.0f), vec4(1.0f) }; Core::active.shader->setParam(uPosScale, rPosScale[0], 2); Core::active.shader->setParam(uTexParam, vec4(1.0f / item.data[0]->width, 1.0f / item.data[0]->height, s.x / item.data[0]->width, s.y / item.data[0]->height)); for (int i = 0; i < dropCount; i++) { Drop &drop = drops[i]; vec3 p; p.x = (drop.pos.x - (item.pos.x - item.size.x)) * DETAIL; p.z = (drop.pos.z - (item.pos.z - item.size.z)) * DETAIL; Core::active.shader->setParam(uParam, vec4(p.x, p.z, drop.radius * DETAIL, -drop.strength)); item.data[0]->bind(sNormal); Core::setTarget(item.data[1], NULL, RT_STORE_COLOR); Core::setViewport(0, 0, int(s.x + 0.5f), int(s.y + 0.5f)); game->getMesh()->renderQuad(); swap(item.data[0], item.data[1]); } } void step(Item &item) { if (item.timer < SIMULATE_TIMESTEP) return; vec2 s(item.size.x * DETAIL * 2.0f, item.size.z * DETAIL * 2.0f); game->setShader(Core::passWater, Shader::WATER_SIMULATE); Core::active.shader->setParam(uParam, vec4(0.995f, 1.0f, randf() * 0.5f, Core::params.x)); Core::active.shader->setParam(uTexParam, vec4(1.0f / item.data[0]->width, 1.0f / item.data[0]->height, s.x / item.data[0]->width, s.y / item.data[0]->height)); Core::active.shader->setParam(uRoomSize, vec4(1.0f / item.mask->origWidth, 1.0f / item.mask->origHeight, float(item.mask->origWidth) / item.mask->width, float(item.mask->origHeight) / item.mask->height)); while (item.timer >= SIMULATE_TIMESTEP) { // water step item.data[0]->bind(sNormal); Core::setTarget(item.data[1], NULL, RT_STORE_COLOR); Core::setViewport(0, 0, int(s.x + 0.5f), int(s.y + 0.5f)); game->getMesh()->renderQuad(); swap(item.data[0], item.data[1]); item.timer -= SIMULATE_TIMESTEP; } if (Core::settings.detail.water < Core::Settings::HIGH) return; // calc caustics game->setShader(Core::passWater, Shader::WATER_CAUSTICS); vec4 rPosScale[2] = { vec4(0.0f), vec4(32767.0f / PLANE_DETAIL) }; Core::active.shader->setParam(uPosScale, rPosScale[0], 2); float sx = item.size.x * DETAIL / (item.data[0]->width / 2); float sz = item.size.z * DETAIL / (item.data[0]->height / 2); Core::active.shader->setParam(uTexParam, vec4(1.0f / item.data[0]->width, 1.0f / item.data[0]->height, sx, sz)); Core::whiteTex->bind(sReflect); item.data[0]->bind(sNormal); Core::setTarget(item.caustics, NULL, RT_CLEAR_COLOR | RT_STORE_COLOR); Core::validateRenderState(); // force clear color for borders Core::setViewport(1, 1, item.caustics->width - 1, item.caustics->width - 1); // leave 2px for black border game->getMesh()->renderPlane(); #ifdef BLUR_CAUSTICS // v blur Core::setTarget(item.caustics_tmp, CLEAR_ALL); game->setShader(Core::passFilter, Shader::FILTER_BLUR, false, false); Core::active.shader->setParam(uParam, vec4(0, 1, 1.0f / item.caustics->width, 0));; item.caustics->bind(sDiffuse); game->getMesh()->renderQuad(); Core::invalidateTarget(false, true); // h blur Core::setTarget(item.caustics, CLEAR_ALL); game->setShader(Core::passFilter, Shader::FILTER_BLUR, false, false); Core::active.shader->setParam(uParam, vec4(1, 0, 1.0f / item.caustics->width, 0));; item.caustics_tmp->bind(sDiffuse); game->getMesh()->renderQuad(); Core::invalidateTarget(false, true); #endif } void renderRays() { #ifdef _OS_PSV // TODO return; #endif if (!visible) return; PROFILE_MARKER("WATER_RAYS"); for (int i = 0; i < count; i++) { Item &item = items[i]; if (!item.visible || !item.caustics) continue; // render water plane game->setShader(Core::passWater, Shader::WATER_RAYS); item.caustics->bind(sReflect); Core::ditherTex->bind(sMask); vec3 bCenter = vec3(item.pos.x, item.pos.y + WATER_VOLUME_HEIGHT / 2, item.pos.z); vec3 bSize = vec3(item.size.x, WATER_VOLUME_HEIGHT / 2, item.size.z); Box box(bCenter - bSize, bCenter + bSize); vec4 rPosScale[2] = { vec4(bCenter, 0.0), vec4(bSize, 1.0) }; Core::active.shader->setParam(uPosScale, rPosScale[0], 2); Core::active.shader->setParam(uParam, vec4(level->rooms[item.to].getOffset(), 0.35f)); Core::setBlendMode(bmAdd); Core::setCullMode(cmBack); Core::setDepthWrite(false); game->getMesh()->renderWaterVolume(item.to); Core::setDepthWrite(true); Core::setCullMode(cmFront); Core::setBlendMode(bmNone); } } void renderMask() { if (!visible) return; PROFILE_MARKER("WATER_MASK"); // mask underwater geometry by zero alpha game->setShader(Core::passWater, Shader::WATER_MASK); Core::active.shader->setParam(uTexParam, vec4(1.0f)); Core::setColorWrite(false, false, false, true); Core::setDepthWrite(false); Core::setCullMode(cmNone); Core::setBlendMode(bmNone); for (int i = 0; i < count; i++) { Item &item = items[i]; if (!item.visible) continue; vec4 rPosScale[2] = { vec4(item.pos, 0.0f), vec4(item.size, 1.0) }; Core::active.shader->setParam(uPosScale, rPosScale[0], 2); game->getMesh()->renderQuad(); } Core::setColorWrite(true, true, true, true); Core::setDepthWrite(true); Core::setCullMode(cmFront); } Texture* getScreenTex() { int w = Core::viewportDef.width; int h = Core::viewportDef.height; // get refraction texture if (!refract || w != refract->origWidth || h != refract->origHeight) { PROFILE_MARKER("WATER_REFRACT_INIT"); delete refract; refract = new Texture(w, h, 1, FMT_RGBA, OPT_TARGET); #ifdef USE_SCREEN_TEX delete screen; screen = new Texture(w, h, 1, FMT_RGBA, OPT_TARGET); #endif } return screen; } void copyScreenToRefraction() { PROFILE_MARKER("WATER_REFRACT_COPY"); // get refraction texture int x, y; if (!screen) { x = Core::viewportDef.x; y = Core::viewportDef.y; } else { x = y = 0; } if (screen) { Core::setTarget(refract, NULL, RT_LOAD_DEPTH | RT_STORE_COLOR | RT_STORE_DEPTH); bool flip = false; #if defined(_GAPI_D3D9) || defined(_GAPI_GXM) flip = true; #endif blitTexture(screen, flip); Core::setTarget(screen, NULL, RT_LOAD_COLOR | RT_LOAD_DEPTH | RT_STORE_COLOR); } else { Core::copyTarget(refract, 0, 0, x, y, Core::viewportDef.width, Core::viewportDef.height); // copy framebuffer into refraction texture } } void simulate() { PROFILE_MARKER("WATER_SIMULATE"); // simulate water Core::setDepthTest(false); Core::setBlendMode(bmNone); for (int i = 0; i < count; i++) { Item &item = items[i]; if (!item.visible) continue; if (item.timer >= SIMULATE_TIMESTEP || dropCount) { Core::noiseTex->bind(sDiffuse); item.mask->bind(sMask); // add water drops drop(item); // simulation step step(item); } } Core::setDepthTest(true); } void renderReflection() { if (!visible) return; PROFILE_MARKER("WATER_REFLECT"); for (int i = 0; i < count; i++) { Item &item = items[i]; if (item.visible && item.blank) item.init(game); } // render mirror reflection Core::setTarget(reflect, NULL, RT_CLEAR_COLOR | RT_CLEAR_DEPTH | RT_STORE_COLOR); Camera *camera = (Camera*)game->getCamera(); game->setupBinding(); // merge visible rooms for all items int roomsList[256]; int roomsCount = 0; for (int i = 0; i < level->roomsCount; i++) level->rooms[i].flags.visible = false; bool underwater = level->rooms[camera->getRoomIndex()].flags.water; vec4 reflectPlane; for (int i = 0; i < count; i++) { Item &item = items[i]; if (!item.visible) continue; reflectPlane = vec4(0, 1, 0, -item.pos.y); camera->reflectPlane = &reflectPlane; camera->setup(true); game->getVisibleRooms(roomsList, roomsCount, TR::NO_ROOM, underwater ? item.from : item.to, vec4(-1.0f, -1.0f, 1.0f, 1.0f), false); } if (roomsCount) { // select optimal water plane float waterDist = 10000000.0f; int waterItem = 0; for (int i = 0; i < count; i++) { Item &item = items[i]; if (!item.visible) continue; float d = fabsf(item.pos.x - camera->eye.pos.x) + fabsf(item.pos.z - camera->eye.pos.z); if (d < waterDist) { waterDist = d; waterItem = i; } } float waterLevel = items[waterItem].pos.y; reflectPlane = vec4(0, 1, 0, -waterLevel); camera->reflectPlane = &reflectPlane; camera->setup(true); // render reflections frame float sign = underwater ? -1.0f : 1.0f; game->setClipParams(sign, waterLevel * sign); game->renderView(TR::NO_ROOM, false, roomsCount, roomsList); } game->setClipParams(1.0f, NO_CLIP_PLANE); camera->reflectPlane = NULL; camera->setup(true); } void compose() { if (!visible) return; PROFILE_MARKER("WATER_COMPOSE"); for (int i = 0; i < count; i++) { Item &item = items[i]; if (!item.visible) continue; // render water plane game->setShader(Core::passWater, Shader::WATER_COMPOSE); Core::updateLights(); Core::active.shader->setParam(uParam, vec4(float(refract->origWidth) / refract->width, float(refract->origHeight) / refract->height, 0.05f, 0.0f)); float sx = item.size.x * DETAIL / (item.data[0]->width / 2); float sz = item.size.z * DETAIL / (item.data[0]->height / 2); Core::active.shader->setParam(uTexParam, vec4(1.0f / item.data[0]->width, 1.0f / item.data[0]->height, sx, sz)); Core::active.shader->setParam(uRoomSize, vec4(1.0f / item.mask->origWidth, 1.0f / item.mask->origHeight, float(item.mask->origWidth) / item.mask->width, float(item.mask->origHeight) / item.mask->height)); refract->bind(sDiffuse); reflect->bind(sReflect); item.mask->bind(sMask); item.data[0]->bind(sNormal); Core::setCullMode(cmNone); Core::setBlendMode(bmAlpha); #ifdef WATER_USE_GRID vec4 rPosScale[2] = { vec4(item.pos, 0.0f), vec4(item.size * vec3(1.0f / PLANE_DETAIL, 512.0f, 1.0f / PLANE_DETAIL), 1.0f) }; Core::active.shader->setParam(uPosScale, rPosScale[0], 2); game->getMesh()->renderPlane(); #else vec4 rPosScale[2] = { vec4(item.pos, 0.0f), vec4(item.size, 1.0) }; Core::active.shader->setParam(uPosScale, rPosScale[0], 2); game->getMesh()->renderQuad(); #endif Core::setCullMode(cmFront); Core::setBlendMode(bmNone); } dropCount = 0; } void blitTexture(Texture *tex, bool flip = false) { ASSERT(tex); game->setShader(Core::passGUI, Shader::DEFAULT); mat4 mProj = GAPI::ortho(0.0f, float(tex->origWidth), 0.0f, float(tex->origHeight), 0.0f, 1.0f); Core::active.shader->setParam(uViewProj, mProj); Core::active.shader->setParam(uMaterial, vec4(1.0f)); tex->bind(0); int w = tex->width; int h = tex->height; Index indices[6] = { 0, 1, 2, 0, 2, 3 }; Vertex vertices[4]; vertices[0].coord = short4(0, h, 0, 0); vertices[1].coord = short4(w, h, 0, 0); vertices[2].coord = short4(w, 0, 0, 0); vertices[3].coord = short4(0, 0, 0, 0); vertices[0].light = vertices[1].light = vertices[2].light = vertices[3].light = ubyte4(255, 255, 255, 255); #if defined(_GAPI_D3D9) || defined(_GAPI_GXM) flip = !flip; #endif if (flip) { vertices[0].texCoord = short4( 0, 0, 0, 0); vertices[1].texCoord = short4(32767, 0, 0, 0); vertices[2].texCoord = short4(32767, 32767, 0, 0); vertices[3].texCoord = short4( 0, 32767, 0, 0); } else { vertices[0].texCoord = short4( 0, 32767, 0, 0); vertices[1].texCoord = short4(32767, 32767, 0, 0); vertices[2].texCoord = short4(32767, 0, 0, 0); vertices[3].texCoord = short4( 0, 0, 0, 0); } Core::setDepthTest(false); Core::setBlendMode(bmNone); game->getMesh()->renderBuffer(indices, COUNT(indices), vertices, COUNT(vertices)); Core::setDepthTest(true); } #undef MAX_SURFACES #undef MAX_INVISIBLE_TIME #undef SIMULATE_TIMESTEP #undef DETAIL }; struct ZoneCache { struct Item { uint16 zone; uint16 count; uint16 *zones; uint16 *boxes; Item *next; Item(uint16 zone, uint16 count, uint16 *zones, uint16 *boxes, Item *next) : zone(zone), count(count), zones(zones), boxes(boxes), next(next) {} ~Item() { delete[] boxes; delete next; } } *items; IGame *game; // dummy arrays for path search uint16 *nodes; uint16 *parents; uint16 *weights; ZoneCache(IGame *game) : items(NULL), game(game) { TR::Level *level = game->getLevel(); nodes = new uint16[level->boxesCount * 3]; parents = nodes + level->boxesCount; weights = nodes + level->boxesCount * 2; } ~ZoneCache() { delete items; delete[] nodes; } Item *getBoxes(uint16 zone, uint16 *zones) { Item *item = items; while (item) { if (item->zone == zone && item->zones == zones) return item; item = item->next; } int count = 0; TR::Level *level = game->getLevel(); for (int i = 0; i < level->boxesCount; i++) if (zones[i] == zone) nodes[count++] = i; ASSERT(count > 0); uint16 *boxes = new uint16[count]; memcpy(boxes, nodes, sizeof(uint16) * count); return items = new Item(zone, count, zones, boxes, items); } uint16 findPath(int ascend, int descend, bool big, int boxStart, int boxEnd, uint16 *zones, uint16 **boxes) { if (boxStart == TR::NO_BOX || boxEnd == TR::NO_BOX) return 0; TR::Level *level = game->getLevel(); memset(parents, 0xFF, sizeof(uint16) * level->boxesCount); // fill parents by 0xFFFF memset(weights, 0x00, sizeof(uint16) * level->boxesCount); // zeroes weights uint16 count = 0; nodes[count++] = boxEnd; uint16 zone = zones[boxStart]; if (zone != zones[boxEnd]) return 0; TR::Box &b = level->boxes[boxStart]; int sx = (b.minX + b.maxX) >> 11; // box center / 1024 int sz = (b.minZ + b.maxZ) >> 11; while (count) { // get min weight int minI = 0; int minW = weights[nodes[minI]]; for (int i = 1; i < count; i++) if (weights[nodes[i]] < minW) { minI = i; minW = weights[nodes[i]]; } int cur = nodes[minI]; // peek min weight item from array count--; for (int i = minI; i < count; i++) nodes[i] = nodes[i + 1]; // check for end of path if (cur == boxStart) { count = 0; while (cur != boxEnd) { nodes[count++] = cur; cur = parents[cur]; } nodes[count++] = cur; *boxes = nodes; return count; } // add overlap boxes TR::Box &b = game->getLevel()->boxes[cur]; TR::Overlap *overlap = &level->overlaps[b.overlap.index]; do { uint16 index = overlap->boxIndex; // unvisited yet if (parents[index] != 0xFFFF) continue; // has same zone if (zones[index] != zone) continue; // check passability if (big && level->boxes[index].overlap.blockable) continue; // check blocking (doors) if (level->boxes[index].overlap.block) continue; // check for height difference int d = level->boxes[index].floor - b.floor; if (d > ascend || d < descend) continue; int dx = sx - ((b.minX + b.maxX) >> 11); int dz = sz - ((b.minZ + b.maxZ) >> 11); int w = abs(dx) + abs(dz); ASSERT(count < level->boxesCount); nodes[count++] = index; parents[index] = cur; weights[index] = weights[cur] + w; } while (!(overlap++)->end); } return 0; } }; ShaderCache *shaderCache; #undef UNDERWATER_COLOR #endif
aiden00713/PS09
PS0904/PS090423.c
#include <stdio.h> void afunc(char a[],int n,char b[]); int main(void) { char a[80],b[80]; int n; scanf("%s",a); scanf("%d",&n); afunc(a,n,b); printf("[%s]",b); return 0; } void afunc(char a[],int n,char b[]) { int i,end,j=0,k; for(i=0;a[i]!=0;i++) { } end=i; for(i=n;i<end;i++) { b[j++]=a[i]; } b[j]=0; return; }
aiden00713/PS09
PS0903/PS090321.c
#include <stdio.h> int main(void) { int a[80],i=0; scanf("%d",&a[i]); while (a[i]!=0) scanf("%d",&a[++i]); printf("[%d] ", afunc(a)); for (i=0;a[i]!=0;i++) printf("%d ",a[i]); return 0; } int afunc(int a[]) { int i; int top = a[0]; for (i=0;a[i]!=0;i++) { a[i-1]=a[i]; } a[i-1]=0; return top; }
aiden00713/PS09
PS0904/PS090419.c
<reponame>aiden00713/PS09<filename>PS0904/PS090419.c #include <stdio.h> int afunc(char a[],char b[],char c[]); int main(void) { char a[80],b[80],c[80]; scanf("%s",a); scanf("%s",b); afunc(a,b,c); printf("[%s]\n",c); return 0; } int afunc(char a[],char b[],char c[]) { int i,end; for(i=0;a[i]!=0 && b[i]!=0;i++) { ; } end=i; for(i=0;i<end;i++) { if(a[i]!=b[i]) c[i]='1'; else c[i]='0'; } c[i]=0; return ; }
aiden00713/PS09
PS0901/PS090102.c
<filename>PS0901/PS090102.c #include <stdio.h> int main(void) { int a[20]; int i=0,j=0,end; for(i=0;i<20;i++) { scanf("%d",&a[i]); if(a[i]==0) break; } end=i; for(j=end-1;j>0;j--) { printf("%d ",a[j]); } printf("%d",a[0]); return 0; }
aiden00713/PS09
PS0904/PS090408.c
<reponame>aiden00713/PS09 #include <stdio.h> void afunc(char a[],char b[]); int main(void) { char a[80],b[80]; scanf("%s",a); afunc(a,b); printf("[%s]\n",b); return 0; } void afunc(char a[],char b[]) { int i,end,j=0; for(i=0;a[i]!=0;i++) { if(a[i]>='0' && a[i]<='9') b[j++]=a[i]; } b[j]=0; return; }
aiden00713/PS09
PS0903/PS090305.c
<filename>PS0903/PS090305.c #include <stdio.h> int afunc(int a[]); int main(void) { int a[80],i=0; scanf("%d",&a[i]); while (a[i]!=0) scanf("%d",&a[++i]); printf("[%d]",afunc(a)); return 0; } int afunc(int a[]) { int i,j,sum; for(i=0;a[i]!=0;i++) { ; } for(j=0;j<i;j++) { sum+=a[j]; } a[j]=0; return sum; }
aiden00713/PS09
PS0901/PS090136.c
<reponame>aiden00713/PS09 #include <stdio.h> int main(void) { int m[12]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int a,b,i=0,sum=0,d=0; scanf("%d %d",&a,&b); for(i=0;i<a;i++) { sum+=m[i]; } d=sum+b; printf("%d",d); return 0; }
aiden00713/PS09
PS0904/PS090462.c
#include <stdio.h> int main(void) { char a[16]; char b[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; int i,j=0,k=0,end; scanf("%s",a); for(i=0;a[i]!=0;i++) { } end=i; for(i=0;i<end;i++) { for(j=0;j<16;j++) { if(a[i]==b[j]) { k++; } } } if(k==end) { printf("=%d",k); } else { printf("=NO",k); } return 0; }
aiden00713/PS09
PS0901/PS090107.c
#include <stdio.h> int main(void) { int n,i=0,j; int a[80]; scanf("%d",&n); while(n>0) { a[i++]=n%2; n/=2; } for(j=i-1;j>=0;j--) { printf("%d",a[j]); } return 0; }
aiden00713/PS09
PS0904/PS090431.c
<filename>PS0904/PS090431.c #include <stdio.h> void afunc(char a[],char b[]); int main(void) { char a[80],b[80]; gets(a); afunc(a,b); printf("[%s]",b); return 0; } void afunc(char a[],char b[]) { int i,j=0,end; for(i=0;a[i]!=0;i++) { if(a[i]!=' ') { b[j++]=a[i]; } } b[j]=0; return ; }
aiden00713/PS09
PS0904/PS090436.c
<filename>PS0904/PS090436.c #include <stdio.h> int afunc(char a[]); int main(void) { char a[80]; gets(a); printf("[%d]",afunc(a)); return 0; } int afunc(char a[]) { char b[80]; int i,end,j=0; for(i=0;a[i]!=0;i++) { if(a[i]>='0' && a[i]<='9') b[j++]=a[i]; } if(j==0) return -1; for(i=0;i<j;i++) { if(b[i+1]<b[i]) { b[i+1]=b[i]; } else { b[i]=b[i+1]; } } return b[i]-'0'; }
aiden00713/PS09
PS0904/PS090461.c
#include <stdio.h> int main(void) { char a[16]; int i,end,j=0; scanf("%s",a); for(i=0;a[i]!=0;i++) { } end=i; for(i=0;i<end;i++) { if(a[i]>='0' && a[i]<='9') { j++; } else { printf("=NO"); return 0; } } printf("=%d",j); return 0; }
aiden00713/PS09
PS0901/PS090108.c
#include <stdio.h> int main(void) { int n,i=0,j,num[80]; scanf("%d",&n); for(;n>0;) //除16 { num[i++]=n%16; n/=16; } char h[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; for(j=i-1;j>0;j--) //倒著印出 如果設j>=0 就會多印出- { printf("%c-",h[num[j]]); //用j的數字來指定h要印出多少 } printf("%c",h[num[0]]); //最後再印出num[0] return 0; }
aiden00713/PS09
PS0903/PS090315.c
<gh_stars>0 #include <stdio.h> void afunc(int a[],int b[],int n); int main(void) { int a[80],b[80],i=0,n; scanf("%d",&a[i]); while (a[i]!=0) scanf("%d",&a[++i]); scanf("%d",&n); afunc(a,b,n); for (i=0;b[i]!=0;i++) printf("%d ",b[i]); return 0; } void afunc(int a[],int b[],int n) { int i,end,j=0; for(i=0;i<n;i++) { b[j++]=a[i]; } b[j]=0; return; }
aiden00713/PS09
PS0903/PS090302.c
<reponame>aiden00713/PS09<filename>PS0903/PS090302.c #include <stdio.h> int main(void) { int a[81],i=0; scanf("%d",&a[i]); while (a[i]!=0) scanf("%d",&a[++i]); printf("[%d]\n",afunc(a)); return 0; } int afunc(int a[]) { int i=0,end; for(i=0;a[i]!=0;i++) { ; } return i; }
aiden00713/PS09
PS0903/PS090332.c
#include <stdio.h> void afunc(int a[],int n); int main(void) { int a[80],n,i; scanf("%d",&n); afunc(a,n); for (i=0;a[i]!=0;i++) printf("%d ",a[i]); return 0; } void afunc(int a[],int n) { int i=0; while(n>0) { a[i++]=n%10; n/=10; } a[i]=0; return; }
aiden00713/PS09
PS090202.c
<reponame>aiden00713/PS09 #include <stdio.h> int main(void) { int num[80][2]; int fail1=0,fail2=0; int i,j=0,end,n,pass; for(i=0;i<80;i++) { scanf("%d",&n); if(n==0) { break; } scanf("%d",&num[i][0]); scanf("%d",&num[i][1]); } end=i; scanf("%d",&pass); for(i=0;i<end;i++) { if(num[i][0]<pass) fail1++; if(num[i][1]<pass) fail2++; } printf("FAIL=%d %d",fail1,fail2); return 0; }
aiden00713/PS09
PS0901/PS090110.c
#include <stdio.h> int main(void) { int n[80]; int i=0,j=0,k=0,m,end; scanf("%d",&m); for(;m>0;) { n[i++]=m%2; m/=2; } end=i; for(i=0;i<end;i++) { if(n[i]==1) k++; } printf("%d",k); return 0; }
aiden00713/PS09
PS0901/PS090103.c
#include <stdio.h> int main(void) { int i,n,end,j=0; int num[80]; for(i=0;i<80;i++) { scanf("%d",&num[i]); if(num[i]==0) break; } end=i; scanf("%d",&n); for(i=0;i<end;i++) { if(num[i]==n) j++; } printf("%d",j); return 0; }
aiden00713/PS09
PS0903/PS090306.c
#include <stdio.h> int afunc(int a[]); int main(void) { int a[80],i=0; scanf("%d",&a[i]); while (a[i]!=0) scanf("%d",&a[++i]); printf("[%d]",afunc(a)); return 0; } int afunc(int a[]) { int i,j=0; for(i=0;a[i]!=0;i++) { if(a[i]%2==0) j++; } return j; }
aiden00713/PS09
PS0901/PS090135.c
<reponame>aiden00713/PS09<gh_stars>0 #include <stdio.h> int main(void) { //int num[13]={0,1月,2月,3月,4月,5月,6月,7月,8月,9月,10月,11月,12月}; int num[]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int n,i=0; scanf("%d",&n); for(i=0;n>num[i];i++) { n-=num[i]; } printf("%d %d",i,n); return 0; }
aiden00713/PS09
PS0901/PS090106.c
#include <stdio.h> int main(void) { int a[10]; int b[10]; int i,j,k=0,end; for(i=0;i<10;i++) { scanf("%d",&a[i]); if(a[i]==0) break; } for(j=0;j<10;j++) { scanf("%d",&b[j]); if(b[j]==0) break; } end=i; for(i=0;i<end;i++) { if(a[i]!=b[i]) k++; } printf("%d",k); return 0; }
aiden00713/PS09
PS0904/PS090401.c
#include <stdio.h> int afunc(char a[]); int main(void) { char a[80]; scanf("%s",a); printf("[%d]",afunc(a)); return 0; } int afunc(char a[]) { int i,end; for(i=0;a[i]!=0;i++) { } end=i; return end; }
aiden00713/PS09
PS0901/PS090105.c
<filename>PS0901/PS090105.c #include <stdio.h> int main(void) { int i,j=0,end,n; int a[20]; for(i=0;i<20;i++) { scanf("%d",&a[i]); if(a[i]==0) break; } end=i; scanf("%d",&n); if(n>=end) { printf("NO"); } else { for(i=0;i<end;i++) { if(i==n) printf("%d",a[i]); } } return 0; }
aiden00713/PS09
PS0901/PS090101.c
<reponame>aiden00713/PS09 #include <stdio.h> int main(void) { int i,j; int num[80]; for(i=0;i<80;i++) { scanf("%d",&num[i]); if(num[i]==0) break; } for(j=0;j<i;j++) { printf("%d ",num[j]); } num[j]=0; return 0; }
aiden00713/PS09
PS0903/PS090303.c
<filename>PS0903/PS090303.c<gh_stars>0 #include <stdio.h> void afunc(int a[]); int main(void) { int a[80],i; afunc(a); for (i=0;a[i]!=0;i++) printf("%d ",a[i]); return 0; } void afunc(int a[]) { int i; for(i=0;i<80;i++) { scanf("%d",&a[i]); if(a[i]==0) break; } return; }
aiden00713/PS09
PS0904/PS090412.c
#include <stdio.h> void afunc(char a[]); int main(void) { char a[80]; scanf("%s",a); afunc(a); printf("[%s]\n",a); return 0; } void afunc(char a[]) { int i,end,j=0; char b[80]; for(i=0;a[i]!=0;i++) { } end=i; for(i=0;i<end;i++) { if(a[i]>='A' && a[i]<='Z') a[i]=a[i]-'A'+'a'; else if(a[i]>='a' && a[i]<='z') a[i]=a[i]-'a'+'A'; } a[i]=0; return ; }
aiden00713/PS09
PS0903/PS090324.c
<reponame>aiden00713/PS09 #include <stdio.h> void afunc(int a[],int m,int n); int main(void) { int a[80],i=0,n,m; scanf("%d",&a[i]); while (a[i]!=0) scanf("%d",&a[++i]); scanf("%d%d",&m,&n); afunc(a,m,n); for (i=0;a[i]!=0;i++) printf("%d ",a[i]); return 0; } void afunc(int a[],int m,int n) { int i,end,j=0; for(i=0;a[i]!=0;i++) { } end=i; if(m>=end)//假設m的值等於字串最尾端 { a[i]=n; //尾端位置=n值 return; } for(i=end-1;i>0;i--) //倒著數 { if(i==m) //假設i到達m指定的位置時 { a[i+1]=a[i]; a[i]=n; //加入n值 return; } else //否則持續做位置+1的移位 { a[i+1]=a[i]; } } }
aiden00713/PS09
PS0901/PS090138.c
#include <stdio.h> int main(void) { int n,m,sum,sum2,i; int a[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; scanf("%d",&n); scanf("%d",&m); for(i=0;i<n;i++) { sum+=a[i]; } sum2=(sum+m+6)%7; printf("%d",sum2); return 0; }
madhupolisetti/iossdk
SMSCountryApi/Classes/CompletionBlocks.h
// // CompletionBlocks.h // SMSCountryApi // // Created by <NAME> on 03/10/16. // Copyright © 2016 SMS Country. All rights reserved. // typedef void (^ErrorBlock)(RKObjectRequestOperation *operation, NSError *error);
madhupolisetti/iossdk
Example/SMSCountryApi/SCViewController.h
<gh_stars>0 // // SCViewController.h // SMSCountryApi // // Created by <NAME> on 10/04/2016. // Copyright (c) 2016 <NAME>. All rights reserved. // @import UIKit; @interface SCViewController : UIViewController @end
madhupolisetti/iossdk
SMSCountryApi/Classes/SMSService.h
// // SMSService.h // SMSCountryApi // // Created by <NAME> on 03/10/16. // Copyright © 2016 SMS Country. All rights reserved. // #import <Foundation/Foundation.h> #import "SendSMSRequest.h" #import "SendSMSResponse.h" #import "SMSCountryApi.h" #import "CompletionBlocks.h" typedef void (^SendSMSSuccessBlock)(SendSMSResponse *sendSMSResponse); @interface SMSService : NSObject @property (nonatomic, strong) SMSCountryApi *smsCountryApi; -(void)initWith:(SMSCountryApi *)smsCountryApi; -(void)sendSMS:(SendSMSRequest *)sendSMSRequest success:(SendSMSSuccessBlock)successBlock failure:(ErrorBlock)errorBlock; @end
madhupolisetti/iossdk
SMSCountryApi/Classes/SendSMSResponse.h
<gh_stars>0 // // SendSMSResponse.h // SMSCountryApi // // Created by <NAME> on 04/10/16. // Copyright © 2016 SMS Country. All rights reserved. // #import "BaseResponse.h" @interface SendSMSResponse: BaseResponse @property (nonatomic, strong) NSString *messageUUID; @end
madhupolisetti/iossdk
Example/Pods/Target Support Files/Pods-SMSCountryApi_Example/Pods-SMSCountryApi_Example-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_SMSCountryApi_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SMSCountryApi_ExampleVersionString[];
madhupolisetti/iossdk
Example/Pods/Target Support Files/Pods-SMSCountryApi_Tests/Pods-SMSCountryApi_Tests-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_SMSCountryApi_TestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SMSCountryApi_TestsVersionString[];