Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: 1 ... 318 319 [320] 321 322 ... 796

Author Topic: if self.isCoder(): post() #Programming Thread  (Read 882694 times)

Mego

  • Bay Watcher
  • [PREFSTRING:MADNESS]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4785 on: July 31, 2013, 06:48:40 pm »

DIBS

Let's start off with dealing with errors first, and then we'll talk about improving the code.

Compiling with gcc 4.7.2:

Code: [Select]
main.cpp: In function ‘std::unordered_map<std::basic_string<char>, MarkovNode> MarkovBuilder(std::queue<std::basic_string<char> >)’:
main.cpp:39:41: error: ‘class std::map<std::basic_string<char>, unsigned int>’ has no member named ‘emplace’
main.cpp:48:48: error: ‘class std::map<std::basic_string<char>, unsigned int>’ has no member named ‘emplace’
main.cpp: In function ‘std::unordered_map<std::basic_string<char>, MarkovNode> MarkovBuilder(std::queue<std::basic_string<char> >, std::unordered_map<std::basic_string<char>, MarkovNode>)’:
main.cpp:67:38: error: ‘class std::map<std::basic_string<char>, unsigned int>’ has no member named ‘emplace’
main.cpp:77:45: error: ‘class std::map<std::basic_string<char>, unsigned int>’ has no member named ‘emplace’
main.cpp: In function ‘std::queue<std::basic_string<char> > Tokeniser(std::string)’:
main.cpp:96:38: error: ‘strtok’ was not declared in this scope

All but the last error comes from the fact that you're trying to call map::emplace, which doesn't exist. Change those to unordered_map, or (what I believe is your intention) use map::operator[]. Also, iterators act like pointers, so you'll need to dereference them to access the value.

The last error comes from the fact that you're trying to call the strtok function without including <cstring>. Include it, and use std::strtok.

Some warnings also popped up about not returning anything from non-void functions. FindLikeliest and MarkovBuilder will have issues if tokens is empty, because then they will reach the end of the function without a return statement. I added some throws in there to circumvent that. It'll help your testing.

Fixed code:

Code: [Select]
#include <map>
#include <unordered_map>
#include <queue>
#include <string>
#include <fstream>
#include <iostream>
#include <cstring>

struct MarkovNode {
   MarkovNode();
   std::string FindLikeliest();
   unsigned int totalLinksCount;
   std::map <std::string, unsigned int> linksForward;
};

MarkovNode::MarkovNode() {
   totalLinksCount = 0;
}
std::map <std::string, unsigned int> linksForward;

std::string MarkovNode::FindLikeliest() {
   std::pair <std::string, unsigned int> likeliest;
   if (linksForward.empty() != true) {
      likeliest = *linksForward.begin();
      for ( std::map <std::string, unsigned int>::iterator it = linksForward.begin(); it != linksForward.end(); ++it ) {
         if(it->second > likeliest.second); likeliest = *it;
      }
      return likeliest.first;
   } else throw std::exception();
}

std::unordered_map <std::string, MarkovNode> MarkovBuilder (std::queue <std::string> tokens) {
   if (tokens.empty() != true) {
      std::string lastWord;
      std::unordered_map <std::string, MarkovNode> markovChain; // New graph

      markovChain.emplace ("START", MarkovNode()); // Start node for empty text

      markovChain.emplace (tokens.front(), MarkovNode()); // Node for first
      markovChain["START"].linksForward[tokens.front()] = 1; // Link to start node

      lastWord = tokens.front();
      while (tokens.empty() == false) {
         tokens.pop(); // Removes first word
         markovChain.emplace (tokens.front(), MarkovNode()); // Node for second
         if ( markovChain[lastWord].linksForward.count(tokens.front()) == 1 ) { // Increments count for link to second word if one exists
            markovChain[lastWord].linksForward[tokens.front()]++;
         } else {
            markovChain[lastWord].linksForward[tokens.front()] = 1; // Creates a new link.
         }
         lastWord = tokens.front(); // Moves on to third.
      }

      return markovChain;
   } else throw std::exception();
}
   // Chain always starts with a START node.

std::unordered_map <std::string, MarkovNode> MarkovBuilder
      ( std::queue <std::string> tokens, std::unordered_map <std::string, MarkovNode> markovChain) {

   std::string lastWord;

   markovChain.emplace (tokens.front(), MarkovNode()); // Node for first
   if (markovChain["START"].linksForward.count(tokens.front()) == 1 ) {
      markovChain["START"].linksForward[tokens.front()]++;
   } else {
   markovChain["START"].linksForward[tokens.front()] = 1; // Link to start node
   }

   lastWord = tokens.front();
   while (tokens.empty() == false) {
      tokens.pop(); // Removes first word
      markovChain.emplace (tokens.front(), MarkovNode()); // Node for second; if existing, this will simply let it refer to the earlier occurrence.
      if ( markovChain[lastWord].linksForward.count(tokens.front()) == 1 ) { // Increments count for link to second word if one exists
         markovChain[lastWord].linksForward[tokens.front()]++;
      } else {
         markovChain[lastWord].linksForward[tokens.front()] = 1; // Creates a new link.
      }
      lastWord = tokens.front(); // Moves on to third.
   }

   return markovChain;
}

