exception thrown with random numbers in c++ - c++

I'm trying to make a game which requires pseudo random numbers to set the enemies to random spots. So I tried including the stdlib header file and used srand before getting random numbers for the enemies using rand, my code until the first srand looks like this:
#include "pch.h"
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <time.h>
int screenWidth = 70, screenHeight = 80;
class Enemy {
public:
int column, lives;
Enemy() {};
Enemy(int nColumn, int nLives) {
column = nColumn;
lives = nLives;
}
};
int main()
{
wchar_t *screen = new wchar_t[screenWidth * screenHeight];
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole);
DWORD bytesWritten = 0;
int x = 0, y = 0, width = 10, height = 10;
std::wstring canvas = L"";
wchar_t *title = new wchar_t[8];
wsprintf(title, L"retro shooter");
SetConsoleTitle(title);
int enemiesLength = screenWidth / width;
Enemy* enemies = new Enemy[enemiesLength];
srand(time(NULL)); // It throws the error at this line
for (int i = 0; i < enemiesLength; i++) {
if (rand() % 2) enemies[i] = Enemy(i, 1);
}
// the code doesn't end here that's why I didn't put out the closing curly bracket
The code above gives me the error/exception:
Exception thrown at 0x76EDE496 (ntdll.dll) in retroShooter.exe: 0xC0000005: Access violation reading location 0x183A0FA2.
I have tried using vectors but the exception is the same.
I have also tried include-ing cstdlib like: #include <cstdlib> but the exception is the exact same.
This exception is thrown after it has been compiled and it isn't marked as an error in visual studio

This is robably the issue:
wchar_t *title = new wchar_t[8]; // 8 is a lot shorter
wsprintf(title, L"retro shooter"); // than 14

Related

Simple usage example of gif-h library

I'm attempting to create a minimal usage example for https://github.com/ginsweater/gif-h
But, starting with a vector<uint8_t> of size imageWidth*imageHeight, the second GifWriteFrame call throws an access violation reading location exception
My attempt:
#include <gif.h>
#include "BOBImageConversion.h"
int main(void)
{
// USAGE:
// Create a GifWriter struct. Pass it to GifBegin() to initialize and write the header.
// Pass subsequent frames to GifWriteFrame().
// Finally, call GifEnd() to close the file handle and free memory.
int delay = 100;
auto i1 = BOBImageIO::BOBLoadImage("Camera7.png");
auto i2 = BOBImageIO::BOBLoadImage("Camera18.png");
vector<uint8_t> vi1 = BOBImageConversion::ARGB2RGBAuint8(i1);
vector<uint8_t> vi2 = BOBImageConversion::ARGB2RGBAuint8(i2);
cout << (vi1.size() == i1.Width()*i1.Height()) << endl; // true
cout << (vi2.size() == i2.Width()*i2.Height()) << endl; // true
auto fileName = "gif.gif";
GifWriter g;
GifBegin(&g, fileName, i1.Width(), i1.Height(), delay);
GifWriteFrame(&g, vi1.data(), i1.Width(), i1.Height(), delay);
GifWriteFrame(&g, vi2.data(), i2.Width(), i2.Height(), delay); // Exception thrown: Access violation reading location
GifEnd(&g);
return 0;
}
For the above point the code posted is a minimal example. What's wrong?
This works
#include <vector>
#include <cstdint>
#include <gif.h>
int main()
{
int width = 100;
int height = 200;
std::vector<uint8_t> vi1(width * height * 4, 0);
std::vector<uint8_t> vi2(width * height * 4, 255);
auto fileName = "bwgif.gif";
int delay = 100;
GifWriter g;
GifBegin(&g, fileName, width, height, delay);
GifWriteFrame(&g, vi1.data(), width, height, delay);
GifWriteFrame(&g, vi2.data(), width, height, delay);
GifEnd(&g);
return 0;
}

How do I properly use the OpenH264 Usage Code Example for Encoding?

