Shared posts

17 Nov 12:13

How Lambdas Make Function Extraction Safer

by Jonathan Boccara

One of the most interesting talks I saw when I was at CppCon 2019 was also one of the shortest ones.

During one of the lightning talks evenings, Ezra (a.k.a. eracpp) demonstrated a technique to extract some code from a long function in a systematic way. Long functions are common in C++ legacy code, and extracting sub-functions out of them is a great way to make their code more expressive.

This technique, inspired from a tutorial of the Jai language, allows to perform refactoring of legacy C++ code in a relatively safe and stressless way.

Thanks to Ezra for reviewing this post.

Extracting a function in several steps

In short, the technique consists in the following steps:

  • surround the code you want to extract by a immediately invoked lambda,
  • use the compiler to show the outputs of this function, and add them,
  • use the compiler to show the inputs of this function, and add them,
  • copy-paste the code into a sub-function.

To illustrate those steps, let’s see an example of code that needs function extraction:

void aggregateAndDisplay(std::map<int, std::string> const& source, std::map<int, std::string> const& destination)
{
    auto aggregatedMap = destination;
    for (auto const& sourceEntry : source)
    {
        auto destinationPosition = aggregatedMap.find(sourceEntry.first);
        if (destinationPosition == aggregatedMap.end())
        {
            aggregatedMap.insert(std::make_pair(sourceEntry.first, sourceEntry.second));
        }
        else
        {
            aggregatedMap[sourceEntry.first] = sourceEntry.second + " or " + destinationPosition->second;
        }
    }

    for (auto const& entry : aggregatedMap)
    {
        std::cout << "Available translations for " << entry.first << ": "
                  << entry.second << '\n';
    }
}

As its name suggests, this function does two things: aggregating data into a map, and displaying the aggregated data.

With the following calling code:

auto const source = std::map<int, std::string>{{1, "one"}, {2, "two"}, {3, "three"}};
auto const destination = std::map<int, std::string>{{2, "dos"}, {3, "tres"}, {4, "quatro"}};
aggregateAndDisplay(source, destination);

The program outputs this:

Available translations for 1: one
Available translations for 2: two or dos
Available translations for 3: three or tres
Available translations for 4: quatro

The code begs for function extraction (and for other design improvements as well, but which we won’t focus on here): one sub-function that performs the aggregation, and another one that performs the display.

This function is adapted to illustrate the technique, because its structure is apparent. In legacy C++ code, the structure may be less apparent. Identifying the relevant blocks to extract is out of the scope of this technique, but I’d love to know how you go about that. We’ll go back to that at the end of the post.

Assuming we identified those blocks, let’s extract them into sub-functions.

Surrounding the code to extract

As a first step, let’s start by surround the code to extract with an immediately invoked lambda expression:

void aggregateAndDisplay(std::map<int, std::string> const& source, std::map<int, std::string> const& destination)
{
    [&]
    {
        auto aggregatedMap = destination;
        for (auto const& sourceEntry : source)
        {
            auto destinationPosition = aggregatedMap.find(sourceEntry.first);
            if (destinationPosition == aggregatedMap.end())
            {
                aggregatedMap.insert(std::make_pair(sourceEntry.first, sourceEntry.second));
            }
            else
            {
                aggregatedMap[sourceEntry.first] = sourceEntry.second + " or " + destinationPosition->second;
            }
        }
    }();

    for (auto const& entry : aggregatedMap)
    {
        std::cout << "Available translations for " << entry.first << ": "
                  << entry.second << '\n';
    }
}

The lambda captures everything by reference, and is invoked on the same statement as its creation. This means that the code of the lambda is immediately executed. And thanks to the capture by reference, it can affect the objects inside the function just like the initial code did.

Finding out the outputs

But introducing the lambda generates an error for the values that are created by the code to extract and used later on in the function:

<source>: In function 'void aggregateAndDisplay(const std::map<int, std::__cxx11::basic_string<char> >&, const std::map<int, std::__cxx11::basic_string<char> >&)':
<source>:29:30: error: 'aggregatedMap' was not declared in this scope
   29 |     for (auto const& entry : aggregatedMap)
      |                              ^~~~~~~~~~~~~

Those values are the “outputs” of the code to extract.

To make the code compile and run again, we can make the lambda return those outputs for the rest of the function to use them:

void aggregateAndDisplay(std::map<int, std::string> const& source, std::map<int, std::string> const& destination)
{
    auto const aggregatedMap = [&]() -> std::map<int, std::string>
    {
        auto aggregatedMap = destination;
        for (auto const& sourceEntry : source)
        {
            auto destinationPosition = aggregatedMap.find(sourceEntry.first);
            if (destinationPosition == aggregatedMap.end())
            {
                aggregatedMap.insert(std::make_pair(sourceEntry.first, sourceEntry.second));
            }
            else
            {
                aggregatedMap[sourceEntry.first] = sourceEntry.second + " or " + destinationPosition->second;
            }
        }
        return aggregatedMap;
    }();

    for (auto const& entry : aggregatedMap)
    {
        std::cout << "Available translations for " << entry.first << ": "
                  << entry.second << '\n';
    }
}

Now the code compiles and the output of the program remains the same as before:

Available translations for 1: one
Available translations for 2: two or dos
Available translations for 3: three or tres
Available translations for 4: quatro

Note the nice side effect: aggregate is now a const value, since all the modifications needed for its filling are done inside the lambda.

Finding out the inputs

Let’s now use the compiler again to find the inputs of the code we want to extract.

Those inputs are the values that are captured by the lambda. Removing the capture makes them appear in compile errors:

void aggregateAndDisplay(std::map<int, std::string> const& source, std::map<int, std::string> const& destination)
{
    auto const aggregatedMap = []() -> std::map<int, std::string>
    {
        auto aggregatedMap = destination;
        for (auto const& sourceEntry : source)
        {
            auto destinationPosition = aggregatedMap.find(sourceEntry.first);
            if (destinationPosition == aggregatedMap.end())
            {
                aggregatedMap.insert(std::make_pair(sourceEntry.first, sourceEntry.second));
            }
            else
            {
                aggregatedMap[sourceEntry.first] = sourceEntry.second + " or " + destinationPosition->second;
            }
        }
        return aggregatedMap;
    }();

    for (auto const& entry : aggregatedMap)
    {
        std::cout << "Available translations for " << entry.first << ": "
                  << entry.second << '\n';
    }
}

Here are the compile errors:

<source>: In lambda function:
<source>:14:30: error: 'destination' is not captured
   14 |         auto aggregatedMap = destination;
      |                              ^~~~~~~~~~~
<source>:12:33: note: the lambda has no capture-default
   12 |     auto const aggregatedMap = []() -> std::map<int, std::string>
      |                                 ^
<source>:10:102: note: 'const std::map<int, std::__cxx11::basic_string<char> >& destination' declared here
   10 | void aggregateAndDisplay(std::map<int, std::string> const& source, std::map<int, std::string> const& destination)
      |                                                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~
<source>:15:40: error: 'source' is not captured
   15 |         for (auto const& sourceEntry : source)
      |                                        ^~~~~~
<source>:12:33: note: the lambda has no capture-default
   12 |     auto const aggregatedMap = []() -> std::map<int, std::string>

Our inputs are therefore source and destination. Let’s add them as inputs of the lambda:

void aggregateAndDisplay(std::map<int, std::string> const& source, std::map<int, std::string> const& destination)
{
    auto const aggregatedMap = [](std::map<int, std::string> const& source, std::map<int, std::string> const& destination) -> std::map<int, std::string>
    {
        auto aggregatedMap = destination;
        for (auto const& sourceEntry : source)
        {
            auto destinationPosition = aggregatedMap.find(sourceEntry.first);
            if (destinationPosition == aggregatedMap.end())
            {
                aggregatedMap.insert(std::make_pair(sourceEntry.first, sourceEntry.second));
            }
            else
            {
                aggregatedMap[sourceEntry.first] = sourceEntry.second + " or " + destinationPosition->second;
            }
        }
        return aggregatedMap;
    }(source, destination);

    for (auto const& entry : aggregatedMap)
    {
        std::cout << "Available translations for " << entry.first << ": "
                  << entry.second << '\n';
    }
}

The code now compiles and runs again.

Copy-paste the code into a sub-function

The code is now ready to be extract in a single swoop. Indeed, the lambda is already a function within our function. We only need to take it out of the function, remove the [], add an auto and give it a name:

auto aggregate(std::map<int, std::string> const& source, std::map<int, std::string> const& destination) -> std::map<int, std::string>
{
    auto aggregatedMap = destination;
    for (auto const& sourceEntry : source)
    {
        auto destinationPosition = aggregatedMap.find(sourceEntry.first);
        if (destinationPosition == aggregatedMap.end())
        {
            aggregatedMap.insert(std::make_pair(sourceEntry.first, sourceEntry.second));
        }
        else
        {
            aggregatedMap[sourceEntry.first] = sourceEntry.second + " or " + destinationPosition->second;
        }
    }
    return aggregatedMap;
}

void aggregateAndDisplay(std::map<int, std::string> const& source, std::map<int, std::string> const& destination)
{
    auto const aggregatedMap = aggregate(source, destination);

    for (auto const& entry : aggregatedMap)
    {
        std::cout << "Available translations for " << entry.first << ": "
                  << entry.second << '\n';
    }
}

A recipe means less stress

What I find very nice in this technique presented by Ezra is that, no matter the complexity of the code to extract, the refactoring is broken down in a couple of simple steps that compile, runs and pass the tests (which we didn’t see here).

Those steps can become a mechanic way to change code, that ensures we don’t miss any input or outputs of the code to extract. I find that this makes refactoring fun (or even more fun if, like me, you enjoy refactoring as an activity).

That said, there is another important step that occurs before all this extraction: identifying the scope of the code to extract. We didn’t touch on this in this article.

How do you proceed when you extract code from a long function? How do you decide what to extract in a sub-function? Please leave your answers in a comment below, I’d love to read them.

You will also like

Share this post!FacebooktwitterlinkedinDon't want to miss out ? Follow: &nbsp&nbsptwitterlinkedinrss

The post How Lambdas Make Function Extraction Safer appeared first on Fluent C++.

22 Nov 21:32

Слово о репостмодернизме

glyph

ИУИ вернулся!

В последние годы Истинному Учителю Истины (то есть мне) Друзья и посетители всё чаще жалуются на странное чувство, будто "истины вокруг всё меньше, а какой-то фигни всё больше".

Я тряхнул стариной, провёл расследование и обнаружил, что уважаемые современники, как обычно, правы. В их мир действительно с наглостью биодобавки вмешивается вредоносное явление, которое проф. Инъязов назвал "репостмодернизмом".

Явление это относительно новое, но оно приняло уже столь угрожающие масштабы, что настала пора рассказать о нём публично.

Если коротко - речь идёт о новом, почти совершенном способе распространения лжи - лжи, уже не нуждающейся ни в чьём доверии.

Эту мысль необходимо пояснить.

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

В далёкие времена эта большая ложь нуждалась в постоянных носителях, потому что её (как и вообще любой информации) было немного, а распространение стоило времени и денег. Чтобы выжить, ложь нуждалась в подписчиках, прихожанах и фанатах. Она оккупировала мозг носителя, как умела баррикадировалась изнутри и время от времени пришпоривала его, направляя в гущу ничего не подозревающих современников проповедовать.

Самые оголтелые носители вранья искренне считали его правдой. Защищали в спорах и несли его факел. Они указывали тёмным скептикам, что раз этой лжи написаны многие тома и тысячи людей её благодарно читают - значит, она на самом деле правда, ведь не могут же ошибаться столь многие. Нередко собеседник, жаждавший убедить вас, что вы идиот и ничего не понимаете в жизни, даже умолял вас помочь в этом непростом деле. "Вы прочли бы основные шесть томов учения Рыбальцева, прежде чем называть глупостью его утверждение о происхождении всех языков от русского! - канючили такие собеседники. - Вы же совсем не помогаете мне давить вас интеллектом. Хорошо, давайте так договоримся - ваш отказ от чтения шести томов Рыбальцева я буду засчитывать как слив, а?"

Сейчас всё это в прошлом, ибо пришло время репостмодерна.

...Новый способ вирусного распространения лжи, о котором пойдёт речь - мог возникнуть, разумеется, только в наше перенасыщенное буквами, звуками и картинками время...

18 Oct 22:48

The Listening Leader

by Bobby

listeningleadimagesmall-1
Essay by Bobby White
Edited by Chelsea Lee
Illustrations by Courtney Sieh

 
 

Ultimately, aren’t we all just looking for the most fulfilling dance?

And in a true partnership dance, fulfilling dancing is about other skills in addition to having good lead/follow technique and knowing moves and variations. These other skills are not often touched upon in classes.

One of the most important leading skills that isn’t emphasized much in the classroom, for instance, is listening. In fact, we would argue it’s one of the most important partnership dancing skills there is.

Here’s what we mean. The best swing dance leaders…

Listen to the music

Seems obvious, but you’d be surprised.

Part of the secret of being a musical dancer (leader or follower) is waiting for the music to tell you what to do. First the rhythm and feel of a song will start to lead the way. Then, a good melody and solo will give even more direction.

To improve at listening to the music you can take musicality classes, or even just watch Ken Burns’s documentary Jazz , but we recommend first and foremost simply listening and re-listening to great early jazz and swing music, which should give you a great subconscious education. You can hear this music at your local dances, at dance events, or even online on Spotify or Pandora.

dancerpianosmall
Many leaders don’t realize that the music hugely helps with the accuracy of their leading (assuming the leader is doing something to the music). Because the follower and leader are listening to the same music, when the leader dances to the music, the music reinforces every movement the leader hopes to translate to the follower (and vice versa). So when you want both you and your partner to pitter-patter with your feet and then jump when the song goes “Ba-da-da-da-da-da-da—BOOM!”, it’s more likely to happen than if you led the pitter-patter-jump outside the context of the music.

Many leaders spend a great deal of their time and attention on this single aspect of listening. However, listening to the music is only a fraction of the listening great leaders do.

Listen to the follower’s variations

Now let’s get to what is really at the heart of a leader’s listening: listening to the follower. One of the most common, obvious ways followers add their voice to the partnership conversation is through variations and solo dance expression. A good leader can “listen” to this first by watching the follower and what they do in the dance. Again, might seem obvious, but, again, you’d be surprised.

When a follower does a variation, a leader can allow it to inspire them in several different ways:

• The leader can then do something that the move inspired. A follower does a swoopy leg thing; the leader can then do a swoopy leg thing.

• The leader, in the moment, can try to complement the variation. A follower does a swoopy thing; the leader “complements” by holding their own shape to draw more attention to the follower’s swoopy movement.

• The leader, in the moment, can alter the movement of the dance to play with the variation. A follower does a leg swoopy thing; the leader balances the follower and continues the momentum so they swoopy around longer than they originally would have.

And, this incredibly simple response must be mentioned: The leader can vocally say something to show that they have noticed a particularly awesome follower contribution: “Yeah!” “Nice!” “Hell Yeah!”

Now then. A very specific way leaders can help followers express their variations is by listening to their balance. Leaders, you may or may not realize that followers often have to help us with the final 20% or so of our moves. We meant for our partner to do an outside turn after our fancy hand switch behind the back, but maybe we only led 80% of that, cause, well, that happens sometimes. Followers often help out by doing the final 20% and making sure the outside turn happens in the correct timing. We can return the favor by helping followers with their balance — let’s say they decide to take a risk and try out a variation, but only stay 80% on balance; if we’re listening, we can spot that and help with the other 20% of that balance.

A leader who takes inspiration from a follower’s variations gives the follower the power to shape the direction of the dance.

Listen to the follower’s general movement and personality

personality-followers-small-1

Though listening to a follower’s variations is very good, it’s only the tip of the listening iceberg. The foundation of a follower’s voice and expression comes from the general way they move and their demeanor as they move. Is their movement bouncy, smooth, grooving, elegant, or something else? What personality do they show in that movement — are they serious, silly, joyful, excited, something else?

Look back at the original dancers, and you’ll see that many of the followers we know and love — such as Jewel McGowan, Irene Thomas, Ann Johnson, and Jean Veloz — had their own quality of movement and demeanor and didn’t change those things dramatically no matter what leader they were dancing with. They always moved like themselves. (Among the SoCal followers, it’s almost as if they had a meeting: “Okay, it’s decided then; Jewel calls elegant, Jean gets cute, and Irene chooses sassy.”)

Modern followers are used to adapting their movement quality to suit their partner and the partnership — but a great leader meets them halfway, so that they can help support the follower’s voice as much as the follower tries to help support the leader’s. In this case, listening means paying attention to the follower’s movement quality and making choices that show off that movement quality and personality.

Listen to the follower’s mechanics

There are many different theories of dance mechanics that dancers dance by, and every one of those has as many subtle variations as there are dancers. Great leaders listen to their follower’s mechanics, like how they create stretch and compression, what things shine with their mechanics (do those more often), and what things their mechanics do not respond as well to (don’t do those as often). Great leaders listen to the follower’s “frame” — how their arms are related to their bodies. Are their arms super relaxed, or do they hold a certain amount of tension on purpose? How do their frames react to rotational forces versus linear forces versus the combination of the two?

Again, leaders don’t have to change completely for their followers, but a follower’s mechanics are a very large part of their dancing personality, and leaders should let that guide them in their leading choices, rather than expecting the follower to change completely to their specific leading mechanics.

Listen to the follower’s momentum

One of the quickest paths to good leading is being aware of your partner’s momentum—because it doesn’t always do what you expect it to. Sometimes this is because the leading or following was off, and sometimes this is intentional.

Leading/following doesn’t always work perfectly (nor is that necessarily the point), especially if both partners are playing a lot and taking risks. A leader who pays attention to the follower’s momentum on count [2] will be able to predict where the follower will be by count [6], and if this is not as expected, they will be able to begin adapting to the new momentum (which usually just involves moving themselves into the proper position to continue the dance with as much flow as possible).

Followers (advanced ones especially) often play with momentum on purpose — they might slow down momentum for one part of music or speed it up for another (or do one right after the other if they want to cancel out their momentum changes). The point is, a leader listening to these momentum changes can help keep the dance successful, and take the dance to new places because of the inspiration it gives.

For example, sometimes a follower will change momentum so much they will need their leader for physical support. Perhaps they will sit away from the leader to strike a dramatic pose, and if the leader is listening to the follower’s body movement and momentum, they will be able to give them the support they require.

Listen to the follower’s physical comfort

dancerdipsmall-1
By listening to the connection you have with your partner, you can begin to tell when you’re putting your partner in a physically uncomfortable position. Take for instance, a Texas Tommy: The leader puts the follower’s arm behind the follower’s back in order for the leader to grab it from the other side. There are many opportunities for discomfort when it comes to putting someone’s arm behind their back, because the joints of the arm only work smoothly in certain ways.

If every moment of the Texas Tommy goes smoothly, it should feel pretty comfortable. However, if part of it goes un-smoothly—let’s say, the follower’s arm gets tighter rather than remains loose as the leader starts maneuvering it behind the follower’s back, or the arm doesn’t go on the path the leader expects—then these are signs that continuing to use force will cause discomfort. At that point, it’s better to let the arm go and make something different out of the move than to try to force the Texas Tommy.

There’s also a visual aspect to this: Often, you can visually deduce that what you’re doing is physically comfortable or uncomfortable to your follower. A dancer’s arm being forced behind them uncomfortably looks like it’s uncomfortable.

By paying attention to the smoothness of the physical connection and the visual feedback, leaders will realize when their strong leads actually “shove” or “yank” the followers and can make changes in the future.

Listen to the follower’s psychological comfort

It’s important to know that leading and following is a constant agreement.

It is not a given that a follower will follow everything the leader will do just by simply accepting a dance; instead, every single time a leader leads anything in a dance, the follower is agreeing to do it or not.

The first step in listening to follower’s psychological comfort is to not take this for granted.

In general, followers have a fun enough time dancing that they will happily try most of the stuff a leader does, and, because of the nature of modern society, etiquette, and numerous cultural and psychological factors, it’s rare that followers will vocally say when they find a lead psychologically uncomfortable. So, great leaders must spend a lot of time listening to body language.

Body language will seem subtle at first, but once you start to recognize it, it will talk pretty loudly. Imagine the people in your life who are comfortable with hugging versus those who aren’t:

Those who are comfortable with hugging are quick to join in a hug or offer one. When they do hug, they seem to relax into the hug, perhaps even rub the back; they tend to linger in hugs for the amount of a deep breath. They may literally smile or have a pleased look on their face before or after.

Those who aren’t comfortable with hugging may have tension in their body when they hug and may not give back as much “hug” as the initiator. They rarely initiate hugs; they may even hold their breath during hugs or have a slightly anxious look in their eyes before or after.

It’s the same with dance moves. When doing them, pay attention to how much your partner “goes” with the idea.

If you start taking them into a dip, and they gladly give their weight, you can assume permission is given. If, however, they stiffen up, even slightly, and perhaps have an anxious look on their face, great leaders stop leading the dip and lead something more psychologically comfortable.

With all of this said, followers should speak up vocally and not only rely on body language if they feel psychological or physical discomfort. “Please don’t dip me.” “Please give me a little more space.” “Please don’t ______.”

Sadly, I think there is a common and unspoken problem in the world which we will call “convince by force.” I have seen “loving” people who love hugs, for instance, hug someone who clearly doesn’t like hugs, as if to convince them that hugs are great by forcing hugs upon them.