std::queue <std::string> Tokeniser (std::string filename) {
   std::queue <std::string> token;
   std::ifstream file (filename, std::ios::in|std::ios::binary|std::ios::ate);
   if (file.is_open())
   {
      file.seekg(0, std::ios::end);
      unsigned long size = file.tellg();
      char *contents = new char [size];
      file.seekg (0, std::ios::beg);
      file.read (contents, size);
      file.close();
      char* tok = std::strtok(contents," ");
      while (tok != NULL) {
         token.push(tok);
         tok = strtok(NULL," ");
      }
      delete [] contents;
   }
   return token;
}

int main ()
{
   std::queue <std::string> tokens = Tokeniser ("sample.txt");
   std::unordered_map <std::string, MarkovNode> markovChain = MarkovBuilder(tokens);

   unsigned int outputLengthTokens = 5;

   std::string nextToken;
   std::string temp;

   std::string typicalPhrase;
   nextToken = markovChain["START"].FindLikeliest();
   temp = nextToken;
   typicalPhrase = nextToken;

   for(unsigned short i = 1; i < outputLengthTokens; ++i) {
      nextToken = markovChain[temp].FindLikeliest();
      temp = nextToken;
      typicalPhrase.append(" ");
      typicalPhrase.append(nextToken);
   }

   std::cout << typicalPhrase;

   return 0;
}

There are more issues, but I trust that you will be able to figure them out on your own.

ECrownofFire

  • Bay Watcher
  • Resident Dragoness
    • View Profile
    • ECrownofFire
Re: if self.isCoder(): post() #Programming Thread
« Reply #4786 on: August 01, 2013, 02:17:55 am »

But map::emplace does exist, it's just that GCC 4.7 doesn't implement it.

4.8.1 has it, though. Stop using outdated compilers :P
Logged

lordnincompoop

  • Bay Watcher
  • Allusionist
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4787 on: August 01, 2013, 03:12:19 am »

Yeah, I get none of those errors, Mego. std::map has an emplace member as specified in the standard. There are lots of things about c++11 that gcc 4.7 doesn't implement.

Thanks about the throws, but leaving the most critical error (the iteration runtime error) as "something to figure out on my own" when I've already spent too many hours pulling my hair at this before coming here is counter-productive.


Use the debugger and find out where it crashed. MSVC has a fairly good one. It sounds like you might be dereferencing an "end" iterator or an iterator inside an empty container.

Alright, I'll try that later today.

On other notes, that code hurts my eyes :P

You should really be using range-for loops.
MarkovNode constructor is unnecessary and inefficient, you should just use default initialization (totalLinksCount = 0;).
This is incredibly overcomplicated. Just have each node store its own string and a std::list of its children.

Hey, I never said I was good at this stuff.

I needed a counter for each child because that's the only way of keeping track of what is the most commonly used word after that one. I also wanted to implement a probabilistic method later down the road to create paragraphs that the user would conceivably write (in the program's mind). I realise the findLikeliest function and all that is inefficient, but I'm not familiar enough with STL to know a better alternative than std::map that allows for such convenient coupling b/w the word and its commonality.

'sides, this is a kinda hacky proof-of-concept for a mathematics essay. It doesn't need to be fully compatible with the Programming Best Practices.
Logged

Mego

  • Bay Watcher
  • [PREFSTRING:MADNESS]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4788 on: August 01, 2013, 07:16:11 am »

But map::emplace does exist, it's just that GCC 4.7 doesn't implement it.

4.8.1 has it, though. Stop using outdated compilers :P

And apparently outdated reference materials - the site I was using for reference didn't have it listed, even though it had unordered::map documented. My bad.

lordnincompoop - I would help you, but I have no idea what kind of data you're giving to the program. If you uploaded sample.txt, I'd be able to help you better.

lordnincompoop

  • Bay Watcher
  • Allusionist
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4789 on: August 01, 2013, 07:27:33 am »

Fair enough.

sample.txt is just a bunch of lorem ipsum, but any prose text would do. For example:

Spoiler (click to show/hide)
Logged

MorleyDev

  • Bay Watcher
  • "It is not enough for it to just work."
    • View Profile
    • MorleyDev
Re: if self.isCoder(): post() #Programming Thread
« Reply #4790 on: August 01, 2013, 02:57:32 pm »

Technically the GCC C++ compiler is fully C++11 compliant now.

Unfortunately the standard library, libstdc++, is lagging behind significantly. Which is annoying me because I really want built-in support for regular expressions...
Logged

Mego

  • Bay Watcher
  • [PREFSTRING:MADNESS]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4791 on: August 01, 2013, 06:06:08 pm »