I have an image and want to encode it with OpenH264.
So far this is the code I derived from their wiki:
#include <fstream>
#include <iterator>
#include <iostream>
#include <codec_api.h> //standard api for openh264
//additional libaries used by sample code
#include <codec_app_def.h>
#include <codec_def.h>
#include <codec_ver.h>
#include <assert.h>
#include <vector>
#include <cstring>
int main()
{
//parameter values
int width = 1920;
int height = 1080;
int framerate = 60;
int bitrate = 5000000;
int total_num = 500; //what does this value do?
//end parameter values
//Read in the File from bmp
std::vector<char> buf; //to store the image information
std::basic_ifstream<char> file("/home/megamol/Git/h264_sample/build/test.bmp", std::ios::binary); //opens bitstream to source
buf = std::vector<char>((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); // reads in data to the vector
std::cout << "sizeof buf: " << buf.size() << std::endl;
//Step 1: set up Encoder
ISVCEncoder* encoder_; //declaration of encoder pointer
int rv = WelsCreateSVCEncoder (&encoder_);
//Step 2: initialize with basic parameter
SEncParamBase param;
memset(&param, 0, sizeof (SEncParamBase));
param.iUsageType = EUsageType::SCREEN_CONTENT_REAL_TIME;
param.fMaxFrameRate = framerate;
param.iPicWidth = width;
param.iPicHeight = height;
param.iTargetBitrate = bitrate; //default value of example
encoder_->Initialize(&param);
//Step 3: set video format
int videoFormat = videoFormatI420;
encoder_->SetOption (ENCODER_OPTION_DATAFORMAT, &videoFormat);
//Step 4: encocode and store output bitstream
int frameSize = width * height * 3 / 2;
buf.resize(frameSize);
SFrameBSInfo info;
std::vector<char> compressedData;
memset (&info, 0, sizeof (SFrameBSInfo));
SSourcePicture pic;
memset (&pic, 0, sizeof (SSourcePicture));
pic.iPicWidth = width;
pic.iPicHeight = height;
pic.iColorFormat = videoFormatI420;
pic.iStride[0] = pic.iPicWidth;
pic.iStride[1] = pic.iStride[2] = pic.iPicWidth >> 1;
pic.pData[0] = reinterpret_cast<unsigned char*>(&buf[0]);
pic.pData[1] = pic.pData[0] + width * height;
pic.pData[2] = pic.pData[1] + (width * height >> 2);
//encodes the frame
rv = encoder_->EncodeFrame (&pic, &info); // encodes the Frame
//encoding done encoded Frame should be stored in &info
//begin decoding block
ISVCDecoder *pSvcDecoder;
unsigned char *pBuf= &info;
return 0;
}
I'm not entirely sure whether this is the correct usage of OpenH264 but I'm also not sure how to test it properly.
Now the code example is kind of poorly documented.
What is BufferedData buf; for example? I get that that's supposed to be the input but what is that type? Like how do I load my test.bmp as BufferedData? I don't think that I'm doing that correctly yet.
Another thing I'm pretty confused about is how do I access the output after the encoding? In the example it just says //output bitstream and nothing about saving this output anywhere. I thought the output was info like it says in the codec_api.h header file:
/**
* #brief Encode one frame
* #param kpSrcPic the pointer to the source luminance plane
* chrominance data:
* CbData = kpSrc + m_iMaxPicWidth * m_iMaxPicHeight;
* CrData = CbData + (m_iMaxPicWidth * m_iMaxPicHeight)/4;
* the application calling this interface needs to ensure the data validation between the location
* #param pBsInfo output bit stream
* #return 0 - success; otherwise -failed;
*/
virtual int EXTAPI EncodeFrame (const SSourcePicture* kpSrcPic, SFrameBSInfo* pBsInfo) = 0;
But apparently it only saves informations about the output. I'm just really confused about all of this.
Based on https://github.com/cisco/openh264/blob/master/codec/console/enc/src/welsenc.cpp
#include <codec_api.h>
#include <cassert>
#include <cstring>
#include <vector>
#include <fstream>
#include <iostream>
//Tested with OpenCV 3.3
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace std;
using namespace cv;
int main()
{
ISVCEncoder *encoder_ = nullptr;
int rv = WelsCreateSVCEncoder (&encoder_);
assert (0==rv);
assert (encoder_ != nullptr);
int width = 640;
int height = 480;
int total_num = 100;
SEncParamBase param;
memset (&param, 0, sizeof (SEncParamBase));
param.iUsageType = CAMERA_VIDEO_REAL_TIME;
param.fMaxFrameRate = 30;
param.iPicWidth = width;
param.iPicHeight = height;
param.iTargetBitrate = 5000000;
encoder_->Initialize (&param);
Mat image = imread("test.jpg", IMREAD_COLOR );
Mat imageResized, imageYuv, imageYuvMini;
resize(image, imageResized, Size(width, height));
Mat imageYuvCh[3], imageYuvMiniCh[3];
cvtColor(imageResized, imageYuv, cv::COLOR_BGR2YUV);
split(imageYuv, imageYuvCh);
resize(imageYuv, imageYuvMini, Size(width/2, height/2));
split(imageYuvMini, imageYuvMiniCh);
SFrameBSInfo info;
memset (&info, 0, sizeof (SFrameBSInfo));
SSourcePicture pic;
memset (&pic, 0, sizeof (SSourcePicture));
pic.iPicWidth = width;
pic.iPicHeight = height;
pic.iColorFormat = videoFormatI420;
pic.iStride[0] = imageYuvCh[0].step;
pic.iStride[1] = imageYuvMiniCh[1].step;
pic.iStride[2] = imageYuvMiniCh[2].step;
pic.pData[0] = imageYuvCh[0].data;
pic.pData[1] = imageYuvMiniCh[1].data;
pic.pData[2] = imageYuvMiniCh[2].data;
ofstream outFi;
outFi.open ("test.264", ios::out | ios::binary);
for(int num = 0; num<total_num; num++)
{
//prepare input data
rv = encoder_->EncodeFrame (&pic, &info);
assert (rv == cmResultSuccess);
if (info.eFrameType != videoFrameTypeSkip /*&& cbk != nullptr*/)
{
//output bitstream
for (int iLayer=0; iLayer < info.iLayerNum; iLayer++)
{
SLayerBSInfo* pLayerBsInfo = &info.sLayerInfo[iLayer];
int iLayerSize = 0;
int iNalIdx = pLayerBsInfo->iNalCount - 1;
do {
iLayerSize += pLayerBsInfo->pNalLengthInByte[iNalIdx];
--iNalIdx;
} while (iNalIdx >= 0);
unsigned char *outBuf = pLayerBsInfo->pBsBuf;
outFi.write((char *)outBuf, iLayerSize);
}
}
}
if (encoder_) {
encoder_->Uninitialize();
WelsDestroySVCEncoder (encoder_);
}
outFi.close();
}

C++ How to remove vertical scrollbar?

I am trying to make a fun program where it display random numbers, but I need to remove the scrollbar so it looks more convincing. I managed to make the program full screen but I can't remove the vertical scrollbar. Screenshot
Code:
#include <iostream>
#include <Windows.h>
using namespace std;
int main() {
SetConsoleDisplayMode(GetStdHandle(STD_OUTPUT_HANDLE), CONSOLE_FULLSCREEN_MODE, 0);
int output;
bool done = false;
system("color a");
while (!done) {
output = 1 + (rand() % (int)(1000 - 1 + 1));
cout << output;
}
}
There are many ways, one of them is manipulating the size of the internal buffer of the console to have the same size of the window and then using ShowScrollBar function to remove the scrolls.
#include <iostream>
#include <Windows.h>
#include <WinUser.h>
using namespace std;
int main() {
SetConsoleDisplayMode(GetStdHandle(STD_OUTPUT_HANDLE), CONSOLE_FULLSCREEN_MODE, 0);
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hstdout, &csbi);
csbi.dwSize.X = csbi.dwMaximumWindowSize.X;
csbi.dwSize.Y = csbi.dwMaximumWindowSize.Y;
SetConsoleScreenBufferSize(hstdout, csbi.dwSize);
HWND x = GetConsoleWindow();
ShowScrollBar(x, SB_BOTH, FALSE);
int output;
bool done = false;
system("color a");
while (!done) {
output = 1 + (rand() % (int)(1000 - 1 + 1));
cout << output;
}
}
Another way is to rely on conio.h or another C/C++ header/library which implements user interface functions.