It’s a particularly easy trait for leaders to pick up, who are so used to having followers follow their lead. Their partner seems to not like dips — well, no problem, I will convince them that my dips are strong and fun and nothing to worry about by putting them into them. Leaders, please don’t argue with the follower or try to convince them by force. If a follower says “please don’t dip me” — whether out loud or just through body language — a leader who respects their partner and themselves chooses a different move.

Swungover editor Chelsea Lee has found a particularly subtle place where some leaders feel justified in going against their follower’s wishes: What if you don’t like close embrace, but still want to dance Bal-Swing or Blues, dances that commonly involve close embrace? She writes, “In my experience, people who don’t like close embrace often get their feelings dismissed on the grounds that close embrace is an integral part of these dances, as though that is supposed to override personal comfort.”

So, leaders, always prioritize your partner’s comfort, assuming you want to continue to have partners. If someone doesn’t like to hug, perhaps try a smile and wave. Likewise, if you want to dance Bal or Blues with someone who is less comfortable in close embrace, dance these dances using more open-position movements.

And, of course, reading the follower’s body language has a positive side: When followers really enjoy something, their body language can show it, which means the leaders could do more of that kind of thing, tailoring their dance to their follower’s happiness.

Learning how to listen takes time. These skills are not built in a practice, but over many years.

But once you learn to listen, you’ll be amazed at the wonderful things you can hear.

(Cough) Check out PRACTICE SWING!

The information in this article is a tiny fraction of some of the ideas found in Practice Swing: The Swungover* Choose-Your-Own-Adventure Guide to Improving Your Dancing. The book works like this: There are tons of ways great dancers have gotten great, based on their personality types and learning styles; the book explores a wide variety of paths, drills, and practicing principles dancers can choose to get to the next level of their dancing, and far beyond. It also gives several examples of exercises that will hone a partnership’s dance floor communication ability.

Also, readers of this article may enjoy: The Proactive Follower post.

ABOUT THE ARTIST: COURTNEY SIEH

maggiemillerphotoSwungover* is thrilled to highlight the art of illustrator (and dancer) Courtney Sieh in this article.

Courtney is a fresh out of the box illustrator and comic artist freelancing and dancing in Cleveland, OH. She graduated with a BFA from the Cleveland Institute of Art in 2016 and is a proud alumni of the Case Western Reserve University Swing Club. Nothing makes her happier than a good social dance unless it is a properly dark and depressing story. She also enjoys teaching both Lindy Hop and art when she has the opportunity.

Her hopes are to finish her graphic novel before she turns 30 and to one day get enough sleep. Follow her work on Facebook and @c.sieh.illustrator on Instagram, and contact her at cmariahsieh@gmail.com for prints and commission inquiries. She is always happy to brand and make promotional art for swing workshops.


07 Sep 08:04

Достойна ли Half-Life 2 своего предшественника?

Гордон Фримен на медведе

А если мы расскажем вам, что Гордон Фримен вовсе не главный герой в Half-Life 2? Что если настоящий главный герой мёртв и именно поэтому мы никогда не увидим новую игру из вселенной Half‑Life?

Именно так считает Док Барфорд - редактор игрового сайта Stomp, внештатный автор в Kotaku и PC Gamer. Док получил высшее образование по профессии игрового дизайнера и периодически пишет статьи, в которых детально разбирает благодаря чему нам нравятся те или иные видеоигры. Или как говорит он сам - "я раскрываю трюки магов".

В статье "Почему Half-Life 2 никогда не будет достойна своего предшественника", опубликованной на Kotaku, Док рассуждает о разнице между первым и вторым Half-Life с точки зрения развития главного действующего лица - Гордона Фримена и выводит теорию, по которой в конце концов игра осталась без сюжетного двигателя и вряд ли сможет двигаться дальше.

Для затравки цитата без спойлеров:
По мере прохождения Half‑Life люди возлагают на вас всё больше и больше ответственности. Отправься на помощь туда! Убей гигантского монстра здесь! Найди учёных в Комплексе Лямбда! В конце концов, неодобрительные фразы персонала вроде: "Ах, Гордон", сменяются на: "Гордон, мы пристально следили за тобой через мониторы, мы верили в тебя".

Гораздо интереснее то, каким образом вы этого добились. Фримен на ваших глазах из какого-то неприметного парня превратился в неуязвимого живчика и местного супергероя. И всё это благодаря именно вашей деятельности! Такое постепенное развитие образа Гордона - важная сторона привлекательности Half‑Life. Ваше путешествие становится не столько "географическим", сколько - "эмоциональным".
Читайте, а после обязательно поделитесь своим мнением в комментариях.
29 Aug 03:23

Acceleration Structures

by Nicholas

Clockwork Empires relies internally on a series of tags, as I think we’ve discussed on this blog far too many times. When you go to look for something like food, we check the game for every object with the “raw_food” tag, and then you go to eat it. Here is where the bad news happens: once you have a sufficiently long game, you can stockpile large quantities of food. Let us say that a player has 500 pieces of raw food. Let us also say you have 150 characters – so, to put it into perspective, the player has accumulated 3 days worth of food. (This isn’t even that large a number.) Every day, the 150 characters must go and eat 150 pieces of food out of the 500. The problem is – they want to eat the *closest* food. So now we have to check 500 pieces of food vs 150 players to see which piece is the closest, for a total of 150 * 500 = 75,000 distance queries. Well, that can be a bit slow, especially when our AI budget is very tight and we have a lot to do. However, we’re now seeing games where characters have huge amounts of food – 5,000 pieces of food, say – and the game slows to a crawl. Clearly, smarter programming is required.

A lovely sea-side desert colony sent in by a player as part of a bug report.

A lovely sea-side desert colony sent in by a player as part of a bug report.

Clockwork Empires stores all information about object positions in a spatial dictionary. The handling of tags is done by a “tag index” class, which is essentially a giant array of information consisting of the following attributes: “position, object, previous item with this tag, next item with this tag”. When a tag is set, we grab a tag index from a giant statically allocated pool of tag indices, so that we don’t have a memory allocation, and attach it to the linked list of tags. The problem is… there’s no way to easily find the “closest” tag to your point. What is needed is a spatial acceleration structure of some kind – a way of dividing the world into regions so that we can start in our region, check it for the closest whatever, and then move on.

The solution I came up with after some hacking is very similar to what we already do for raycasting to pick items for selection in-game: an object grid. The world map (256×256) is divided into cells (currently 16×16), and we keep a list of what tags are in each cell as part of the same tag index. A tag can only be in one cell by definition, so we can use the same data structure and make the cell logic part of the existing tag registration/deregistration process. When doing a distance query, we check our cell first for tags – and then we find the closest one in that cell, and we’re good, right? Wrong. You can have this behaviour:

cell_structure

In this lovingly rendered piece of programmer art, the yellow sphere is the player, and the red spheres are two food items. You can have a case where the closest object is in a neighbouring cell, which means we need to find it. So the obvious solution is to check the neighbouring cells. The problem is now that you need some sort of way to stop the algorithm – when do you decide not to check a neighbouring cell? Well, you shouldn’t check a neighbouring cell if you *know* that it’s going to be further away than your most recently seen best object – a problem which is equivalent to asking “what is the closest point in the cell to the current location”? We need to find this quickly, which… well, that seems like math.

Fortunately, cells are axis-aligned bounding boxes. Here is some more hastily drawn programmer art:

cell_structure_2