While looking through your code in search of the segfault, I noticed how you're handling reading in from the file. Why are you reading in binary format? Much simpler and easier to debug:

Code: [Select]
std::ifstream file(filename);
    if(file.is_open()) {
        while(file.good()) {
            std::string word;
            file >> word;
            token.push(word);
        }
    }

lordnincompoop

  • Bay Watcher
  • Allusionist
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4792 on: August 03, 2013, 09:36:01 am »

While looking through your code in search of the segfault, I noticed how you're handling reading in from the file. Why are you reading in binary format? Much simpler and easier to debug:

Code: [Select]
std::ifstream file(filename);
    if(file.is_open()) {
        while(file.good()) {
            std::string word;
            file >> word;
            token.push(word);
        }
    }

That was just something I overlooked. Sorry.
Logged

lordnincompoop

  • Bay Watcher
  • Allusionist
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4793 on: August 03, 2013, 10:06:35 am »

An update: I still don't know what caused it, but I rewrote the tokeniser to output an std::vector instead of a queue. That seems to have fixed it.
Logged

MorleyDev

  • Bay Watcher
  • "It is not enough for it to just work."
    • View Profile
    • MorleyDev
Re: if self.isCoder(): post() #Programming Thread
« Reply #4794 on: August 03, 2013, 10:30:28 am »

Argh, trying to get clang building my unit testing library on a Raspberry Pi is a headache. Build clang, got it so clang builds a simple runnable hello world program fine. So almost got it working, but now it's just giving undefined references to __atomic_add_4 at the linker stage.

And now, having given up on clang and Linux for the time being, I'm trying to get it building in Visual Studio 2013 (The introduction of variadic templates was a requirement for this being even possible). Turns out that Visual Studio's macro support really sucks because as soon as you start to do complex stuff involving variadic macros and nesting macros inside each other nothing works.

