Skip to content

Commit

Permalink
map drawing
Browse files Browse the repository at this point in the history
  • Loading branch information
ssloy committed Feb 10, 2019
1 parent 90b7cfb commit c6a1206
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
Binary file added doc/002.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
43 changes: 43 additions & 0 deletions tinyraycaster.cpp
Expand Up @@ -29,11 +29,43 @@ void drop_ppm_image(const std::string filename, const std::vector<uint32_t> &ima
ofs.close(); ofs.close();
} }


void draw_rectangle(std::vector<uint32_t> &img, const size_t img_w, const size_t img_h, const size_t x, const size_t y, const size_t w, const size_t h, const uint32_t color) {
assert(img.size()==img_w*img_h);
for (size_t i=0; i<w; i++) {
for (size_t j=0; j<h; j++) {
size_t cx = x+i;
size_t cy = y+j;
assert(cx<img_w && cy<img_h);
img[cx + cy*img_w] = color;
}
}
}

int main() { int main() {
const size_t win_w = 512; // image width const size_t win_w = 512; // image width
const size_t win_h = 512; // image height const size_t win_h = 512; // image height
std::vector<uint32_t> framebuffer(win_w*win_h, 255); // the image itself, initialized to white std::vector<uint32_t> framebuffer(win_w*win_h, 255); // the image itself, initialized to white


const size_t map_w = 16; // map width
const size_t map_h = 16; // map height
const char map[] = "0000222222220000"\
"1 0"\
"1 11111 0"\
"1 0 0"\
"0 0 1110000"\
"0 3 0"\
"0 10000 0"\
"0 0 11100 0"\
"0 0 0 0"\
"0 0 1 00000"\
"0 1 0"\
"2 1 0"\
"0 0 0"\
"0 0000000 0"\
"0 0"\
"0002222222200000"; // our game map
assert(sizeof(map) == map_w*map_h+1); // +1 for the null terminated string

for (size_t j = 0; j<win_h; j++) { // fill the screen with color gradients for (size_t j = 0; j<win_h; j++) { // fill the screen with color gradients
for (size_t i = 0; i<win_w; i++) { for (size_t i = 0; i<win_w; i++) {
uint8_t r = 255*j/float(win_h); // varies between 0 and 255 as j sweeps the vertical uint8_t r = 255*j/float(win_h); // varies between 0 and 255 as j sweeps the vertical
Expand All @@ -43,6 +75,17 @@ int main() {
} }
} }


const size_t rect_w = win_w/map_w;
const size_t rect_h = win_h/map_h;
for (size_t j=0; j<map_h; j++) { // draw the map
for (size_t i=0; i<map_w; i++) {
if (map[i+j*map_w]==' ') continue; // skip empty spaces
size_t rect_x = i*rect_w;
size_t rect_y = j*rect_h;
draw_rectangle(framebuffer, win_w, win_h, rect_x, rect_y, rect_w, rect_h, pack_color(0, 255, 255));
}
}

drop_ppm_image("./out.ppm", framebuffer, win_w, win_h); drop_ppm_image("./out.ppm", framebuffer, win_w, win_h);


return 0; return 0;
Expand Down

32 comments on commit c6a1206

@RazorNeko
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Подскажите пожалуйста откуда берется дополнительная строка?
assert(sizeof(map) == map_w*map_h+1); // +1 for the null terminated string

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Feb 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не строка дополнительная, а символ. Чтобы промаркировать конец строки, там стоит ещё дополнительный символ с нулевым кодом.

@RazorNeko
Copy link
Contributor

@RazorNeko RazorNeko commented on c6a1206 Feb 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Спасибо! Прочитал как map_w * (map_h + 1)
Отктыл сгенерированный файл в GIMPe цвета почему-то отличаются.

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Feb 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сильно отличаются? Можно скриншот?

@RazorNeko
Copy link
Contributor

@RazorNeko RazorNeko commented on c6a1206 Feb 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sc

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Feb 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень странно. Явно перепутан порядок каналов, вместо rgb он читает grb. Никогда такого формата не видел. Причём на этой стадии даже little endian / big endian не должен влиять... Можете мне .ppm файл скинуть напрямую? Я заинтригован. ha@haqr.eu

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Feb 12, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не получил письма, вы ответили в гитхаб-ветку.

@RazorNeko
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Переслал в лс

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Feb 12, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это прелестный файл! У меня тоже цвета неправильные. Рассказывайте, как вы его получили!!!
Я правильно понимаю, что этот файл получен при помощи кода из этого коммита как есть, без изменений? Если так, то у меня баг. Расскажите, пожалуйста, какая у вас операционная система, и какой компилятор. Хочу всё знать про машину, на которой этот файл сгенерирован.

@RazorNeko
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Код скопирован с вашего коммита без изменений. ОС Windows 10 64. Я использую Microsoft Visual Studio 2017 Community компилятор по умолчанию ничего не менял.

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Feb 12, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У меня на работе есть такой компьютер, завтра проверю. Это точно баг у меня, причём на данный момент я ума не приложу, где он может быть. Я специально старался избегать подобных ситуаций.

@RazorNeko
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Скомпилировал на Ubuntu 64 gcc на тойже машине. Получилось как задуманно.

@itsroar
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По поводу grb. Удалось ли понять в чём проблема?

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Feb 22, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kornerr
Copy link

@kornerr kornerr commented on c6a1206 Mar 7, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Правильно ли я понимаю, что нам не важно, какая именно цифра используется в map? Что 1, что 2, что 3, это всё считается за "наличие". Верно?
Если так, то зачем использовать 1, 2, 3? Есть ли какой-то смысл в этом?

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Mar 7, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, подойдёт любой символ. Но есть тонкость: я использую символы '1', '2', '3'. Они в таблице кодировки идут по порядку. Поэтому разность между двумя символами '1' - '0' = 1 (обратите внимание, что результат - не символ, а число). Того же результата можно было бы добиться, например, 'b' - 'a' = 1. Таким способом я получаю индекс используемой текстуры (число) для данной клетки карты.

@kornerr
Copy link

@kornerr kornerr commented on c6a1206 Mar 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нюанс не ясен. Нигде в коде не вижу получение разницы между '1' и '0' или прочими символами. Выходит, этот нюанс совершенно не нужен?

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Mar 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это используется в дальнейших коммитах.

@kornerr
Copy link

@kornerr kornerr commented on c6a1206 Mar 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Выходит, требоания из следующего этапа затесались в предыдущий. Печаль.

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Mar 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А в чём печаль-то? В том, что я чуть-чуть представляю, что мне может понадобиться через полчаса? Это ведь совершенно очевидно, что нам нужно будет больше одного цвета. Как ещё хранить эту информацию?

@kornerr
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Проблема в том, что описание этапа даже не намекает про хранение цвета, поэтому это совершенно неочевидно для читателя. Неочевидное вызывает вопросы, замедляет понимание.
Я вижу следующие пути разрешения этого непонимания:

  1. проигнорировать непонимание
  2. спросить автора

Оба способа приводят к потерям времени и к риску того, что материал будет понят не полностью. Для предотвращения подобных рисков, на мой взгляд, следует стараться избегать подобной рассинхронизации документации и кода.

Можно посчитать данное отношение излишеством. Уверен, большинство читателей выбрали первый вариант. Я тоже хотел пойти этим путём, но затем поймал себя на мысли, что ведь тогда не прочитаю самого главного - кода. А ведь я хочу не просто прочитать, как вы сделали игру, я хочу узнать каждую деталь, чтобы смочь сделать больше. В связи с этим я взялся прочитать ваши статьи так, чтобы понять буквально всё. Обязуюсь и впредь задавать вопросы, если вас не затрудняет на них отвечать.

@1vanK
Copy link

@1vanK 1vanK commented on c6a1206 Apr 7, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень крутой курс, спасибо огромное! (извините за оффтоп)

@frostyy9
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Assertion `sizeof (map) == map_w * map_h + 1' failed, this assertion is failing, and i haven't gotten the slightest clue on why that's happening.

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Aug 22, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have you modified the source code or are you running exactly the the code from this repository?

@frostyy9
Copy link

@frostyy9 frostyy9 commented on c6a1206 Aug 22, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ssloy yes, i'm sure the code is correct because i checked it for typos 3 times now.

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Aug 22, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Send me the cpp file by mail, i'll look into it. ha@haqr.eu

@frostyy9
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ssloy Sure, but i'll see if i can't figure it out first.

@frostyy9
Copy link

@frostyy9 frostyy9 commented on c6a1206 Aug 22, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ssloy So it turns out the the map char array is 165 bytes in size, but map_w * map_h + 1 is evaluating to 257. I sent you the file btw.

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Aug 23, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@halt27 Apparently, you have modified the map. It must be map_w tiles wide and map_h tiles long. Thus total length of the string map_w*map_h + 1, where +1 is for the null-termination of the string ('\0' character).

@frostyy9
Copy link

@frostyy9 frostyy9 commented on c6a1206 Aug 23, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ssloy I see what the problem was is very strange, since i'm setting chrome to immediately translate other languages to english, it somehow messed up the structure of the map and i ended up with the wrong structure, now it's working fine. Thanks for the help!

@Gallforn
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот такое изображение вышло..
image
.

@ssloy
Copy link
Owner Author

@ssloy ssloy commented on c6a1206 Nov 9, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Maxim-debug-msi

#9

Please sign in to comment.