We can see that the area around a cell is divided into eight sub-regions. In the upper left subregion, any point up here is closest to the top left corner of the cell. In the upper right subregion, any point is closest to the top right corner of the cell, et cetera. So all we need to do to find the closest point on an axis-aligned bounding box to a given point is to check, for each of the x and y components, whether it is to the left of, to the right of, or in the space defined by the axis-aligned bounding box; this means that we can find the closest point in a neighbouring cell with something like four if statements. We then only check those cells that *might* have an object closer to the player than our current cells, and everything else is a recursive algorithm.

This is a pretty good example of a good technical interview question for an entry level AI programmer, now that I think about it. Anyhow, people should be able to have better performance on larger colonies now.

"We are pleased also very hungry."

“We are pleased also very hungry.”

11 Aug 08:43

A Simple Pint At The Pub

by dbaumgart
glyph

правильный способ вести блог про разработку игры

This post was originally going to be about Occult Inspectors but if we gave anything away that’d ruin the fun, wouldn’t it. So why not come down to the pub for a pint? By which I mean, we’ve been doing some iteration of the Public House (and related buildings, and games systems) and, while the trajectory we’ve set upon ourselves here is not yet finished, some interesting bits of design have come up on the path thus far traveled. By which I mean I’ll ramble about random stuff vaguely related to implementing Pub features which may or may not change.

Let’s start with the UI for the Pub, because this has implications through the entire game:

the_pub

First, from the bottom, we see the usual building hipoints, the quality level, and an upkeep display. (Not, mind you, updated to reflect the removal of basic chair upkeep in 53A.) This was added to all buildings in 53A and provides information on exactly how much upkeep is required and when it will be needed.

Let’see, the top is the normal zoom-to, building title, workcrew assignment, and demolish button. Nothing new there. Below that, the workcrew shift widget.

Okay, the main Pub window contents:  At the top, in red, a series of warning can appear telling you why your Pub is not doing what you expect. This was a very old UI idea we’ve had in mind for a while but never quite implemented until Daniel added the ability for empty strings, “”, to take zero space in the UI layout. This means that we can effectively add and remove text without leaving an awkward blank spot in the UI when the text is blank. (This is, for instance, how we were able to implement the amenity TODO list in houses to show what you needed to do upgrades and what upgrades you had already accomplished.) So a subtle tweak of how the UI system handled a certain case let us start adding a lot of helpful information for relatively little effort.

A pub under-construction with a longer list of demands.

A pub under-construction with a longer list of demands.

Then there’s booze selection – the details of which are open to change, mind you. Previously, the Pub would only serve brewed booze and it would always turn into a beer mug when being drunk by a colonist. Now you can select what level of booze you wish to serve with correspondingly greater effect as you move up in potency, and the booze loaded in to the Pub will look the same when coming out. So, for instance, if you load in 3 bottles of whisky and 1 bottle of vodka, that’s what colonists will pull out and drink.

(I also added “drink tea” as a default behaviour for when the Pub is out of booze, with a very minor positive mood effect. The point has been raised that this is confusing due to Tea being a valid agricultural crop in the game. There’s also a consideration for giving Laudanum a more specific and explicit pseudo-medicinal / despair-reduction role. We’ll see how this all pans out. Will note here that “tea” can be made of many things.)

Oh, the other thing: Colonists are now able to self-serve their booze. Coordinating actions between characters is always complex and it’s easy to frustratingly overwhelm the capacity of the Pub workcrew with demand spikes. And while it is possible and even fascinating to write a system wherein Pub workcrews may prioritize stocking jobs vs. serving jobs based on anticipated demand per workshift, I think our development priorities are best served elsewhere. See also: “bruising the fat”.

lively_pub2

What else? Oh, having a drink at the Pub positively affects a colonist’s Quality of Life because it is considered a Proper and Civilized act (blog post on the concept of QoL here). There’s also a whole discussion there about how to better express the conditions which affect the QoL system which we ought not get into just yet, but will be pretty great. You can even see the start of this particular imperative in the new colonist tooltips.

There’s a bit more we have in mind for the Public House, but this should give you an idea of how a few simple enhancements both draws on and affects many other systems working within the game. The Chapel, the other “make people happier” building, will also get some upgrades along these lines to become a bit easier, more expressive, and more interesting.

Can you tell me what kind of tree this is?

Can you tell me what kind of tree this is?

04 Aug 14:14

Цитата #440564

Хабр, обсуждение топа языков программирования:

xxx: Языки не взаимозаменяемы. Они как инструменты. Как бы популярен ни был гаечный ключ, он никогда не сможет заменить отвёртку. Как можно планировать личное будущее, отталкиваясь от популярности инструмента, которая вообще ничего не значит? Вот потребуется тебе через пару лет закрутить шуруп, а ты уже похоронил отвёртку и два года изучал приёмы работы с гаечным ключом, который все эти два года был фантастически популярен и не покидал чартов. Как эта его популярность поможет закрутить шуруп?

yyy: Вы не умеете закручивать шурупы гаечным ключём? И вы называете себя программистом?
04 Aug 14:13

Of Hidden Things

by Daniel
glyph

как правильно вести блог про разработку игры

My quest for the last several months to improve the visibility of information that players care about through our UI has been a really interesting process. There’s a lot going on under the hood of Clockwork Empires, and we simply didn’t have the tools to show it to you before. But our UI has been getting steadily better at presenting data (and I’ve become less and less terrible at UI design) so I keep getting cool opportunities to show you what you actually want to see when you’re looking at various parts of the game.

At this point I think there’s only one system that we haven’t shown at all but is pretty central to the way the game functions, and we actually had to avoid taking advantage of it because if we couldn’t show it to you, it got confusing. But now we can! And this system is tags.

Tags!

Every object in the game has a set of tags (attributes, if you will) that are generated when we first create an item, and can change over time as an object interacts with the world. Tags such as “timber” or “food” are straightforward examples.

2016-8-3

The common log. Flammable, timber, what more could anyone ask for in a log? Perhaps for a message, but only if you’re ready to listen.

These tags are what are searched for in order for a character to use something. For example to eat, characters will search for an object with the “food” tag. Similarly the fire system uses these tags to spread cheerful conflagration. Objects are given ignition points via tags, when they ignite they all burn with the same temperature (sorry), and they use a cellular automata-like model for spreading.

2016-8-3-2

Okay, I mean, I guess bread is pretty flammable.

To give an example of why this is awesome: Displaying tags allows players to draw a direct link between previous vague requirements for certain types of food and the actual ingredients which can fulfill these requirements. “Farmer’s Stew” requires two “raw vegetables”, but what does that mean? Is Maize a vegetable? Is the Flesh Cube a vegetable? Now you have what you need to know.

Even better, once you actually cook the Farmer’s Stew, you will see a tag on it that shows that this a food that will make middle-class Overseers content if they eat it unlike, say, Cabbage Stew which is fit only for satisfying lower-class Labourers.

What lovely stew made from raw_fungus!

What lovely stew made from raw_fungus!

Better access to information gives the player what they need to make good decisions in managing their colony. There are a bunch of similar situations where the simulation was using data that was just sitting in the tags but because we had no method of displaying the tags, we weren’t able to make the systems have much impact on the game – and have the game feel fair. Now that we CAN show them, though, we get to do some fun stuff 🙂

(We can’t, of course, just tell you about fun stuff. You’ll have to find it for yourself. )