:(

EDIT: Oh it gets even better. It crashes the compiler. My code. Crashes. The visual studio 2013 compiler. That makes me feel oddly proud. I mean, I've heard of a brain drain problem at Microsoft but it's starting to just look embarrassing for them.

EDIT2: Yay, got it compiling and running fine. All tests pass in GCC still, but two fail in Visual Studio 2013. Turns out there's a bug associated with initializer lists. On the bright side, the library is still usable. On the downside, this means that functionality doesn't work. Fortunately it's easy to not use.
« Last Edit: August 04, 2013, 06:57:08 am by MorleyDev »
Logged

Putnam

  • Bay Watcher
  • DAT WIZARD
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4795 on: August 10, 2013, 02:04:14 am »

Code: [Select]
-- Assigns claspects based on personality, attributes etc.

claspects = {
aspects={
"breath", --1
"light",
"time",
"space",
"life",
"hope",
"void",
"heart",
"blood",
"doom",
"mind",
"rage"},
classes={
"heir", --1
"seer",
"knight",
"witch",
"maid",
"page",
"rogue",
"prince",
"sylph",
"mage",
"thief",
"bard"}
}

personality_weights = {
{ --aspects
{ --breath
ANXIETY                 = -3,
ANGER                   =  0,
DEPRESSION              = -2,
SELF_CONSCIOUSNESS      = -5,
IMMODERATION            =  2,
VULNERABILITY           =  0,
FRIENDLINESS            =  2,
GREGARIOUSNESS          =  3,
ASSERTIVENESS           =  3,
ACTIVITY_LEVEL          =  2,
EXCITEMENT_SEEKING      =  6,
CHEERFULNESS            =  4,
IMAGINATION             =  1,
ARTISTIC_INTEREST       =  1,
EMOTIONALITY            =  1,
ADVENTUROUSNESS         =  6,
INTELLECTUAL_CURIOSITY =  1,
LIBERALISM              =  0,
TRUST                   =  1,
STRAIGHTFORWARDNESS     =  2,
ALTRUISM                =  1,
COOPERATION             =  2,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           =  5,
ORDERLINESS             = -2,
DUTIFULNESS             = -3,
ACHIEVEMENT_STRIVING    =  1,
SELF_DISCIPLINE         = -1,
CAUTIOUSNESS            =  1},

{ --light
ANXIETY                 = -1,
ANGER                   =  0,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  1,
IMMODERATION            =  0,
VULNERABILITY           =  0,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  1,
INTELLECTUAL_CURIOSITY = 10,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           =  0,
ORDERLINESS             =  1,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  1,
SELF_DISCIPLINE         =  1,
CAUTIOUSNESS            =  1},

{ --time
ANXIETY                 =  1,
ANGER                   =  0,
DEPRESSION              =  1,
SELF_CONSCIOUSNESS      = -1,
IMMODERATION            =  0,
VULNERABILITY           = -1,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  1,
EXCITEMENT_SEEKING      =  1,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  1,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  1,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  2,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           =  5,
ORDERLINESS             = 10,
DUTIFULNESS             =  1,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  5,
CAUTIOUSNESS            =  2},

{ --space
ANXIETY                 =  0,
ANGER                   =  0,
DEPRESSION              = -1,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           =  0,
FRIENDLINESS            =  2,
GREGARIOUSNESS          =  2,
ASSERTIVENESS           =  2,
ACTIVITY_LEVEL          =  2,
EXCITEMENT_SEEKING      =  1,
CHEERFULNESS            =  1,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  1,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  1,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0},

{ --life
ANXIETY                 = -1,
ANGER                   = -2,
DEPRESSION              = -2,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            = -1,
VULNERABILITY           = -2,
FRIENDLINESS            =  5,
GREGARIOUSNESS          =  3,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  5,
IMAGINATION             =  2,
ARTISTIC_INTEREST       =  1,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  1,
ALTRUISM                = 10,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  1,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0},

{ --hope
ANXIETY                 =  1,
ANGER                   =  1,
DEPRESSION              =  1,
SELF_CONSCIOUSNESS      =  5,
IMMODERATION            =  2,
VULNERABILITY           =  5,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  2,
ACTIVITY_LEVEL          =  0,
EXCITEMENT_SEEKING      =  3,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  5,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 = -1,
SYMPATHY                = -4, --douchebags
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            = -2},

{ --void
ANXIETY                 =  0,
ANGER                   =  0,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           =  0,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ACTIVITY_LEVEL          =  0,
ASSERTIVENESS           =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  1,
ARTISTIC_INTEREST       =  2,
EMOTIONALITY            =  1,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         = -2,
CAUTIOUSNESS            =  0},

{ --heart
ANXIETY                 =  1,
ANGER                   =  0,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  2,
IMMODERATION            =  0,
VULNERABILITY           =  1,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ACTIVITY_LEVEL          =  0,
ASSERTIVENESS           =  1,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  2,
ARTISTIC_INTEREST       =  2,
EMOTIONALITY            = 20,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 = -1,
SYMPATHY                =  3,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            = -1},

{ --blood
ANXIETY                 =  2,
ANGER                   =  2,
DEPRESSION              =  1,
SELF_CONSCIOUSNESS      =  2,
IMMODERATION            =  1,
VULNERABILITY           =  1,
FRIENDLINESS            = -1,
GREGARIOUSNESS          = 20,
ASSERTIVENESS           = -2,
ACTIVITY_LEVEL          =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            = -1,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  1,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  1,
LIBERALISM              = 30,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  1,
COOPERATION             =  5,
MODESTY                 = -3,
SYMPATHY                =  1,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0},

{ --doom
ANXIETY                 =  5,
ANGER                   =  5,
DEPRESSION              =  5,
SELF_CONSCIOUSNESS      = -1,
IMMODERATION            =  1,
VULNERABILITY           = -1,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          = -1,
ASSERTIVENESS           =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  1,
ARTISTIC_INTEREST       =  3,
EMOTIONALITY            =  1,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  8,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     = -2,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  2,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  4,
ACHIEVEMENT_STRIVING    =  1,
SELF_DISCIPLINE         =  1,
CAUTIOUSNESS            = -1},

{ --mind
ANXIETY                 =  0,
ANGER                   =  0,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           =  0,
FRIENDLINESS            =  5,
GREGARIOUSNESS          =  3,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  0,
ASSERTIVENESS           =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  5,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY = 15,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     = 10,
ALTRUISM                =  0,
COOPERATION             = 15,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0},

{ --rage
ANXIETY                 = 30,
ANGER                   = 50,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           = 20,
FRIENDLINESS            = -1,
GREGARIOUSNESS          = -1,
ASSERTIVENESS           =  8,
ACTIVITY_LEVEL          =  0,
ASSERTIVENESS           =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            = -1,
IMAGINATION             =  1,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  1,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              = 80,
TRUST                   = -5,
STRAIGHTFORWARDNESS     = -1,
ALTRUISM                = -2,
COOPERATION             = -1,
MODESTY                 = -1,
SYMPATHY                = -1,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  5}
},
     { --classes
{ --heir
ANXIETY                 =  0,
ANGER                   =  0,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           =  1,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           = -5,
ACTIVITY_LEVEL          =  0,
ASSERTIVENESS           =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  5,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             = 10,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0},

{ --seer
ANXIETY                 =  0,
ANGER                   =  0,
DEPRESSION              =  2,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           =  1,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  0,
ASSERTIVENESS           =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         = -1,
INTELLECTUAL_CURIOSITY = 10,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     = -2,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           =  0,
ORDERLINESS             =  1,
DUTIFULNESS             =  1,
ACHIEVEMENT_STRIVING    = -1,
SELF_DISCIPLINE         =  1,
CAUTIOUSNESS            =  1},

{ --knight
ANXIETY                 =  1,
ANGER                   =  1,
DEPRESSION              =  1,
SELF_CONSCIOUSNESS      = 10,
IMMODERATION            = -1,
VULNERABILITY           =  2,
FRIENDLINESS            =  3,
GREGARIOUSNESS          =  4,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  0,
ASSERTIVENESS           =  0,
EXCITEMENT_SEEKING      =  2,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  4,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 = -4,
SYMPATHY                =  0,
SELF_EFFICACY           = -1,
ORDERLINESS             =  1,
DUTIFULNESS             = 15,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         = -1,
CAUTIOUSNESS            =  0},

{ --witch
ANXIETY                 =  1,
ANGER                   =  1,
DEPRESSION              = -1,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           =  0,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            = 50,
IMAGINATION             = 10,
ARTISTIC_INTEREST       =  8,
EMOTIONALITY            =  3,
ADVENTUROUSNESS         =  5,
INTELLECTUAL_CURIOSITY =  2,
LIBERALISM              =  1,
TRUST                   =  1,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  2,
COOPERATION             =  1,
MODESTY                 = -1,
SYMPATHY                =  0,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0},

{ --maid
ANXIETY                 =  1,
ANGER                   =  5,
DEPRESSION              =  2,
SELF_CONSCIOUSNESS      =  1,
IMMODERATION            =  8,
VULNERABILITY           =  8,
FRIENDLINESS            =  5,
GREGARIOUSNESS          =  5,
ASSERTIVENESS           =  6,
ACTIVITY_LEVEL          =  4,
EXCITEMENT_SEEKING      =  3,
CHEERFULNESS            =  2,
IMAGINATION             =  2,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  1,
ADVENTUROUSNESS         =  7,
INTELLECTUAL_CURIOSITY =  2,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           = -1,
ORDERLINESS             =  0,
DUTIFULNESS             = -1,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         = -5,
CAUTIOUSNESS            =  0},

{ --page
ANXIETY                 =  5,
ANGER                   =  0,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  5,
IMMODERATION            =  3,
VULNERABILITY           =  1,
FRIENDLINESS            =  5,
GREGARIOUSNESS          = 10,
ASSERTIVENESS           =  1,
ACTIVITY_LEVEL          =  0,
EXCITEMENT_SEEKING      =  1,
CHEERFULNESS            =  2,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           = -1,
ORDERLINESS             = -1,
DUTIFULNESS             = -1,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0},

{ --rogue
ANXIETY                 =  1,
ANGER                   =  0,
DEPRESSION              =  1,
SELF_CONSCIOUSNESS      =  1,
IMMODERATION            =  0,
VULNERABILITY           =  1,
FRIENDLINESS            =  1,
GREGARIOUSNESS          =  1,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          = -1,
EXCITEMENT_SEEKING      = -1,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     = -1,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           =  0,
ORDERLINESS             = -1,
DUTIFULNESS             = -1,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0},

{ --prince
ANXIETY                 =  1,
ANGER                   =  0,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  1,
IMMODERATION            =  0,
VULNERABILITY           =  0,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  2,
ACTIVITY_LEVEL          =  2,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  1,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY = -1,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                = -2,
SELF_EFFICACY           = -1,
ORDERLINESS             = -1,
DUTIFULNESS             = -1,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         = -1,
CAUTIOUSNESS            = -2},

{ --sylph
ANXIETY                 =  0,
ANGER                   =  0,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           = -1,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  1,
LIBERALISM              =  0,
TRUST                   =  1,
STRAIGHTFORWARDNESS     =  5,
ALTRUISM                =  5,
COOPERATION             =  5,
MODESTY                 =  5,
SYMPATHY                =  5,
SELF_EFFICACY           =  5,
ORDERLINESS             =  5,
DUTIFULNESS             =  5,
ACHIEVEMENT_STRIVING    =  5,
SELF_DISCIPLINE         =  5,
CAUTIOUSNESS            =  5},

{ --mage
ANXIETY                 =  0,
ANGER                   =  0,
DEPRESSION              =  1,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           =  0,
FRIENDLINESS            =  0,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          = -1,
EXCITEMENT_SEEKING      =  1,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  1,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     = -1,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           = -1,
ORDERLINESS             =  0,
DUTIFULNESS             =  1,
ACHIEVEMENT_STRIVING    =  0,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0,},

{ --thief
ANXIETY                 =  0,
ANGER                   =  2,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  1,
IMMODERATION            =  0,
VULNERABILITY           =  1,
FRIENDLINESS            = -1,
GREGARIOUSNESS          = -1,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  0,
EXCITEMENT_SEEKING      =  5,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  2,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   = -1,
STRAIGHTFORWARDNESS     =  1,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                =  0,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  0,
ACHIEVEMENT_STRIVING    =  5,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0},

{ --bard
ANXIETY                 =  0,
ANGER                   =  0,
DEPRESSION              =  0,
SELF_CONSCIOUSNESS      =  0,
IMMODERATION            =  0,
VULNERABILITY           =  0,
FRIENDLINESS            = -1,
GREGARIOUSNESS          =  0,
ASSERTIVENESS           =  0,
ACTIVITY_LEVEL          =  0,
EXCITEMENT_SEEKING      =  0,
CHEERFULNESS            =  0,
IMAGINATION             =  0,
ARTISTIC_INTEREST       =  0,
EMOTIONALITY            =  0,
ADVENTUROUSNESS         =  0,
INTELLECTUAL_CURIOSITY =  0,
LIBERALISM              =  0,
TRUST                   =  0,
STRAIGHTFORWARDNESS     =  0,
ALTRUISM                =  0,
COOPERATION             =  0,
MODESTY                 =  0,
SYMPATHY                = -5,
SELF_EFFICACY           =  0,
ORDERLINESS             =  0,
DUTIFULNESS             =  1,
ACHIEVEMENT_STRIVING    =  1,
SELF_DISCIPLINE         =  0,
CAUTIOUSNESS            =  0
}
    }
}

local function getTotal(tbl)
local total = {0,0}
for k,v in pairs(tbl) do
if v>0
then
total[1]=v+total[1]
else
total[2]=v+total[2]
end
end
return total
end

function getSignlessTotal(tbl)
local total=0
for k,v in pairs(tbl) do
total=v+total
end
return total
end

local function getWeightAverages()
local weightAverages={{0,0},{0,0}}
for i=1,2 do
for k,claspect in ipairs(personality_weights[i]) do
local total = getTotal(claspect)
for ii=1,2 do
weightAverages[i][ii]=weightAverages[i][ii]+total[ii]
end
end
for ii=1,2 do
weightAverages[i][ii]=weightAverages[i][ii]/12
end
end
return weightAverages
end

function fixWeights() --this is here so I don't have to think about my weights meaning anything :D What's important is that they stay similar relative to one another, which this preserves.
local weightAverages=getWeightAverages()
for i=1,2 do
for k,claspect in ipairs(personality_weights[i]) do
local total=getTotal(claspect)
for kk,trait in pairs(claspect) do
if trait>0
then
trait=(weightAverages[i][1]/total[1])*trait
elseif trait<0 then
trait=(weightAverages[i][2]/total[2])*trait
else
trait=0 --:V
end
end
end
end
print("claspect assignment enabled.")
end

local function alreadyHasSyndrome(unit,syn_id)
    for _,syndrome in ipairs(unit.syndromes.active) do
        if syndrome.type == syn_id then return true end
    end
    return false
end

local function assignSyndrome(target,syn_id) --taken straight from here, but edited so I can understand it better: https://gist.github.com/warmist/4061959/. Also implemented expwnent's changes for compatibility with syndromeTrigger. I have used this so much ;_;
    if df.isnull(target) then
        return nil
    end
    if alreadyHasSyndrome(target,syn_id) then
        return true --I can omit the reset because they aren't going to ever lose their claspect
    end
    local newSyndrome=df.unit_syndrome:new()
    local target_syndrome=df.syndrome.find(syn_id)
    newSyndrome.type=target_syndrome.id
    newSyndrome.year=df.global.cur_year
    newSyndrome.year_time=df.global.cur_year_tick
    newSyndrome.ticks=1
    newSyndrome.unk1=1
    for k,v in ipairs(target_syndrome.ce) do
        local sympt=df.unit_syndrome.T_symptoms:new()
        sympt.ticks=1
        sympt.flags=2
        newSyndrome.symptoms:insert("#",sympt)
    end
    target.syndromes.active:insert("#",newSyndrome)
    return true
end

function assignClaspect(unit,creatureClass,creatureAspect) --Putting all of the claspect combos into a single table would be... problematic.
for k,v in ipairs(df.global.world.raws.syndromes.all) do
if string.find(string.lower(v.syn_name),string.lower(creatureClass)) and string.find(string.lower(v.syn_name),string.lower(creatureAspect)) then
assignSyndrome(unit,k)
end
end
end

function unitAlreadyHasClaspect(unit)
    for k,c_syn in ipairs(unit.syndromes.active) do
for _,ce in ipairs(df.global.world.raws.syndromes.all[c_syn.type].ce) do
if string.find(tostring(ce),"display_namest") and string.find(ce.name,"hero") then return true end
end
end
    return false
end

local function getHighestClaspects(claspects)
local highest={}
for i=1,2 do --1 is aspect, 2 is class
local topValue=-1000000000 --meaning top value after weight calculations; "highest" refers to the highest claspect, which can be referred to by the table at the top
for claspect=1,12 do
if getSignlessTotal(claspects[i][claspect])>topValue then
topValue=getSignlessTotal(claspects[i][claspect])
highest[i]=claspect
end
end
end
return highest
end

function makeClaspect(unit)
if unitAlreadyHasClaspect(unit) then return nil end
local personality    =  unit.status.current_soul.traits
local creatureWeights=  {{},{}}
for i=1,2 do
for k,claspect in ipairs(personality_weights[i]) do
for trait_name,trait in pairs(claspect) do
creatureWeights[i][k]={}
creatureWeights[i][k][trait_name]=(personality[trait_name]-50)*trait
end
end
end
local highestClaspect = getHighestClaspects(creatureWeights)
local creatureAspect  = claspects.aspects[highestClaspect[1]]
local creatureClass   = claspects.classes[highestClaspect[2]]
assignClaspect(unit,creatureClass,creatureAspect)
end

dfhack.onStateChange.claspect = function(code)
if code==SC_WORLD_LOADED then
dfhack.timeout(1,'ticks',monthlyClaspectAssign)
end
end

function monthlyClaspectAssign()
for _,unit in ipairs(df.global.world.units.active) do
makeClaspect(unit)
end
dfhack.timeout(200,'ticks',monthlyClaspectAssign) --okay so not monthly but still
end

dfhack.onStateChange.claspect()

fixWeights()

Why is? Two pairs, every time, class and aspect are independent, but my results, I have over 300 creatures, I run the script, only two pairs of class and aspect, different every time, heir of breath, knight of hope? This time same, both of them, no heart in sight, what changed? Why 1+1 and 3+6? Did I do something stupid with the weights? Looks like I did, and my laziness is my downfall, O, the folly of Putnam! God dang I'm dramatic today.

Putnam

  • Bay Watcher
  • DAT WIZARD
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4796 on: August 11, 2013, 05:08:17 am »

Sorry for double post. I rewrote much of it, still getting the problem. However, I think I may have the culprit.
Code: [Select]
for trait_name,trait in pairs(claspect) doThe pairs(table) function is an undefined-behavior motherfucker, as the order of the items in the table being iterated order is not defined. However, that's not the problem. The problem is that I can't figure out the goddamn problem.
Okay, this function:
Code: [Select]
local function getHighestClaspects(claspects)
local highest={}
for i=1,2 do --1 is aspect, 2 is class
local topValue=-1000000000 --meaning top value after weight calculations; "highest" refers to the highest claspect, which can be referred to by the table at the top
for claspect=1,12 do
if getSignlessTotal(claspects[i][claspect])>topValue then
topValue=getSignlessTotal(claspects[i][claspect])
highest[i]=claspect
end
end
print(highest)
end
return highest
end
Is currently returning only two tables:
{10,2}
and
{11,9}
Why only those two, I wonder?
Well, it probably has something to do with the getSignlessTotal(table) function:
Code: [Select]
function getSignlessTotal(tbl)
local total=0
for k,v in pairs(tbl) do
total=v+total
end
return total
end
There's that "pairs" function again. But why would that change it? Let's see the debug result for that, done by adding print(v) below total=v+total and print("DEMARCATE") above return total:
Code: [Select]
200
DEMARCATE
5
DEMARCATE
Shit. I've found my problem, and it is pairs. Let's change it to ipairs:
Code: [Select]
DEMARCATE
DEMARCATE
DEMARCATE
DEMARCATE
WELP.
Check the size of the input table:
Code: [Select]
0
Oh.

Let's get out of the rabbit hole a bit.

#claspects[\i][claspect]

Code: [Select]
0Oh. Found it. Turns out, my original intuition was entirely correct. It's right here:
Code: [Select]
for trait_name,trait in pairs(claspect) do
creatureWeights[i][k]={}
creatureWeights[i][k][trait_name]=(personality[trait_name]-50)*trait
end
That third line is my exact issue. creatureWeights[\i][k][trait_name] remains perfectly nil and nothing told me that until I found it.

EDIT: So it's not pairs() fault, I just misunderstood the = operator or tables. Joy.

EDIT 2: There's a thunderstorm outside and it didn't come close to the sound of my palm slapping my face. table.insert().

EDIT 3: ALSO I MISUNDERSTOOD #

EDIT 4: table.insert() is still giving me only one value when there should be FUCKING 30

EDIT 5: Holy fuuuuuuuuck:

Code: [Select]
for trait_name,trait in pairs(claspect) do
creatureWeights[i][k]={} --DING DING LOOK HERE'S THE ISSUE YOU REDEFINED THE ENTIRE TABLE THAT CONTAINS THESE VALUES EVERY TIME YOU ADD ONE YOU STUPID ASS
« Last Edit: August 11, 2013, 05:53:26 am by Putnam »
Logged

alexandertnt

  • Bay Watcher
  • (map 'list (lambda (post) (+ post awesome)) posts)
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4797 on: August 11, 2013, 07:07:45 am »

So, polygon clipping algorithms, specifically this one for Unity

Code: (C#) [Select]
                        // Select vertexes for triangle, as "triangle" is just a list of int indexes of the triangle
                        List<Vertex> outputs = new List<Vertex>(triangle.Select(x => vs[x]));
for(int i = 0; i < 4; i++){ // for each edge
List<Vertex> inputList = new List<Vertex>(outputs);
outputs = new List<Vertex>();
if (inputList.Any()){
Vertex S = inputList.Last();
foreach (Vertex E in inputList){
if (Inside(i, E.ProjectedPosition)){  // Inside is a simple switch for an integer.
if (!Inside(i, S.ProjectedPosition)){
Vector2 ls = Vector2.zero;
ls = LineIntersect(new Line(new Vector2(S.ProjectedPosition.x, S.ProjectedPosition.y), new Vector2(E.ProjectedPosition.x, E.ProjectedPosition.y)), Edges[i]);
outputs.Add(CalculateVertexFrom(S, E, ls));
}
outputs.Add(E);
} else if (Inside(i, S.ProjectedPosition)){
Vector2 ls = Vector2.zero;
ls = LineIntersect(new Line(new Vector2(S.ProjectedPosition.x, S.ProjectedPosition.y), new Vector2(E.ProjectedPosition.x, E.ProjectedPosition.y)), Edges[i]);
outputs.Add(CalculateVertexFrom(S, E, ls));
}
S = E;
}
}
}

This works, but apart from the fact it is messy (its all a WIP), is there anything that particularly stands out as being horribly slow? It takes about 500ms on a 30,000 tri skinned mesh (it is executed for each triangle), which is too slow. It is ran on a seperate thread, so it doesnt impact FPS, but still...
Logged
This is when I imagine the hilarity which may happen if certain things are glichy. Such as targeting your own body parts to eat.

You eat your own head
YOU HAVE BEEN STRUCK DOWN!

MagmaMcFry

  • Bay Watcher
  • [EXISTS]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4798 on: August 11, 2013, 08:09:45 am »

Well, you are allocating 120000 new Lists every iteration, so there's that. Try using a Vertex[7] instead, because if you're only working with triangles and a rectangle, you'll never need more than 7 vertices per list anyway.

Edit: To clarify, you should allocate that Vertex[7] right at the start of the algorithm and reuse it for all 30k triangles.
« Last Edit: August 11, 2013, 08:13:39 am by MagmaMcFry »
Logged

alexandertnt

  • Bay Watcher
  • (map 'list (lambda (post) (+ post awesome)) posts)
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #4799 on: August 11, 2013, 10:14:19 am »

After proper time measurement, it (the original version) actually takes about 250ms to execute.

Are you referring to the "outputs" list? As far as I can tell, it is allocated 120000 for each total mesh clip (30,000 triangles * 4)
I replaced the outputs list with a 7 long array allocated outside the loop and an integer (to keep track of where to place the new Vertex in) and it slowed it down by 100ms (to about 350ms)...

Code: (C#) [Select]
Vertex[] Outputs = new Vertex[7];
int OutputAdd = 0;
foreach(IEnumerable<int> triangle in Triangles.Batch(3)){
List<Vertex> outputs = new List<Vertex>(triangle.Select(x => vs[x]));
for (int i = 0; i < outputs.Count; i++){
Outputs[i] = outputs[i];
}
OutputAdd = outputs.Count;
for(int i = 0; i < 4; i++){ // for each edge
List<Vertex> inputList = new List<Vertex>(Outputs.Take(OutputAdd));
OutputAdd = 0;
if (inputList.Any()){
Vertex S = inputList.Last();
foreach (Vertex E in inputList){
if (Inside(i, E.ProjectedPosition)){
if (!Inside(i, S.ProjectedPosition)){
Vector2 ls = Vector2.zero;
ls = LineIntersect(new Line(new Vector2(S.ProjectedPosition.x, S.ProjectedPosition.y), new Vector2(E.ProjectedPosition.x, E.ProjectedPosition.y)), Edges[i]);
//outputs.Add(CalculateVertexFrom(S, E, ls));
Outputs[OutputAdd] = CalculateVertexFrom(S, E, ls);
OutputAdd++;
}
//outputs.Add(E);
Outputs[OutputAdd] = E;
OutputAdd++;
} else if (Inside(i, S.ProjectedPosition)){
Vector2 ls = Vector2.zero;
ls = LineIntersect(new Line(new Vector2(S.ProjectedPosition.x, S.ProjectedPosition.y), new Vector2(E.ProjectedPosition.x, E.ProjectedPosition.y)), Edges[i]);
//outputs.Add(CalculateVertexFrom(S, E, ls));
Outputs[OutputAdd] = CalculateVertexFrom(S, E, ls);
OutputAdd++;
}
S = E;
}
}
}
}

I could try to replace inputList in a similar fashion perhaps, but I have a feeling the compiler is doing some black magic that may nullify any potential speed gain from doing this.
I am also working on threading the algorithm (work on batches of triangles in several seperate threads, rather than just running the whole thing in a single thread).
Logged
This is when I imagine the hilarity which may happen if certain things are glichy. Such as targeting your own body parts to eat.

You eat your own head
YOU HAVE BEEN STRUCK DOWN!
Pages: 1 ... 318 319 [320] 321 322 ... 796