dispose is not a member of GDI+ Image class

So I have a program that pulls random images from a folder and creates a collage out of them, and set it to the windows wallpaper. Which seems to work fine. So I thought I would put in a sleep timer and let it automatically update itself without me having to run it every half hour or what ever. I did that and it works great, but I ran into a problem of a memory leak that wasn't noticed before I started looping it. I am attempting to dispose of the GDI+objects, but I keep getting the error that dispose is not a member of GDIplus::Image
I am loading an picture into an Image object, then resizing it and putting it into an array of Images, then I would like to dispose of the first Image. I would then like to dispose of the array after I finish working with the images in it.
This is being done with an old copy of VS2005.
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
#include <string>
#include <iostream>
#include <vector>
#include <dirent.h>
#include <time.h>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include "cwp05rnd.h"
using namespace Gdiplus;
using namespace std;
#pragma comment (lib,"Gdiplus.lib")
#pragma comment (lib, "user32.lib")
int main()
{
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
HDC hdc;
Graphics graphics(hdc);
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
CLSID jpegClsid;
GetEncoderClsid(L"image/jpeg", &jpegClsid);
SetCurrentDirectoryA("E:\\Photos");
ofstream outfile;
outfile.open ("outimgs.txt");
ofstream outfile2;
outfile2.open("imgpos.txt");
srand(time(NULL));
init_genrand(time(NULL));
vector<string> dirlist;
DIR *d;
struct dirent *dir;
int i=0;
d=opendir(".");
if (d)
{
while ((dir=readdir(d)) != NULL)
{
i++;
dirlist.push_back(dir->d_name);
}
closedir(d);
}
Image wp(L"E:\\Dropbox\\Photos\\wallpaper.jpg");
Graphics* wpimage = Graphics::FromImage(&wp);
int r;
int rvsize=100;
int rv[100]={0};
string img;
std::wstring wimg;
const wchar_t* rimg;
double cwidth;
double cheight;
double ratio;
int nheight;
int counter=0;
int full = 0;
int tries = 0;
int hfull = 0;
int imgnum =0;
int last=0;
Image* newpic[10];
while ( tries <10)
{
redo:
tries++;
int newrv=0;
while (newrv ==0)
{
r=genrand_int32()%i;
for (int k=0; k < rvsize; k++)
{
if (rv[k] > 0 && rv[k]==r )
{
break;
}
if (rv[k]==0 && r < i)
{
newrv =1;
rv[k]=r;
last=k;
break;
}
if (rv[k] ==0)
{
break;
}
}
}
img = dirlist[r];
if (img[0]=='.')
{
newrv=0;
goto redo;
}
wimg = std::wstring(img.begin(),img.end());
rimg = wimg.c_str();
Image pic(rimg);
cwidth = pic.GetWidth();
cheight = pic.GetHeight();
if (cheight ==0)
{
outfile2 << "error" << img << endl;
rv[last]=0;
system("pause");
goto redo;
}
ratio = cwidth/cheight;
nheight = nwidth/ratio;
pic.RotateFlip(Rotate180FlipNone);
pic.RotateFlip(Rotate180FlipNone);
newpic[imgnum] = pic.GetThumbnailImage(nwidth,nheight,NULL,NULL);
delete pic[0];
imgnum = imgnum + 1;
}
then there is a long section of flips and rotates on the images in newpic, according to various random values.
wpimage->DrawImage(newpic[k],(j*nwidth),(((k+1)*whitespace)+htot),nwidth,nh[k]);
wp.Save(L"C:\\Temp\\wallpaper\\nwallpaper.jpg", &jpegClsid, NULL);
delete newpic;
setWall();
delete wpimage;
delete wp;
return 0;
}
When I attempt to delete the Image objects, I get an error that says either it can not delete objects that are not pointers, or it cannot convert from GDIplus::Image to void*
Any advice would be appreciated.
I noticed you have Image pic(rimg);
But you are doing delete pic[0];
pic is not a pointer.. not dynamically allocated or something... nor is a array (or maybe it is.. but intuitively I think no..)
* Add *
Oh yeah, if you already solved this, suggests you close the question or at least mention it...