03 Aug 20:37

Household Tips

To make your shoes feel more comfortable, smell better, and last longer, try taking them off before you shower.
02 Aug 09:42

Why You’re Stagnating

by Rebecca Brightly

The first in my Lindy Hop According to Bruce Lee series. Read the second post.

To fit in with an opponent one needs direct perception. There is no direct perception where there is resistance, a “this is the only way” attitude.

Having totality means being capable of following “what is,” because “what is” is constantly moving and changing. If one is anchored to a particular view, one will not be able to follow the swift movements of “what is.”Brue Lee


bruce lee statue by jonrawlinson flickr
I found this quote on page 18 of Bruce Lee’s book, Tao of Jeet Kune Do, which I’ve been perusing lately for inspiration. I relish getting inspiration from unexpected sources. This particular source deserves deeper examination.

Before I delve into answering, “What the hell is Bruce Lee talking about, and what does it have to do with lindy hop?” let me share one more:

A so-called martial artist is the result of three thousand years of propaganda and conditioning.

Why do individuals depend on thousands of years of propaganda? They may preach “softness” as the ideal to “firmness,” but when “what is” hits, what happens? Ideals, principles, the “what should be” leads to hypocrisy.

(From page 22.)

Lindy hop is also mired in “propaganda,” so to speak.

We bring in ideals from outside lindy hop. We absorb ideals from videos, new and old. We take on the ideals our role models demonstrate and teach.

And for some, the way we perceive lindy hop history gives us the strongest ideals of all.

Lindy hop has been around for over 80 years. It has graduated from adolescence and moved into early maturity. The dance changes much more slowly now. While there is strength in maturity, the risk is stagnation. As lindy hop continues its march toward uniformity, that risk becomes more palpable.

The risk of stagnation appears as your own dancing matures, also. Are you stuck on an endless plateau? Lucky for us, Bruce has some excellent advice.

Accurately Perceive Your Partner (And Yourself)

To mesh with your partner, you need accurate perception.

There’s no chance of accurate perception when you’ve got a preconceived notion of what you or your partner should be or should do, a “this is the only way” attitude.

Follow reality in social dancing. Reality is constantly moving and constantly changing. If you are attached to a particular ideal, you will not be able to follow what you and your partner are actually doing in the moment.

If you are attached to “shoulds” and ideals, your dancing will stagnate, and your mind will be unhappy.

Do Not Be Attached to Your Ideals

Bruce rhetorically asks, “Why do individuals…depend on propaganda?” Why do we lean so hard on the “shoulds?” When reality conflicts with our ideals, reality shoves our ideals right out of the way. Bruce seems to argue that clinging to ideals sets you up for failure.

You don’t need to be a Zen Buddhist to see the value in perceiving reality as accurately as possible.

Didn’t see that person swinging out in your direction? Your loss.

Thought your partner was moving more slowly than they actually were? Your loss.

Oh, and how about this: Thought you had that dance move down, but when you watch yourself on video you look like shit? Your loss.

Unfortunately, accurately perceiving reality is much harder than you might think. Instead of labeling our perceptions as black-and-white, accurate or inaccurate, let’s agree that our perceptions can either be “more accurate” or “less accurate.”

Which of these thoughts do you think are more accurate (closer to reality), and which are less accurate (more idealistic)?

  • I will get bumped and kicked on the dance floor.
  • That person sucks at dancing.
  • The best dancers win the competitions.
  • Some nights I dance well, and other nights I don’t.
  • If you’re not having fun, you’re doing it wrong.
  • The lead leads, and the follow follows.
  • That move didn’t work the way I expected.

Realities of Partner Dancing

Here are some common ideals I’ve noticed in dancers:

  1. Mistakes are bad and must be avoided.
  2. My dancing should progress linearly (and if it doesn’t, it means there is something wrong with me).
  3. Dancing shouldn’t take so much practice and work.
  4. Our partners should do what we want them to do and be predictable.
  5. My partner’s dance ability determines how much I enjoy dancing with them.

These thoughts are much less accurate than they could be. In my experience, the following are more accurate perceptions of the realities of partner dancing:

  1. Planned mistakes are great learning tools. Unplanned mistakes can be embarrassing, but make you a better dancer if you learn from them.
  2. Your progress will slow at some point. It will probably make you feel bad about yourself.
  3. Everyone who is good at dancing worked really hard to get there–possibly much harder than you think.
  4. Your partner will ultimately do what they want, which may or may not be what you’re expecting. This is something you can handle and learn to respond to.
  5. At the end of the day, you are in charge of your enjoyment of the dance. You are responsible for your feelings and actions.

Ask yourself this: Where have you misperceived “what is” in favor of ideals or fears? What would be a more accurate way to look at it?

When you’ve gotten your perceptions more on track, then it’s time to address your actions. After all, actions speak louder than thoughts.

What will you do differently when you perceive reality more accurately?

How will it change your dancing?

How will it affect the way you treat yourself and the way you interact with others?

Photo credits: Jon Rawlinson (Bruce Lee statue)

02 Aug 09:41

Recovering from “Whiplash”

by Bobby

maxresdefault

This post will probably make little sense if you haven’t seen last year’s film Whiplash, and, on top of that, contains spoilers. Proceed accordingly.

The film Whiplash is about a student jazz drummer pushed by an abusive teacher. Being a recent student of swing drumming, I was interested to see it, especially since the last film to focus on a jazz drummer was probably The Gene Krupa Story in 1959. However, being passionate about pedagogy, swing/jazz, fiction writing, and also being a swing dancer who has worked very hard to get to where I have gotten, the film left me with a lot of thoughts.

Here are most of them.

(1) It is a well-told — and deceptively complex — story.

Completely from a dramatic point of view, this story, with its single, simple plotline, is very well-told. The writing is powerfully minimalistic, the acting is powerfully emotional, and the camerawork is powerfully bold. I can close my eyes and still hear the tone of voice of the teacher Fletcher, can see nothing but his eyes and the skin wrinkle around them, can still see the cymbal fall during the solo.

Furthermore, if you’re not thinking too much into it, the film’s finale is the kind that pulls you out of your seat and demands you tackle your worst demons. Or, at the very least, bang on something.

Fascinatingly, the very barrage of drums and cymbals that create this sensation also cover-up the more quiet implications and mysteries of the ending.

For instance, in his final defiant solo, the character proved he could play drums incredibly well. But what else it proved is ambiguous. Did he prove the teacher had no control over him, or, by winning the teacher’s approval, could the teacher now be more in control of him than ever? Did he prove he had what it took all along, or did he prove the abusive teaching methods worked?

Though the film ends with both the student and teacher more or less experiencing triumph in their own way, you don’t know what will happen next with the student/teacher relationship in the film, or with the life and happiness of the young drummer Andrew. (The writer/director Damien Chazelle himself, as we will discuss, thought the young man had a bleak — rather than inspirational — future.)

(2) The film gives a subtle shout-out to temperamental drummers.

I do appreciate the film seemingly giving a tip of the hat to Buddy Rich’s famous temper tantrums in some of Fletcher’s behavior. (Which, side note, is why the Beastie Boys say “I’m Buddy Rich when I fly off the handle” in the song Sabotage.)

Buddy Rich

Buddy Rich

(3) The teacher has a flawed understanding of good teaching.

In response to the film, a lot of people seem to debate whether the teacher Fletcher is good or bad. “Do his methods not ultimately lead to the student’s becoming a better musician?” seems to be the main argument in this “debate.”

I put “debate” in quotes because I think it’s fundamentally flawed to try to categorize the teacher as either “good” or “bad.” Some of his methods are good, some of them are bad. The fact that they are tied together is what makes him compelling/horrific to watch, but also sadly what makes some viewers think he is somehow justified in the way he acts. To those who don’t understand effective teaching, his methods can give a mistaken impression of what it takes to be an effective teacher with very high standards.

When he says “You are not keeping my tempo.” “Were you rushing or dragging?” “You have to earn the part,” he is being a good teacher. He is stating facts (and thus keeping critiques as realistic observation rather than charged with negative emotions), asking students about their awareness of their craft, and challenging students that it will take a great deal of work and attention to get the best part.

When Fletcher insults the student, threatens him, physically abuses him, and throws furniture at him, he is being a bad teacher. It causes crippling anxiety, self-destructive behavior, and ultimately the understandable desire in students to attack their teacher.

The tricky part is that even when Fletcher is being tough, it is showing both the good and the bad teaching aspects of being tough: dropping students from their first chair position the moment someone else plays better than them is a common practice in conservatories, and is about simple, unemotional assessment of skill. Person A is better than person B at this part. Therefore person A gets to play the part. But abusing them verbally while doing so is not. Top conservatory professors, annoyed that people will be turned away from jazz programs by this film, have gone on record to say a man like Fletcher would be thrown out of their schools quickly no matter how great he was.

When it comes down to it, the teacher/student relationship in the film is really the same as an abusive romantic relationship — just as abusive spouses often justify their actions by saying they strike their spouses in order to teach them and keep order in the house, the teacher Fletcher justifies his actions by saying his abuse was the only way to get the best out of his students.

Some people have asked, would the student have been as good a drummer by the end if it weren’t for Fletcher’s methods? I would like to save this answer until later, after we discuss a few other responses to the film.

(4) The teacher has a flawed understanding of jazz history.

The teacher Fletcher aspires to help one of his students become the next “Charlie Parker,” specifically,his Charlie Parker. He feels it’s his style of teaching that will make one of them that Charlie Parker.

But Charlie Parker was a jazz lover without a single teacher, let alone an abusive one. Jo Jones throwing the cymbal at Charlie Parker’s feet (which is the way, if it happened, it has always been reported as happening) was not the same as Jo Jones following Charlie Parker around and insulting him and humiliating him to greatness. Charlie Parker went away for awhile, and on his own came back as the brilliant saxophonist he was.

All great original jazz musicians I ever heard of were, ultimately, their own invention. They may have often worked under mentors, but their greatness was their own hard work and commitment. Louis Armstrong, Lester Young, Billie Holiday, Dizzy Gillespie, Miles Davis, Artie Shaw, and even the Whiplash student’s idol, Buddy Rich. They were able to keep the highest standards, despise mediocrity, and practice till they got it right without someone else’s abuse to make them shake while they tried to do it.

“Papa” Jo Jones, drummer for the Count Basie All-American Rhythm Section.

Let’s focus specifically on the Count Basie band’s Jo Jones — my greatest swing drummer influence, and the man who threw the cymbal at Charlie Parker’s feet. Jo Jones learned drumming by sitting at the feet of other great drummers of his time, and then by trying to play and keep up in jams, cutting contests, and bands. He could imitate many of the greatest drummers of his youth because he spent so much time trying to play like them. But he also had developed a hugely influential and playful voice of his own, pioneering a good deal of the way we hear swing drumming today, and had such high mastery of his craft that he is widely regarded as one of the greatest jazz drummers to ever live. Like fellow great jazz drummer Buddy Rich, he was ornery, a perfectionist, and open with his opinions. But all of that was his own doing.

From a storytelling point of view, I personally would be much more interested in Jo’s story of becoming a great jazz drummer than the young Whiplash conservatory student. I think it would say a lot more realistically about greatness in general, as well.

But that’s me projecting what I wanted Whiplash to be, not what it is. I think it’s really just the story of an abusive relationship; not the story of the difference between a good jazz musician and a great one, or the spirit of jazz. (If it is supposed to be about these things, it’s underwhelming, as it’s only advice is to work very hard and possibly be abused. End of story.)

Which leads us to…

(5) The characters have a flawed understanding of the cost of greatness.

Fletcher and the student are two people under the delusion that greatness has to cost you great sacrifices not just in time, but in physical health, mental health, and happiness.

Charlie Parker

Charlie Parker

Thus, the film makes the choice to concentrate on Charlie Parker’s end — dead in his 30s from years of drug abuse (this is also the way the writer/director of the film saw the student’s life ending, as stated in an interview). And both the student and the teacher display the greatest reverence for Parker and, eerily, the desire for the student to have the same path in life even at the same costs. But both of them, and the film, completely ignore the fact that among all the great jazz musicians, Charlie Parker’s tragically young death was by no means the rule. Louis Armstrong, Artie Shaw, Count Basie, as well as the great swing drummers Buddy Rich (the student’s idol) and Jo Jones, all had long and prolific careers.

Three short footnotes before we move on:

I’d like to compare, not all in jest, the student’s desire to cut off a social life in order to practice more with Lester Young’s desire to quit drums and take up saxophone so that he could put his instrument away quicker and meet women.

There’s also the interesting point that trying to get “the next Charlie Parker” out of a drummer is in itself kind of a a flawed concept. From my understanding, what made Parker great was how he almost single-handedly created an entirely new way of understanding jazz and jazz soloing based on the notes of the melody, and thus played a huge role in evolving jazz to its next iteration. As good a jazz drummer as the student could be, he probably would not be able to do something comparable to that.

Finally, I understand I’m talking only about swing musicians here, the ones I know; I’m very not up to date on post-50s jazz musicians. But, luckily for me, the teacher and student in the film’s conservatory (unrealistically) only mention pre-1950s jazz musicians, so I think I’m allowed.

(6) The film/student has terrible practicing habits.

The film creates a dramatic spectacle: the student playing drums so hard and forcefully that his hands bleed. By storytelling standards, its a simple and powerful way to show you how hard this student is working towards his goal, and at what cost.

But before you learn your practice habits from Hollywood, it’s important to understand the reality. Just one example: conservatory musicians practice being as relaxed as possible to achieve their goals. If a drummer simply practices by gripping a stick harder and harder (like the student in the film), then the sound is more and more “stiff.” Powerful drum sounds are from the sticks bouncing off of the head or cymbal, not being driven into it with an iron grip. Yes, playing faster requires more precise use of greater tension, but it should not require bulging tension throughout the arms and body, tight grimmaces, and blood spattering onto the drums.

Granted, the practicing scenes would not be as dramatic if the student were constantly stopping and making sure he relaxed before playing again.

Sadly, put all of this together, and I can’t help but argue that…

(7) This film is kinda bad for jazz.

As I mentioned earlier, Whiplash isn’t really about jazz or even drumming, really. The jazz drumming is just a dramatic vehicle to showcase the story of a high-pressure abusive relationship. The story could very easily be about a ballerina, or a boxer, or a competitive Polka dancer — and I think the story would still work just as well. (The meta TV show Community proved this by doing a great parody of Whiplash set in a community theater preparing for a stage production of The Karate Kid, which is itself a movie about a much more successful mentor/student relationship.)