C++ 2Dimensional array

I'm currently learning c++,and the code went so far,until
i made array variables to call a function instead of string,but something went wrong,and i can't figure out what it is.Problem is,it couts correctly only first 2 letters,then it couts the rest as └└└└ symbols.
Here's the code:
#include <iostream>
#include <string>
#include <windows.h>
#include <conio.h>
using namespace std;
int land(){
HANDLE hConsole;
hConsole = GetStdHandle (STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN);
char H = 72;
cout<<H;
}
int player(){
HANDLE hConsole;
hConsole = GetStdHandle (STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
char X = 88;
cout<<X;
}
/*previously,i declared a string inside worldgen,and generated 2d array inside the for loop,but when i changed variables to call a function,first letters were X and H,but then it went └└└└└└└└└└└└└└└└└└└└└└└ for all the remaining characters.What's wrong here? */
int worldgen(int dimX,int dimY,int x,int y){
HANDLE hConsole;
hConsole = GetStdHandle (STD_OUTPUT_HANDLE);
system("TITLE MyTitleText");
int H = land();
int X = player();
string world[dimX][dimY];
for(int c = 0;c<dimY;c++){
for(int count = 0;count<dimX;count++){
world[count][c] = H;
world[x][y] = X;
cout<<world[count][c];
}
cout<<endl;
}
}
int main(){
HANDLE hConsole;
hConsole = GetStdHandle (STD_OUTPUT_HANDLE);
worldgen(70,15,10,10);
cin.get();
}
Neither land() nor player() return anything so neither H nor X are getting any meaningful data are are just garbage data that was uninitialized.
I'm surprised this is even compiling since you have two functions that are supposed to return ints but aren't set to return anything.