There is nothing out of the ordinary about this. Most genre stories are actually about much more broad human experiences.

Characters in a film that actually shows something inspiring about the spirit of Jazz.

From a film that actually was about the spirit of jazz.


Swing Kids, for instance, is not about swing dance — it’s about a youth raised in a fascist state learning to stand up against fascism. However, I’d argue that the film wouldn’t work near as well if you took out the swing music and dancing and instead used youth boxing or Polka (Polka Kids). That’s because the spirit of swing is joyful, cross-cultural, cross-class, democratic — all things that are the contrast to fascism. And it’s exactly the kind of activity that would make a young, sensitive German youth rethink the racist dogma he was expected to believe.

Sure, it didn’t get any Oscar nods or win any awards. But at least swing music was actually important to Swing Kids. In turn, the film was great for classic swing; it reminded the world that “Sing, Sing, Sing” existed and was a pretty fantastic song, and seeing how the characters in the film loved the music and dance so much got people like me really excited about joining in their experience. After all, the world of swing is portrayed as music so good and so right you’d risk getting arrested just to experience it.

In Whiplash, however, the world of jazz is portrayed as abusive conservatory masters, people practicing joylessly and anxiously cutting out all their social life, the idea that you have to be bullied into greatness.

Jazz gets a bad name in this film. And, if it had to be jazz musicians the film was about — one who listens to Buddy Rich solos over and over, and who appreciates Charlie Parker as an idol — I don’t like it that the director/writer made only a tiny bit of effort to show the positive spirit of jazz, and why jazz is worth all the hard work these two people are putting into it.

It wouldn’t have taken a lot. Maybe, while on his way to practice until he punches through another drum head, the student walks by a group of street jazz musicians tearing it up and actually having fun while they played.

Maybe at some point he watches something other than just Buddy Rich YouTube solos, and we the audience join him in awe as he watches the quieter wryness of the Count Basie rhythm section, or the anxious dreaminess of “Blues in Green” by Miles Davis. The kind of jazz where the silence of the drummers is just as important as the noise.

Maybe he tries his hand at an actual jam session and actually trades 4s or 8s with a great musician, so the film can acknowledge that the spirit of jazz is just as much a conversation as it is a solo.

(8) So, would the student have been as good a drummer by the end if it weren’t for Fletcher’s methods?

My answer would be, “It’d be up to the student.”

And that’s where I think the responsibility belongs, as it has with all the other jazz greats.

Had Fletcher kept to only the “good” teaching traits mentioned, he would have been a fantastic resource for the student to use to achieve greatness on his own — as a teacher, Fletcher is clearly passionate about the music, knows his stuff, and knows how to challenge his students.

Sure, there might have not been the abuse to push the student to work at his drumming at the expense of his health and happiness so that he could be amazing at that very moment. But surely if the student is meant to be a great drummer, it should be his own responsibility and choice to push himself to that greatness. Not have to be forced or manipulated into it by a bully.

Also, without an overbearing teacher, the student might be able to actually learn how to interact with other musicians.

Then he could play jazz with them, rather than only alongside them.


02 Aug 09:40

21 best Windows 10 keyboard shortcuts you should know

by Mark Guim

Keyboard shortcuts can save you time as you use Windows 10. You probably already know about Ctrl + C and Ctrl +V (copy and paste), but we're here to tell you 21 other shortcuts that you should know when using Windows 10. Some of these shortcuts might already be familiar to you, but think of new users who just switched from a Mac or simply have relied more on mice or touchscreens.










02 Aug 09:39

О памяти. Часть 1

by superhimik


   После затянувшейся паузы я хотел было продолжить рассказ о различиях между ноотропами и пcиxocтимyлятopами, но понял, что написать понятное, краткое и содержательное сообщение без разговора о памяти – мишени их действия, которая меня интересует, не получится.
   О некоторых молекулярных аспектах памяти я и хочу рассказать.
    Только для гиков.
02 Aug 09:39

[Перевод] Мультиплеер в быстрых играх (Часть IV: Хэдшот! Путешествуем во времени)

by marsermd

  1. Части I, II (синглплеер с авторитарным сервером)
  2. Часть III (Появление врага)
  3. Часть IV (Хэдшот!)

Как повесить идеальный хэдшот если у тебя пинг 2 секунды? Вы узнаете в этой статье.

Текущий алгоритм работы мультиплеера


  • Сервер получает команды с клиентов и времена их отправления
  • Сервер обновляет состояние мира
  • Сервер с некоторой частотой отправляет свое состояние всем клиентам
  • Клиент отправляет команды и локально воспроизводит их результат
  • Клиент получает обновленные состояния мира и:
    • Применяет состояние от сервера
    • Заново применяет все свои команды, которые сервер не успел применить.
    • Интерполирует предыдущие состояния других игроков
  • С точки зрения игрока, есть два серьезных последствия:
    • Игрок видит себя в настоящем
    • Игрок видит других в прошлом.

Обычно это отлично работает, но это становится большой проблемой для событий, которым нужна высокая пространственно-временная точность. Например если хочется разнести врагу бошку!
Читать дальше →
02 Aug 09:37

Saturday Morning Breakfast Cereal - Parenting Game Theory

by tech@thehiveworks.com


Hovertext:
Who says game theory isn't useful in real life?

New comic!
Today's News:
02 Aug 09:18

[Перевод] 22 сообщения надежды (и науки) для креационистов

by SLY_G
glyph

самое интересное - спор в комментариях о том, нужны ли такие статьи на гиктаймсе

Никакого сарказма, никакого осуждения – просто честные ответы на 22 вопроса от креационистов.



В науке часто бывает, что учёные говорят, «Знаете, ваш аргумент очень хорош; я ошибался» и затем они на самом деле меняют мнение и их старых представлений от них уже не слышно. Они на самом деле так поступают. Это случается не так часто, как хотелось бы, поскольку учёные – это люди и иногда перемены причиняют боль. Но это происходит ежедневно. Не помню, когда в последний раз что-то подобное происходило в политике или религии.
— Карл Саган


Вчера спор по теме эволюции и креационизма продолжался два с половиной часа. Сегодня я обнаружил этот пост на Buzzfeed, на который ссылаются все кому не лень. Он, судя по всему, издевается над креационистами, показывая «глупые и высокомерные» вопросы или сообщения, которые они адресуют людям, верящим в эволюцию.

Но если вы только и занимаетесь тем, что насмехаетесь над несогласными с вами людьми, вы упускаете шанс честно подискутировать с ними, узнать, откуда они, и, возможно, научить их чему-то, чего они могли не знать. Я не биолог; я астрофизик, но когда я увидел эти 22 сообщения, я задумался о большом количестве молодых людей, которых я встречал в жизни в школах, классах и образовательных ситуациях. Если бы эти вопросы были адресованы мне, чтобы я сказал?
Читать дальше →
10 Feb 11:50

Цитата #437908

hhh: Двадцать два - это уже норм взрослый, можно мультики смотреть и всякое прочее, что в пятнадцать - лютый зашквар.
12 Mar 07:26

Photo



03 Oct 06:37

#394: WHEN THE DJ THROWS ON A 230 BPM SONG FOR THE CONTEST FINAL

05 Sep 21:56

This Dog Just Cant Wait To Go Swimming